Initial commit: new MAMS front end (React, Vite, TypeScript, MUI)

Replaces only the front end of the legacy ColdFusion system; the backend is
unchanged. Arabic (RTL) is the default language with English, light theme by
default with dark mode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-08 16:55:26 +03:00
commit ebefaa7533
95 changed files with 13220 additions and 0 deletions

2
.env.example Normal file
View File

@ -0,0 +1,2 @@
VITE_API_BASE=/OmanTCS_stg
VITE_BACKEND_ORIGIN=http://192.168.6.46

7
.env.production Normal file
View File

@ -0,0 +1,7 @@
# Production build for mamsv2.nafith.om (static files) with the backend on https://mamsbe.nafith.om (at its root).
# The front end calls /api on its own host; Apache forwards /api/ to the backend (see deploy/apache-mamsv2.conf),
# so the browser only ever talks to one origin and the session cookie works.
VITE_BASE=/
VITE_API_BASE=/api
# the backend hands out report/attachment links on its own host; the app fetches them through /api instead
VITE_BACKEND_PUBLIC_ORIGIN=https://mamsbe.nafith.om,https://mams.nafith.om

9
.env.staging Normal file
View File

@ -0,0 +1,9 @@
# Staging: the app is served by the same IIS host as the staging backend (http://192.168.6.46/OmanTCS_stg),
# at /mams/, exactly like the first deployment. The browser sees one origin, so the session cookie works.
# npm run dev:staging dev server, backend proxied from 192.168.6.46
# npm run build:staging writes dist-staging/ (copy its contents to C:\inetpub\wwwroot\mams\ on 192.168.6.46)
# npm run start:staging builds, then serves it on http://127.0.0.1:4173/mams/ with the backend proxied
VITE_BASE=/mams/
VITE_API_BASE=/OmanTCS_stg
# only used by the dev / preview proxy, never baked into the build
VITE_BACKEND_ORIGIN=http://192.168.6.46

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
node_modules
dist
dist-staging
.env
*.log
tsconfig.tsbuildinfo
.vite

66
README.md Normal file
View File

@ -0,0 +1,66 @@
# MAMS front end (React)
Replacement front end for the ColdFusion app `OmanTCS_STG`. The ColdFusion backend is unchanged;
this app calls the same `backend/core/controller.cfc` endpoint.
## Develop
```
npm install
npm run dev # http://127.0.0.1:5173/mams/ , proxies /OmanTCS_stg to VITE_BACKEND_ORIGIN
npm run typecheck
```
Copy `.env.example` to `.env` to change `VITE_API_BASE` (default `/OmanTCS_stg`) or the dev proxy target.
## How modules are built
Lists, search, view pages and Excel export are generic: they are driven by what the backend says per module
(`getGridStructure`, search metadata, field metadata from `getConfig`). Only the **form layout** (section and
field order) comes from the legacy pages:
```
node scripts/gen-layouts.mjs [path/to/legacy/frontend/entities] # writes src/features/forms/generated-layouts.json
```
Run it again if a legacy page changes. `src/features/forms/layouts.ts` merges that file with the backend metadata,
hand-written layouts (Users, Trucks) win, and owner / governorate-state-city pickers are wired automatically.
A required dropdown the new UI has no data source for disables Save on that form (with a notice).
Menu: `FLEET_TRACKING_SERVICES` is hidden (`HIDDEN_ENTITIES` in `src/layout/nav.ts`); the old home-page dashboards
live under the "Dashboard" menu (`src/features/dashboard`).
## Run the production build on your PC (backend stays on 192.168.6.46)
```
npm start # builds, then serves http://127.0.0.1:4173/mams/ with the backend proxied
```
## Environments
| Environment | Command | Frontend | Backend |
|---|---|---|---|
| Local | `npm run dev` | http://localhost:5173/mams/ | proxied to `VITE_BACKEND_ORIGIN` (default 192.168.6.46, `/OmanTCS_stg`) |
| Staging | `npm run build:staging` (or `dev:staging`, `start:staging`) | `/mams/` on the staging IIS host, files from `dist-staging/` | http://192.168.6.46/OmanTCS_stg (same host) |
| Production | `npm run build` | https://mamsv2.nafith.om, files from `dist/` | https://mamsbe.nafith.om through the `/api` forward (see `deploy/apache-mamsv2.conf`) |
Each one reads its own env file: `.env` (local overrides), `.env.staging`, `.env.production`.
### Deploy to staging
1. `npm run build:staging`
2. Copy the contents of `dist-staging/` to `C:inetpubwwwrootmams` on 192.168.6.46 (next to `OmanTCS_stg`); the app is then at `http://192.168.6.46/mams/`.
3. IIS needs the **URL Rewrite** module for `web.config` (it is copied into the build).
## Deploy to a server (IIS, same host as the backend)
The app must be served from the **same host** as the backend (session cookies, no CORS).
1. `npm run build`
2. Copy the contents of `dist/` (not the folder itself) to `C:\inetpub\wwwroot\mams\` on the server
that hosts `OmanTCS_stg` (192.168.6.46). The app is then at `http://<server>/mams/`.
3. The server needs the IIS **URL Rewrite** module for `web.config` (SPA fallback to `/mams/index.html`).
Do not copy `node_modules`, `src` or `package.json` to the server.
Built for the `/mams/` path. To serve under another path, build with `VITE_BASE=/other/ npm run build`
and edit the rewrite target in `public/web.config`.

58
deploy/apache-mamsv2.conf Normal file
View File

@ -0,0 +1,58 @@
# Apache 2.4 on Ubuntu: static front end for mamsv2.nafith.om, backend forwarded to mamsbe.nafith.om.
# sudo a2enmod proxy proxy_http ssl rewrite headers deflate expires
# copy this file to /etc/apache2/sites-available/mamsv2.conf, fix the certificate paths, then:
# sudo a2ensite mamsv2 && sudo apache2ctl configtest && sudo systemctl reload apache2
# build: npm run build (reads .env.production) then copy dist/* to /var/www/mamsv2/
<VirtualHost *:443>
ServerName mamsv2.nafith.om
DocumentRoot /var/www/mamsv2
SSLEngine on
SSLCertificateFile /etc/ssl/certs/mamsv2.crt
SSLCertificateKeyFile /etc/ssl/private/mamsv2.key
# --- backend: /api on this host is the root of https://mamsbe.nafith.om ---
SSLProxyEngine on
SSLProxyCheckPeerName on
ProxyPreserveHost Off
# login and large exports can take 15 s or more
ProxyTimeout 180
ProxyPass /api/ https://mamsbe.nafith.om/
ProxyPassReverse /api/ https://mamsbe.nafith.om/
ProxyPassReverseCookieDomain mamsbe.nafith.om mamsv2.nafith.om
# attachment uploads: 50 MB, match the backend's own limit
LimitRequestBody 52428800
# --- single-page app: any unknown path serves index.html ---
<Directory /var/www/mamsv2>
Require all granted
Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.html [L]
</Directory>
# --- caching: hashed assets forever, index.html never ---
<Location /assets/>
Header set Cache-Control "public, max-age=31536000, immutable"
</Location>
<Files "index.html">
Header set Cache-Control "no-cache"
</Files>
# --- security headers (a Content-Security-Policy is left for the security team: fonts and reCAPTCHA load from Google) ---
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Referrer-Policy "same-origin"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set Permissions-Policy "geolocation=(), camera=(), microphone=()"
Header always unset X-Powered-By
</VirtualHost>
<VirtualHost *:80>
ServerName mamsv2.nafith.om
Redirect permanent / https://mamsv2.nafith.om/
</VirtualHost>

26
index.html Normal file
View File

@ -0,0 +1,26 @@
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="referrer" content="same-origin" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<!-- Cairo: the Arabic/Latin font used on nafith.eg's own login page, covers both languages in one family -->
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
<link rel="icon" type="image/png" href="/src/assets/logo/favicon.png" />
<script>
// the page language is known before the app loads: set it now so the first paint is already Arabic (right to left) or English
try {
var l = (localStorage.getItem('mams.lang') || 'AR').toLowerCase();
document.documentElement.lang = l;
document.documentElement.dir = l === 'ar' || l === 'urd' ? 'rtl' : 'ltr';
} catch (e) {}
</script>
<title>Nafith@Madayn</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

1912
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
package.json Normal file
View File

@ -0,0 +1,40 @@
{
"name": "mams",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev:staging": "vite --mode staging",
"build": "tsc -b && vite build",
"build:staging": "tsc -b && vite build --mode staging",
"preview": "vite preview",
"preview:staging": "vite preview --mode staging",
"start": "vite build && vite preview",
"start:staging": "vite build --mode staging && vite preview --mode staging",
"typecheck": "tsc -b --noEmit"
},
"dependencies": {
"@emotion/cache": "^11.13.0",
"@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0",
"@mui/icons-material": "^6.1.0",
"@mui/material": "^6.1.0",
"@tanstack/react-query": "^5.59.0",
"dompurify": "^3.1.7",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.5",
"stylis": "^4.3.4",
"stylis-plugin-rtl": "^2.1.1"
},
"devDependencies": {
"@types/node": "^26.6.6",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@types/stylis": "^4.2.7",
"@vitejs/plugin-react": "^6.1.2",
"typescript": "~5.6.3",
"vite": "^8.3.5"
}
}

24
public/web.config Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="SPA fallback" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/mams/index.html" />
</rule>
</rules>
</rewrite>
<httpProtocol>
<customHeaders>
<add name="X-Content-Type-Options" value="nosniff" />
<add name="X-Frame-Options" value="SAMEORIGIN" />
<add name="Referrer-Policy" value="same-origin" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>

115
scripts/gen-layouts.mjs Normal file
View File

@ -0,0 +1,115 @@
// Generates src/features/forms/generated-layouts.json from the legacy create pages.
//
// node scripts/gen-layouts.mjs [--only=ENTITY,ENTITY] [path-to-legacy-frontend/entities]
//
// For every <entity>/<entity>create/<entity>create.html it records, in the order the legacy page SHOWS
// them, the tab panes, fieldset legends and `div_<FIELD>` containers:
// - HTML comments are dropped first (the pages keep many retired fields commented out);
// - the pages lay fields out in 3 independent columns (`col-md-4`), so the columns are interleaved
// row by row, which is how they read on screen;
// - a number + area-code pair sharing one `d-flex` row stays adjacent.
// At runtime the list is intersected with the backend's own field metadata (types, required flags,
// options), so only real fields are shown.
//
// `--only` regenerates just the named entities and keeps every other entry of the existing file as is.
import { readdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const args = process.argv.slice(2);
const only = args.find((a) => a.startsWith('--only='))?.slice(7).split(',').map((s) => s.trim().toUpperCase());
const root = args.find((a) => !a.startsWith('--')) ?? 'C:/inetpub/wwwroot/OmanTCS_STG/frontend/entities';
const out = join(here, '../src/features/forms/generated-layouts.json');
// div ids that wrap something other than a form field
const NOT_FIELDS = /^(EXRTA_FIELD|EXTRA_FIELD)$|_ACTIONS?$|^MAIN_|^SECOND_|^THIRD_/;
function parse(rawHtml, entity) {
const html = rawHtml.replace(/<!--[\s\S]*?-->/g, '');
const sections = [];
let pane = '';
let legend = '';
const current = () => {
const key = legend || pane || `${entity}_INFO`;
let s = sections.find((x) => x.key === key);
if (!s) sections.push((s = { key, title: key, columns: [] }));
return s;
};
// every opening/closing <div> and <legend>, in document order; the stack tells which column / flex row a field sits in
const tag = /<(\/?)(div|legend)\b([^>]*)>/gi;
const stack = [];
let seq = 0;
for (let m; (m = tag.exec(html)); ) {
const closing = m[1] === '/';
const name = m[2].toLowerCase();
const attrs = m[3];
if (name === 'legend') {
if (!closing) {
const id = /\bid\s*=\s*"([^"]+)"/i.exec(attrs)?.[1];
if (id) legend = id;
}
continue;
}
if (closing) {
stack.pop();
continue;
}
const id = /\bid\s*=\s*"([^"]+)"/i.exec(attrs)?.[1];
const cls = /\bclass\s*=\s*"([^"]*)"/i.exec(attrs)?.[1] ?? '';
const selfClosing = /\/\s*$/.test(attrs);
const entry = { kind: 'other', seq: seq++ };
if (!id && /\bcol-(md|lg|xl)-\d+\b/.test(cls)) entry.kind = 'col';
else if (!id && /\bd-flex\b/.test(cls)) entry.kind = 'flex';
if (!selfClosing) stack.push(entry);
if (id && /\btab-pane\b/.test(cls)) {
pane = id;
legend = '';
} else if (id?.startsWith('div_')) {
const field = id.slice(4);
if (NOT_FIELDS.test(field) || !/^[A-Z][A-Z0-9_]*$/.test(field)) continue;
const s = current();
if (s.columns.some((c) => c.cells.some((cell) => cell.fields.includes(field)))) continue;
const col = [...stack].reverse().find((e) => e.kind === 'col');
const flex = [...stack].reverse().find((e) => e.kind === 'flex');
const colKey = col ? col.seq : `loose${entry.seq}`;
let column = s.columns.find((c) => c.key === colKey);
if (!column) s.columns.push((column = { key: colKey, cells: [] }));
const cellKey = flex ? flex.seq : `single${entry.seq}`;
let cell = column.cells.find((c) => c.key === cellKey);
if (!cell) column.cells.push((cell = { key: cellKey, fields: [] }));
cell.fields.push(field);
}
}
// columns -> reading order: first cell of every column, then the second cell of every column, ...
return sections
.map((s) => {
const rows = Math.max(0, ...s.columns.map((c) => c.cells.length));
const fields = [];
for (let r = 0; r < rows; r++) for (const c of s.columns) fields.push(...(c.cells[r]?.fields ?? []));
return {
title: /^ATTACHMENT/.test(s.key) ? 'ATTACHMENTS' : /^(INFO|INFORMATIONS?|MAIN)$/i.test(s.key) ? `${entity}_INFO` : s.key,
fields,
};
})
.filter((s) => s.fields.length);
}
const result = only && existsSync(out) ? JSON.parse(readFileSync(out, 'utf8')) : {};
for (const dir of readdirSync(root, { withFileTypes: true })) {
if (!dir.isDirectory()) continue;
const entity = dir.name.toUpperCase();
if (only && !only.includes(entity)) continue;
const page = join(root, dir.name, `${dir.name}create`, `${dir.name}create.html`);
if (!existsSync(page)) continue;
const sections = parse(readFileSync(page, 'utf8'), entity);
if (sections.length) result[entity] = sections;
}
writeFileSync(out, JSON.stringify(result, null, 1));
const n = Object.keys(result).length;
const f = Object.values(result).reduce((a, s) => a + s.reduce((b, x) => b + x.fields.length, 0), 0);
console.log(`wrote ${n} entities, ${f} fields -> ${out}`);

34
src/App.tsx Normal file
View File

@ -0,0 +1,34 @@
import { lazy, Suspense } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { LoadingScreen } from './components/LoadingScreen';
import { useAuth } from './auth/AuthContext';
import { AppShell } from './layout/AppShell';
import { EntityPage, HomePage, LoginPage } from './pages';
// dashboards are rarely the first page, so they load on demand
const DashboardPage = lazy(() => import('./features/dashboard/DashboardPage').then((m) => ({ default: m.DashboardPage })));
// the public self-registration pages are reached by very few visitors, so they load on demand too
const RegisterHub = lazy(() => import('./features/register/RegisterHub').then((m) => ({ default: m.RegisterHub })));
const RegisterEntityPage = lazy(() => import('./features/register/RegisterEntityPage').then((m) => ({ default: m.RegisterEntityPage })));
export function App() {
const { user, ready } = useAuth();
if (!ready) return <LoadingScreen />;
return (
<BrowserRouter basename={import.meta.env.BASE_URL.replace(/\/$/, '')}>
<Suspense fallback={<LoadingScreen />}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterHub />} />
<Route path="/register/:entity" element={<RegisterEntityPage />} />
<Route element={user ? <AppShell /> : <Navigate to="/login" replace />}>
<Route index element={<HomePage />} />
<Route path="e/:entity/:view/:id?" element={<EntityPage />} />
<Route path="dashboard/:slug" element={<DashboardPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}

15
src/api/account.ts Normal file
View File

@ -0,0 +1,15 @@
import { ApiError, rpc, type Envelope } from './client';
/** The CHANGE_PASSWORD action on USERS, for the signed-in user's own account. */
export async function changePassword(userId: number, oldPassword: string, newPassword: string, confirmPassword: string) {
const res = await rpc<Envelope>(
'USERS',
'CHANGE_PASSWORD',
{ id: userId, data: { OLDPASSWORD: oldPassword, NEWPASSWORD: newPassword, conpassword: confirmPassword } },
{ post: true },
);
if (String(res.CODE) !== '000' && res.CODE !== 0) {
throw new ApiError(String(res.MESSAGECODE ?? res.MESSAGE ?? 'ACTION_FAILED'), res.CODE);
}
return res;
}

69
src/api/attachments.ts Normal file
View File

@ -0,0 +1,69 @@
import { API_BASE, ApiError, parseBackendJson, rpc, viaBackendProxy, type Envelope } from './client';
const UPLOAD_URL = `${API_BASE}/backend/core/controller.cfc?method=receiveAttachmentRequest&EntityName=ATTACHMENTS&MethodName=addAttachment`;
/** An already stored attachment, as returned inside getView DATA.ATTACHMENTS. */
export interface StoredAttachment {
ID: number;
NAME: string; // entity folder
FILE_NAME: string;
FILE_BUSINESS_TYPE: string;
ENTITY_ID?: number;
RECORD_ID?: number;
FILE_TYPE?: string;
}
/** A file uploaded to the server's temporary folder, waiting for the form to be saved. */
export interface PendingFile {
fileType: string; // the attachment field it belongs to
file: string; // temp server id returned by the upload
name: string; // original name, for display only
}
const ACCEPT = /^(image\/(?!gif)|application\/pdf$|application\/vnd\.(openxmlformats-officedocument\.spreadsheetml\.sheet|ms-excel)$|application\/(msword|doc)$)/;
export const ACCEPT_ATTR = 'image/*,.pdf,.xls,.xlsx,.doc';
export function checkFile(file: File, maxMb: number): string | null {
if (file.size <= 0) return 'INVALID_FILE_TYPE';
if (file.type === 'image/gif' || (file.type && !ACCEPT.test(file.type))) return 'INVALID_FILE_TYPE';
if (file.size > maxMb * 1024 * 1024) return 'FILE_TOO_BIG';
return null;
}
/** Same call the old Dropzone made: multipart POST with the file in the `args` field. */
export async function uploadAttachment(file: File): Promise<string> {
const body = new FormData();
body.append('args', file, file.name);
const res = await fetch(UPLOAD_URL, { method: 'POST', body, credentials: 'same-origin' });
if (!res.ok) throw new ApiError('UPLOAD_ATTACHMENT_ERROR', res.status);
const text = (await res.text()).trim();
// The backend answers with an HTML error dump (<style>...) when it rejects the file.
if (!text || text.includes('<style') || text.includes('<script')) throw new ApiError('UPLOAD_ATTACHMENT_ERROR');
const id = text.replace(/^\/\//, '').replace(/^"|"$/g, '').trim();
if (id.startsWith('{')) {
const j = parseBackendJson<Envelope>(text);
throw new ApiError(String(j.MESSAGE ?? j.message ?? 'UPLOAD_ATTACHMENT_ERROR'));
}
return id;
}
export const attachmentUrl = (base: string, a: StoredAttachment) => viaBackendProxy(`${base}${a.NAME}/${a.FILE_NAME.trim()}`);
/** Remove a stored attachment (the legacy `request.deleteAttachment`). */
export async function deleteAttachment(entity: string, a: StoredAttachment, all: StoredAttachment[]) {
const rest = all.filter((x) => x.ID !== a.ID);
const r = await rpc<Envelope>(
'ATTACHMENTS',
'delete',
{
ID: a.ID,
ENTITY_NAME: entity,
FILE_NAME: a.FILE_NAME.trim(),
ENTITY_ID: a.ENTITY_ID,
Attachment_ARR: JSON.stringify(rest),
},
{ post: true },
);
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGECODE ?? r.MESSAGE ?? 'ACTION_FAILED'), r.CODE);
return r;
}

97
src/api/client.ts Normal file
View File

@ -0,0 +1,97 @@
// Thin client for the legacy ColdFusion RPC endpoint (backend/core/controller.cfc).
// Entity name, method name and args are base64 encoded exactly like the old Request.js.
export const API_BASE: string = import.meta.env.VITE_API_BASE ?? '/OmanTCS_stg';
const ENDPOINT = `${API_BASE}/backend/core/controller.cfc?method=receiveRequest`;
// When the backend lives on another host (reached through a forwarding prefix such as /api), the links it hands out
// (report files, attachments) are absolute addresses on that host. The browser must fetch them through the same
// prefix, or the session cookie would not be sent. VITE_BACKEND_PUBLIC_ORIGIN lists those host(s), comma separated.
const BACKEND_ORIGINS = String(import.meta.env.VITE_BACKEND_PUBLIC_ORIGIN ?? '')
.split(',')
.map((o) => o.trim().replace(/\/+$/, ''))
.filter(Boolean);
export function viaBackendProxy(url: string): string {
for (const o of BACKEND_ORIGINS) if (url === o || url.startsWith(o + '/')) return API_BASE + url.slice(o.length);
return url;
}
export class ApiError extends Error {
constructor(
message: string,
public code?: string | number,
/** the envelope's DATA, e.g. { HTMLID: 'FIRST_REGISTRATION_DATE' } on a validation error */
public data?: unknown,
) {
super(message);
}
/** the form field a business-rule error points at (the backend calls it HTMLID) */
get field(): string | undefined {
const d = this.data as { HTMLID?: unknown } | undefined;
return typeof d?.HTMLID === 'string' && d.HTMLID ? d.HTMLID : undefined;
}
}
const b64 = (s: string) => {
// btoa is Latin1-only; args can hold Arabic text.
const bytes = new TextEncoder().encode(s);
let bin = '';
bytes.forEach((b) => (bin += String.fromCharCode(b)));
return btoa(bin);
};
/** The backend prefixes JSON with "//" (secureJSON) and sometimes wraps it as a JSON string. */
export function parseBackendJson<T = unknown>(raw: string): T {
// ColdFusion sometimes emits a leftover cfdump <style> block before the payload.
const clean = (s: string) => s.replace(/<style[\s\S]*?<\/style>/gi, '').trim().replace(/^\/\//, '');
let text = clean(raw.replace(/<script[\s\S]*?<\/script>/gi, ''));
if (!/^[{["\d-]|^(true|false|null)/.test(text)) {
// An HTML error / cfdump page rather than a JSON payload.
const msg = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160);
throw new ApiError(msg || 'BACKEND_ERROR');
}
let value: unknown = JSON.parse(text);
if (typeof value === 'string') {
text = clean(value);
value = JSON.parse(text);
}
return value as T;
}
export interface Envelope<T = unknown> {
CODE?: string | number;
MESSAGE?: string;
MESSAGECODE?: string;
DATA?: T;
[k: string]: unknown;
}
export async function rpc<T = unknown>(
entity: string,
method: string,
args: Record<string, unknown> = {},
opts: { post?: boolean; signal?: AbortSignal } = {},
): Promise<T> {
const body = new URLSearchParams({
entityName: b64(entity),
methodName: b64(method),
args: b64(JSON.stringify(args)),
});
const res = await fetch(opts.post ? ENDPOINT : `${ENDPOINT}&${body}`, {
method: opts.post ? 'POST' : 'GET',
credentials: 'same-origin',
headers: opts.post ? { 'Content-Type': 'application/x-www-form-urlencoded' } : undefined,
body: opts.post ? body : undefined,
signal: opts.signal,
});
if (!res.ok) throw new ApiError(`HTTP ${res.status}`, res.status);
const data = parseBackendJson<T>(await res.text());
const env = data as Envelope;
if (env && typeof env === 'object' && !Array.isArray(env)) {
// 405 = session ended; 470 = request rejected by the regex guard.
if (env.code === 405 || env.CODE === 405) throw new ApiError('SESSION_ENDED', 405);
if (env.code === 470) throw new ApiError('ACCESS_DENIED', 470);
}
return data;
}

40
src/api/config.ts Normal file
View File

@ -0,0 +1,40 @@
import { rpc } from './client';
import { loadFleetLookups } from './fleetLookups';
// getConfig returns ~3 MB (captions for every language, menu, per-role field metadata).
// It is fetched once per session and kept in memory by React Query.
export interface AppConfig {
MENU_STRUCTURE_VIEW: string;
LT_CAPTIONS_VIEW: Record<string, Record<string, string>>;
LT_LANGUAGE: { CODE: string; ID: number; NAME: string }[];
ROLE_FIELD_STATUS_AUTHORITY_VIEW: FieldMeta[];
ROLE_SEARCH_FIELD_AUTHORITY_VIEW: SearchFieldMeta[];
AUTHORITY: { ACTION_NAME: string; ENTITY_NAME?: string; [k: string]: unknown }[];
[k: string]: unknown;
}
export interface FieldMeta {
ENTITY_NAME: string;
FIELD_NAME: string;
FIELD_TYPE: string;
FIELD_CAPTION_CODE: string;
REQUIRED: string | number;
REGEX: string;
FIELD_LENGTH: string | number;
PUBLIC_ERROR_CODE: string;
}
export interface SearchFieldMeta {
ENTITY_NAME: string;
HTML_ID: string;
FIELD_TYPE: string;
CAPTION_CODE: string;
REGEX: string;
LENGTH: number | string;
PUBLIC_ERROR_CODE: string;
}
export const getConfig = async () => {
const [config] = await Promise.all([rpc<AppConfig>('CONFIG', 'getConfig', {}), loadFleetLookups()]);
return config;
};

117
src/api/entity.ts Normal file
View File

@ -0,0 +1,117 @@
import { ApiError, rpc, type Envelope } from './client';
export interface EntityAction {
ACTION_NAME: string;
ACTION_CAPTION_CODE?: string;
ACTION_ICON_COLOR_CLASS?: string;
[k: string]: unknown;
}
export interface EntityView {
data: Record<string, unknown>;
actions: EntityAction[];
/** affiliations: the trailers hooked to the truck head, sent next to DATA */
trailers: Record<string, unknown>[];
/** reconciliations: the file's detail lines, sent next to DATA */
details: Record<string, unknown>[];
}
export const isOk = (r: Envelope) => String(r.CODE) === '000' || r.CODE === 0;
/** getView -> { CODE, DATA: {...fields}, ENTITY_ACTIONS: [...] } (ID is the encrypted id from the grid) */
export async function getView(entity: string, id: string): Promise<EntityView> {
const r = await rpc<Envelope<Record<string, unknown>> & { ENTITY_ACTIONS?: EntityAction[]; TRAILERS?: Record<string, unknown>[]; DETAILS_ARRAY?: Record<string, unknown>[] }>(entity, 'getView', {
ID: id,
});
if (!isOk(r)) throw new ApiError(String(r.MESSAGECODE ?? r.MESSAGE ?? 'LOAD_FAILED'), r.CODE);
// records with no actions come back as "" or {} rather than []
return { data: (r.DATA ?? {}) as Record<string, unknown>, actions: Array.isArray(r.ENTITY_ACTIONS) ? r.ENTITY_ACTIONS : [],
trailers: Array.isArray(r.TRAILERS) ? r.TRAILERS : [],
details: Array.isArray(r.DETAILS_ARRAY) ? r.DETAILS_ARRAY : [],
};
}
export interface ExtraField {
name: string;
label: string;
kind: 'select' | 'textarea' | 'text';
required: boolean;
maxLength?: number;
options?: { value: string; label: string }[];
}
export interface ExtraSpec {
title: string;
fields: ExtraField[];
}
/**
* Some actions (reject, cancel, deactivate…) ask for a reason first. The backend describes that popup as a
* small HTML form; we only read the fields out of it (name, label, required, options) and never insert it.
*/
export async function getExtraFields(entity: string, action: string): Promise<ExtraSpec | null> {
const r = await rpc<{ EXTRA_FIELD_EXIST?: number | boolean; DATA?: string; EXTRA_FIELD_TITLE?: string }>(
'CONFIG',
'getRoleActionExtraField',
{ ACTION_NAME: action, ENTITY_NAME: entity },
);
if (!r.EXTRA_FIELD_EXIST || !r.DATA) return null;
const doc = new DOMParser().parseFromString(r.DATA, 'text/html');
const fields: ExtraField[] = [...doc.querySelectorAll('.form-group')].flatMap((g) => {
const el = g.querySelector('select, textarea, input');
const name = el?.getAttribute('name');
if (!el || !name) return [];
const kind = el.tagName === 'SELECT' ? 'select' : el.tagName === 'TEXTAREA' ? 'textarea' : 'text';
const max = Number(el.getAttribute('maxlength'));
return [
{
name,
label: g.querySelector('h6, label')?.textContent?.trim() ?? name,
kind,
required: el.hasAttribute('required'),
maxLength: max > 0 ? max : undefined,
options:
kind === 'select'
? [...el.querySelectorAll('option')].filter((o) => o.getAttribute('value')).map((o) => ({ value: o.getAttribute('value')!, label: o.textContent?.trim() ?? '' }))
: undefined,
} satisfies ExtraField,
];
});
return fields.length ? { title: r.EXTRA_FIELD_TITLE ?? '', fields } : null;
}
/**
* CREATE / UPDATE / ... exactly as Request.commonAction posts them.
* `creationSource` mirrors the old `Register == 'Yes'` flag: 'external' for the public self-registration
* pages (so the backend runs its applicant/approval flow), 'internal' for everything behind login.
*/
export async function runAction(
entity: string,
action: string,
data: Record<string, unknown>,
id?: string,
files: { fileType: string; file: string }[] = [],
extra?: Record<string, string>,
creationSource: 'internal' | 'external' = 'internal',
): Promise<Envelope> {
const payload: Record<string, unknown> = {
data: { ...data, FILES: files.map(({ fileType, file }) => ({ fileType, file })), ...(extra ? { EXTRA_FIELD: extra } : {}) },
};
if (action === 'CREATE') {
(payload.data as Record<string, unknown>).CREATION_SOURCE = creationSource;
} else {
payload.id = id;
delete (payload.data as Record<string, unknown>).LAST_LOGIN_DATE;
}
const r = await rpc<Envelope>(entity, action, payload, { post: true });
if (!isOk(r)) throw new ApiError(String(r.MESSAGE ?? r.MESSAGECODE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
return r;
}
export interface Option {
CODE: string | number;
CAPTION_CODE?: string;
NAME?: string;
}
export const getOptions = (method: string, args: Record<string, unknown>) =>
rpc<Option[]>('CONFIG', method, args);

31
src/api/fleetLookups.ts Normal file
View File

@ -0,0 +1,31 @@
import { rpc } from './client';
import type { Option } from './entity';
/**
* The legacy fleet forms fill "vehicle make" and "use description" from CONFIG.getLT_FLEET (one short list per entity),
* not from the 208-value list the role metadata carries for those two fields. These are loaded once with the config.
*/
const USE_TYPE_ENTITY: Record<string, string> = { TRUCKS: '8', TRAILERS: '5', EQUIPMENTS: '6', BUSES: '9' };
const VEHICLE_TYPE_ENTITIES = ['TRUCKS', 'EQUIPMENTS', 'BUSES', 'CARS', 'TRAILERS'];
const lists = new Map<string, Option[]>();
export async function loadFleetLookups(): Promise<void> {
const jobs: Promise<void>[] = [];
const get = (key: string, Type: string, id: string) =>
jobs.push(
rpc<Option[]>('CONFIG', 'getLT_FLEET', { Type, supported_entity_id: id })
.then((r) => { if (Array.isArray(r) && r.length) lists.set(key, r); })
.catch(() => undefined), // a failed lookup leaves the role metadata's own list in place
);
for (const [entity, id] of Object.entries(USE_TYPE_ENTITY)) get(`${entity}.USE_DESCRIPTION`, 'UseType', id);
// the make list is the same for every entity: fetch once, share
jobs.push(
rpc<Option[]>('CONFIG', 'getLT_FLEET', { Type: 'vehicleType', supported_entity_id: '8' })
.then((r) => { if (Array.isArray(r) && r.length) for (const e of VEHICLE_TYPE_ENTITIES) lists.set(`${e}.VEHICLE_TYPE`, r); })
.catch(() => undefined),
);
await Promise.all(jobs);
}
export const fleetOptions = (entity: string, field: string): Option[] | undefined => lists.get(`${entity}.${field}`);

51
src/api/grid.ts Normal file
View File

@ -0,0 +1,51 @@
import { ApiError, rpc, type Envelope } from './client';
export interface GridColumn {
name: string;
hidden?: boolean;
width?: number;
align?: string;
formatter?: string;
}
export interface GridStructure {
columns: GridColumn[];
fields: string[];
settings: Record<string, unknown>;
}
// getGridStructure -> [columns[], settings{}, entity, [], fieldNames[]]
export async function getGridStructure(entity: string): Promise<GridStructure> {
const r = await rpc<unknown[]>(entity, 'getGridStructure', {});
return {
columns: r[0] as GridColumn[],
settings: (r[1] ?? {}) as Record<string, unknown>,
fields: (r[4] ?? []) as string[],
};
}
export interface GridPage {
total: number;
records: number;
rows: string[][];
/** customer balances: the sum of the final balances over the whole search */
totalBalance?: number;
}
export async function getGrid(
entity: string,
p: { page: number; rows: number; filter?: Record<string, unknown>; sidx?: string; sord?: string },
): Promise<GridPage> {
const r = await rpc<Envelope<string[][]>>(entity, 'getGrid', {
data: p.filter ?? {},
page: p.page,
rows: p.rows,
...(p.sidx ? { sidx: p.sidx, sord: p.sord ?? 'asc' } : {}),
});
// business rejections come back as an envelope with a non-zero CODE (e.g. FILTER_EMPTY: this list needs a filter)
if (r.CODE !== undefined && String(r.CODE) !== '0' && String(r.CODE) !== '000') {
throw new ApiError(String(r.MESSAGE ?? 'LOAD_FAILED'), r.CODE, r.DATA);
}
const tb = (r as unknown as { TOTAL_BALANCE?: number | string }).TOTAL_BALANCE;
return { total: Number(r.TOTAL ?? 0), records: Number(r.RECORDS ?? 0), rows: r.DATA ?? [], totalBalance: tb === undefined || tb === '' ? undefined : Number(tb) };
}

97
src/api/gridActions.ts Normal file
View File

@ -0,0 +1,97 @@
import { ApiError, rpc, type Envelope } from './client';
import { downloadReport } from './report';
/** One button the backend drew inside a grid row (legacy: `commonGridAction('NAME','ID')` anchors in the ACTION_ICONS cell). */
export interface RowAction {
name: string;
id: string;
label: string;
}
/** Actions this front end can run itself. Others the backend lists (e.g. a withdrawal popup) are not offered yet. */
export const SUPPORTED_ROW_ACTIONS = new Set(['PRINT_STATMENT', 'PRINT_STATMENT_EXCEL', 'GET_INVOICE', 'CREDIT_MEMO', 'POST', 'WITHDRAW_BALANCE']);
/** Actions that change money or records: they ask for confirmation first. */
export const CONFIRM_ROW_ACTIONS = new Set(['CREDIT_MEMO', 'POST']);
/** Actions that open a form of their own instead of running straight away. */
export const DIALOG_ROW_ACTIONS = new Set(['WITHDRAW_BALANCE']);
export function parseRowActions(html: string): RowAction[] {
const out: RowAction[] = [];
const re = /commonGridAction\('([A-Z_]+)'\s*,\s*'([^']+)'\)[^>]*>([^<]*)</g;
let m: RegExpExecArray | null;
while ((m = re.exec(html))) out.push({ name: m[1], id: m[2], label: m[3].trim() });
return out.filter((a) => SUPPORTED_ROW_ACTIONS.has(a.name));
}
/** The statement report reads every search field as a flat key (empty ones included) plus filtersOrder, like the Excel export. */
function flatFilter(filter: Record<string, unknown> | undefined): Record<string, string> {
const keys = ['CREATION_DATE', 'CRN', 'SHOW_ZERO_BALANCES', 'STAKEHOLDER_ENTITY_ID', 'STAKEHOLDER_NAME'];
const out: Record<string, string> = {};
for (const k of keys) out[k] = String(filter?.[k] ?? '');
out.filtersOrder = keys.filter((k) => out[k] !== '').map((k) => k + ',').join('');
return out;
}
/**
* Run one row action. Statements and invoices produce a file: the backend answers with its location and we download it.
* Returns the backend's message to show the user.
*/
export async function runRowAction(entity: string, a: RowAction, filter: Record<string, unknown> | undefined): Promise<string> {
if (a.name === 'PRINT_STATMENT' || a.name === 'PRINT_STATMENT_EXCEL') {
const r = await rpc<Envelope<string>>(
entity,
'getReport',
{ ...flatFilter(filter), REPORT_TYPE: { reportType: a.name, ID: a.id } },
{ post: true },
);
if (String(r.CODE) !== '000' || typeof r.DATA !== 'string' || !r.DATA) throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
await downloadReport(r.DATA);
return String(r.MESSAGE ?? 'REPORT_SUCCESS_GENERATED');
}
// posting sends the row's id as DATA.NEW_ID; fleet subscriptions go through the common action shape ({ id, data }) like the old page
const args =
a.name === 'POST' ? { NEW_ID: 0, DATA: { NEW_ID: a.id } } : entity === 'SUBSCRIPTIONS' ? { id: a.id, data: { FILES: [] } } : { ID: a.id };
const r = await rpc<Envelope<{ FILE?: string } | undefined>>(entity, a.name, args, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
const file = (r.DATA as { FILE?: string } | undefined)?.FILE;
if (file) await downloadReport(file);
return String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION');
}
// ---------------------------------------------------------------------------------------------
// Buttons at the top of a grid (legacy: actions whose SUPPORTED_ACTION_LOCATION contains MAIN)
// ---------------------------------------------------------------------------------------------
/** Top-of-grid actions this front end can run. */
export const MAIN_ACTIONS = new Set(['INVOICES_STATEMENTS', 'MAZYOUNAH_INVOICES', 'PUBLISH_MAZ_INVOICES', 'RECONCILIATION_UPLOAD_FILE', 'PUBLISH', 'SETTINGS']);
/** They act on the rows ticked in the grid (status must match the action's CURRENT_STATUS_NAME). */
export const SELECTION_ACTIONS = new Set(['PUBLISH']);
/** They change records for everyone in the search: ask first. */
export const CONFIRM_MAIN_ACTIONS = new Set(['PUBLISH_MAZ_INVOICES', 'PUBLISH']);
/** Every search field as a flat key (empty ones included) plus filtersOrder, as the old report calls sent them. */
export function flatSearch(ids: string[], filter: Record<string, unknown>): Record<string, string> {
const out: Record<string, string> = {};
for (const id of ids) out[id] = String(filter[id] ?? '');
out.filtersOrder = ids.filter((id) => out[id] !== '').map((id) => id + ',').join('');
return out;
}
export async function runMainAction(
entity: string,
name: string,
search: Record<string, string>,
selected: { id: string }[],
): Promise<string> {
if (name === 'PUBLISH') {
const r = await rpc<Envelope>(entity, name, { ID_ARR: JSON.stringify(selected.map((x) => ({ ID: x.id }))) }, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
return String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION');
}
const r = await rpc<Envelope<Record<string, string> | undefined>>(entity, name, { data: search }); // the old search form posted its fields as { data: {...} }
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
const d = r.DATA as Record<string, string> | undefined;
// the statement and the Mazyouna invoices answer with the generated files
for (const k of ['FILE', 'XLS', 'PDF', 'INVOICE_PDF']) if (d && typeof d[k] === 'string' && d[k]) await downloadReport(d[k]);
return String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION');
}

257
src/api/packages.ts Normal file
View File

@ -0,0 +1,257 @@
import { ApiError, rpc } from './client';
/**
* The subscription wizard's choices (service group, package, service, subscription) come from the backend as
* ready-made HTML cards. We only read the text and the button's arguments out of them; the HTML is never inserted.
*/
export interface PackageCard {
id: string;
title: string;
/** description / duration / price lines, in the order the card shows them */
lines: { kind: 'info' | 'duration' | 'price' | 'text'; text: string }[];
/** arguments of the button's click handler, e.g. getServiceSubscriptions('MT0003','ACCESS',title,'FLEET') */
args: string[];
}
interface Cols {
COL_1?: string;
COL_2?: string;
COL_3?: string;
COL_4?: string;
}
const ARG = /'((?:[^'\\]|\\.)*)'/g;
const KIND: [string, PackageCard['lines'][number]['kind']][] = [['la-info', 'info'], ['la-calendar', 'duration'], ['la-money', 'price']];
function parseColumn(html: unknown): PackageCard[] {
if (typeof html !== 'string' || !html.trim()) return [];
const doc = new DOMParser().parseFromString(html, 'text/html');
return [...doc.querySelectorAll('.card')].map((card) => {
const click = card.querySelector('[onclick]')?.getAttribute('onclick') ?? '';
const lines = [...card.querySelectorAll('p.card-text')].map((p) => {
const icon = p.querySelector('i')?.className ?? '';
return { kind: KIND.find(([c]) => icon.includes(c))?.[1] ?? 'text', text: p.textContent?.replace(/\s+/g, ' ').trim() ?? '' };
});
return {
id: card.id.replace(/_card$|_serviceCard$/, ''),
title: card.querySelector('.card-title, h3, h4')?.textContent?.replace(/\s+/g, ' ').trim() ?? '',
lines: lines.filter((l) => l.text),
args: [...click.matchAll(ARG)].map((m) => m[1].trim()),
};
});
}
/** The backend spreads the cards over up to four columns; interleave them back into reading order. */
function parseCards(r: Cols): PackageCard[] {
const cols = [r.COL_1, r.COL_2, r.COL_3, r.COL_4].map(parseColumn);
const out: PackageCard[] = [];
for (let i = 0; i < Math.max(...cols.map((c) => c.length)); i++) for (const c of cols) if (c[i]) out.push(c[i]);
return out;
}
const TYPE = 'FLEET_SUBSCRIPTIONS';
export const getPackageGroups = async () => parseCards(await rpc<Cols>('subscriptions', 'get_packages', { Subscription_Type: TYPE }));
export const getPackages = async (group: string) =>
parseCards(await rpc<Cols>('subscriptions', 'get_packages', { Subscription_Type: TYPE, packageGroupName: group }));
export const getServiceCategories = async (packageCode: string, group: string) =>
parseCards(await rpc<Cols>('subscriptions', 'get_package_services', { package_code: packageCode, packageGroupName: group }));
export interface ServiceSubscriptions {
cards: PackageCard[];
estates: { CODE: string | number; CAPTION_CODE?: string }[];
/** price per vehicle by subscription code ("SUB_<code>") */
prices: Record<string, number>;
/** extra per-vehicle platform service price, same keys */
platformPrices: Record<string, number>;
}
export async function getServiceSubscriptions(packageCode: string, service: string, group: string): Promise<ServiceSubscriptions> {
const r = await rpc<
Cols & { INDUSTRIALESTATES?: ServiceSubscriptions['estates']; PAYMENT_SUB_PRICE?: Record<string, number>; PAYMENT_NAFDSP_SERVICEPRICE?: Record<string, number> }
>('subscriptions', 'get_package_services', { package_code: packageCode, service_code: service, packageGroupName: group });
return {
cards: parseCards(r),
estates: r.INDUSTRIALESTATES ?? [],
prices: r.PAYMENT_SUB_PRICE ?? {},
platformPrices: r.PAYMENT_NAFDSP_SERVICEPRICE ?? {},
};
}
export interface Selectable {
VALUE: string;
TEXT: string;
}
export interface FleetSearchField {
name: string;
label: string;
kind: 'text' | 'select';
maxLength?: number;
options: { CODE: string | number; CAPTION_CODE?: string; NAME?: string }[];
}
/**
* Multi-trip vehicles. A company user gets the list straight away; a staff user (role group NAFITH) gets the
* definition of a search form instead and lists vehicles only after searching.
*/
export type FleetResult = { kind: 'list'; items: Selectable[] } | { kind: 'search'; fields: FleetSearchField[] };
interface FleetArgs {
packageCode: string;
service: string;
subscription: string;
estate: string;
}
const fleetArgs = (a: FleetArgs) => ({
package_code: a.packageCode,
service_code: a.service,
service_group_code: a.subscription,
SUBSCRIPTION_LOCATION_ID: a.estate,
});
export async function getFleet(a: FleetArgs): Promise<FleetResult> {
const r = await rpc<unknown[]>('subscriptions', 'get_package_fleet', fleetArgs(a));
const first = r[0] as Record<string, unknown> | undefined;
if (first && 'HTML' in first && 'NAME' in first) {
return {
kind: 'search',
fields: (r as { HTML: string; DDL?: FleetSearchField['options']; NAME: string }[]).map((x) => {
const doc = new DOMParser().parseFromString(x.HTML, 'text/html');
const select = doc.querySelector('select');
return {
name: x.NAME,
label: doc.querySelector('h6, label')?.textContent?.replace(/\s+/g, ' ').trim() ?? x.NAME,
kind: select ? 'select' : 'text',
maxLength: Number(doc.querySelector('input')?.getAttribute('maxlength')) || undefined,
options: x.DDL ?? [],
};
}),
};
}
return { kind: 'list', items: r as Selectable[] };
}
/** Staff search: the vehicles that match the filled-in search fields. */
export const getFilteredFleet = (a: FleetArgs, filters: Record<string, string>) =>
rpc<Selectable[]>('subscriptions', 'get_filtered_package_fleet', { ...fleetArgs(a), SEARCH_FILTERS: filters });
/** The classes (truck types…) available for the chosen fleet type. */
export const getFleetClasses = (fleetType: string) =>
rpc<{ CODE: string | number; CAPTION_CODE?: string; NAME?: string }[]>('CONFIG', 'getFleetSubscriptionClass', { fleetType });
export const getEmployees = (packageCode: string) => rpc<Selectable[]>('subscriptions', 'get_package_employees', { package_code: packageCode });
export const getRiyadaCount = (entityId: string, recordId: string) =>
rpc<number>('CONFIG', 'getRiyadaSubscribedVehiclesCount', { stakeholderEntityID: entityId, stakeholderEntityRecordID: recordId });
export interface PaymentMethod {
ID: number;
NAME: string;
}
/** Payment methods come with the subscription list (step 2). */
export const getPaymentMethods = async (group: string) =>
(await rpc<{ PAYMENT_METHODS?: PaymentMethod[] }>('subscriptions', 'get_packages', { Subscription_Type: TYPE, packageGroupName: group })).PAYMENT_METHODS ?? [];
export const validateReceipt = (receipt: string, amount: number) =>
rpc<string>('CONFIG', 'VALIDATE_POS_RECEIPT', { receipt_id: receipt, amount });
export interface SubscriptionRequest {
packageCode: string;
packageGroupCode: string[];
fleetArray: string;
paymentMethod: number | string;
subscriptionDetailsType: string;
packageGroupType: string;
approval_number_id: number;
periodicSubscriptionLocationID: string;
receipt_id?: string;
}
export interface CreateResult {
CODE?: string | number;
MESSAGE?: string;
RECEIVABLES?: string;
PAYMENT_METHOD?: string;
/** one-trip requests answer with a RESULTCODE instead of CODE */
RESULTCODE?: string;
RESULTDATA?: { response_code?: string; response_error_codes?: string }[];
}
/** The request the old wizard's "Pay" button sends. */
export async function createSubscription(p: SubscriptionRequest) {
const r = await rpc<CreateResult>('subscriptions', 'CREATE', p as unknown as Record<string, unknown>, { post: true });
// one-trip requests report their outcome in RESULTCODE (handled by the wizard); everything else uses CODE
if (r.RESULTCODE === undefined && String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE);
return r;
}
/* ---------------------------------- one-trip permits ---------------------------------- */
type Opt = { CODE: string | number; CAPTION_CODE?: string; NAME?: string };
/** The drop-down data of the one-trip truck form. */
export interface OneTripData {
NATIONALITY?: Opt[];
FLEET_PLATE_CODE?: Opt[];
TRAILER_TYPES?: Opt[];
INDUSTRIAL_ESTATE?: Opt[];
CARGO_TYPE?: Opt[];
OPERATION_TYPES?: Opt[];
PERSONAL_DOC_TYPE?: Opt[];
AREA_CODE?: Opt[];
INVESTORS_NAME?: Opt[];
GOVERNORATES?: Opt[];
APPROVAL_NUMBER?: string | number;
}
export const getOneTripData = (fleetRequestNumber: 0 | 1) =>
rpc<OneTripData>('CONFIG', 'getOneTripTrucksData', { GET_FLEET_REQUEST_NUM: fleetRequestNumber });
export interface ApprovalResult {
RESULT: {
CODE: number | string;
MESSAGE?: string;
INDUSTRIAL_ESTATE_ID?: string | number;
INVESTOR_RECORD_ID?: string | number;
REQUEST_ID?: string | number;
TOTAL_FLEET_NO?: string | number;
USED_FLEET_NO?: string | number;
};
}
export const validateApprovalNumber = (approvalNumber: string) =>
rpc<ApprovalResult>('CONFIG', 'validateFleetApprovalNumber', { APPROVAL_NUMBER: approvalNumber });
export interface PermitValidation {
RESULTCODE?: string;
RESULTDATA?: Record<string, string>[];
TRUCK_VALID_FOR_MATCHING_SERVICE?: number | string;
}
/** Checks a truck (or a driver) the way the old form did before a row could be added. */
export const validatePermit = (
fleetData: Record<string, unknown>[],
ctx: { packageCode: string; subscriptionCode: string; packageGroupType: string; approvalNumberId: number | string },
) =>
rpc<PermitValidation>('subscriptions', 'validate_permit', {
fleetData: JSON.stringify(fleetData),
package_code: ctx.packageCode,
packageGroupCode: ctx.subscriptionCode,
validationFlag: 1,
packageGroupType: ctx.packageGroupType,
approval_number_id: ctx.approvalNumberId,
});
/** 200 / 1999 mean the waybill number is acceptable. */
export const checkWaybillNumber = (a: { plateNumber: string; plateCode: string; waybillNumber: string; nationality: string }) =>
rpc<number | string>('CONFIG', 'checkWayBillNumber', {
plateNumber: a.plateNumber,
plateCode: a.plateCode,
waybillNumber: a.waybillNumber,
TRUCK_NATIONALITY: a.nationality,
});

28
src/api/register.ts Normal file
View File

@ -0,0 +1,28 @@
import { rpc, type Envelope } from './client';
/**
* The mobile-OTP pre-check that gates OWNERS and FREEZONE_CLEARING_COMPANIES self-registration: a
* mobile number (plus a few identifying fields) gets an SMS code before the applicant ever sees the
* full form. Field names differ slightly per entity because the legacy popups used different ids.
*/
export type OtpEntity = 'OWNERS' | 'FREEZONE_CLEARING_COMPANIES';
export interface OtpFieldMap {
mobile: string;
areaCode: string;
nationality: string;
docType: string;
/** OWNERS only: the applicant's national/ID number */
cn?: string;
}
export const OTP_FIELDS: Record<OtpEntity, OtpFieldMap> = {
OWNERS: { mobile: 'MOBILE_NUMBER', areaCode: 'AREA_CODE_POPUP', nationality: 'LICENSE_NATIONALITY_CODE_POPUP', docType: 'PERSONAL_DOCUMENT_TYPE_POPUP', cn: 'CN' },
FREEZONE_CLEARING_COMPANIES: { mobile: 'MOBILE_NUMBER', areaCode: 'AREA_CODE', nationality: 'LICENSE_NATIONALITY_CODE', docType: 'PERSONAL_DOCUMENT_TYPE' },
};
export const sendVerificationCode = (entity: OtpEntity, data: Record<string, string>) =>
rpc<Envelope>(entity, 'SEND_VERIFICATION_CODE', { id: 0, data }, { post: true });
export const verifySms = (entity: OtpEntity, data: Record<string, string>) =>
rpc<Envelope>(entity, 'VERIFY_SMS', { data }, { post: true });

60
src/api/report.ts Normal file
View File

@ -0,0 +1,60 @@
import { API_BASE, ApiError, rpc, viaBackendProxy, type Envelope } from './client';
/**
* Ask the backend to build the Excel report for the current search (legacy `<ENTITY>_Report('EXCEL')`).
* The backend wants every search field as a flat key (empty ones included), `filtersOrder` and REPORT_TYPE, and answers
* with the generated file's location in DATA.
*/
export async function requestReport(
entity: string,
searchFieldIds: string[],
filter: Record<string, string>,
type: 'EXCEL' | 'PDF' = 'EXCEL',
): Promise<{ message: string; file: string }> {
// the customer balances report reads REPORT_TYPE as { reportType, ID } (it also prints statements); the others read a plain word
const args: Record<string, unknown> = { REPORT_TYPE: entity === 'CUSTOMER_BALANCES' ? { reportType: type, ID: 0 } : type };
for (const id of searchFieldIds) args[id] = filter[id] ?? '';
// the old UI also sent the filled-in fields as a comma list in form order (with a trailing comma); several
// entities' getReport (POS transactions, permit status, overdue charges…) read it and fail without it
args.filtersOrder = searchFieldIds.filter((id) => (filter[id] ?? '') !== '').map((id) => id + ',').join('');
const r = await rpc<Envelope<string>>(entity, 'getReport', args, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
if (typeof r.DATA !== 'string' || !r.DATA) throw new ApiError('ACTION_FAILED');
return { message: String(r.MESSAGE ?? 'REPORT_SUCCESS_GENERATED'), file: r.DATA };
}
/**
* Download the generated file. The backend returns an absolute URL on its own host; we fetch it via the
* app's own origin when it is under the API base (so the proxy/session apply), and retry because the old
* UI waited 5 s before downloading, i.e. the file is not always ready the moment the call returns.
*/
export async function downloadReport(file: string): Promise<void> {
const url = new URL(viaBackendProxy(file), window.location.origin);
// a link on any other host (the backend's own public name, which can differ from the one it is reached through)
// cannot be fetched from this page: the browser refuses it (CORS) and would not send the session cookie.
// The file lives on the backend, so ask for the same path through the API prefix instead.
const sameOrigin = url.origin === window.location.origin;
const target = url.pathname.startsWith(API_BASE) ? url.pathname + url.search : sameOrigin || !API_BASE.startsWith('/') ? url.href : API_BASE + url.pathname + url.search;
const name = decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/') + 1)) || 'report.xlsx';
let lastStatus = 0;
for (let attempt = 0; attempt < 8; attempt++) {
const res = await fetch(target, { credentials: 'same-origin' });
lastStatus = res.status;
const isHtml = (res.headers.get('content-type') ?? '').includes('text/html');
if (res.ok && !isHtml) {
const blob = await res.blob();
const href = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = href;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(href), 10_000);
return;
}
await new Promise((r) => setTimeout(r, 1500));
}
throw new ApiError(`REPORT_DOWNLOAD_FAILED (${lastStatus})`);
}

70
src/api/session.ts Normal file
View File

@ -0,0 +1,70 @@
import { API_BASE, rpc, ApiError, type Envelope } from './client';
export interface SessionUser {
user_id: number;
login: string;
name: string;
role_code: string;
role_group?: string;
language: string;
language_id?: string;
is_login: number;
[k: string]: string | number | undefined;
}
// index.cfm embeds the session as `sessionUser["key"] = "value";` lines (ColdFusion toScript).
// We read them with a strict pattern instead of evaluating the page's JavaScript.
const ASSIGN = /sessionUser\["(\w+)"\]\s*=\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)\s*;/g;
export async function fetchSessionUser(lang: string): Promise<SessionUser | null> {
const res = await fetch(`${API_BASE}/index.cfm?lang=${encodeURIComponent(lang)}`, {
credentials: 'same-origin',
});
if (!res.ok) return null;
const html = await res.text();
const user: Record<string, string | number> = {};
for (const m of html.matchAll(ASSIGN)) {
user[m[1]] = m[2].startsWith('"') ? (JSON.parse(m[2]) as string) : Number(m[2]);
}
return user.is_login === 1 ? (user as unknown as SessionUser) : null;
}
export async function login(username: string, password: string, languageId: number, rememberMe = false) {
const res = await rpc<Envelope>('CONFIG', 'login', {
// the backend reads DATA.REMEMBER_ME unconditionally on a successful login, even though it does nothing with it here
data: { USERNAME: username, PASSWORD: password, LANGUAGE: languageId, REMEMBER_ME: rememberMe },
});
if (String(res.CODE) !== '000' && res.CODE !== 0) {
throw new ApiError(String(res.MESSAGECODE ?? res.MESSAGE ?? 'LOGIN_FAILED'), res.CODE);
}
return res;
}
export const logout = (languageId: number) =>
rpc('CONFIG', 'logout', { data: { LANGUAGE: languageId } });
/** The public reCAPTCHA site key is only ever handed out embedded in index.cfm's inline script. */
export async function fetchRecaptchaSiteKey(lang: string): Promise<string> {
const res = await fetch(`${API_BASE}/index.cfm?lang=${encodeURIComponent(lang)}`, { credentials: 'same-origin' });
const html = await res.text();
return /env\.recaptcha_key\s*=\s*'([^']*)'/.exec(html)?.[1] ?? '';
}
/**
* "Forgot password" runs before login, so there is no session yet: the old UI first opens an unauthenticated
* registration-role session (same call the sign-up pages use), then sends the request under it.
*/
export const createExternalSession = (lang: string) => rpc<Envelope>('CONFIG', 'createExternalSession', { data: { LANGUAGE: lang } });
export async function forgotPassword(loginOrEmail: string, recaptchaToken: string) {
const res = await rpc<Envelope>(
'USERS',
'FORGET_PASSWORD',
{ id: 0, data: { loginOrEmail, 'g-recaptcha-response': recaptchaToken } },
{ post: true },
);
if (String(res.CODE) !== '000' && res.CODE !== 0) {
throw new ApiError(String(res.MESSAGECODE ?? res.MESSAGE ?? 'ACTION_FAILED'), res.CODE);
}
return res;
}

BIN
src/assets/logo/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

124
src/auth/AuthContext.tsx Normal file
View File

@ -0,0 +1,124 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query';
import { rpc } from '../api/client';
import { createExternalSession, fetchSessionUser, login as apiLogin, logout as apiLogout, type SessionUser } from '../api/session';
import { getConfig, type AppConfig } from '../api/config';
interface AuthState {
user: SessionUser | null;
config: AppConfig | undefined;
lang: string;
setLang: (l: string) => void;
ready: boolean;
/** the backend session already speaks `lang`: language-dependent data fetched before this would come back in the old language */
langReady: boolean;
signIn: (u: string, p: string, rememberMe?: boolean) => Promise<void>;
signOut: () => Promise<void>;
/** true once the unauthenticated "self-registration" session + its config (role REGISTER) are ready */
registerReady: boolean;
/** opens the anonymous REGISTER-role session the public sign-up pages run under; safe to call repeatedly */
beginRegistration: () => void;
}
const Ctx = createContext<AuthState>(null as never);
export const useAuth = () => useContext(Ctx);
const LANG_IDS: Record<string, number> = { AR: 1, EN: 2, URD: 3 };
export function AuthProvider({ children }: { children: ReactNode }) {
const qc = useQueryClient();
const [lang, setLangState] = useState(() => localStorage.getItem('mams.lang') || 'AR');
const setLang = (l: string) => {
localStorage.setItem('mams.lang', l);
setLangState(l);
};
const session = useQuery({
queryKey: ['session'],
queryFn: () => fetchSessionUser(lang),
staleTime: Infinity,
retry: false,
});
const user = session.data ?? null;
// The public sign-up pages (and "forgot password") act before any login exists: they run under an
// unauthenticated, role-REGISTER session instead. Starting it is idempotent and only ever done when
// there is no real user.
const [registering, setRegistering] = useState(false);
const beginRegistration = () => setRegistering(true);
const registerSession = useQuery({
queryKey: ['register-session', lang],
queryFn: () => createExternalSession(lang),
enabled: registering && !user,
staleTime: Infinity,
retry: false,
});
// The backend answers in the language of the session (names, plate numbers, statuses…), so the session must follow
// the language chosen here, exactly as the old "change language" link did. Data already on screen is then reloaded.
const backendLang = useQuery({
queryKey: ['backend-lang', user?.user_id, lang],
queryFn: async () => {
try {
await rpc('CONFIG', 'setLanaguage', { language: lang });
} catch {
/* the interface language still changes; data stays in the previous language */
}
await qc.invalidateQueries({ predicate: (q) => !['session', 'config', 'backend-lang'].includes(String(q.queryKey[0])) });
return lang;
},
enabled: !!user,
staleTime: Infinity,
retry: false,
placeholderData: keepPreviousData,
});
// the menu captions inside the config are written in the session language, so it is read again after a language change
const cfg = useQuery({
queryKey: ['config', user ? user.user_id : registering ? 'register' : 'none', lang],
queryFn: getConfig,
enabled: user ? backendLang.data === lang && !backendLang.isPlaceholderData : registering && registerSession.isSuccess,
staleTime: Infinity,
placeholderData: keepPreviousData,
});
const registerReady = !user && registering && registerSession.isSuccess && cfg.isSuccess && !cfg.isPlaceholderData;
useEffect(() => {
document.documentElement.lang = lang.toLowerCase();
document.documentElement.dir = lang === 'AR' || lang === 'URD' ? 'rtl' : 'ltr';
}, [lang]);
const signIn = async (u: string, p: string, rememberMe = false) => {
await apiLogin(u, p, LANG_IDS[lang] ?? 1, rememberMe);
await qc.invalidateQueries({ queryKey: ['session'] });
};
const signOut = async () => {
try {
await apiLogout(LANG_IDS[lang] ?? 1);
} finally {
// set this directly rather than clear()-then-invalidate: clear() removes the 'session' query
// from the cache first, so the invalidate that follows has nothing left to match and never refetches
qc.setQueryData(['session'], null);
qc.removeQueries({ predicate: (q) => q.queryKey[0] !== 'session' });
}
};
return (
<Ctx.Provider
value={{
user,
config: cfg.data,
lang,
setLang,
langReady: !user || (backendLang.data === lang && !backendLang.isPlaceholderData),
ready: !session.isPending && (!user || (!!cfg.data && !!backendLang.data)),
signIn,
signOut,
registerReady,
beginRegistration,
}}
>
{children}
</Ctx.Provider>
);
}

View File

@ -0,0 +1,124 @@
import { useState } from 'react';
import {
Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, InputAdornment, TextField,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import { useAuth } from './AuthContext';
import { useT, useUi } from '../i18n';
import { ApiError } from '../api/client';
import { changePassword } from '../api/account';
function PasswordField({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
const [show, setShow] = useState(false);
const ui = useUi();
return (
<TextField
label={label}
type={show ? 'text' : 'password'}
value={value}
onChange={(e) => onChange(e.target.value)}
required
fullWidth
slotProps={{
input: {
endAdornment: (
<InputAdornment position="end">
<IconButton size="small" edge="end" tabIndex={-1} aria-label={show ? ui('hidePassword') : ui('showPassword')} onClick={() => setShow((v) => !v)}>
{show ? <VisibilityOff fontSize="small" /> : <Visibility fontSize="small" />}
</IconButton>
</InputAdornment>
),
},
}}
/>
);
}
export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const { user } = useAuth();
const t = useT();
const ui = useUi();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [busy, setBusy] = useState(false);
const [result, setResult] = useState<{ ok: boolean; text: string } | null>(null);
const reset = () => {
setOldPassword('');
setNewPassword('');
setConfirmPassword('');
setResult(null);
};
const submit = async () => {
if (newPassword !== confirmPassword) {
setResult({ ok: false, text: t('NEW_PASS_MISS_MATCH') });
return;
}
setBusy(true);
setResult(null);
try {
const res = await changePassword(user!.user_id, oldPassword, newPassword, confirmPassword);
setResult({ ok: true, text: t(String(res.MESSAGECODE ?? 'CHANGE_PASSWORD.SUCCESS')) });
} catch (x) {
setResult({ ok: false, text: x instanceof ApiError ? t(x.message) : t('ACTION_FAILED') });
} finally {
setBusy(false);
}
};
return (
<Dialog
open={open}
onClose={() => {
reset();
onClose();
}}
maxWidth="xs"
fullWidth
>
<DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
{t('CHANGE_PASSWORD')}
<IconButton
size="small"
onClick={() => {
reset();
onClose();
}}
>
<CloseIcon fontSize="small" />
</IconButton>
</DialogTitle>
<DialogContent>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 0.5 }}>
{result && <Alert severity={result.ok ? 'success' : 'error'}>{result.text}</Alert>}
{!result?.ok && (
<>
<PasswordField label={t('OLD_PASSWORD')} value={oldPassword} onChange={setOldPassword} />
<PasswordField label={t('NEW_PASSWORD')} value={newPassword} onChange={setNewPassword} />
<PasswordField label={t('CON_NEW_PASSWORD')} value={confirmPassword} onChange={setConfirmPassword} />
</>
)}
</Box>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5 }}>
<Button
onClick={() => {
reset();
onClose();
}}
>
{ui('cancel')}
</Button>
{!result?.ok && (
<Button variant="contained" disabled={busy || !oldPassword || !newPassword || !confirmPassword} onClick={submit}>
{busy ? <CircularProgress size={20} color="inherit" /> : t('SAVE')}
</Button>
)}
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,79 @@
import { useEffect, useState } from 'react';
import {
Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, TextField,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { useAuth } from './AuthContext';
import { useT, useUi } from '../i18n';
import { ApiError } from '../api/client';
import { createExternalSession, fetchRecaptchaSiteKey, forgotPassword } from '../api/session';
import { useRecaptcha } from './recaptcha';
export function ForgotPasswordDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const { lang } = useAuth();
const t = useT();
const ui = useUi();
const [loginOrEmail, setLoginOrEmail] = useState('');
const [busy, setBusy] = useState(false);
const [result, setResult] = useState<{ ok: boolean; text: string } | null>(null);
const captcha = useRecaptcha(open && !result?.ok, lang, fetchRecaptchaSiteKey);
useEffect(() => {
if (open) {
setLoginOrEmail('');
setResult(null);
}
}, [open]);
const submit = async () => {
setBusy(true);
setResult(null);
try {
await createExternalSession(lang);
const res = await forgotPassword(loginOrEmail, captcha.token);
setResult({ ok: true, text: t(String(res.MESSAGECODE ?? 'FORGET_PASSWORD_SEND_EMAIL')) });
} catch (x) {
setResult({ ok: false, text: x instanceof ApiError ? t(x.message) : t('ACTION_FAILED') });
} finally {
setBusy(false);
captcha.reset();
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
{ui('forgotPassword')}
<IconButton size="small" onClick={onClose}>
<CloseIcon fontSize="small" />
</IconButton>
</DialogTitle>
<DialogContent>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 0.5 }}>
{result && <Alert severity={result.ok ? 'success' : 'error'}>{result.text}</Alert>}
{!result?.ok && (
<>
<TextField
label={t('LOGIN_OR_EMAIL')}
fullWidth
value={loginOrEmail}
onChange={(e) => setLoginOrEmail(e.target.value)}
autoFocus
required
/>
<Box ref={captcha.ref} />
</>
)}
</Box>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5 }}>
<Button onClick={onClose}>{ui('cancel')}</Button>
{!result?.ok && (
<Button variant="contained" disabled={busy || !loginOrEmail || !captcha.token} onClick={submit}>
{busy ? <CircularProgress size={20} color="inherit" /> : t('CONTINUE')}
</Button>
)}
</DialogActions>
</Dialog>
);
}

60
src/auth/recaptcha.ts Normal file
View File

@ -0,0 +1,60 @@
import { useEffect, useRef, useState } from 'react';
declare global {
interface Window {
grecaptcha?: {
ready: (cb: () => void) => void;
render: (container: HTMLElement, params: { sitekey: string; callback: (token: string) => void; 'expired-callback'?: () => void }) => number;
reset: (id?: number) => void;
};
}
}
let recaptchaScript: Promise<void> | null = null;
// api.js installs a stub `grecaptcha` immediately; `render`/`reset` only exist once `ready()`'s callback fires.
export const loadRecaptchaScript = () =>
(recaptchaScript ??= new Promise<void>((resolve, reject) => {
if (window.grecaptcha) return window.grecaptcha.ready(resolve);
const s = document.createElement('script');
s.src = 'https://www.google.com/recaptcha/api.js';
s.async = true;
s.defer = true;
s.onload = () => window.grecaptcha?.ready(resolve);
s.onerror = () => reject(new Error('RECAPTCHA_LOAD_FAILED'));
document.head.appendChild(s);
}));
/** Renders the widget into the returned ref whenever `active`, and hands back its current token. */
export function useRecaptcha(active: boolean, lang: string, fetchSiteKey: (lang: string) => Promise<string>) {
const ref = useRef<HTMLDivElement>(null);
const [token, setToken] = useState('');
const [widgetId, setWidgetId] = useState<number | null>(null);
useEffect(() => {
if (!active) return;
setToken('');
let cancelled = false;
(async () => {
const [siteKey] = await Promise.all([fetchSiteKey(lang), loadRecaptchaScript().catch(() => '')]);
if (cancelled || !ref.current || !window.grecaptcha || !siteKey) return;
ref.current.innerHTML = '';
const id = window.grecaptcha.render(ref.current, {
sitekey: siteKey,
callback: (tok) => setToken(tok),
'expired-callback': () => setToken(''),
});
setWidgetId(id);
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active, lang]);
const reset = () => {
setToken('');
if (widgetId !== null) window.grecaptcha?.reset(widgetId);
};
return { ref, token, reset };
}

View File

@ -0,0 +1,97 @@
import { useRef, useState } from 'react';
import { IconButton, InputAdornment, TextField, type TextFieldProps } from '@mui/material';
import CalendarMonthOutlined from '@mui/icons-material/CalendarMonthOutlined';
import { useAuth } from '../auth/AuthContext';
import { isRtl, useUi } from '../i18n';
const isoToDisplay = (iso: string) => (/^\d{4}-\d{2}-\d{2}$/.test(iso) ? `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}` : '');
/** keeps only digits and puts the slashes in while typing: 25122026 -> 25/12/2026 */
const mask = (raw: string) => {
const d = raw.replace(/\D/g, '').slice(0, 8);
return [d.slice(0, 2), d.slice(2, 4), d.slice(4, 8)].filter(Boolean).join('/');
};
const displayToIso = (display: string) => {
const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(display);
if (!m) return '';
const [, dd, mm, yyyy] = m;
const date = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
const real = date.getFullYear() === Number(yyyy) && date.getMonth() === Number(mm) - 1 && date.getDate() === Number(dd);
return real ? `${yyyy}-${mm}-${dd}` : '';
};
/**
* A date box that reads dd/mm/yyyy in the app's own language. The browser's native date input shows its own
* placeholder ("mm/dd/yyyy") in the browser's language, which cannot be changed from the page, so the text is
* typed here and the native calendar is only opened from the icon. `value` and `onChange` use ISO (yyyy-mm-dd).
*/
export function DateField({
value,
onChange,
...rest
}: { value: string; onChange: (iso: string) => void } & Omit<TextFieldProps, 'value' | 'onChange' | 'type'>) {
const { lang } = useAuth();
const ui = useUi();
const [typed, setTyped] = useState<string | null>(null);
const native = useRef<HTMLInputElement>(null);
const shown = typed ?? isoToDisplay(value);
const placeholder = ui('datePlaceholder');
return (
<TextField
{...rest}
value={shown}
placeholder={placeholder}
onChange={(e) => {
const text = mask(e.target.value);
setTyped(text);
// a complete, real date is committed at once; an incomplete one clears the value until it is finished
onChange(displayToIso(text));
}}
onBlur={(e) => {
setTyped(null);
rest.onBlur?.(e);
}}
slotProps={{
...rest.slotProps,
inputLabel: { shrink: true, ...(rest.slotProps as { inputLabel?: object } | undefined)?.inputLabel },
htmlInput: { inputMode: 'numeric', dir: 'ltr', style: { textAlign: isRtl(lang) ? 'right' : 'left' }, maxLength: 10 },
input: {
endAdornment: (
<InputAdornment position="end">
<IconButton
size="small"
tabIndex={-1}
disabled={rest.disabled}
aria-label={ui('pickDate')}
onClick={() => {
const el = native.current;
if (!el) return;
el.value = value;
// showPicker is missing in older browsers; focusing is the fallback
if (typeof el.showPicker === 'function') el.showPicker();
else el.click();
}}
>
<CalendarMonthOutlined fontSize="small" />
</IconButton>
<input
ref={native}
type="date"
tabIndex={-1}
aria-hidden
lang={lang.toLowerCase()}
style={{ position: 'absolute', opacity: 0, pointerEvents: 'none', width: 1, height: 1 }}
onChange={(e) => {
setTyped(null);
onChange(e.target.value);
}}
/>
</InputAdornment>
),
},
}}
/>
);
}

View File

@ -0,0 +1,307 @@
import { useEffect, useMemo, useState } from 'react';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import DOMPurify from 'dompurify';
import EditOutlined from '@mui/icons-material/EditOutlined';
import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined';
import MoreVertOutlined from '@mui/icons-material/MoreVertOutlined';
import SearchOffOutlined from '@mui/icons-material/SearchOffOutlined';
import {
alpha, Alert, Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Menu, MenuItem, Paper, Skeleton, Stack, Table, TableBody, TableCell, TableContainer,
TableHead, TablePagination, TableRow, TableSortLabel, Tooltip, Typography,
} from '@mui/material';
import { useAuth } from '../auth/AuthContext';
import { getGrid, getGridStructure } from '../api/grid';
import { isRtl, useLabel, useT, useUi } from '../i18n';
import { roleLabel } from '../i18n/roles';
import { useMutation } from '@tanstack/react-query';
import { useNotify } from '../notify/NotifyProvider';
import { WithdrawDialog } from '../features/gridActions/WithdrawDialog';
import { CONFIRM_ROW_ACTIONS, DIALOG_ROW_ACTIONS, parseRowActions, runRowAction, type RowAction } from '../api/gridActions';
import { StatusChip } from './StatusChip';
import { PlateBadge } from './PlateBadge';
/** What the grid is waiting for, said plainly; after a few seconds it adds that large lists can take a while. */
function GridLoading({ text }: { text: string }) {
const ui = useUi();
const [slow, setSlow] = useState(false);
useEffect(() => {
const h = setTimeout(() => setSlow(true), 5000);
return () => clearTimeout(h);
}, []);
return (
<Stack direction="row" spacing={2} alignItems="center" role="status" aria-live="polite" sx={{ px: 2, py: 1.5, bgcolor: 'action.hover', borderBottom: 1, borderColor: 'divider' }}>
<CircularProgress size={22} />
<Box>
<Typography fontWeight={700} fontSize={14}>{text}</Typography>
{slow && <Typography fontSize={12.5} color="text.secondary">{ui('gridLoadingSlow')}</Typography>}
</Box>
</Stack>
);
}
/** Lists whose records the business does not open (the legacy menu has no record page for them). */
const NO_VIEW = new Set(['RECONCILIATION', 'RECONCILIATION_POS', 'POSTING_TRANSACTIONS', 'FIN_FINANCIAL_TRANSACTIONS', 'CUSTOMER_BALANCES']);
const HTML_COLUMNS = /ICON/i;
// every plate column (PLATE_NUMBER_GRID_AR, FLEET_PLATE_NUMBER_GRID_AR, TRAILER_PLATE_NUMBER_GRID_AR…) is drawn as a plate
const PLATE = /PLATE_NUMBER_GRID/;
// grid columns that have no caption of their own but share one with another screen
const CAPTION_ALIAS: Record<string, string> = { STAKEHOLDER_LOCATION_NAME: 'INDUSTRIAL_ESTATE' };
export interface GridProps {
entity: string;
filter?: Record<string, unknown>;
canEdit?: boolean;
onTotal?: (n: number) => void;
/** the backend refuses to list this entity without a filter (FILTER_EMPTY) */
onFilterRequired?: () => void;
/** the list's grand total, when the backend sends one (customer balances) */
onTotalBalance?: (n: number | undefined) => void;
/** tick boxes for actions that work on several rows: the ticked ids with their status codes */
selectable?: boolean;
selected?: Record<string, string>;
onSelectedChange?: (s: Record<string, string>) => void;
}
/** Generic, metadata-driven list: columns come from getGridStructure, rows from getGrid. */
export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, onTotalBalance, selectable, selected = {}, onSelectedChange }: GridProps) {
const t = useT();
const { lang, langReady } = useAuth();
const lab = useLabel();
const ui = useUi();
const nav = useNavigate();
const notify = useNotify();
const [menu, setMenu] = useState<{ el: HTMLElement; actions: RowAction[] } | null>(null);
const [confirmAction, setConfirmAction] = useState<RowAction | null>(null);
const [withdrawId, setWithdrawId] = useState<string | null>(null);
const doAction = useMutation({
meta: { loading: 'processing' },
mutationFn: (a: RowAction) => runRowAction(entity, a, filter),
onSuccess: (msg) => {
notify.success(msg, ui('saved'));
void data.refetch();
},
onError: (e) => notify.error(e),
});
const [page, setPage] = useState(0);
const [rows, setRows] = useState(10);
const [sort, setSort] = useState<{ field?: string; dir: 'asc' | 'desc' }>({ dir: 'asc' });
const filterKey = JSON.stringify(filter ?? {});
// a new search always starts on the first page
useEffect(() => setPage(0), [filterKey, entity]);
const structure = useQuery({
// column names depend on the session language: keyed by it, and only fetched once the backend has switched
queryKey: ['grid-structure', entity, lang],
queryFn: () => getGridStructure(entity),
staleTime: Infinity,
enabled: langReady,
});
const data = useQuery({
queryKey: ['grid', entity, lang, page, rows, sort, filterKey],
queryFn: () => getGrid(entity, { page: page + 1, rows, filter, sidx: sort.field, sord: sort.dir }),
placeholderData: keepPreviousData,
enabled: !!structure.data && langReady,
});
useEffect(() => {
if (data.data) onTotal?.(data.data.records);
}, [data.data, onTotal]);
useEffect(() => {
onTotalBalance?.(data.data?.totalBalance);
}, [data.data, onTotalBalance]);
const noView = NO_VIEW.has(entity);
// the backend refuses to list some entities without a filter: a generic "pick something" (FILTER_EMPTY),
// or — for a few financial grids — specifically a date range within its allowed span (PLEASE_SELECT_1_MOS_PERIOD)
const filterNeededCode = data.error instanceof Error && (data.error.message === 'FILTER_EMPTY' || data.error.message === 'PLEASE_SELECT_1_MOS_PERIOD')
? data.error.message
: undefined;
useEffect(() => {
if (filterNeededCode) onFilterRequired?.();
}, [filterNeededCode, onFilterRequired]);
const fields = structure.data?.fields ?? [];
const statusIdx = fields.indexOf('StatusWithoutCaption');
const actionsIdx = (structure.data?.columns ?? []).findIndex((c) => c.name === 'ACTION_ICONS');
// The old grid opened a record with the id inside the row's own action buttons (SUBSCRIPTIONS_view('13F5…')).
// That is the record's id; the first column is not always it (for fleet subscriptions it is the subscription
// number, which several rows share), so use the button's id and only fall back to the first column.
const rowId = (r: string[]) => (actionsIdx >= 0 ? /\w+_view\('([^']+)'\)/.exec(String(r[actionsIdx] ?? ''))?.[1] : undefined) ?? String(r[0]);
const cols = useMemo(
() => (structure.data?.columns ?? []).map((c, i) => ({ ...c, index: i })).filter((c) => !c.hidden),
[structure.data],
);
if (filterNeededCode) return <Alert severity="info">{t(filterNeededCode)}</Alert>;
if (structure.error || data.error) {
return <Alert severity="error">{ui('loadError')}: {t(String(((structure.error ?? data.error) as Error).message))}</Alert>;
}
const loading = structure.isPending || (data.isPending && !data.data);
const list = data.data?.rows ?? [];
const cell = (c: (typeof cols)[number], r: string[]) => {
const v = String(r[c.index] ?? '');
if (c.name === 'ACTION_ICONS') return null;
if (entity === 'USERS' && (c.name === 'JOB_TITLE' || fields[c.index] === 'JOB_TITLE')) return roleLabel(v, t, lab, isRtl(lang)) || '—';
if (c.name.toUpperCase() === 'STATUS_CODE') return <StatusChip status={statusIdx >= 0 ? String(r[statusIdx] ?? '') : v} caption={v} />;
if (PLATE.test(c.name)) return <PlateBadge text={v} />;
if (HTML_COLUMNS.test(c.name)) return <Box dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(v) }} />;
return v || '—';
};
return (
<Paper variant="outlined" sx={{ overflow: 'hidden' }}>
{(loading || data.isFetching) && <GridLoading key={loading ? 'first' : 'refresh'} text={loading ? ui('gridLoading') : ui('gridSearching')} />}
<TableContainer sx={{ maxHeight: 'calc(100vh - 340px)', minHeight: 240 }}>
<Table stickyHeader size="medium">
<TableHead>
<TableRow>
{selectable && (
<TableCell padding="checkbox">
<Checkbox
size="small"
inputProps={{ 'aria-label': ui('selectAll') }}
checked={list.length > 0 && list.every((r) => rowId(r) in selected)}
indeterminate={list.some((r) => rowId(r) in selected) && !list.every((r) => rowId(r) in selected)}
onChange={(e) => {
const next = { ...selected };
for (const r of list) {
if (e.target.checked) next[rowId(r)] = statusIdx >= 0 ? String(r[statusIdx] ?? '') : '';
else delete next[rowId(r)];
}
onSelectedChange?.(next);
}}
/>
</TableCell>
)}
{cols.map((c) => {
const field = fields[c.index] ?? c.name;
const sortable = !HTML_COLUMNS.test(c.name) && c.name.toUpperCase() !== 'STATUS_CODE';
// the old grid titled a column with the caption of the FIELD it shows (the structure's fifth array), so that comes
// first ("Operation type", "Count", "Creation date"); the column's own name is only the fallback
const caption = [field, c.name, CAPTION_ALIAS[c.name], field.toUpperCase(), c.name.toUpperCase()].find((k) => k && t(k) !== k);
const title = caption ? t(caption) : lab(c.name);
return (
<TableCell key={c.name} align={c.name === 'ACTION_ICONS' ? 'right' : 'left'}>
{c.name === 'ACTION_ICONS' ? null : sortable ? (
<TableSortLabel
active={sort.field === field}
direction={sort.dir}
onClick={() => setSort({ field, dir: sort.field === field && sort.dir === 'asc' ? 'desc' : 'asc' })}
>
{title}
</TableSortLabel>
) : (
title
)}
</TableCell>
);
})}
</TableRow>
</TableHead>
<TableBody>
{loading &&
Array.from({ length: 8 }).map((_, i) => (
<TableRow key={i}>
{cols.length
? cols.map((c) => <TableCell key={c.name}><Skeleton width="70%" /></TableCell>)
: <TableCell><Skeleton /></TableCell>}
</TableRow>
))}
{!loading &&
list.map((r, ri) => (
<TableRow key={String(rowId(r)) + ri} hover={!noView} sx={{ cursor: noView ? 'default' : 'pointer', '&:nth-of-type(even)': { bgcolor: (t) => alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.09 : 0.05) } }} onClick={noView ? undefined : () => nav(`/e/${entity}/view/${rowId(r)}`)}>
{selectable && (
<TableCell padding="checkbox" onClick={(e) => e.stopPropagation()}>
<Checkbox
size="small"
inputProps={{ 'aria-label': ui('selectRow') }}
checked={rowId(r) in selected}
onChange={(e) => {
const next = { ...selected };
if (e.target.checked) next[rowId(r)] = statusIdx >= 0 ? String(r[statusIdx] ?? '') : '';
else delete next[rowId(r)];
onSelectedChange?.(next);
}}
/>
</TableCell>
)}
{cols.map((c) =>
c.name === 'ACTION_ICONS' ? (
<TableCell key={c.name} align="right" onClick={(e) => e.stopPropagation()} sx={{ whiteSpace: 'nowrap' }}>
{!noView && (
<Tooltip title={ui('view')}>
<IconButton size="small" aria-label={ui('view')} onClick={() => nav(`/e/${entity}/view/${rowId(r)}`)}><VisibilityOutlined fontSize="small" /></IconButton>
</Tooltip>
)}
{actionsIdx >= 0 && parseRowActions(String(r[actionsIdx] ?? '')).length > 0 && (
<IconButton size="small" aria-label={ui('moreActions')} onClick={(e) => setMenu({ el: e.currentTarget, actions: parseRowActions(String(r[actionsIdx] ?? '')) })}>
<MoreVertOutlined fontSize="small" />
</IconButton>
)}
{canEdit && (
<Tooltip title={ui('edit')}>
<IconButton size="small" color="primary" aria-label={ui('edit')} onClick={() => nav(`/e/${entity}/create/${rowId(r)}`)}><EditOutlined fontSize="small" /></IconButton>
</Tooltip>
)}
</TableCell>
) : (
<TableCell key={c.name}>{cell(c, r)}</TableCell>
),
)}
</TableRow>
))}
</TableBody>
</Table>
{!loading && !list.length && (
<Stack alignItems="center" spacing={1} sx={{ py: 8, color: 'text.secondary' }}>
<SearchOffOutlined sx={{ fontSize: 40 }} />
<Typography>{ui('noResults')}</Typography>
</Stack>
)}
</TableContainer>
<TablePagination
component="div"
count={data.data?.records ?? 0}
page={page}
rowsPerPage={rows}
rowsPerPageOptions={[10, 25, 50]}
dir={isRtl(lang) ? 'rtl' : 'ltr'}
labelRowsPerPage={ui('rowsPerPage')}
labelDisplayedRows={({ from, to, count }) => `${from}–${to} ${ui('pagerOf')} ${count !== -1 ? count : to}`}
getItemAriaLabel={(type) => ui(type === 'first' ? 'firstPage' : type === 'last' ? 'lastPage' : type === 'next' ? 'nextPage' : 'prevPage')}
onPageChange={(_, p) => setPage(p)}
onRowsPerPageChange={(e) => {
setRows(Number(e.target.value));
setPage(0);
}}
sx={{ borderTop: 1, borderColor: 'divider' }}
/>
<Menu anchorEl={menu?.el} open={!!menu} onClose={() => setMenu(null)}>
{menu?.actions.map((a) => (
<MenuItem
key={a.name}
onClick={() => {
setMenu(null);
if (DIALOG_ROW_ACTIONS.has(a.name)) setWithdrawId(a.id);
else if (CONFIRM_ROW_ACTIONS.has(a.name)) setConfirmAction(a);
else doAction.mutate(a);
}}
>
{a.label || t(a.name)}
</MenuItem>
))}
</Menu>
{withdrawId && <WithdrawDialog id={withdrawId} onClose={() => setWithdrawId(null)} onDone={() => { setWithdrawId(null); void data.refetch(); }} />}
<Dialog open={!!confirmAction} onClose={() => setConfirmAction(null)}>
<DialogTitle>{confirmAction?.label || t(confirmAction?.name ?? '')}</DialogTitle>
<DialogContent>{t('CONFIRM_MSG')}</DialogContent>
<DialogActions>
<Button onClick={() => setConfirmAction(null)}>{t('NO')}</Button>
<Button variant="contained" onClick={() => { const a = confirmAction; setConfirmAction(null); if (a) doAction.mutate(a); }}>{t('YES')}</Button>
</DialogActions>
</Dialog>
</Paper>
);
}

View File

@ -0,0 +1,49 @@
import { useEffect, useState } from 'react';
import { useIsFetching, useMutationState } from '@tanstack/react-query';
import { Backdrop, CircularProgress, LinearProgress, Paper, Stack, Typography } from '@mui/material';
import { useUi } from '../i18n';
import type { UiKey } from '../i18n/ui';
/** true only after `on` has been true for `ms` — quick calls never flash a loader */
function useDelayed(on: boolean, ms: number) {
const [shown, setShown] = useState(false);
useEffect(() => {
if (!on) return setShown(false);
const h = setTimeout(() => setShown(true), ms);
return () => clearTimeout(h);
}, [on, ms]);
return shown;
}
/**
* Feedback while the backend answers:
* - a slim progress bar at the top for any data being fetched
* - a "Saving… / Processing…" card over the page while a change is in flight (mutation meta.loading
* names the message), which also blocks double submits
*/
export function GlobalLoading() {
const ui = useUi();
const fetching = useIsFetching();
const pending = useMutationState({
filters: { status: 'pending' },
select: (m) => (m.options.meta?.loading as UiKey | undefined) ?? 'processing',
});
const bar = useDelayed(fetching > 0 || pending.length > 0, 250);
const card = useDelayed(pending.length > 0, 300);
const slow = useDelayed(pending.length > 0, 6000);
return (
<>
{bar && <LinearProgress sx={{ position: 'fixed', top: 0, insetInline: 0, height: 3, zIndex: (t) => t.zIndex.tooltip + 2 }} />}
<Backdrop open={card} sx={{ zIndex: (t) => t.zIndex.modal + 10, bgcolor: 'rgba(8, 16, 28, 0.45)', backdropFilter: 'blur(2px)' }}>
<Paper sx={{ px: 4, py: 3, minWidth: 280, textAlign: 'center', borderRadius: 3 }} elevation={8}>
<Stack spacing={1.5} alignItems="center">
<CircularProgress />
<Typography fontWeight={700}>{ui(pending[0] ?? 'processing')}</Typography>
<Typography variant="body2" color="text.secondary">{slow ? ui('stillWorking') : ui('pleaseWait')}</Typography>
</Stack>
</Paper>
</Backdrop>
</>
);
}

View File

@ -0,0 +1,28 @@
import { useEffect, useState } from 'react';
import { Box, CircularProgress, Stack, Typography } from '@mui/material';
import { useUi } from '../i18n';
import { Logo } from './Logo';
/** Full-page loader for the first load (session + the ~3 MB config): says what is happening, and why it is slow. */
export function LoadingScreen() {
const ui = useUi();
const [slow, setSlow] = useState(false);
useEffect(() => {
const h = setTimeout(() => setSlow(true), 4000);
return () => clearTimeout(h);
}, []);
return (
<Box sx={{ display: 'grid', placeItems: 'center', minHeight: '100vh', p: 2 }}>
<Stack spacing={2.5} alignItems="center" textAlign="center">
<Logo height={48} />
<CircularProgress size={36} />
<Box>
<Typography fontWeight={600}>{ui('loadingWorkspace')}</Typography>
<Typography variant="body2" color="text.secondary" sx={{ minHeight: 22, transition: 'opacity .4s', opacity: slow ? 1 : 0 }}>
{ui('firstLoad')}
</Typography>
</Box>
</Stack>
</Box>
);
}

View File

@ -0,0 +1,61 @@
import type { SxProps, Theme } from '@mui/material';
import { Box } from '@mui/material';
/**
* A light, decorative skyline for the login brand panel: an industrial estate (warehouses, a
* gantry crane, stacked containers) with a truck on the road in front — drawn by hand as SVG so
* the panel needs no external photo asset.
*/
export function LoginArt({ sx }: { sx?: SxProps<Theme> }) {
return (
<Box
component="svg"
viewBox="0 0 900 460"
preserveAspectRatio="xMidYMax slice"
sx={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', ...sx }}
aria-hidden
>
<g fill="#fff" opacity={0.1}>
<rect x="40" y="200" width="120" height="150" />
<polygon points="40,200 100,160 160,200" />
<rect x="190" y="230" width="90" height="120" />
<rect x="640" y="190" width="130" height="160" />
<polygon points="640,190 705,150 770,190" />
<rect x="790" y="240" width="80" height="110" />
</g>
{/* gantry crane */}
<g stroke="#fff" strokeWidth={5} opacity={0.14} fill="none" strokeLinecap="round" strokeLinejoin="round">
<line x1="330" y1="350" x2="330" y2="140" />
<line x1="470" y1="350" x2="470" y2="140" />
<line x1="310" y1="150" x2="500" y2="150" />
<line x1="400" y1="150" x2="400" y2="190" />
<line x1="370" y1="175" x2="430" y2="175" />
</g>
{/* stacked containers */}
<g opacity={0.14}>
<rect x="520" y="300" width="70" height="50" fill="#fff" />
<rect x="520" y="300" width="70" height="50" fill="none" stroke="#fff" strokeWidth={2} />
<rect x="595" y="300" width="70" height="50" fill="#fff" />
<rect x="557" y="248" width="70" height="50" fill="#fff" />
</g>
{/* road */}
<rect x="0" y="378" width="900" height="6" fill="#fff" opacity={0.16} />
<g stroke="#fff" strokeWidth={4} strokeDasharray="22 18" opacity={0.14}>
<line x1="0" y1="400" x2="900" y2="400" />
</g>
{/* truck */}
<g transform="translate(150,322)" fill="#fff" opacity={0.22}>
<rect x="0" y="0" width="150" height="38" rx="3" />
<rect x="150" y="10" width="46" height="28" rx="3" />
<rect x="160" y="16" width="22" height="14" rx="2" opacity={0.6} />
<circle cx="36" cy="46" r="14" />
<circle cx="96" cy="46" r="14" />
<circle cx="170" cy="46" r="14" />
</g>
</Box>
);
}

29
src/components/Logo.tsx Normal file
View File

@ -0,0 +1,29 @@
import { Box, type SxProps, type Theme } from '@mui/material';
import { useAuth } from '../auth/AuthContext';
import { useColorMode } from '../theme';
import { isRtl } from '../i18n';
import logoDarkAr from '../assets/logo/logo-dark-lg-ar.png';
import logoDarkEn from '../assets/logo/logo-dark-en.png';
import logoLightAr from '../assets/logo/logo-light-lg-ar.png';
import logoLightEn from '../assets/logo/logo-light-en.png';
import logoIcon from '../assets/logo/logo-icon.png';
/**
* The wordmark. By default it follows the app's light/dark mode (dark text on light, white text on dark);
* pass `on` to pin it to whatever the surface actually is, e.g. the white-text version on a colored panel
* that stays dark regardless of the app's theme.
*/
export function Logo({ height = 32, on, sx }: { height?: number; on?: 'light' | 'dark'; sx?: SxProps<Theme> }) {
const { lang } = useAuth();
const { mode } = useColorMode();
const ar = isRtl(lang);
// "on" names the surface colour: a logo readable "on dark" is the white-text version, and vice versa.
const surface = on ?? (mode === 'dark' ? 'dark' : 'light');
const src = surface === 'dark' ? (ar ? logoLightAr : logoLightEn) : ar ? logoDarkAr : logoDarkEn;
return <Box component="img" src={src} alt="Nafith@Madayn" sx={{ height, width: 'auto', display: 'block', ...sx }} />;
}
/** The arrow mark alone, used where there isn't room for the wordmark (collapsed sidebar, favicon-sized spots). */
export function LogoIcon({ size = 32, sx }: { size?: number; sx?: SxProps<Theme> }) {
return <Box component="img" src={logoIcon} alt="Nafith@Madayn" sx={{ height: size, width: 'auto', display: 'block', ...sx }} />;
}

View File

@ -0,0 +1,49 @@
import type { ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, IconButton, Stack, Tooltip, Typography } from '@mui/material';
import ArrowBack from '@mui/icons-material/ArrowBack';
import { useT } from '../i18n';
/** Back one step in the browser history, or to `to` when this page was opened directly. */
export function BackButton({ to }: { to: string }) {
const nav = useNavigate();
const t = useT();
const goBack = () => {
const idx = (window.history.state as { idx?: number } | null)?.idx ?? 0;
if (idx > 0) nav(-1);
else nav(to);
};
return (
<Tooltip title={t('BACK')}>
<IconButton onClick={goBack} size="small" sx={{ border: 1, borderColor: 'divider' }} aria-label={t('BACK')}>
<ArrowBack fontSize="small" className="flip-rtl" />
</IconButton>
</Tooltip>
);
}
export function PageHeader({
title, subtitle, actions, lead, backTo,
}: {
title: ReactNode;
subtitle?: ReactNode;
actions?: ReactNode;
lead?: ReactNode;
/** show a back button; the value is where to go when there is no history */
backTo?: string;
}) {
return (
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} alignItems={{ sm: 'center' }} justifyContent="space-between" sx={{ mb: 2 }}>
<Stack direction="row" spacing={1.5} alignItems="center" sx={{ minWidth: 0 }}>
{backTo && <BackButton to={backTo} />}
{lead}
<Box sx={{ minWidth: 0 }}>
{/* the page's one h1: a screen reader's outline starts from it */}
<Typography variant="h5" component="h1" fontWeight={800} noWrap sx={{ color: '#d1a233' }}>{title}</Typography>
{subtitle && <Typography variant="body2" color="text.secondary" component="div">{subtitle}</Typography>}
</Box>
</Stack>
{actions && <Stack direction="row" spacing={1} flexShrink={0}>{actions}</Stack>}
</Stack>
);
}

View File

@ -0,0 +1,50 @@
import { Box } from '@mui/material';
import { useAuth } from '../auth/AuthContext';
import { isRtl } from '../i18n';
/** Number plate look: bordered, bold, always left-to-right whatever the page direction. */
export function PlateBadge({ text, large }: { text: string; large?: boolean }) {
const { lang } = useAuth();
// Arabic plates show the code on the left and the number on the right. The backend sends the pair as
// "<number> <code>" or "<code> <number>" depending on the screen, so find the number and put it last.
const t = text.trim();
const m = isRtl(lang) ? t.match(/^(\d+)\s+(\D.*)$/) ?? t.match(/^(\D.*?)\s+(\d+)$/) : null;
const parts = m ? (/^\d+$/.test(m[1]) ? { number: m[1], code: m[2].trim() } : { number: m[2], code: m[1].trim() }) : null;
return (
<Box
dir="ltr"
sx={{
display: 'inline-flex',
alignItems: 'center',
gap: large ? 1.25 : 0.75,
px: large ? 2 : 0.75,
py: large ? 0.6 : 0,
// the small badge is the same height as a small status chip, so they sit level in a header
minHeight: large ? undefined : 24,
boxSizing: 'border-box',
border: large ? 3 : 1.5,
borderColor: 'text.primary',
borderRadius: large ? 2 : 0.75,
bgcolor: 'background.paper',
fontWeight: 800,
fontSize: large ? 26 : 12.5,
lineHeight: large ? 1.3 : 1.5,
letterSpacing: '.08em',
fontVariantNumeric: 'tabular-nums',
whiteSpace: 'nowrap',
}}
>
{parts ? (
// Arabic letters and digits written in one string always end up with the digits on the left (the browser
// treats the digits after Arabic letters as part of the same right-to-left run), whatever order they are
// written in. Two separate pieces in a left-to-right row put the code on the left and the number on the right.
<>
<bdi dir="rtl">{parts.code}</bdi>
<bdi dir="ltr">{parts.number}</bdi>
</>
) : (
text
)}
</Box>
);
}

View File

@ -0,0 +1,75 @@
import type { ReactNode } from 'react';
import { alpha, Box } from '@mui/material';
import type { Theme } from '@mui/material';
import { sectionIcon } from './sectionIcons';
/** The frame around a group of fields: a clear blue-tinted outline, so each section reads as its own block. */
export const sectionFrame = {
border: '1.5px solid',
borderColor: (t: Theme) => alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.5 : 0.35),
borderRadius: 2,
};
/**
* The heading of a group of fields.
* - on a form: a light gray bar with a thick accent edge at the start of the line (left in English, right in Arabic);
* - on a record page (`view`): no background, a fitting icon in front of the title and a thin line under it.
* `code` is the group's title code; the icon on record pages is chosen from it.
*/
export function SectionTitle({ children, code, view, mb = 1.5 }: { children: ReactNode; code?: string; view?: boolean; mb?: number }) {
const Icon = sectionIcon(code ?? '');
if (view) {
return (
<Box
component="h2"
sx={{
display: 'flex',
alignItems: 'center',
gap: 1,
m: 0,
mb,
pb: 0.75,
fontSize: 15,
fontWeight: 800,
lineHeight: 1.4,
color: 'text.primary', // the dark blue of the app's text (light in dark mode)
borderBottom: 1,
borderColor: 'divider',
}}
>
<Icon sx={{ fontSize: 20, color: 'inherit' }} />
{children}
</Box>
);
}
return (
<Box
component="h2"
sx={(t) => ({
display: 'flex',
alignItems: 'center',
gap: 1,
m: 0,
mb,
px: 1.5,
py: 0.75,
fontSize: 15,
fontWeight: 800,
lineHeight: 1.4,
color: 'text.primary', // the dark blue of the app's text (light in dark mode)
// light gray bar (a lighter shade of the surface in dark mode); the blue accent edge and title stay
bgcolor: t.palette.mode === 'dark' ? alpha('#ffffff', 0.08) : '#eceff3',
borderInlineStart: 4,
borderInlineStartStyle: 'solid',
borderColor: 'primary.main',
// rounded on the far side only, so the accent edge is a straight bar
borderRadius: 1,
borderStartStartRadius: 0,
borderEndStartRadius: 0,
})}
>
{code && <Icon sx={{ fontSize: 20, color: 'inherit' }} />}
{children}
</Box>
);
}

View File

@ -0,0 +1,13 @@
import { SvgIcon, type SvgIconProps } from '@mui/material';
/** "Square pen" (a pen over a square, the usual "new record" mark): drawn as strokes so it matches the outlined icons. */
export function SquarePenIcon(props: SvgIconProps) {
return (
<SvgIcon {...props}>
<g fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
<path d="M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z" />
</g>
</SvgIcon>
);
}

View File

@ -0,0 +1,38 @@
import { Chip, type ChipProps } from '@mui/material';
import { useAuth } from '../auth/AuthContext';
import { isRtl, useT } from '../i18n';
const COLORS: Record<string, ChipProps['color']> = {
REGISTERED: 'success',
ACTIVE: 'success',
APPROVED: 'success',
COMPLETED: 'success',
PROCESSED: 'success',
PENDING: 'info',
PENDING_UPDATE: 'info',
NEW: 'info',
INCOMPLETE: 'warning',
RETURNED: 'warning',
INACTIVE: 'default',
REJECTED: 'error',
BLOCKED: 'error',
DELETED: 'error',
};
// statuses the caption table has no entry for (they showed as raw codes)
const FALLBACK: Record<string, { en: string; ar: string }> = {
COMPLETED: { en: 'Completed', ar: 'مكتمل' },
CANCELLED: { en: 'Cancelled', ar: 'ملغي' },
PROCESSED: { en: 'Completed', ar: 'مكتمل' },
};
/** A status code (REGISTERED, INCOMPLETE, …) as a coloured, translated chip. */
export function StatusChip({ status, size = 'small', caption }: { status: string; size?: ChipProps['size']; caption?: string }) {
const t = useT();
const { lang } = useAuth();
const code = status.trim();
if (!code) return null;
// last resort: the caption the backend already translated in the grid's own status column
const label = t(code) !== code ? t(code) : FALLBACK[code] ? (isRtl(lang) ? FALLBACK[code].ar : FALLBACK[code].en) : caption?.trim() || code;
return <Chip size={size} label={label} color={COLORS[code] ?? 'default'} variant="outlined" />;
}

View File

@ -0,0 +1,8 @@
import { alpha, type Theme } from '@mui/material';
/** The "new record" button beside a module: a plus inside a circle, in the blue of the main buttons. */
export const newRecordSx = {
p: 0.4,
color: 'primary.main',
'&:hover': { bgcolor: (t: Theme) => alpha(t.palette.primary.main, 0.12) },
};

View File

@ -0,0 +1,44 @@
import type { ElementType } from 'react';
import InfoOutlined from '@mui/icons-material/InfoOutlined';
import LocationOnOutlined from '@mui/icons-material/LocationOnOutlined';
import PersonOutline from '@mui/icons-material/PersonOutline';
import BadgeOutlined from '@mui/icons-material/BadgeOutlined';
import AttachFileOutlined from '@mui/icons-material/AttachFileOutlined';
import VerifiedUserOutlined from '@mui/icons-material/VerifiedUserOutlined';
import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined';
import DescriptionOutlined from '@mui/icons-material/DescriptionOutlined';
import PaymentsOutlined from '@mui/icons-material/PaymentsOutlined';
import ContactPhoneOutlined from '@mui/icons-material/ContactPhoneOutlined';
import WorkOutline from '@mui/icons-material/WorkOutline';
import ForumOutlined from '@mui/icons-material/ForumOutlined';
import ReceiptLongOutlined from '@mui/icons-material/ReceiptLongOutlined';
import BusinessOutlined from '@mui/icons-material/BusinessOutlined';
import CardMembershipOutlined from '@mui/icons-material/CardMembershipOutlined';
import HealthAndSafetyOutlined from '@mui/icons-material/HealthAndSafetyOutlined';
import ShieldOutlined from '@mui/icons-material/ShieldOutlined';
import SpeedOutlined from '@mui/icons-material/SpeedOutlined';
import EmailOutlined from '@mui/icons-material/EmailOutlined';
/** A fitting icon for a group of fields, chosen from the group's title code ("OWNERINFO", "COMPANY_ADDRESS"…). */
const RULES: [RegExp, ElementType][] = [
[/ATT|DOCUMENT_ATT|ATTACHMENT/, AttachFileOutlined],
[/ADDRESS|LOCATION|ESTATE/, LocationOnOutlined],
[/REPLY|TICKET/, ForumOutlined],
[/HEALTH/, HealthAndSafetyOutlined],
[/INSURANCE/, ShieldOutlined],
[/CAPACITY/, SpeedOutlined],
[/LICEN[CS]E|CARD/, CardMembershipOutlined],
[/MANAGER|OWNER|DRIVER|PERSON|EMPLOYEE|SENDER|STAKEHOLDER_INFO|INVESTOR|USERS/, PersonOutline],
[/TRUCK|TRAILER|VEHICLE|FLEET|BUS|CAR|EQUIP/, LocalShippingOutlined],
[/FINANC|PAYMENT|INVOICE|BILLING|PRICE|AMOUNT/, PaymentsOutlined],
[/RECONCIL|SUMMARY|LINES/, ReceiptLongOutlined],
[/REGISTRATION|COMPANY|ENTITY/, BusinessOutlined],
[/CONTACT|PHONE|EMERGENCY/, ContactPhoneOutlined],
[/EMAIL|MAIL/, EmailOutlined],
[/JOB|WORK/, WorkOutline],
[/PERMIT|ORDER|REQUEST|DETAILS/, DescriptionOutlined],
[/VERIF|SECURITY|AUTH/, VerifiedUserOutlined],
[/PERSONAL|ID_|IDENT/, BadgeOutlined],
];
export const sectionIcon = (code: string): ElementType => RULES.find(([re]) => re.test(code.toUpperCase()))?.[1] ?? InfoOutlined;

View File

@ -0,0 +1,274 @@
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { Link as RouterLink, Navigate, useSearchParams } from 'react-router-dom';
import { HIDDEN_ENTITIES, WIZARD_KEY } from '../layout/nav';
import { Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Stack, Typography } from '@mui/material';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { rpc } from '../api/client';
import { useNotify } from '../notify/NotifyProvider';
import { CONFIRM_MAIN_ACTIONS, MAIN_ACTIONS, SELECTION_ACTIONS, flatSearch, runMainAction } from '../api/gridActions';
import { ReconciliationUpload } from './gridActions/ReconciliationUpload';
import { PendingSettingsDialog } from './gridActions/PendingSettingsDialog';
import LockOutlined from '@mui/icons-material/LockOutlined';
import AddIcon from '@mui/icons-material/Add';
import { useAuth } from '../auth/AuthContext';
import { useT, useUi } from '../i18n';
import { useNav } from '../layout/NavContext';
import { PageHeader } from '../components/PageHeader';
import { EntityGrid } from '../components/EntityGrid';
import { SearchPanel } from './search/SearchPanel';
import { ExportButton } from './export/ExportButton';
import { filterFromParams, filterToParams, toApiFilter, useSearchFields } from './search/filters';
// the form and view pages carry the generated layouts, so they load only when opened
const EntityForm = lazy(() => import('./forms/EntityForm').then((m) => ({ default: m.EntityForm })));
const SubscriptionWizard = lazy(() => import('./subscriptions/SubscriptionWizard').then((m) => ({ default: m.SubscriptionWizard })));
const EntityView = lazy(() => import('./view/EntityView').then((m) => ({ default: m.EntityView })));
const PageLoading = () => (
<Box sx={{ display: 'grid', placeItems: 'center', py: 10 }}>
<CircularProgress />
</Box>
);
/** yyyymmdd of a date */
const ymd = (d: Date) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
/** Defaults the legacy grids filled in with script: balances open on today, posting on the current month. */
function dynamicDefaults(entity: string): Record<string, string> {
const now = new Date();
if (entity === 'CUSTOMER_BALANCES') return { CREATION_DATE: ymd(now) };
if (entity === 'POSTING_TRANSACTIONS') {
return { TRANSACTIONS_DATE_GRID: `${ymd(new Date(now.getFullYear(), now.getMonth(), 1))}-${ymd(new Date(now.getFullYear(), now.getMonth() + 1, 0))}` };
}
return {};
}
const PENDING_ENTITY = 'FLEET_PENDING_FINANCIAL_TRANSACTIONS';
/** "05/11/2026 - 16/10/2023" (either order) -> "20231016-20261105" */
function receivablesRange(range: string): string {
const ds = range.split('-').map((p) => p.trim().split('/'));
if (ds.length !== 2 || ds.some((d) => d.length !== 3)) return '';
const [a, b] = ds.map(([dd, mm, yyyy]) => `${yyyy}${mm}${dd}`).sort();
return `${a}-${b}`;
}
/**
* Overdue charges: the old page opened with the event date set to the range configured in the receivables settings
* (when receivables are activated), so the grid waits for that setting before its first request.
*/
function PendingGridGate() {
const settings = useQuery({
queryKey: ['pending-settings'],
queryFn: () => rpc<{ ACTIVATE_RECEIVABLES?: boolean; DATE_RANGE?: string }>(PENDING_ENTITY, 'GET_TRANSACTIONS_SETTING', {}),
staleTime: 60_000,
});
const s = settings.data;
const range = s?.ACTIVATE_RECEIVABLES && s.DATE_RANGE ? receivablesRange(s.DATE_RANGE) : '';
const extra = useMemo<Record<string, string>>(() => (range ? { EVENT_DATE: range } : ({} as Record<string, string>)), [range]);
if (settings.isPending) return <PageLoading />;
return <GridPage entity={PENDING_ENTITY} extraDefaults={extra} />;
}
function GridPage({ entity, extraDefaults }: { entity: string; extraDefaults?: Record<string, string> }) {
const { config, user } = useAuth();
const { labelOf } = useNav();
const ui = useUi();
const t = useT();
const notify = useNotify();
const qc = useQueryClient();
const [params, setParams] = useSearchParams();
const allFields = useSearchFields(config, entity);
// only the Nafith side keeps "pending" (not yet approved) charges; every other role works with the payable ones
const nafithSide = user?.role_group === 'NAFITH';
const fields = useMemo(
() =>
entity === PENDING_ENTITY && !nafithSide
? allFields.map((f) => (f.id === 'STATUS_CODE' ? { ...f, options: f.options?.filter((o) => String(o.CODE) !== 'PENDING'), defaultValue: f.defaultValue === 'PENDING' ? undefined : f.defaultValue } : f))
: allFields,
[allFields, entity, nafithSide],
);
const [selected, setSelected] = useState<Record<string, string>>({});
const [uploadOpen, setUploadOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [totalBalance, setTotalBalance] = useState<number | undefined>();
const [confirmMain, setConfirmMain] = useState<{ ACTION_NAME: string; ACTION_CAPTION_CODE?: string; CURRENT_STATUS_NAME?: string } | null>(null);
const urlFilter = filterFromParams(params, fields);
const [total, setTotal] = useState<number | null>(null);
const onTotal = useCallback((n: number) => setTotal(n), []);
// some lists (permits, subscriptions…) are refused without a filter: apply the module's own default, as
// the old page did, until the URL has actually come to reflect SOME filter (ours or the user's) — not the
// instant we *ask* for it, since `setParams` lands a render later than our own state and briefly reading
// back an empty `urlFilter` in between would fire the grid once with no filter, then again with it. Once
// seeded, the user's own choice always wins from then on, including deliberately clearing back to "All" —
// otherwise every clear would silently snap back to the default instead of showing everything.
// plus the two defaults the old pages set in script rather than in the metadata (see dynamicDefaults)
const defaultFilter = useMemo(() => {
const out: Record<string, string> = Object.fromEntries(fields.filter((f) => f.defaultValue).map((f) => [f.id, f.defaultValue!]));
for (const [id, v] of Object.entries({ ...dynamicDefaults(entity), ...extraDefaults })) if (fields.some((f) => f.id === id)) out[id] = v;
return out;
}, [fields, entity, extraDefaults]);
const hasDefaults = Object.keys(defaultFilter).length > 0;
const [seeded, setSeeded] = useState(() => !!params.toString() || !hasDefaults);
const filter = seeded ? urlFilter : defaultFilter;
const onFilterRequired = useCallback(() => {
// once seeded, an empty/rejected filter is the user's own choice (e.g. "All") — don't silently
// override it again; the info alert the grid shows already explains why nothing is listed
if (!hasDefaults || seeded) return;
setParams(filterToParams(defaultFilter), { replace: true });
}, [hasDefaults, defaultFilter, setParams, seeded]);
const can = (action: string) => !!config?.AUTHORITY.some((a) => a.ENTITY_NAME === entity && a.ACTION_NAME === action);
// buttons the old grid drew at its top (actions located at MAIN), limited to the ones this app can run
type Main = { ACTION_NAME: string; ACTION_CAPTION_CODE?: string; CURRENT_STATUS_NAME?: string; SUPPORTED_ACTION_LOCATION?: string };
const mainActions = useMemo(() => {
const seen = new Set<string>();
return ((config?.AUTHORITY ?? []) as unknown as (Main & { ENTITY_NAME: string })[]).filter((a) => {
if (a.ENTITY_NAME !== entity || !String(a.SUPPORTED_ACTION_LOCATION ?? '').includes('MAIN') || !MAIN_ACTIONS.has(a.ACTION_NAME) || seen.has(a.ACTION_NAME)) return false;
seen.add(a.ACTION_NAME);
return true;
});
}, [config, entity]);
const selectable = mainActions.some((a) => SELECTION_ACTIONS.has(a.ACTION_NAME));
const filterKeyForSelection = JSON.stringify(filter);
useEffect(() => setSelected({}), [filterKeyForSelection, entity]);
const runMain = useMutation({
meta: { loading: 'processing' },
mutationFn: (a: Main) => runMainAction(entity, a.ACTION_NAME, flatSearch(fields.map((f) => f.id), filter), Object.keys(selected).map((id) => ({ id }))),
onSuccess: (msg) => {
notify.success(msg, ui('saved'));
setSelected({});
void qc.invalidateQueries({ queryKey: ['grid', entity] });
},
onError: (e) => notify.error(e),
});
const startMain = (a: Main) => {
if (a.ACTION_NAME === 'RECONCILIATION_UPLOAD_FILE') return setUploadOpen(true);
if (a.ACTION_NAME === 'SETTINGS') return setSettingsOpen(true);
if (SELECTION_ACTIONS.has(a.ACTION_NAME)) {
const picked = Object.entries(selected);
if (!picked.length) return notify.warning('SELECT_RECORD_TO_COMPLETE', ui('selectRow'));
if (a.CURRENT_STATUS_NAME && picked.some(([, st]) => st !== a.CURRENT_STATUS_NAME)) return notify.warning('CHECK_STATUS_BEFORE_CHANGE', ui('selectRow'));
}
if (CONFIRM_MAIN_ACTIONS.has(a.ACTION_NAME)) setConfirmMain(a);
else runMain.mutate(a);
};
// ask for the default exactly once
useEffect(() => {
if (!seeded) onFilterRequired();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// only now — once the URL has actually caught up — stop falling back to the default
useEffect(() => {
if (params.toString()) setSeeded(true);
}, [params]);
return (
<>
<PageHeader
title={labelOf(entity)}
subtitle={total === null ? undefined : `${total.toLocaleString()} ${ui('records')}`}
actions={
<>
{can('GETREPORT') && <ExportButton entity={entity} fields={fields} filter={filter} total={total} />}
{mainActions.map((a) => (
<Button key={a.ACTION_NAME} variant={SELECTION_ACTIONS.has(a.ACTION_NAME) ? 'contained' : 'outlined'} disabled={runMain.isPending} onClick={() => startMain(a)}>
{t(String(a.ACTION_CAPTION_CODE || a.ACTION_NAME))}
{SELECTION_ACTIONS.has(a.ACTION_NAME) && Object.keys(selected).length > 0 ? ` (${Object.keys(selected).length})` : ''}
</Button>
))}
{can('CREATE') && (
<Button variant="contained" startIcon={<AddIcon />} component={RouterLink} to={`/e/${entity}/create`}>
{ui('new')}
</Button>
)}
</>
}
/>
<SearchPanel entity={entity} fields={fields} filter={filter} onChange={(f) => setParams(filterToParams(f), { replace: true })} />
{totalBalance !== undefined && (
<Typography fontWeight={800} fontSize={18} sx={{ mb: 1 }}>
{t('TOTAL_BALANCE')} : <bdi dir="ltr">{totalBalance.toFixed(3)}</bdi> {t('RO')}
</Typography>
)}
<EntityGrid entity={entity} filter={toApiFilter(filter)} canEdit={can('UPDATE')} onTotal={onTotal} onFilterRequired={onFilterRequired} selectable={selectable} selected={selected} onSelectedChange={setSelected} onTotalBalance={setTotalBalance} />
{uploadOpen && (entity === 'RECONCILIATION' || entity === 'RECONCILIATION_POS') && (
<ReconciliationUpload entity={entity} onClose={() => setUploadOpen(false)} onDone={() => { setUploadOpen(false); void qc.invalidateQueries({ queryKey: ['grid', entity] }); }} />
)}
{settingsOpen && entity === PENDING_ENTITY && (
<PendingSettingsDialog
onClose={() => setSettingsOpen(false)}
onDone={() => {
setSettingsOpen(false);
// the grid's default date range comes from these settings
void qc.invalidateQueries({ queryKey: ['pending-settings'] });
void qc.invalidateQueries({ queryKey: ['grid', entity] });
}}
/>
)}
<Dialog open={!!confirmMain} onClose={() => setConfirmMain(null)}>
<DialogTitle>{t(String(confirmMain?.ACTION_CAPTION_CODE || confirmMain?.ACTION_NAME || ''))}</DialogTitle>
<DialogContent>{t('CONFIRM_MSG')}</DialogContent>
<DialogActions>
<Button onClick={() => setConfirmMain(null)}>{t('NO')}</Button>
<Button variant="contained" onClick={() => { const a = confirmMain; setConfirmMain(null); if (a) runMain.mutate(a); }}>{t('YES')}</Button>
</DialogActions>
</Dialog>
</>
);
}
/** A whole-page "not authorized" — no grid chrome, no filters, just what happened and the way out. */
function NotAuthorized() {
const ui = useUi();
return (
<Box sx={{ display: 'grid', placeItems: 'center', py: 10, textAlign: 'center' }}>
<Stack spacing={2} alignItems="center" sx={{ maxWidth: 460 }}>
<LockOutlined sx={{ fontSize: 56, color: 'text.disabled' }} />
<Typography variant="h5" fontWeight={800}>{ui('notAuthorizedTitle')}</Typography>
<Typography color="text.secondary">{ui('notAuthorizedText')}</Typography>
<Button variant="contained" component={RouterLink} to="/">{ui('home')}</Button>
</Stack>
</Box>
);
}
export function EntityRoute({ entity, view, id }: { entity: string; view: string; id?: string }) {
const { labelOf, sectionOf } = useNav();
const { config } = useAuth();
const ui = useUi();
const [params] = useSearchParams();
if (HIDDEN_ENTITIES.has(entity)) return <Navigate to="/" replace />;
// a role with no authority row and no menu entry for the entity cannot open it, however the URL was reached
if (config && !config.AUTHORITY.some((a) => a.ENTITY_NAME === entity) && !sectionOf(entity)) return <NotAuthorized />;
if (view === 'view' && id) {
return (
<Suspense fallback={<PageLoading />}>
<EntityView entity={entity} id={id} />
</Suspense>
);
}
if (view === 'create' && entity === 'SUBSCRIPTIONS' && !id) {
return (
<>
<PageHeader backTo={`/e/${entity}/grid`} title={labelOf(WIZARD_KEY)} />
<Suspense fallback={<PageLoading />}>
<SubscriptionWizard />
</Suspense>
</>
);
}
if (view === 'create') {
const profile = entity === 'USERS' && !!id && params.get('profile') === '1';
return (
<>
<PageHeader backTo={profile ? '/' : `/e/${entity}/grid`} title={profile ? ui('myProfile') : `${id ? ui('edit') : ui('new')} · ${labelOf(entity)}`} />
<Suspense fallback={<PageLoading />}>
<EntityForm entity={entity} id={id} />
</Suspense>
</>
);
}
if (entity === PENDING_ENTITY) return <PendingGridGate />;
return <GridPage entity={entity} />;
}

View File

@ -0,0 +1,53 @@
import { Link as RouterLink } from 'react-router-dom';
import { Box, IconButton, Paper, Stack, Tooltip, Typography } from '@mui/material';
import AddCircleOutline from '@mui/icons-material/AddCircleOutline';
import { newRecordSx } from '../components/newRecordSx';
import { useAuth } from '../auth/AuthContext';
import { useNav } from '../layout/NavContext';
import { isRtl, useLabel, useT, useUi } from '../i18n';
import { roleLabel } from '../i18n/roles';
/** Landing page: every section the role can open, as shortcuts. */
export function HomeLauncher() {
const { user, lang } = useAuth();
const t = useT();
const ui = useUi();
const humanize = useLabel();
const { sections, title, labelOf } = useNav();
return (
<>
<Typography variant="h5" component="h1" sx={{ mb: 0.5 }}>{user?.name}</Typography>
<Typography color="text.secondary" sx={{ mb: 3 }}>{roleLabel(String(user?.job_title ?? user?.role_code ?? ''), t, humanize, isRtl(lang))}</Typography>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{sections.map((s) => {
const Icon = s.icon;
return (
<Paper key={s.key} variant="outlined" sx={{ p: 2.5 }}>
<Stack direction="row" spacing={1.5} alignItems="center" sx={{ mb: 1.5 }}>
<Box sx={{ display: 'grid', placeItems: 'center', width: 30, height: 30, borderRadius: 1.5, bgcolor: 'action.hover', color: 'primary.main' }}><Icon sx={{ fontSize: 18 }} /></Box>
<Typography component="h2" fontWeight={700}>{title(s)}</Typography>
</Stack>
<Stack spacing={0.25}>
{s.items.map((i) => (
<Stack key={i.entity} direction="row" alignItems="center" justifyContent="space-between">
<Typography component={RouterLink} to={i.to} color="text.secondary" sx={{ textDecoration: 'none', py: 0.4, flex: 1, '&:hover': { color: 'primary.main' } }}>
{labelOf(i.entity)}
</Typography>
{/* the same "+" the menu shows beside a module that can create records */}
{i.canCreate && (
<Tooltip title={ui('new')}>
<IconButton size="small" sx={newRecordSx} component={RouterLink} to={`/e/${i.entity}/create`} aria-label={`${ui('new')} · ${labelOf(i.entity)}`}>
<AddCircleOutline sx={{ fontSize: 16 }} />
</IconButton>
</Tooltip>
)}
</Stack>
))}
</Stack>
</Paper>
);
})}
</Box>
</>
);
}

View File

@ -0,0 +1,333 @@
import { useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Alert, Avatar, Box, Chip, Paper, Skeleton, Stack, Typography, alpha, useTheme } from '@mui/material';
import { useAuth } from '../../auth/AuthContext';
import { isRtl, useLabel, useT, useUi } from '../../i18n';
import { PageHeader } from '../../components/PageHeader';
import { rpc } from '../../api/client';
import type { Option } from '../../api/entity';
import { DASHBOARDS } from '../../layout/nav';
import { buildDashboard, buildInfographic, type Block, type Item } from './model';
import { blockIcon, itemTint } from './icons';
interface Page {
kind: 'dashboard' | 'infographic';
name: string;
/** offers the industrial-city filter the old page had */
locations?: boolean;
}
const PAGES: Record<string, Page> = {
stakeholders: { kind: 'dashboard', name: 'STAKEHOLDER_DASHBOARD', locations: true },
fleet: { kind: 'dashboard', name: 'FLEET_DASHBOARD', locations: true },
personnel: { kind: 'dashboard', name: 'PERSONNEL_DASHBOARD', locations: true },
'fleet-infographic': { kind: 'infographic', name: 'FLEET_INFOGRAPH' },
'personnel-infographic': { kind: 'infographic', name: 'PERSONNEL_INFOGRAPH' },
'stakeholders-infographic': { kind: 'infographic', name: 'STAKEHOLDERS_INFOGRAPH' },
};
const fmt = (n: number) => n.toLocaleString();
// titles / categories the system has no caption for (it falls back to a readable version of the code)
const OWN: Record<string, { en: string; ar: string }> = {
REGISTERED_STAKEHOLDER: { en: 'Registered stakeholders', ar: 'الجهات المسجلة' },
STAKEHOLDER_STATUS_CODES: { en: 'Stakeholders by status', ar: 'الجهات حسب الحالة' },
STAKEHOLDER_LOCATION: { en: 'Stakeholders by industrial city', ar: 'الجهات حسب المدينة الصناعية' },
PERSONNEL_EDUCATIONAL_LEVEL: { en: 'Education level', ar: 'المستوى التعليمي' },
PERSONNEL_EMPLOYMENT_CATEGORY: { en: 'Employment category', ar: 'فئة التوظيف' },
PERSONNEL_HEADER: { en: 'Workforce overview', ar: 'نظرة عامة على العاملين' },
PERSONNEL_RELATIVES: { en: 'Relatives', ar: 'الأقارب' },
PERSONNEL_STATUS_CODES: { en: 'Personnel by status', ar: 'العاملون حسب الحالة' },
TOP_NATIONALITY: { en: 'Top nationalities', ar: 'أعلى الجنسيات' },
USAGE_TYPE_CARGO: { en: 'Trailers by cargo type', ar: 'المقطورات حسب نوع الحمولة' },
USAGE_TYPE_TANK: { en: 'Tankers by type', ar: 'الصهاريج حسب النوع' },
FLEET_LOCATION: { en: 'Fleet by industrial city', ar: 'المركبات حسب المدينة الصناعية' },
OTHER_TRAILERS_TYPE: { en: 'Other trailer types', ar: 'أنواع المقطورات الأخرى' },
STAKEHOLDER_FLEET: { en: 'Fleet by stakeholder type', ar: 'المركبات حسب نوع صاحب المصلحة' },
TRAILERS_TYPE: { en: 'Trailer types', ar: 'أنواع المقطورات' },
Educational_Level: { en: 'Education level', ar: 'المستوى التعليمي' },
Nationality: { en: 'Nationality', ar: 'الجنسية' },
HEAVY: { en: 'Heavy', ar: 'ثقيل' },
MEDIUM: { en: 'Medium', ar: 'متوسط' },
SMALL: { en: 'Small', ar: 'صغير' },
LARGE: { en: 'Large', ar: 'كبير' },
HEAVYEQUIPMENT: { en: 'Heavy equipment', ar: 'معدات ثقيلة' },
MEDIUMEQUIPMENT: { en: 'Medium equipment', ar: 'معدات متوسطة' },
OMN_NAT: { en: 'Omani', ar: 'عماني' },
OTHERS_NAT: { en: 'Non-Omani', ar: 'غير عماني' },
SUBSCRIPED: { en: 'Subscribed', ar: 'مشترك' },
NOT_SUBSCRIPED: { en: 'Not subscribed', ar: 'غير مشترك' },
OTHER_NAT_DRVR: { en: 'Drivers of other nationalities', ar: 'سائقون من جنسيات أخرى' },
OMN_NAT_DRVR: { en: 'Omani drivers', ar: 'سائقون عمانيون' },
INVESTORS_RUSAIL: { en: 'Rusayl investors', ar: 'مستثمرو الرسيل' },
INVESTORS_ALMAZYUNAH: { en: 'Al Mazyunah investors', ar: 'مستثمرو المزيونة' },
INVESTORS_NIZWA: { en: 'Nizwa investors', ar: 'مستثمرو نزوى' },
INVESTORS_SUHAR: { en: 'Sohar investors', ar: 'مستثمرو صحار' },
DRIVERS: { en: 'Drivers', ar: 'السائقون' },
OTHERS: { en: 'Others', ar: 'أخرى' },
YES: { en: 'Yes', ar: 'نعم' },
NO: { en: 'No', ar: 'لا' },
};
function Tiles({ items }: { items: Item[] }) {
return (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: 'repeat(auto-fill, minmax(170px, 1fr))' }}>
{items.map((i, idx) => {
const { icon: Icon, color } = itemTint(i.code, idx);
return (
<Paper
key={i.label}
variant="outlined"
sx={{
p: 1.75,
display: 'flex',
alignItems: 'center',
gap: 1.5,
borderInlineStart: 3,
borderInlineStartColor: color,
}}
>
<Avatar sx={{ bgcolor: alpha(color, 0.15), color, width: 42, height: 42 }}>
<Icon fontSize="small" />
</Avatar>
<Box sx={{ minWidth: 0 }}>
<Typography variant="h5" fontWeight={800} sx={{ color, lineHeight: 1.1 }}>{fmt(i.value)}</Typography>
<Typography variant="body2" color="text.secondary" noWrap sx={{ unicodeBidi: 'plaintext', textAlign: 'start' }}>{i.label}</Typography>
</Box>
</Paper>
);
})}
</Box>
);
}
/** A CSS conic-gradient donut: no charting library needed for a handful of slices. */
function Pie({ items }: { items: Item[] }) {
const theme = useTheme();
const ui = useUi();
const total = Math.max(1, items.reduce((a, i) => a + i.value, 0));
let acc = 0;
const stops = items
.filter((i) => i.value > 0)
.map((i, idx) => {
const from = (acc / total) * 100;
acc += i.value;
const to = (acc / total) * 100;
return { ...i, color: itemTint(i.code, idx).color, from, to };
});
const gradient = stops.length
? `conic-gradient(${stops.map((s) => `${s.color} ${s.from}% ${s.to}%`).join(', ')})`
: theme.palette.action.hover;
return (
<Stack direction="row" spacing={3} alignItems="center" flexWrap="wrap" useFlexGap>
<Box sx={{ position: 'relative', width: 150, height: 150, flexShrink: 0 }}>
<Box sx={{ width: '100%', height: '100%', borderRadius: '50%', background: gradient }} />
<Box
sx={{
position: 'absolute', inset: 22, borderRadius: '50%', bgcolor: 'background.paper',
display: 'grid', placeItems: 'center', boxShadow: `0 0 0 1px ${theme.palette.divider} inset`,
}}
>
<Box sx={{ textAlign: 'center' }}>
<Typography variant="h6" fontWeight={800} lineHeight={1.1}>{fmt(items.reduce((a, i) => a + i.value, 0))}</Typography>
<Typography variant="caption" color="text.secondary">{ui('total')}</Typography>
</Box>
</Box>
</Box>
<Stack spacing={0.75} sx={{ flex: 1, minWidth: 160 }}>
{stops.map((s) => (
<Stack key={s.label} direction="row" alignItems="center" spacing={1}>
<Box sx={{ width: 10, height: 10, borderRadius: '50%', bgcolor: s.color, flexShrink: 0 }} />
<Typography variant="body2" sx={{ flex: 1, unicodeBidi: 'plaintext', textAlign: 'start' }} noWrap title={s.label}>{s.label}</Typography>
<Typography variant="body2" fontWeight={700}>{fmt(s.value)}</Typography>
<Typography variant="caption" color="text.secondary" sx={{ width: 40, textAlign: 'end' }}>
{Math.round((s.value / total) * 100)}%
</Typography>
</Stack>
))}
</Stack>
</Stack>
);
}
function Bars({ items }: { items: Item[] }) {
const max = Math.max(1, ...items.map((i) => i.value));
return (
<Stack spacing={1}>
{items.map((i) => (
<Box key={i.label}>
<Stack direction="row" justifyContent="space-between" sx={{ mb: 0.25 }}>
<Typography variant="body2">{i.label}</Typography>
<Typography variant="body2" fontWeight={700}>{fmt(i.value)}</Typography>
</Stack>
<Box sx={{ height: 8, borderRadius: 4, bgcolor: 'action.hover', overflow: 'hidden' }}>
<Box sx={{ width: `${(i.value / max) * 100}%`, height: '100%', bgcolor: 'primary.main', borderRadius: 4, minWidth: i.value ? 3 : 0 }} />
</Box>
</Box>
))}
</Stack>
);
}
function Stacked({ items }: { items: Item[] }) {
const theme = useTheme();
const color: Record<string, string> = {
REGISTERED: theme.palette.success.main,
ACTIVE: theme.palette.success.main,
INCOMPLETE: theme.palette.warning.main,
PENDING: theme.palette.info.main,
PENDING_UPDATE: theme.palette.info.light,
RETURNED: theme.palette.secondary.main,
INACTIVE: theme.palette.grey[500],
};
const palette = [theme.palette.primary.main, theme.palette.secondary.main, theme.palette.success.main, theme.palette.warning.main];
const keys = [...new Set(items.flatMap((i) => i.segments?.map((s) => s.key) ?? []))];
const labels = new Map(items.flatMap((i) => i.segments ?? []).map((s) => [s.key, s.label]));
const col = (k: string) => color[k] ?? palette[keys.indexOf(k) % palette.length];
const max = Math.max(1, ...items.map((i) => i.value));
return (
<Stack spacing={1.25}>
<Stack direction="row" spacing={1.5} useFlexGap flexWrap="wrap">
{keys.map((k) => (
<Stack key={k} direction="row" spacing={0.5} alignItems="center">
<Box sx={{ width: 10, height: 10, borderRadius: 0.5, bgcolor: col(k) }} />
<Typography variant="caption" color="text.secondary">{labels.get(k)}</Typography>
</Stack>
))}
</Stack>
{items.map((i) => (
<Box key={i.label}>
<Stack direction="row" justifyContent="space-between" sx={{ mb: 0.25 }}>
<Typography variant="body2">{i.label}</Typography>
<Typography variant="body2" fontWeight={700}>{fmt(i.value)}</Typography>
</Stack>
<Box sx={{ display: 'flex', height: 10, width: `${Math.max(4, (i.value / max) * 100)}%`, borderRadius: 5, overflow: 'hidden', bgcolor: 'action.hover' }}>
{i.segments?.filter((s) => s.value > 0).map((s) => (
<Box key={s.key} title={`${s.label}: ${fmt(s.value)}`} sx={{ width: `${(s.value / Math.max(1, i.value)) * 100}%`, bgcolor: col(s.key) }} />
))}
</Box>
</Box>
))}
</Stack>
);
}
function BlockCard({ block }: { block: Block }) {
const body =
block.kind === 'tiles' ? <Tiles items={block.items} />
: block.kind === 'pie' ? <Pie items={block.items} />
: block.kind === 'stacked' ? <Stacked items={block.items} />
: <Bars items={block.items} />;
if (block.kind === 'tiles' && !block.title) return body;
const tint = blockIcon(block.key);
return (
<Paper variant="outlined" sx={{ p: 2, height: '100%' }}>
<Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1.5 }}>
{tint && (
<Avatar sx={{ bgcolor: alpha(tint.color, 0.15), color: tint.color, width: 28, height: 28 }}>
<tint.icon sx={{ fontSize: 16 }} />
</Avatar>
)}
<Typography component="h2" fontWeight={700} fontSize={14.5}>{block.title}</Typography>
</Stack>
{body}
</Paper>
);
}
export function DashboardPage() {
const { slug = '' } = useParams();
const page = PAGES[slug];
const { user, lang } = useAuth();
const caption = useT();
const humanize = useLabel();
const ui = useUi();
// system caption first, then our own bilingual title, then a readable form of the code
const lab = (k: string) => {
// on the dashboards OWNERS is the separate 254-record group, not the drivers (those are DRIVERS), so it keeps its own name
if (page?.kind === 'dashboard' && k === 'OWNERS') return isRtl(lang) ? 'المالكون' : 'Owners';
const own = OWN[k] ?? OWN[k.toUpperCase()];
return caption(k) !== k ? caption(k) : own ? (isRtl(lang) ? own.ar : own.en) : humanize(k);
};
const [location, setLocation] = useState(0);
const [nat, setNat] = useState('ALL');
const meta = Object.values(DASHBOARDS).find((d) => d.slug === slug);
// users bound to one industrial city only ever see that city (as in the old page)
const lockedTo = Number(user?.use_location_id) === 1 ? Number(user?.location_id) : null;
const loc = lockedTo ?? location;
const locations = useQuery({
queryKey: ['dash-locations'],
queryFn: () => rpc<{ INDUSTRIALESTATESARRAY?: Option[] }>('CONFIG', 'getIndustrialLocs', { related_entity_id: '', related_entity_record_id: '' }),
enabled: !!page?.locations,
staleTime: 10 * 60_000,
});
const data = useQuery({
queryKey: ['dashboard', slug, loc],
queryFn: () =>
page!.kind === 'dashboard'
? rpc<unknown>('CONFIG', 'GetDashBoard', { DASHBOARD_NAME: page!.name, LOCATIONID: loc })
: rpc<unknown>('CONFIG', 'GetInfoGraphic', { INFOGRAPH_NAME: page!.name }),
enabled: !!page,
staleTime: 60_000,
});
const model = useMemo(() => {
if (!page || !data.data) return { blocks: [] as Block[], nats: [] as string[] };
if (page.kind === 'dashboard') return { blocks: buildDashboard(data.data, lab), nats: [] as string[] };
return buildInfographic(data.data, lab, nat);
}, [page, data.data, lab, nat]);
if (!page) return <Alert severity="info">{ui('noResults')}</Alert>;
const title = meta ? (isRtl(lang) ? meta.ar : meta.en) : slug;
const estates = locations.data?.INDUSTRIALESTATESARRAY ?? [];
return (
<>
<PageHeader title={title} />
{page.locations && estates.length > 0 && (
<Stack direction="row" spacing={0.75} useFlexGap flexWrap="wrap" sx={{ mb: 2 }}>
<Chip label={lab('ALL_LOCATIONS')} color={loc === 0 ? 'primary' : 'default'} variant={loc === 0 ? 'filled' : 'outlined'} disabled={lockedTo !== null} onClick={() => setLocation(0)} />
{estates.map((e) => (
<Chip key={String(e.CODE)} label={lab(e.CAPTION_CODE ?? String(e.CODE))} color={Number(e.CODE) === loc ? 'primary' : 'default'} variant={Number(e.CODE) === loc ? 'filled' : 'outlined'} disabled={lockedTo !== null && Number(e.CODE) !== lockedTo} onClick={() => setLocation(Number(e.CODE))} />
))}
</Stack>
)}
{model.nats.length > 0 && (
<Stack direction="row" spacing={0.75} useFlexGap flexWrap="wrap" sx={{ mb: 2 }}>
{model.nats.map((n) => (
<Chip key={n} label={n === 'ALL' ? ui('all') : lab(n)} color={n === nat ? 'primary' : 'default'} variant={n === nat ? 'filled' : 'outlined'} onClick={() => setNat(n)} />
))}
</Stack>
)}
{data.error && <Alert severity="error">{ui('loadError')}</Alert>}
{data.isPending && (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)' } }}>
{[0, 1, 2, 3].map((i) => <Skeleton key={i} variant="rounded" height={160} />)}
</Box>
)}
{!data.isPending && (() => {
// the statistics (KPI tiles) always come first, as their own full-width row; the diagrams
// that follow sit in a multi-column grid so they line up side by side wherever there is room
const stats = model.blocks.filter((b) => b.kind === 'tiles');
const charts = model.blocks.filter((b) => b.kind !== 'tiles');
return (
<Stack spacing={1.5}>
{stats.length > 0 && (
<Stack spacing={1.5}>
{stats.map((b) => <BlockCard key={b.key} block={b} />)}
</Stack>
)}
{charts.length > 0 && (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', xl: 'repeat(3, 1fr)' }, alignItems: 'stretch' }}>
{charts.map((b) => <BlockCard key={b.key} block={b} />)}
</Box>
)}
</Stack>
);
})()}
</>
);
}

View File

@ -0,0 +1,95 @@
import type { ElementType } from 'react';
import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined';
import Inventory2Outlined from '@mui/icons-material/Inventory2Outlined';
import ConstructionOutlined from '@mui/icons-material/ConstructionOutlined';
import DirectionsBusOutlined from '@mui/icons-material/DirectionsBusOutlined';
import DirectionsCarOutlined from '@mui/icons-material/DirectionsCarOutlined';
import BusinessOutlined from '@mui/icons-material/BusinessOutlined';
import BadgeOutlined from '@mui/icons-material/BadgeOutlined';
import TrendingUpOutlined from '@mui/icons-material/TrendingUpOutlined';
import GroupsOutlined from '@mui/icons-material/GroupsOutlined';
import PeopleAltOutlined from '@mui/icons-material/PeopleAltOutlined';
import WarehouseOutlined from '@mui/icons-material/WarehouseOutlined';
import StoreOutlined from '@mui/icons-material/StoreOutlined';
import CheckCircleOutline from '@mui/icons-material/CheckCircleOutline';
import ScheduleOutlined from '@mui/icons-material/ScheduleOutlined';
import ErrorOutlineOutlined from '@mui/icons-material/ErrorOutlineOutlined';
import UndoOutlined from '@mui/icons-material/UndoOutlined';
import BlockOutlined from '@mui/icons-material/BlockOutlined';
import AutorenewOutlined from '@mui/icons-material/AutorenewOutlined';
import PublicOutlined from '@mui/icons-material/PublicOutlined';
import MapOutlined from '@mui/icons-material/MapOutlined';
import SchoolOutlined from '@mui/icons-material/SchoolOutlined';
import WorkOutline from '@mui/icons-material/WorkOutline';
import DashboardOutlined from '@mui/icons-material/DashboardOutlined';
import CategoryOutlined from '@mui/icons-material/CategoryOutlined';
/** A vivid, fixed tint per code — picked to read well in both light and dark mode, like the old dashboard's icons. */
export interface Tint {
icon: ElementType;
color: string;
}
// entities shown as the colourful overview stat cards
const ENTITY: Record<string, Tint> = {
TRUCKS: { icon: LocalShippingOutlined, color: '#2c98d4' },
TRAILERS: { icon: Inventory2Outlined, color: '#cbb67d' },
EQUIPMENTS: { icon: ConstructionOutlined, color: '#5fb87a' },
BUSES: { icon: DirectionsBusOutlined, color: '#d16475' },
CARS: { icon: DirectionsCarOutlined, color: '#7c6fd1' },
USERS: { icon: PeopleAltOutlined, color: '#2c98d4' },
PERSONNEL: { icon: PeopleAltOutlined, color: '#2c98d4' },
DRIVERS: { icon: BadgeOutlined, color: '#a5894f' },
COMPANIES: { icon: BusinessOutlined, color: '#2c98d4' },
OWNERS: { icon: BadgeOutlined, color: '#cbb67d' },
INVESTORS: { icon: TrendingUpOutlined, color: '#5fb87a' },
OTHER_STAKEHOLDERS: { icon: GroupsOutlined, color: '#7c6fd1' },
FREEZONE_CLEARING_COMPANIES: { icon: WarehouseOutlined, color: '#d1a233' },
FREEZONE_DEPOSITORS: { icon: StoreOutlined, color: '#d16475' },
};
// statuses used across every status breakdown (fleet, personnel, stakeholders…)
const STATUS: Record<string, Tint> = {
REGISTERED: { icon: CheckCircleOutline, color: '#5fb87a' },
ACTIVE: { icon: CheckCircleOutline, color: '#5fb87a' },
SUBSCRIPED: { icon: CheckCircleOutline, color: '#5fb87a' },
PENDING: { icon: ScheduleOutlined, color: '#e2a93b' },
PENDING_UPDATE: { icon: AutorenewOutlined, color: '#2c98d4' },
INCOMPLETE: { icon: ErrorOutlineOutlined, color: '#d1a233' },
RETURNED: { icon: UndoOutlined, color: '#7c6fd1' },
INACTIVE: { icon: BlockOutlined, color: '#8d98a4' },
NOT_SUBSCRIPED: { icon: BlockOutlined, color: '#8d98a4' },
};
/** Card-header icon for a dashboard block, keyed by its DASHBOARD_SECTION / infographic key. */
export const BLOCK_ICON: Record<string, Tint> = {
REGISTERED_STAKEHOLDER: { icon: GroupsOutlined, color: '#2c98d4' },
STAKEHOLDER_STATUS_CODES: { icon: CheckCircleOutline, color: '#5fb87a' },
STAKEHOLDER_LOCATION: { icon: MapOutlined, color: '#7c6fd1' },
STAKEHOLDER_FLEET: { icon: LocalShippingOutlined, color: '#2c98d4' },
PERSONNEL_HEADER: { icon: PeopleAltOutlined, color: '#2c98d4' },
PERSONNEL_EDUCATIONAL_LEVEL: { icon: SchoolOutlined, color: '#7c6fd1' },
PERSONNEL_EMPLOYMENT_CATEGORY: { icon: WorkOutline, color: '#d1a233' },
PERSONNEL_STATUS_CODES: { icon: CheckCircleOutline, color: '#5fb87a' },
PERSONNEL_RELATIVES: { icon: GroupsOutlined, color: '#d16475' },
TOP_NATIONALITY: { icon: PublicOutlined, color: '#2c98d4' },
USAGE_TYPE_CARGO: { icon: Inventory2Outlined, color: '#cbb67d' },
USAGE_TYPE_TANK: { icon: Inventory2Outlined, color: '#d16475' },
TRAILERS_TYPE: { icon: Inventory2Outlined, color: '#2c98d4' },
OTHER_TRAILERS_TYPE: { icon: Inventory2Outlined, color: '#7c6fd1' },
FLEET_LOCATION: { icon: MapOutlined, color: '#5fb87a' },
TOTALS: { icon: DashboardOutlined, color: '#2c98d4' },
};
const FALLBACK_ICON = CategoryOutlined;
// cycled for codes we have no specific tint for, so every slice/tile still gets a distinct colour
const PALETTE = ['#2c98d4', '#d16475', '#5fb87a', '#e2a93b', '#7c6fd1', '#cbb67d', '#1cabe3', '#a5894f', '#8d98a4', '#13964c'];
/** The tint for one item's code (entity name, status, category…), falling back to a cycled colour. */
export function itemTint(code: string | undefined, index: number): Tint {
if (code && ENTITY[code]) return ENTITY[code];
if (code && STATUS[code]) return STATUS[code];
return { icon: FALLBACK_ICON, color: PALETTE[index % PALETTE.length] };
}
export const blockIcon = (key: string): Tint | undefined => BLOCK_ICON[key];

View File

@ -0,0 +1,126 @@
// Turns what the backend returns for the old home-page dashboards / infographics into display blocks.
export type Row = Record<string, unknown>;
export interface Item {
label: string;
value: number;
/** the raw backend code behind the label (entity name, status, category…), for icon/colour lookups */
code?: string;
/** a status (or type) breakdown: shown as a stacked bar */
segments?: { key: string; label: string; value: number }[];
}
export interface Block {
key: string;
title: string;
kind: 'tiles' | 'bars' | 'stacked' | 'pie';
items: Item[];
order: number;
}
type Label = (key: string) => string;
// DATA / DATALBL repeat the category's own number and name on the usage-type rows
const META = new Set(['DASHBOARD_ORDER', 'DASHBOARD_SECTION', 'ENTITY_NAME', 'LOCATION_NAME', 'DATA', 'DATALBL']);
const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// a part-to-whole breakdown reads well as a pie once it has only a handful of slices
const PIE_MAX_SLICES = 8;
const metrics = (r: Row) =>
Object.entries(r).filter(([k, v]) => !META.has(k) && !/^\d+$/.test(k) && isNum(v)) as [string, number][];
/** GetDashBoard: rows tagged with DASHBOARD_SECTION (plus a trailing TOP_NATIONALITY object). */
export function buildDashboard(data: unknown, label: Label): Block[] {
const rows = (Array.isArray(data) ? data : []) as Row[];
const sections = new Map<string, Row[]>();
const blocks: Block[] = [];
for (const r of rows) {
const s = r.DASHBOARD_SECTION;
if (typeof s === 'string' && s) sections.set(s, [...(sections.get(s) ?? []), r]);
else if (r.TOP_NATIONALITY && typeof r.TOP_NATIONALITY === 'object') {
const items = Object.entries(r.TOP_NATIONALITY as Record<string, unknown[]>)
.map(([code, v]) => ({ label: label(code), value: Number(v?.[0] ?? 0), code }))
.sort((a, b) => b.value - a.value);
if (items.length) {
blocks.push({ key: 'TOP_NATIONALITY', title: label('TOP_NATIONALITY'), kind: items.length <= PIE_MAX_SLICES ? 'pie' : 'bars', items, order: 1000 });
}
}
}
for (const [key, list] of sections) {
const order = Math.min(...list.map((r) => Number(r.DASHBOARD_ORDER ?? 0)));
const perRow = list.map((r) => ({ r, m: metrics(r) })).filter((x) => x.m.length);
if (!perRow.length) continue;
const name = (r: Row) => label(String(r.ENTITY_NAME ?? r.LOCATION_NAME ?? ''));
if (perRow.length === 1 && perRow[0].m.length > 1) {
// one row split into several categories or statuses: a part-to-whole breakdown (education level,
// employment category, status codes…) — a pie once there are few enough slices to read, else bars
const items = perRow[0].m.map(([k, v]) => ({ label: label(k), value: v, code: k }));
blocks.push({ key, title: label(key), kind: items.length <= PIE_MAX_SLICES ? 'pie' : 'bars', order, items });
} else if (perRow.every((x) => x.m.length === 1)) {
// a handful of totals read well as tiles; a long list of categories reads better as bars
const items = perRow.map((x) => ({ label: name(x.r), value: x.m[0][1], code: String(x.r.ENTITY_NAME ?? x.r.LOCATION_NAME ?? '') }));
blocks.push({ key, title: label(key), kind: items.length > 6 ? 'bars' : 'tiles', order, items: items.length > 6 ? items.sort((a, b) => b.value - a.value) : items });
} else {
// several rows, each already split into categories: compare them side by side as stacked bars
blocks.push({
key, title: label(key), kind: 'stacked', order,
items: perRow.map((x) => ({
label: name(x.r),
value: x.m.reduce((a, [, v]) => a + v, 0),
segments: x.m.map(([k, v]) => ({ key: k, label: label(k), value: v })),
})),
});
}
}
return blocks.sort((a, b) => a.order - b.order);
}
const STAKEHOLDER_IDS: Record<string, string> = { '7': 'INVESTORS', '10': 'OWNERS', '11': 'COMPANIES', '12': 'OTHER_STAKEHOLDERS' };
/** GetInfoGraphic: flat rows { CNT, TYPE, KEY, ENTITY_NAME?, NAT? }, filtered by nationality when present. */
export function buildInfographic(data: unknown, label: Label, nat: string): { blocks: Block[]; nats: string[] } {
const rows = (Array.isArray(data) ? data : []) as Row[];
const nats = [...new Set(rows.map((r) => r.NAT).filter((n): n is string => typeof n === 'string'))];
const use = nats.length ? rows.filter((r) => r.NAT === nat) : rows;
// no TYPE: one total per entity (stakeholder infographic)
if (!use.some((r) => r.TYPE)) {
const items = use.map((r) => {
const code = String(r.ENTITY_NAME ?? r.KEY ?? '');
return { label: label(code), value: Number(r.CNT ?? 0), code };
});
return { nats, blocks: items.length ? [{ key: 'TOTALS', title: '', kind: 'tiles', items, order: 0 }] : [] };
}
const groups = new Map<string, Row[]>();
for (const r of use) {
const k = `${r.ENTITY_NAME ?? ''}|${r.TYPE}`;
groups.set(k, [...(groups.get(k) ?? []), r]);
}
const blocks: Block[] = [...groups].map(([k, rowsOfGroup], i) => {
const [entity, type] = k.split('|');
// On "All" the backend sends the nationality chart as one row (KEY "ALL", the grand total) and puts the real
// breakdown on the per-nationality rows (OMN, IND, OTHERS…). Those rows add up to the same total, so draw
// them instead of a single 100% slice.
let list = rowsOfGroup;
const split = rows.filter((r) => r.TYPE === type && r.NAT && r.NAT !== 'ALL' && String(r.ENTITY_NAME ?? '') === entity);
if (nat === 'ALL' && list.length === 1 && list[0].KEY === 'ALL' && split.length > 1) list = split.map((r) => ({ ...r, KEY: r.NAT }));
const items = list
.map((r) => {
const code = String(r.KEY ?? '');
return { label: STAKEHOLDER_IDS[code] ? label(STAKEHOLDER_IDS[code]) : label(code), value: Number(r.CNT ?? 0), code: STAKEHOLDER_IDS[code] ?? code };
})
.sort((a, b) => b.value - a.value);
return {
key: k,
title: [entity && label(entity), label(type)].filter(Boolean).join(' — '),
kind: items.length <= PIE_MAX_SLICES ? ('pie' as const) : ('bars' as const),
order: i,
items,
};
});
return { nats, blocks };
}

View File

@ -0,0 +1,58 @@
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import {
Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle,
} from '@mui/material';
import FileDownloadOutlined from '@mui/icons-material/FileDownloadOutlined';
import { useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
import { downloadReport, requestReport } from '../../api/report';
import type { Filter, SearchField } from '../search/filters';
/** Excel export of exactly what the list shows: it sends the same filter the grid is using. */
export function ExportButton({
entity, fields, filter, total,
}: { entity: string; fields: SearchField[]; filter: Filter; total: number | null }) {
const ui = useUi();
const notify = useNotify();
const [confirm, setConfirm] = useState(false);
const run = useMutation({
meta: { loading: 'exporting' },
mutationFn: async () => {
const { message, file } = await requestReport(entity, fields.map((f) => f.id), filter);
notify.success(message, ui('exportReady'));
await downloadReport(file);
},
onError: (e) => notify.error(e),
});
const filtered = Object.keys(filter).length > 0;
return (
<>
<Button
variant="outlined"
startIcon={run.isPending ? <CircularProgress size={16} /> : <FileDownloadOutlined />}
disabled={run.isPending || total === 0}
onClick={() => setConfirm(true)}
>
{run.isPending ? ui('exporting') : ui('exportExcel')}
</Button>
<Dialog open={confirm} onClose={() => setConfirm(false)}>
<DialogTitle>{ui('exportTitle')}</DialogTitle>
<DialogContent>
<DialogContentText>
{total !== null && <strong>{total.toLocaleString()} {ui('records')}</strong>}
{total !== null && ' — '}
{ui('exportBody')}
{!filtered && <><br />{ui('exportAll')}</>}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setConfirm(false)}>{ui('cancel')}</Button>
<Button variant="contained" onClick={() => { setConfirm(false); run.mutate(); }}>{ui('exportExcel')}</Button>
</DialogActions>
</Dialog>
</>
);
}

View File

@ -0,0 +1,129 @@
import { useRef, useState, type DragEvent } from 'react';
import { Alert, Box, Button, CircularProgress, IconButton, Link, Stack, Typography } from '@mui/material';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import DeleteIcon from '@mui/icons-material/Delete';
import { useT } from '../../i18n';
import {
ACCEPT_ATTR, attachmentUrl, checkFile, uploadAttachment, type PendingFile, type StoredAttachment,
} from '../../api/attachments';
const isImage = (a: StoredAttachment) => /\.(png|jpe?g|webp|bmp)$/i.test(a.FILE_NAME.trim());
/** One attachment slot (legacy: one Dropzone). It holds a stored file, a pending upload, or neither. */
export function AttachmentField(props: {
field: string;
label: string;
required: boolean;
error?: string;
readOnly?: boolean;
stored?: StoredAttachment;
baseUrl: string;
maxMb: number;
pending?: PendingFile;
onPending: (p: PendingFile | undefined) => void;
onDeleteStored?: (a: StoredAttachment) => void;
}) {
const { field, label, required, error, readOnly, stored, baseUrl, maxMb, pending, onPending, onDeleteStored } = props;
const t = useT();
const input = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState('');
const [over, setOver] = useState(false);
const [broken, setBroken] = useState(false);
const pick = async (file?: File) => {
if (!file) return;
const bad = checkFile(file, maxMb);
if (bad) return setErr(t(bad));
setErr('');
setBusy(true);
try {
onPending({ fileType: field, file: await uploadAttachment(file), name: file.name });
} catch (e) {
setErr(t(e instanceof Error ? e.message : 'UPLOAD_ATTACHMENT_ERROR'));
} finally {
setBusy(false);
if (input.current) input.current.value = '';
}
};
const onDrop = (e: DragEvent) => {
e.preventDefault();
setOver(false);
if (!readOnly) void pick(e.dataTransfer.files[0]);
};
const shown = pending ? null : stored;
const problem = err || error;
return (
<Box
onDragOver={(e) => { e.preventDefault(); setOver(true); }}
onDragLeave={() => setOver(false)}
onDrop={onDrop}
sx={{
border: '2px dashed',
borderColor: problem ? 'error.main' : over ? 'primary.main' : 'divider',
borderRadius: 2,
p: 1.5,
minHeight: 130,
bgcolor: over ? 'action.selected' : 'action.hover',
}}
>
<Typography variant="body2" fontWeight={600} sx={{ mb: 1 }}>
{label}
{required ? ' *' : ''}
</Typography>
{shown && (
<Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1 }}>
{isImage(shown) && !broken ? (
<Link href={attachmentUrl(baseUrl, shown)} target="_blank" rel="noopener noreferrer">
<Box
component="img"
src={attachmentUrl(baseUrl, shown)}
alt={label}
onError={() => setBroken(true)}
sx={{ height: 64, borderRadius: 1, display: 'block' }}
/>
</Link>
) : (
<Link href={attachmentUrl(baseUrl, shown)} target="_blank" rel="noopener noreferrer" noWrap>
{shown.FILE_NAME.trim()}
</Link>
)}
{!readOnly && onDeleteStored && (
<IconButton size="small" color="error" onClick={() => onDeleteStored(shown)} aria-label={t('DELETE')}>
<DeleteIcon fontSize="small" />
</IconButton>
)}
</Stack>
)}
{pending && (
<Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1 }}>
<Typography variant="body2" noWrap sx={{ flex: 1 }}>{pending.name}</Typography>
<IconButton size="small" color="error" onClick={() => onPending(undefined)} aria-label={t('DELETE')}>
<DeleteIcon fontSize="small" />
</IconButton>
</Stack>
)}
{!readOnly && (
<>
<input ref={input} hidden type="file" accept={ACCEPT_ATTR} onChange={(e) => void pick(e.target.files?.[0])} />
<Button
size="small"
variant="outlined"
startIcon={busy ? <CircularProgress size={14} /> : <UploadFileIcon />}
disabled={busy}
onClick={() => input.current?.click()}
>
{shown || pending ? t('CHANGE') : t('ADD')}
</Button>
</>
)}
{problem && <Alert severity="error" sx={{ mt: 1, py: 0 }}>{problem}</Alert>}
</Box>
);
}

View File

@ -0,0 +1,608 @@
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { SectionTitle, sectionFrame } from '../../components/SectionTitle';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Alert, Autocomplete, Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent,
Avatar, DialogTitle, FormControlLabel, Paper, Stack, Tab, Tabs, TextField, createFilterOptions,
} from '@mui/material';
import { useAuth } from '../../auth/AuthContext';
import { useLabel, useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
import { ApiError, rpc, type Envelope } from '../../api/client';
import { getExtraFields, getView, runAction, type ExtraSpec, type Option } from '../../api/entity';
import { fetchRecaptchaSiteKey } from '../../api/session';
import { useRecaptcha } from '../../auth/recaptcha';
import { fromInputDate, resolveFields, toDisplayDate, toInputDate, toPayload, type Mode, type ResolvedField } from './fields';
import { CREATE_HIDDEN, EDIT_HIDDEN_SECTIONS, FLEET_ENTITIES, HIDDEN_CREATE_TITLES, NON_OMANI_ONLY, getLayout, type DynamicLookup } from './layouts';
import { AttachmentField } from './AttachmentField';
import { DateField } from '../../components/DateField';
import { ExtraFieldsDialog } from './ExtraFieldsDialog';
import { deleteAttachment, type PendingFile, type StoredAttachment } from '../../api/attachments';
type Values = Record<string, unknown>;
const PROFILE_SECTIONS = [
{ title: 'MAININFO', fields: ['NAME', 'EMAIL', 'LOGIN', 'MOBILE', 'AREA_CODE', 'JOB_TITLE', 'LAST_LOGIN_DATE'] },
{ title: 'SETTING', fields: ['LANGUAGE'] },
];
/** Scroll a field into view and focus its input (fields are wrapped with data-field=NAME). */
function focusField(name: string) {
requestAnimationFrame(() => {
const el = document.querySelector<HTMLElement>(`[data-field="${name}"]`);
el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
el?.querySelector<HTMLElement>('input, textarea')?.focus({ preventScroll: true });
});
}
// Plate codes follow the document nationality: Omani ('OMN') picks from a dropdown (`select`), any other
// nationality types the code as free text (`text`). Legacy flips the same pair on every one of these pages.
const PLATE_NATIONALITY_FIELDS = ['LICENCE_NATIONALITY', 'FLEET_NATIONALITY', 'FLEET_NATIONALITY_CODE', 'TRUCK_NATIONALITY', 'NATIONALITY_CODE'];
const PLATE_RULES: { select: string; text: string; nat?: string[] }[] = [
{ select: 'FLEET_PLATE_CODE', text: 'PLATE_CODE_AR' }, // fleet pages, blacklists, RFID tags, violations, fleet request (truck)
{ select: 'FLEET_PLATE_CODE', text: 'PLATE_CODE' }, // trouble shooting
{ select: 'PLATE_CODE', text: 'PLATE_CODE_AR', nat: ['TRUCK_NATIONALITY'] }, // rented truck
{ select: 'FLEET_PLATE_CODE', text: 'FLEET_PLATE_CODE_AR' }, // visitors permits
{ select: 'TRAILER_PLATE_CODE', text: 'TRAILER_PLATE_CODE_AR' }, // fleet request (trailer)
];
// fleet pages: "the vehicle belongs to the stakeholder" tick box. Ticked, the owner is the stakeholder itself (the
// backend fills the details in), so those fields are locked and the personal document row is hidden.
const OWNER_LOCKED = ['OWNER_NAME', 'NATIONALITY_CODE', 'GOVERNORATE_CODE', 'STATE_CODE', 'CITY_CODE', 'ADDRESS'];
const OWNER_DOC = ['PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER', 'NATIONALITY_LICENCE'];
const PLATE_CODE_NAMES = /(^|_)(FLEET_)?PLATE_CODE(_AR)?$/;
const NUMBER_WITH_AREA = new Set(['PHONE_NUMBER', 'FAX_NUMBER', 'MOBILE_NUMBER']);
const NAME_PARTS = ['FIRST_NAME', 'FATHER_NAME', 'GRANDFATHER_NAME', 'FAMILY_NAME'];
/**
* Like the legacy pages: a phone/fax/mobile number and its area code share one cell, and a person's
* name parts sit together in one row, instead of each field taking a grid cell of its own.
*/
function groupFields(list: ResolvedField[]): { kind: 'one' | 'pair' | 'names'; fields: ResolvedField[] }[] {
const out: { kind: 'one' | 'pair' | 'names'; fields: ResolvedField[] }[] = [];
for (let i = 0; i < list.length; i++) {
const f = list[i];
if (NAME_PARTS.includes(f.name)) {
let j = i;
while (j < list.length && NAME_PARTS.includes(list[j].name)) j++;
if (j - i > 1) {
out.push({ kind: 'names', fields: list.slice(i, j) });
i = j - 1;
continue;
}
}
const next = list[i + 1];
if (NUMBER_WITH_AREA.has(f.name) && next && /AREA_CODE$/.test(next.name)) {
out.push({ kind: 'pair', fields: [f, next] });
i++;
continue;
}
// a plate number and its plate code share one cell, number first, as on the legacy fleet pages
if (/(^|_)PLATE_NUMBER$/.test(f.name) && next && PLATE_CODE_NAMES.test(next.name)) {
out.push({ kind: 'pair', fields: [f, next] });
i++;
continue;
}
out.push({ kind: 'one', fields: [f] });
}
return out;
}
// Lists such as the 8k stakeholders would freeze a plain select; show at most 100 matches.
const filter = createFilterOptions<Option>({ limit: 100 });
function FieldInput(props: {
field: ResolvedField;
value: unknown;
onChange: (v: unknown) => void;
error?: string;
dynamic?: DynamicLookup;
parentValue?: string;
alsoValue?: string;
/** a dropdown the new UI has no data source for yet */
unavailable?: boolean;
}) {
const { field, value, onChange, error, dynamic, parentValue, alsoValue, unavailable } = props;
const t = useT();
const ui = useUi();
const lab = useLabel();
const label = `${lab(field.caption)}${field.required ? ' *' : ''}`;
const dyn = useQuery({
queryKey: ['lookup', field.name, parentValue, alsoValue],
queryFn: () => dynamic!.load(parentValue!, alsoValue),
enabled: !!dynamic && !!parentValue,
staleTime: 5 * 60_000,
});
const options = dynamic ? (dyn.data ?? []) : (field.options ?? []);
const text = (o: Option) => o.NAME || t(o.CAPTION_CODE ?? String(o.CODE));
if (field.type === 'DROPDOWN' || field.type === 'DROPDOWN_MULTI') {
const multi = field.type === 'DROPDOWN_MULTI';
const byCode = (c: unknown) => options.find((o) => String(o.CODE) === String(c)) ?? null;
return (
<Autocomplete<Option, boolean>
multiple={multi}
fullWidth
options={options}
loading={dyn.isFetching}
disabled={field.readOnly || unavailable || (!!dynamic && !parentValue)}
filterOptions={filter}
getOptionLabel={text}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
value={multi ? ((Array.isArray(value) ? value : []).map(byCode).filter(Boolean) as Option[]) : byCode(value)}
onChange={(_, v) =>
onChange(multi ? (v as Option[]).map((o) => String(o.CODE)) : v ? String((v as Option).CODE) : '')
}
renderInput={(p) => (
<TextField
{...p}
label={label}
error={!!error}
helperText={error ?? (unavailable ? ui('notAvailableYet') : undefined)}
slotProps={{
input: {
...p.InputProps,
endAdornment: (
<>
{dyn.isFetching && <CircularProgress size={16} />}
{p.InputProps.endAdornment}
</>
),
},
}}
/>
)}
/>
);
}
if (field.type === 'DATE') {
return (
<DateField
label={label}
fullWidth
value={toInputDate(value)}
onChange={(iso) => onChange(fromInputDate(iso))}
disabled={field.readOnly}
error={!!error}
helperText={error}
/>
);
}
return (
<TextField
label={label}
fullWidth
value={String(value ?? '')}
onChange={(e) => onChange(e.target.value)}
disabled={field.readOnly}
error={!!error}
helperText={error}
slotProps={{ htmlInput: { maxLength: field.maxLength } }}
/>
);
}
/**
* `publicMode` runs this same form for the unauthenticated self-registration pages: it adds the
* reCAPTCHA + terms gate the legacy `Register == 'Yes'` flag used to add, tags the record
* CREATION_SOURCE=external so the backend runs its applicant/approval flow, and reports success to the
* caller instead of navigating to a grid the visitor cannot see.
*/
export function EntityForm({
entity, id, initialValues, publicMode, onPublicSuccess,
}: {
entity: string;
id?: string;
initialValues?: Values;
publicMode?: boolean;
onPublicSuccess?: (res: Envelope) => void;
}) {
const { config, lang, user } = useAuth();
const t = useT();
const ui = useUi();
const notify = useNotify();
const nav = useNavigate();
const qc = useQueryClient();
const lab = useLabel();
// My profile (legacy: the user page opened for oneself): Main info and Settings as tabs, login and job title locked
const [search] = useSearchParams();
const profile = entity === 'USERS' && !!id && search.get('profile') === '1';
const [profileTab, setProfileTab] = useState(0);
const baseLayout = useMemo(() => getLayout(entity, config), [entity, config]);
const layout = useMemo(
() => (profile && baseLayout ? { ...baseLayout, sections: PROFILE_SECTIONS } : baseLayout),
[profile, baseLayout],
);
const profileLocked = (n: string) => profile && (n === 'JOB_TITLE' || (n === 'LOGIN' && user?.role_code !== 'NAFITH'));
const mode: Mode = id ? 'EDIT' : 'CREATE';
const [extraSpec, setExtraSpec] = useState<ExtraSpec | null>(null);
const [agree, setAgree] = useState(false);
const captcha = useRecaptcha(!!publicMode && mode === 'CREATE', lang, fetchRecaptchaSiteKey);
const view = useQuery({ queryKey: ['view', entity, id], queryFn: () => getView(entity, id!), enabled: !!id, staleTime: 0 });
const [values, setValues] = useState<Values>(() => initialValues ?? {});
const [errors, setErrors] = useState<Record<string, string>>({});
const [confirm, setConfirm] = useState(false);
const [pending, setPending] = useState<Record<string, PendingFile>>({});
const [toDelete, setToDelete] = useState<StoredAttachment | null>(null);
const sysVar = (name: string) =>
(config?.SYSTEM_VARIABLES as { NAME: string; VALUE: string }[] | undefined)?.find((v) => v.NAME === name)?.VALUE;
const baseUrl = sysVar('ATTACHMENT_URL') ?? '';
const maxMb = Number(sysVar('MAXFILESIZE')) || 8;
const stored = (view.data?.data.ATTACHMENTS as StoredAttachment[] | undefined) ?? [];
const storedFor = (field: string) => stored.find((a) => a.FILE_BUSINESS_TYPE.trim() === field);
useEffect(() => {
if (!view.data) return;
const d = view.data.data;
const aliased = Object.fromEntries(Object.entries(layout?.alias ?? {}).map(([f, src]) => [f, d[src]]));
setValues({ ...d, ...aliased });
}, [view.data, layout]);
const status = view.data ? String(view.data.data.STATUS_CODE ?? '').trim() : undefined;
const fieldNames = useMemo(() => layout?.sections.flatMap((s) => s.fields) ?? [], [layout]);
const fields = useMemo(
() => (config && layout ? resolveFields(config, entity, mode, status, fieldNames) : []),
[config, layout, entity, mode, status, fieldNames],
);
const byName = useMemo(() => new Map(fields.map((f) => [f.name, f])), [fields]);
// fleet entities (trucks, trailers, equipment, buses, cars): the plate-code field is driven by
// the chosen nationality, same as the legacy pages — Omani ('OMN') shows FLEET_PLATE_CODE (a
// dropdown), any other nationality shows PLATE_CODE_AR (free text) instead.
// The same rule applies wherever a form carries a dropdown/text pair of plate codes (truck or trailer),
// whatever the form calls the nationality field.
const plateRules = useMemo(
() =>
PLATE_RULES.flatMap((r) => {
const nat = PLATE_NATIONALITY_FIELDS.find((n) => fieldNames.includes(n) && (!r.nat || r.nat.includes(n)));
return nat && fieldNames.includes(r.select) && fieldNames.includes(r.text) ? [{ ...r, nat }] : [];
}),
[fieldNames],
);
const isPlateField = (name: string) => plateRules.some((r) => r.select === name || r.text === name);
// A trailer plate with no dropdown/text pair of its own (trouble shooting) follows the truck's rule:
// Omani -> a dropdown of the same plate codes, otherwise it stays the free-text field it is.
const trailerPlateAsSelect = (f: ResolvedField) => {
if (f.name !== 'TRAILER_PLATE_CODE' || fieldNames.includes('TRAILER_PLATE_CODE_AR')) return false;
const rule = plateRules.find((r) => r.select === 'FLEET_PLATE_CODE');
return !!rule && !!byName.get('FLEET_PLATE_CODE')?.options?.length && String(values[rule.nat] ?? '').trim().toUpperCase() === 'OMN';
};
const plateHidden = (name: string) =>
plateRules.some((r) => {
const omani = String(values[r.nat] ?? '').trim().toUpperCase() === 'OMN';
return (name === r.select && !omani) || (name === r.text && omani);
});
// system-filled fields (ticket no, gate, creation date…) that legacy only shows once the record exists
// passport details only apply to non-Omani nationalities (legacy hides them for Omanis and while none is chosen)
const nonOmaniOnly = NON_OMANI_ONLY[entity];
const nationality = nonOmaniOnly ? String(values[nonOmaniOnly.nationality] ?? '').trim().toUpperCase() : '';
const isNonOmani = !!nationality && nationality !== 'OMN';
// the Riyada card tick box (driver-owner) is only offered to the operations office, like the old page
const riyadaRole = entity === 'OWNERS' && user?.role_code === 'OPOFF';
const riyadaChecked = values.RIYADA_CARD_HOLDER === true || values.RIYADA_CARD_HOLDER === 1 || ['1', 'YES', 'true'].includes(String(values.RIYADA_CARD_HOLDER));
const ownerToggle = FLEET_ENTITIES.includes(entity) && fieldNames.includes('OWNER_NAME');
const stakeholderIsInvestor = String(values.RELATED_ENTITY_ID ?? '').trim() === '7';
const ownerRaw = values.IS_OWNER;
const isOwner =
ownerToggle &&
(stakeholderIsInvestor ||
(ownerRaw === undefined || ownerRaw === '' || ownerRaw === null ? mode === 'CREATE' : ownerRaw === true || ['YES', 'TRUE'].includes(String(ownerRaw).trim().toUpperCase())));
const ownerLocked = (name: string) => isOwner && OWNER_LOCKED.includes(name);
const formHidden = (name: string) =>
plateHidden(name) ||
(ownerToggle && (name === 'IS_OWNER' || (isOwner && OWNER_DOC.includes(name)))) ||
(mode === 'CREATE' && !!CREATE_HIDDEN[entity]?.includes(name)) ||
(mode === 'EDIT' && !!layout?.sections.some((s) => EDIT_HIDDEN_SECTIONS[entity]?.includes(s.title) && s.fields.includes(name))) ||
(!!nonOmaniOnly?.fields.includes(name) && !isNonOmani) ||
(entity === 'OWNERS' && name === 'OWNER_RIYADAH_CARD_HOLDER_DOC' && !riyadaRole);
// fields that become mandatory because of what was chosen
const conditionallyRequired = (name: string) =>
(!!nonOmaniOnly?.fields.includes(name) && isNonOmani && !(nonOmaniOnly.notRequiredWith && String(values[nonOmaniOnly.notRequiredWith] ?? '').trim() && name !== nonOmaniOnly.attachment)) ||
(name === 'OWNER_RIYADAH_CARD_HOLDER_DOC' && riyadaChecked);
const stakeholderKey = `${values.RELATED_ENTITY_ID ?? ''}_${values.RELATED_ENTITY_RECORD_ID ?? ''}`;
const fillOwner = async () => {
try {
let info: Record<string, unknown> | undefined;
if (user?.role_group === 'NAFITH') {
if (!values.RELATED_ENTITY_ID || !values.RELATED_ENTITY_RECORD_ID) return;
const r = await rpc<Record<string, unknown>>(entity, 'GETINFO', { data: { RELATED_ENTITY_ID: values.RELATED_ENTITY_ID, RELATED_ENTITY_RECORD_ID: values.RELATED_ENTITY_RECORD_ID } });
info = { OWNER_NAME: r.NAME, NATIONALITY_CODE: r.NATIONALITY_CODE, GOVERNORATE_CODE: r.GOVERNORATE_CODE, STATE_CODE: r.STATE_CODE, CITY_CODE: r.CITY_CODE, ADDRESS: r.ADDRESS };
} else if (user) {
info = { OWNER_NAME: user.name, NATIONALITY_CODE: user.nationality_code, GOVERNORATE_CODE: user.stakeholdergoverneratecode, STATE_CODE: user.stakeholderstatecode, CITY_CODE: user.stakeholdercitycode, ADDRESS: user.stakeholderaddress };
}
if (info) setValues((cur) => ({ ...cur, ...info }));
} catch {
/* the backend fills the owner in on save anyway */
}
};
useEffect(() => {
if (isOwner && mode === 'CREATE') void fillOwner();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOwner, mode, stakeholderKey]);
const toggleOwner = (checked: boolean) => {
setValues((cur) => {
const next: Values = { ...cur, IS_OWNER: checked ? 'YES' : 'NO' };
// unticked: the owner is somebody else, so start those details empty (as the old page did)
if (!checked) for (const k of [...OWNER_LOCKED, ...OWNER_DOC]) next[k] = '';
return next;
});
if (checked) void fillOwner();
};
const action = mode === 'CREATE' ? 'CREATE' : 'UPDATE';
const allowed = publicMode
? true
: mode === 'CREATE'
? !!config?.AUTHORITY.some((a) => a.ENTITY_NAME === entity && a.ACTION_NAME === 'CREATE')
: !!view.data?.actions.some((a) => a.ACTION_NAME === 'UPDATE');
const set = (name: string, v: unknown) => {
setValues((cur) => {
const next = { ...cur, [name]: v };
// changing a parent dropdown invalidates every field that depends on it
// (and, in turn, whatever depends on those)
const cleared = [name];
for (let i = 0; i < cleared.length; i++) {
for (const [child, d] of Object.entries(layout?.dynamic ?? {})) {
if ((d.dependsOn === cleared[i] || d.alsoOn === cleared[i]) && !cleared.includes(child)) {
next[child] = '';
cleared.push(child);
}
}
}
return next;
});
setErrors((e) => ({ ...e, [name]: '' }));
};
const validate = () => {
const errs: Record<string, string> = {};
for (const f of fields) {
if (f.type === 'ATTACHMENT') {
if ((f.required || conditionallyRequired(f.name)) && !f.hidden && !f.readOnly && !formHidden(f.name) && !pending[f.name] && !storedFor(f.name)) errs[f.name] = t('MUST_ATTACH_FILE');
continue;
}
if (f.hidden || f.readOnly || formHidden(f.name) || ownerLocked(f.name)) continue;
const v = values[f.name];
const empty = v === undefined || v === null || v === '' || (Array.isArray(v) && !v.length);
// whichever of the plate-code pair is showing is the one that must be filled
const required = isPlateField(f.name) || conditionallyRequired(f.name) ? true : f.required;
if (required && empty) errs[f.name] = t('REQUIRED_FIELD');
else if (!empty && f.regex && typeof v === 'string') {
// date patterns are written for the display format dd/mm/yyyy, values are stored as yyyymmdd
const s = f.type === 'DATE' ? toDisplayDate(v) : v;
if (!f.regex.test(s)) errs[f.name] = t(f.errorCode || 'INVALID_VALUE');
}
}
setErrors(errs);
const first = Object.keys(errs)[0];
if (first) focusField(first);
return !first;
};
const save = useMutation({
meta: { loading: 'saving' },
mutationFn: (reason?: Record<string, string>) => {
const data = toPayload(fields.filter((f) => !formHidden(f.name)), values);
// the old form always posted the tick box as true/false
if (entity === 'OWNERS') data.RIYADA_CARD_HOLDER = riyadaChecked;
if (ownerToggle) data.IS_OWNER = isOwner ? 'YES' : 'NO';
if (publicMode) data['g-recaptcha-response'] = captcha.token;
return runAction(entity, action, data, id, Object.values(pending), reason, publicMode ? 'external' : 'internal');
},
onSuccess: (res) => {
if (publicMode) {
onPublicSuccess?.(res);
return;
}
notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
void qc.invalidateQueries({ queryKey: ['grid', entity] });
nav(profile ? '/' : `/e/${entity}/grid`);
},
onError: (e) => {
setExtraSpec(null);
captcha.reset();
// a business rule can point at the offending field (DATA.HTMLID): mark it and bring it into view
if (e instanceof ApiError && e.field && byName.has(e.field)) {
setErrors((cur) => ({ ...cur, [e.field!]: t(e.message) }));
focusField(e.field);
}
notify.error(e);
},
});
const remove = useMutation({
meta: { loading: 'processing' },
mutationFn: (a: StoredAttachment) => deleteAttachment(entity, a, stored),
onSuccess: (res) => {
notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
setToDelete(null);
void view.refetch();
},
onError: (e) => notify.error(e),
});
// some actions ask for a reason first; the backend says so per action
const startSave = async () => {
try {
const spec = await getExtraFields(entity, action);
if (spec) setExtraSpec(spec);
else save.mutate(undefined);
} catch (e) {
notify.error(e);
}
};
if (!layout) return <Alert severity="info">{lab(entity)}</Alert>;
if (id && view.isPending) return <CircularProgress />;
if (view.error) return <Alert severity="error">{t((view.error as Error).message)}</Alert>;
// a required dropdown with no data source cannot be filled here, so saving would always be rejected
const unavailable = (f: ResolvedField) =>
(f.type === 'DROPDOWN' || f.type === 'DROPDOWN_MULTI') && !f.options?.length && !layout.dynamic?.[f.name];
const blocked = fields.some((f) => !f.hidden && !f.readOnly && !formHidden(f.name) && f.required && unavailable(f));
return (
<Stack spacing={1.5} component="form" onSubmit={(e) => { e.preventDefault(); if (validate()) setConfirm(true); }}>
{profile && (
<Tabs value={profileTab} onChange={(_, v: number) => setProfileTab(v)} sx={{ borderBottom: 1, borderColor: 'divider' }}>
{layout.sections.map((s) => <Tab key={s.title} label={lab(s.title)} />)}
</Tabs>
)}
{layout.sections.map((s, sectionIndex) => {
const visible = s.fields
.map((n) => byName.get(n))
.filter((f): f is ResolvedField => !!f && !f.hidden && !formHidden(f.name))
.map((f) => (isPlateField(f.name) || conditionallyRequired(f.name) ? { ...f, required: true } : f))
.map((f) => (ownerLocked(f.name) || profileLocked(f.name) ? { ...f, readOnly: true } : f))
.map((f) => (trailerPlateAsSelect(f) ? { ...f, type: 'DROPDOWN', options: byName.get('FLEET_PLATE_CODE')!.options } : f));
if (!visible.length) return null;
if (profile && sectionIndex !== profileTab) return null;
const renderField = (f: ResolvedField) => {
const dynamic = layout.dynamic?.[f.name];
const wrap = (node: ReactNode) => <Box key={f.name} data-field={f.name} sx={{ minWidth: 0 }}>{node}</Box>;
if (f.type === 'ATTACHMENT') {
return wrap(
<AttachmentField
key={f.name}
field={f.name}
label={lab(f.caption)}
required={f.required}
readOnly={f.readOnly}
error={errors[f.name]}
stored={storedFor(f.name)}
baseUrl={baseUrl}
maxMb={maxMb}
pending={pending[f.name]}
onPending={(p) => {
setPending((cur) => {
const next = { ...cur };
if (p) next[f.name] = p;
else delete next[f.name];
return next;
});
setErrors((e) => ({ ...e, [f.name]: '' }));
}}
onDeleteStored={id ? setToDelete : undefined}
/>,
);
}
return wrap(
<FieldInput
key={f.name}
field={f}
value={values[f.name]}
onChange={(v) => set(f.name, v)}
error={errors[f.name]}
dynamic={dynamic}
parentValue={dynamic ? String(values[dynamic.dependsOn] ?? '') : undefined}
alsoValue={dynamic?.alsoOn ? String(values[dynamic.alsoOn] ?? '') : undefined}
unavailable={unavailable(f)}
/>,
);
};
return (
<Paper key={s.title} variant="outlined" sx={{ p: 2, ...sectionFrame }}>
{profile && sectionIndex === 0 && (
<Avatar sx={{ width: 72, height: 72, mb: 1.5, bgcolor: 'primary.main', fontSize: 30 }}>{String(values.NAME ?? '').trim().slice(0, 1).toUpperCase()}</Avatar>
)}
{!profile && !(mode === 'CREATE' && HIDDEN_CREATE_TITLES[entity] === s.title) && (
<SectionTitle view code={s.title}>{lab(s.title)}</SectionTitle>
)}
{ownerToggle && s.fields.includes('OWNER_NAME') && (
<FormControlLabel
sx={{ mb: 1, display: 'flex' }}
control={<Checkbox checked={isOwner} disabled={stakeholderIsInvestor} onChange={(e) => toggleOwner(e.target.checked)} />}
label={(() => {
// the caption names the kind of stakeholder, then its name — as the old page's label did
const key = ({ '7': 'FLEET_NOTE_INVESTOR', '12': 'FLEET_NOTE_OTHERSTAKEHOLDERS', '11': 'FLEET_NOTE_COMPANIES', '10': 'FLEET_NOTE_OWNER' } as Record<string, string>)[String(values.RELATED_ENTITY_ID ?? '').trim()] ?? 'FLEET_NOTE';
const name = isOwner && values.OWNER_NAME ? ` ${String(values.OWNER_NAME)}` : '';
return `${t(key) !== key ? t(key) : ui('fleetOwnerNote')}${name}`;
})()}
/>
)}
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{groupFields(visible).map((g) =>
g.kind === 'pair' ? (
<Box key={g.fields[0].name} sx={{ display: 'flex', gap: 1, alignItems: 'flex-start', minWidth: 0 }}>
<Box sx={{ flex: 2, minWidth: 0 }}>{renderField(g.fields[0])}</Box>
<Box sx={{ flex: 1, minWidth: 0 }}>{renderField(g.fields[1])}</Box>
</Box>
) : g.kind === 'names' ? (
<Box
key={g.fields[0].name}
sx={{ gridColumn: '1 / -1', display: 'grid', gap: 1.5, gridTemplateColumns: { xs: 'repeat(2, 1fr)', md: `repeat(${g.fields.length}, 1fr)` } }}
>
{g.fields.map(renderField)}
</Box>
) : (
renderField(g.fields[0])
),
)}
</Box>
{riyadaRole && sectionIndex === 0 && (
<FormControlLabel
sx={{ mt: 1 }}
control={<Checkbox checked={riyadaChecked} onChange={(e) => set('RIYADA_CARD_HOLDER', e.target.checked)} />}
label={lab('RIYADA_CARD_HOLDER')}
/>
)}
</Paper>
);
})}
{blocked && <Alert severity="warning">{ui('blockedForm')}</Alert>}
{publicMode && (
<Paper variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<Box ref={captcha.ref} sx={{ mb: 1.5 }} />
<FormControlLabel
control={<Checkbox checked={agree} onChange={(e) => setAgree(e.target.checked)} />}
label={ui('agreeToTerms')}
/>
</Paper>
)}
<Stack direction="row" spacing={1}>
<Button
type="submit"
variant="contained"
disabled={!allowed || blocked || save.isPending || (!!publicMode && (!agree || !captcha.token))}
>
{t(action)}
</Button>
{!publicMode && <Button onClick={() => nav(profile ? '/' : `/e/${entity}/grid`)}>{t('BACK')}</Button>}
</Stack>
<Dialog open={!!toDelete} onClose={() => setToDelete(null)}>
<DialogTitle>{t('DELETE_CONFIRM_MSG')}</DialogTitle>
<DialogContent>{remove.error && <Alert severity="error">{t((remove.error as Error).message)}</Alert>}</DialogContent>
<DialogActions>
<Button onClick={() => setToDelete(null)}>{t('NO')}</Button>
<Button color="error" variant="contained" disabled={remove.isPending} onClick={() => toDelete && remove.mutate(toDelete)}>
{t('YES')}
</Button>
</DialogActions>
</Dialog>
<Dialog open={confirm} onClose={() => setConfirm(false)}>
<DialogTitle>{t('CONFIRM_MSG')}</DialogTitle>
<DialogContent />
<DialogActions>
<Button onClick={() => setConfirm(false)}>{t('NO')}</Button>
<Button variant="contained" onClick={() => { setConfirm(false); void startSave(); }}>{t('YES')}</Button>
</DialogActions>
</Dialog>
{extraSpec && (
<ExtraFieldsDialog spec={extraSpec} title={t(action)} onCancel={() => setExtraSpec(null)} onSubmit={(reason) => save.mutate(reason)} />
)}
</Stack>
);
}

View File

@ -0,0 +1,58 @@
import { useState } from 'react';
import {
Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField,
} from '@mui/material';
import { useT, useUi } from '../../i18n';
import type { ExtraSpec } from '../../api/entity';
/** The reason / remarks popup some actions require, built from the backend's description of it. */
export function ExtraFieldsDialog({
spec, title, onSubmit, onCancel,
}: { spec: ExtraSpec; title: string; onSubmit: (values: Record<string, string>) => void; onCancel: () => void }) {
const t = useT();
const ui = useUi();
const [values, setValues] = useState<Record<string, string>>({});
const [errors, setErrors] = useState<Record<string, boolean>>({});
const submit = () => {
const bad = Object.fromEntries(spec.fields.filter((f) => f.required && !values[f.name]?.trim()).map((f) => [f.name, true]));
setErrors(bad);
if (!Object.keys(bad).length) onSubmit(Object.fromEntries(spec.fields.map((f) => [f.name, values[f.name] ?? ''])));
};
return (
<Dialog open onClose={onCancel} fullWidth maxWidth="xs">
<DialogTitle>{spec.title ? (t(spec.title) !== spec.title || !/^[A-Z0-9_.]+$/.test(spec.title) ? t(spec.title) : title) : title}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ pt: 1 }}>
{spec.fields.map((f) => (
<TextField
key={f.name}
fullWidth
select={f.kind === 'select'}
multiline={f.kind === 'textarea'}
minRows={f.kind === 'textarea' ? 3 : undefined}
label={`${f.label}${f.required ? ' *' : ''}`}
value={values[f.name] ?? ''}
onChange={(e) => {
setValues((v) => ({ ...v, [f.name]: e.target.value }));
setErrors((x) => ({ ...x, [f.name]: false }));
}}
error={!!errors[f.name]}
helperText={errors[f.name] ? t('REQUIRED_FIELD') : undefined}
slotProps={{ htmlInput: { maxLength: f.maxLength } }}
>
{f.options?.map((o) => (
<MenuItem key={o.value} value={o.value}>{o.label}</MenuItem>
))}
</TextField>
))}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onCancel}>{ui('cancel')}</Button>
<Button variant="contained" onClick={submit}>{t('YES')}</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,102 @@
import type { AppConfig, FieldMeta } from '../../api/config';
import type { Option } from '../../api/entity';
import { fleetOptions } from '../../api/fleetLookups';
export type Mode = 'CREATE' | 'EDIT';
/** The config rows carry optional per-action / per-status overrides and static dropdown values. */
interface Row extends FieldMeta {
ACTION_TYPE?: string;
ENTITY_STATUS_CODE?: string;
FIELD_PROPERTY?: string;
DDL_VALUES?: Option[];
}
export interface ResolvedField {
name: string;
type: string;
caption: string;
required: boolean;
readOnly: boolean;
hidden: boolean;
maxLength?: number;
regex?: RegExp;
errorCode?: string;
options?: Option[];
}
/**
* Collapse every config row for a field into one definition for the given mode and status.
* More specific rows (matching action and/or status) win for FIELD_PROPERTY; REQUIRED is
* true if any applicable row requires it; everything else comes from the first non-empty row.
*/
export function resolveFields(
config: AppConfig,
entity: string,
mode: Mode,
status: string | undefined,
names: string[],
): ResolvedField[] {
const rows = (config.ROLE_FIELD_STATUS_AUTHORITY_VIEW as Row[]).filter((r) => r.ENTITY_NAME === entity);
return names.flatMap((name) => {
const all = rows.filter((r) => r.FIELD_NAME === name);
if (!all.length) return [];
const applicable = all
.filter((r) => (!r.ACTION_TYPE || r.ACTION_TYPE === mode) && (!r.ENTITY_STATUS_CODE || r.ENTITY_STATUS_CODE === status))
.map((r) => ({ r, score: (r.ACTION_TYPE ? 1 : 0) + (r.ENTITY_STATUS_CODE ? 2 : 0) }))
.sort((a, b) => b.score - a.score)
.map((x) => x.r);
const pool = applicable.length ? applicable : all;
const first = <K extends keyof Row>(k: K) => pool.map((r) => r[k]).find((v) => v !== undefined && v !== '');
const prop = pool.map((r) => r.FIELD_PROPERTY).find((v) => v);
const rx = first('REGEX') as string | undefined;
let regex: RegExp | undefined;
try {
regex = rx ? new RegExp(rx) : undefined;
} catch {
regex = undefined;
}
const len = Number(first('FIELD_LENGTH'));
return [
{
name,
type: String(first('FIELD_TYPE') ?? 'TEXT'),
caption: /^TRAILER_PLATE_CODE(_AR|_EN)?$/.test(name) && first('FIELD_CAPTION_CODE') === 'PLATE_CODE' ? 'TRAILER_PLATE_CODE' : String(first('FIELD_CAPTION_CODE') ?? name),
required: pool.some((r) => r.REQUIRED === 'REQUIRED' || r.REQUIRED === 1),
readOnly: prop === 'READONLY',
hidden: prop === 'HIDE',
maxLength: len > 0 ? len : undefined,
regex,
errorCode: first('PUBLIC_ERROR_CODE') as string | undefined,
options: fleetOptions(entity, name) ?? (first('DDL_VALUES') as Option[] | undefined),
} satisfies ResolvedField,
];
});
}
/**
* Field values -> the `data` object the backend expects: hidden fields and attachments are left out,
* dates are trimmed to yyyymmdd (the backend returns yyyymmddHHMMSS but wants 8 digits back).
*/
export function toPayload(fields: ResolvedField[], values: Record<string, unknown>): Record<string, unknown> {
const data: Record<string, unknown> = {};
for (const f of fields) {
if (f.hidden || f.type === 'ATTACHMENT') continue;
// the old form posted every field it showed, empty ones included, and some actions read them unconditionally
// ("Element FIRST_REGISTRATION_DATE is undefined in DATA")
const v = f.name in values ? values[f.name] : '';
data[f.name] = f.type === 'DATE' && v ? String(v).replace(/\D/g, '').slice(0, 8) : v;
}
return data;
}
/** Backend dates are yyyymmdd[HHMMSS]; <input type="date"> wants yyyy-mm-dd. */
export const toInputDate = (v: unknown) => {
const s = String(v ?? '').replace(/\D/g, '');
return s.length >= 8 ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : '';
};
export const toDisplayDate = (v: unknown) => {
const s = String(v ?? '').replace(/\D/g, '');
return s.length >= 8 ? `${s.slice(6, 8)}/${s.slice(4, 6)}/${s.slice(0, 4)}` : String(v ?? '');
};
export const fromInputDate = (v: string) => v.replace(/-/g, '');

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,235 @@
import { rpc } from '../../api/client';
import { getOptions, type Option } from '../../api/entity';
import type { AppConfig } from '../../api/config';
import generatedLayouts from './generated-layouts.json';
export interface Section {
title: string;
fields: string[];
}
/** A dropdown whose options depend on other fields and come from a CONFIG lookup. */
export interface DynamicLookup {
dependsOn: string;
/** a second field the lookup needs (e.g. the stakeholder type next to the stakeholder record) */
alsoOn?: string;
load: (parent: string, also?: string) => Promise<Option[]>;
}
export interface EntityLayout {
sections: Section[];
dynamic?: Record<string, DynamicLookup>;
/** form field -> key in the getView payload, where the backend names them differently */
alias?: Record<string, string>;
/** read-only pages: show this getView key instead of looking a dynamic dropdown up */
viewText?: Record<string, string>;
}
const STAKEHOLDER_NAMES: Record<string, string> = {
'7': 'INVESTORS',
'10': 'OWNERS',
'11': 'COMPANIES',
'12': 'OTHER_STAKEHOLDERS',
};
export const layouts: Record<string, EntityLayout> = {
USERS: {
sections: [
{
title: 'USERS_INFO',
fields: ['LOGIN', 'NAME', 'EMAIL', 'MOBILE', 'AREA_CODE', 'JOB_TITLE', 'LANGUAGE', 'STATUS_CODE', 'LOCATION_IDS', 'LAST_LOGIN_DATE'],
},
],
},
TRUCKS: {
sections: [
// License info leads, with the document nationality first in it: that picks whether FLEET_PLATE_CODE (Omani,
// dropdown) or PLATE_CODE_AR (other nationalities, free text) is the active plate-code field — see EntityForm's plate toggle.
// "Truck Info" and "Vehicle" are merged into one group, as requested.
{ title: 'LICENSEINFO', fields: ['LICENCE_NATIONALITY', 'LICENSE_EXPIRY_FROM', 'LICENSE_EXPIRY_TO', 'FIRST_REGISTRATION_DATE', 'LICENSE_AUTHORITY', 'OPERATING_CARD_NO', 'CARD_EXPIRY_DATE'] },
{ title: 'TRUCKS_INFO', fields: ['PLATE_NUMBER', 'FLEET_PLATE_CODE', 'PLATE_CODE_AR', 'PLATE_TYPE_CODE', 'TRUCK_TYPE', 'USE_DESCRIPTION', 'STATUS_CODE', 'VEHICLE_TYPE', 'COLOR_CODE', 'SUBCOLOR', 'ORIGIN_COUNTRY_CODE', 'MODEL_YEAR', 'MANUFACTURING_YEAR', 'ENGINE_CAPACITY', 'EMPTY_WEIGHT', 'EXTREME_CAPACITY', 'PASSENGER_NUMBER', 'AXES_NUMBER', 'CHASSES_NUMBER', 'ENGINE_NUMBER'] },
{ title: 'OWNERINFO', fields: ['RELATED_ENTITY_ID', 'RELATED_ENTITY_RECORD_ID', 'LOCATION_IDS', 'OWNER_NAME', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER', 'NATIONALITY_LICENCE'] },
{ title: 'INSURANCEINFO', fields: ['INSURANCE_DOCUMENT_NUMBER', 'INSURANCE_TYPE', 'INSURANCE_COMPANY'] },
{ title: 'ADDRESS', fields: ['GOVERNORATE_CODE', 'STATE_CODE', 'CITY_CODE', 'ADDRESS', 'NATIONALITY_CODE', 'NOTES'] },
{ title: 'ATTACHMENTS', fields: ['TRUCK_LICENSE_FRONT', 'TRUCK_LICENSE_BACK', 'OWNER_LICENSE_FRONT', 'OWNER_LICENSE_BACK', 'AUTHORIZATION', 'CARD_EXPIRY_FRONT', 'CARD_EXPIRY_BACK'] },
],
alias: { FLEET_PLATE_CODE: 'PLATE_CODE_EN' },
viewText: { RELATED_ENTITY_RECORD_ID: 'OWNER_NAME' },
dynamic: {
STATE_CODE: { dependsOn: 'GOVERNORATE_CODE', load: (g) => getOptions('getLT_STATES', { GOVERNORATE_CODE: g }) },
CITY_CODE: { dependsOn: 'STATE_CODE', load: (s) => getOptions('getLT_CITY', { STATE_CODE: s }) },
RELATED_ENTITY_RECORD_ID: {
dependsOn: 'RELATED_ENTITY_ID',
load: (id) =>
STAKEHOLDER_NAMES[id]
? getOptions('getStakeHoldersList', { STAKEHOLDER_ID: id, STAKEHOLDER_NAME: STAKEHOLDER_NAMES[id] })
: Promise.resolve([]),
},
},
},
};
/** The vehicle modules: they share the plate-code rule and the "vehicle belongs to the stakeholder" owner tick box. */
export const FLEET_ENTITIES = ['TRUCKS', 'TRAILERS', 'EQUIPMENTS', 'BUSES', 'CARS'];
/** Fields the backend fills in itself: legacy hides them on the create page and shows them once the record exists. */
export const CREATE_HIDDEN: Record<string, string[]> = {
TROUBLE_SHOOTING: ['TS_NUMBER', 'GATE_ID', 'CREATION_DATE', 'PERMIT_NUMBER', 'PERMIT_STATUS_CODE'],
VIOLATIONS: ['TOTAL_SAME_REASON'],
// the "Employee info" / "Driver info" groups hold only backend-required extras the legacy create page never showed
PERSONNEL: ['ADDRESS', 'RESIDENCE_TYPE'],
// a new truck has no status yet; the backend sets it
TRUCKS: ['STATUS_CODE'],
// the old create pages hide the operation number: the system assigns it when the plan is saved
SCHEDULING_PLAN: ['OPERATION_NUMBER'],
WAITING_PLAN: ['OPERATION_NUMBER'],
OWNERS: ['PHONE_NUMBER', 'FAX_NUMBER', 'BILLING_ADDRESS'],
// the "Service provider info" group is backend-required extras the legacy create page never showed
OTHER_STAKEHOLDERS: ['CLASSIFICATION', 'SECONDARY_EMAIL', 'BILLING_ADDRESS', 'MANAGER_NAME'],
COMPLAINTS_SUGGESTIONS: ['REPLY'],
// a new ticket: no reply box, and none of the sender details or the support-side attachments (the system fills the
// sender in; the old page showed those two groups only to the Nafith side)
TICKETS: ['REPLY', 'TICKET_NUMBER', 'ENTITY_NAME', 'USER_TYPE', 'STAKEHOLDER_NAME', 'MOBILE_NUMBER', 'AREA_CODE', 'LOCATION_IDS', 'OPOFF_ATT_NO_1', 'OPOFF_ATT_NO_2', 'OPOFF_ATT_NO_3'],
};
/** Groups left out of the edit form (the record keeps its values; nothing in them is asked again). */
export const EDIT_HIDDEN_SECTIONS: Record<string, string[]> = { COMPANIES: ['COMPANIES_INFO'] };
/** Whole groups the legacy record page does not show (driver info; investor capacity and investor info). */
export const VIEW_HIDDEN_SECTIONS: Record<string, string[]> = {
OWNERS: ['OWNERS_INFO'],
INVESTORS: ['CAPACITYINFO', 'INVESTORS_INFO'],
OTHER_STAKEHOLDERS: ['OTHER_STAKEHOLDERS_INFO'],
FREEZONE_DEPOSITORS: ['FREEZONE_DEPOSITORS_INFO'],
COMPANIES: ['COMPANIES_INFO'],
// the reply box is a popup here; the answers are listed in their own table
TICKETS: ['ADD_REPLY'],
};
/** Fields that only apply to a non-Omani nationality (passport details), and the nationality field that decides it. */
export const NON_OMANI_ONLY: Record<string, { nationality: string; fields: string[]; attachment: string; notRequiredWith?: string }> = {
// legacy: a national number (NN) typed in makes the passport number/expiry optional
PERSONNEL: { nationality: 'NATIONALITY_CODE', fields: ['PASSPORT_NUMBER', 'PASSPORT_EXPIRY_DATE', 'PASSPORT_NOT_OMANI'], attachment: 'PASSPORT_NOT_OMANI', notRequiredWith: 'NN' },
};
/** Sections whose heading is left out of the create form (the fields stay). */
export const HIDDEN_CREATE_TITLES: Record<string, string> = { BLACKLISTS: 'BLACKLISTSINFO' };
export const hasLayout =(entity: string) => entity in layouts;
// ---------------------------------------------------------------------------------------------
// Every other module: the layout is generated from the legacy pages (scripts/gen-layouts.mjs) and
// completed from the backend's own field metadata. Hand-written layouts above win where they exist.
// ---------------------------------------------------------------------------------------------
const generated = generatedLayouts as Record<string, { title: string; fields: string[] }[]>;
const cache = new WeakMap<AppConfig, Map<string, EntityLayout | null>>();
type Row = { ENTITY_NAME: string; FIELD_NAME: string; FIELD_TYPE: string; REQUIRED?: string | number; DDL_VALUES?: Option[] };
/** The backend names some fields differently in the record it returns than in the form's metadata. */
const ENTITY_ALIAS: Record<string, Record<string, string>> = { POS_TRANSACTIONS: { RECEIPT_AMOUNT: 'AMOUNT' } };
/** A group that belongs right after another one (its title, then the title it follows). */
const SECTION_AFTER: Record<string, [string, string]> = { PERMITS: ['TRUCKS_INFO', 'PERMITS_INFO'] };
/** Fields the record page does not show, and fields it puts last in their group. */
export const VIEW_HIDDEN_FIELDS: Record<string, string[]> = { DEPOSITS: ['RECEIPT_ID'] };
export const VIEW_LAST_FIELDS: Record<string, string[]> = { DEPOSITS: ['NOTES'] };
/** Heading of the group that holds an entity's extra backend-required fields, when "<ENTITY>_INFO" would read wrongly. */
const EXTRA_TITLE: Record<string, string> = { PERMITS: 'TRUCKS_INFO' };
/** The layout of an entity, or undefined when neither the legacy page nor the backend know any fields. */
export function getLayout(entity: string, config: AppConfig | undefined): EntityLayout | undefined {
if (!config) return undefined;
let perConfig = cache.get(config);
if (!perConfig) cache.set(config, (perConfig = new Map()));
if (perConfig.has(entity)) return perConfig.get(entity) ?? undefined;
const built = build(entity, config);
perConfig.set(entity, built ?? null);
return built;
}
function build(entity: string, config: AppConfig): EntityLayout | undefined {
const rows = (config.ROLE_FIELD_STATUS_AUTHORITY_VIEW as unknown as Row[]).filter((r) => r.ENTITY_NAME === entity);
const known = new Map<string, Row[]>();
for (const r of rows) known.set(r.FIELD_NAME, [...(known.get(r.FIELD_NAME) ?? []), r]);
if (!known.size && !layouts[entity]) return undefined;
const hand = layouts[entity];
let sections: Section[];
if (hand) sections = hand.sections;
else {
// legacy page order first, then any required field the page did not mention
sections = (generated[entity] ?? []).map((s) => ({ title: s.title, fields: s.fields.filter((f) => known.has(f)) })).filter((s) => s.fields.length);
const placed = new Set(sections.flatMap((s) => s.fields));
const extra = [...known.keys()].filter((n) => !placed.has(n) && known.get(n)!.some((r) => r.REQUIRED === 'REQUIRED'));
if (!sections.length) sections = [{ title: `${entity}_INFO`, fields: [...known.keys()] }];
else if (extra.length) sections.push({ title: EXTRA_TITLE[entity] ?? `${entity}_INFO`, fields: extra });
}
// fleet entities (trucks, trailers, equipment, buses, cars): the document nationality sits in License info, the
// first group, and drives which plate-code field shows (see EntityForm's plate toggle)
const names = new Set(sections.flatMap((s) => s.fields));
const options = (n: string) => known.get(n)?.find((r) => r.DDL_VALUES?.length)?.DDL_VALUES ?? [];
// FLEET_PLATE_CODE is the form's name for the field; the backend's own view returns it as PLATE_CODE_EN
const alias: Record<string, string> = { ...(hand?.alias ?? {}), ...(ENTITY_ALIAS[entity] ?? {}) };
const after = SECTION_AFTER[entity];
if (after) {
const from = sections.findIndex((s) => s.title === after[0]);
if (from > 0) {
const [moved] = sections.splice(from, 1);
sections.splice(sections.findIndex((s) => s.title === after[1]) + 1, 0, moved);
}
}
if (names.has('FLEET_PLATE_CODE') && !alias.FLEET_PLATE_CODE) alias.FLEET_PLATE_CODE = 'PLATE_CODE_EN';
const dynamic: Record<string, DynamicLookup> = { ...(hand?.dynamic ?? {}) };
// owner / stakeholder pickers: <X>_RECORD_ID is filled from the type chosen in <X>_ID
for (const n of names) {
if (dynamic[n] || !n.endsWith('_RECORD_ID') || options(n).length) continue;
const twin = n.replace(/_RECORD_ID$/, '_ID');
const kinds = options(twin);
if (!names.has(twin) || !kinds.length) continue;
dynamic[n] = {
dependsOn: twin,
load: (id) => {
const kind = kinds.find((o) => String(o.CODE) === id)?.CAPTION_CODE;
return kind ? getOptions('getStakeHoldersList', { STAKEHOLDER_ID: id, STAKEHOLDER_NAME: kind }) : Promise.resolve([]);
},
};
}
// governorate -> state -> city
if (names.has('GOVERNORATE_CODE') && names.has('STATE_CODE') && !dynamic.STATE_CODE) {
dynamic.STATE_CODE = { dependsOn: 'GOVERNORATE_CODE', load: (g) => getOptions('getLT_STATES', { GOVERNORATE_CODE: g }) };
}
if (names.has('STATE_CODE') && names.has('CITY_CODE') && !dynamic.CITY_CODE) {
dynamic.CITY_CODE = { dependsOn: 'STATE_CODE', load: (s) => getOptions('getLT_CITY', { STATE_CODE: s }) };
}
// pickers the legacy pages filled by hand with their own backend calls
for (const [field, lookup] of Object.entries(ENTITY_LOOKUPS[entity] ?? {})) {
if (names.has(field) && !dynamic[field]) dynamic[field] = lookup;
}
return { ...hand, sections, dynamic, alias };
}
const ENTITY_LOOKUPS: Record<string, Record<string, DynamicLookup>> = {
// investors that hold the chosen industrial area
RENTED_TRUCK: {
INVESTOR_RECORD_ID: { dependsOn: 'LOCATION_IDS', load: (loc) => getOptions('getInvestorsInLocation', { locationId: loc }) },
},
// the user's own trucks that are not already affiliated to the chosen receiver ("<entity id>_<record id>")
AFFILIATION: {
TRUCK_ID: {
dependsOn: 'RECEIVER_RELATED_ENTITY_RECORD_ID',
alsoOn: 'RECEIVER_RELATED_ENTITY_ID',
load: (record, kind) =>
rpc<Option[]>('AFFILIATION', 'getTrucksID', {
DATA: { RELATED_ENTITY_ID: kind ?? '', RELATED_ENTITY_RECORD_ID: record, ID: 0, TRUCK_ID: 0 },
}),
},
},
};

View File

@ -0,0 +1,156 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import DOMPurify from 'dompurify';
import {
Alert, Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Radio, RadioGroup, Stack,
TextField, Typography,
} from '@mui/material';
import { useAuth } from '../../auth/AuthContext';
import { ApiError, rpc, type Envelope } from '../../api/client';
import { validateReceipt } from '../../api/packages';
import { useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
const ENTITY = 'FLEET_PENDING_FINANCIAL_TRANSACTIONS';
/** the payment gateway is a separate page of the old site: like the subscription wizard, card payment is not offered here */
const CARD_PAYMENT = 3;
const POS_PAYMENT = 6;
interface Summary {
VEHICLE_COUNT?: number;
HTML_CONTENT?: string;
TOTALPRICE?: number;
SUBSCRIPTIONDETAILSCARD?: string;
PAYMENTMETHODS?: { ID: number; NAME: string }[];
PACKAGE_ID?: number | string;
CODE?: unknown;
}
type Tx = Record<string, unknown>;
/**
* "Pay off debit balance" popup of the overdue charges: the order summary for the charge's package, the payment methods
* the role may use, and — for the Nafith side — the option to include the Nafith service fee.
*/
export function PendingPayDialog({ id, data, onClose, onDone }: { id: string; data: Tx; onClose: () => void; onDone: () => void }) {
const { user } = useAuth();
const t = useT();
const ui = useUi();
const notify = useNotify();
const nafith = user?.role_group === 'NAFITH';
const [withNafith, setWithNafith] = useState(false);
const [method, setMethod] = useState('');
const [receipt, setReceipt] = useState('');
const [error, setError] = useState('');
const summary = useQuery({
queryKey: ['pending-summary', id, withNafith],
queryFn: () =>
rpc<Summary>('CONFIG', 'getPendingFinTansactionsSummaryForNafith', {
package_id: withNafith ? data.NAFITH_PACKAGE_ID : data.STAKEHOLDER_PACKAGE_ID,
type: data.TYPE,
...(withNafith ? { includeNafithFee: true } : {}),
}),
staleTime: 0,
});
const s = summary.data;
const empty = !!s && s.VEHICLE_COUNT === 0;
const methods = s?.PAYMENTMETHODS ?? [];
const total = Number(s?.TOTALPRICE ?? 0);
// the cash-balance method is picked first, as in the old popup
useEffect(() => {
if (!methods.length) return setMethod('');
setMethod((m) => (m && methods.some((x) => String(x.ID) === m) ? m : methods.some((x) => x.ID === 1) ? '1' : ''));
}, [s]); // eslint-disable-line react-hooks/exhaustive-deps
const pay = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const params: Record<string, unknown> = { paymentMethodId: method, amount: total, depts_transcation_ids: id, POS_receipt_id: 0 };
if (method === String(POS_PAYMENT)) {
params.POS_receipt_id = receipt.trim();
const ok = await validateReceipt(receipt.trim(), total);
if (ok !== 'VALID') throw new ApiError(String(ok));
if (nafith) {
Object.assign(params, {
depts_transcation_ids: data.ID,
stakeholder_entity_id: data.STAKEHOLDER_ENTITY_ID,
stakeholder_entity_Record_id: data.STAKEHOLDER_ENTITY_RECORD_ID,
fleet_entity_id: data.FLEET_ENTITY_ID,
fleet_entity_record_id: data.FLEET_ENTITY_RECORD_ID,
plate_code_ar: data.PLATE_CODE_AR,
plate_code_en: data.PLATE_CODE_EN,
plate_number: data.PLATE_NUMBER,
stakeholder_crn: data.CRN,
permit_id: data.PERMIT_ID,
package_id: s?.PACKAGE_ID,
});
}
}
const r = await rpc<Envelope>(ENTITY, 'PAY', { data: params }, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE || r.MESSAGECODE || 'ACTION_FAILED'), r.CODE, r.DATA);
return r;
},
onSuccess: (r) => {
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
onDone();
},
onError: (e) => notify.error(e),
});
const submit = () => {
if (!method) return setError(t('PAYMENT_METHOD_NOT_SELECTED'));
if (method === String(POS_PAYMENT) && !receipt.trim()) return setError(t('PLEASE_ENTER_RECEIPT_NUMBER'));
setError('');
pay.mutate();
};
return (
<Dialog open onClose={() => !pay.isPending && onClose()} maxWidth="md">
<DialogTitle>{t('PAY_OFF_DEBIT_BALANCE')}</DialogTitle>
<DialogContent>
<Typography fontWeight={700} sx={{ mb: 1 }}>{t('ORDER_SUMMARY')}</Typography>
{nafith && (
<FormControlLabel
control={<Checkbox checked={withNafith} onChange={(e) => { setWithNafith(e.target.checked); setMethod(''); }} />}
label={t('INCLUDE_NAFDAP_SERVICE_LBL')}
/>
)}
{summary.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}><CircularProgress size={28} /></Box>}
{summary.error && <Alert severity="error">{t((summary.error as Error).message)}</Alert>}
{s && empty && (
<Box sx={{ textAlign: 'center', py: 3 }} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(s.HTML_CONTENT ?? '') }} />
)}
{s && !empty && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Box sx={{ '& .card': { border: 1, borderColor: 'divider', borderRadius: 1.5, p: 1.5 }, '& h4': { fontSize: 15, m: 0, mb: 1 }, '& h1': { fontSize: 20, m: 0 }, '& p': { m: 0, mb: 0.5 }, '& i': { display: 'none' } }}
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(s.SUBSCRIPTIONDETAILSCARD ?? '') }} />
<Box sx={{ border: 1, borderColor: 'divider', borderRadius: 1.5, p: 1.5 }}>
<Typography fontWeight={700} sx={{ mb: 0.5 }}>{t('PAYMENT_METHOD')}</Typography>
<RadioGroup value={method} onChange={(e) => setMethod(e.target.value)}>
{methods.map((m) => (
<Box key={m.ID}>
<FormControlLabel value={String(m.ID)} disabled={m.ID === CARD_PAYMENT} control={<Radio size="small" />} label={m.NAME} />
{m.ID === CARD_PAYMENT && <Typography variant="caption" color="text.secondary" sx={{ marginInlineStart: 4, display: 'block' }}>{ui('wizCardLater')}</Typography>}
{m.ID === POS_PAYMENT && method === String(POS_PAYMENT) && (
<TextField size="small" label={t('RECEIPT_NUMBER')} value={receipt} onChange={(e) => setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} />
)}
</Box>
))}
</RadioGroup>
</Box>
</Box>
)}
{error && <Alert severity="warning" sx={{ mt: 2 }} onClose={() => setError('')}>{error}</Alert>}
{pay.error && <Alert severity="error" sx={{ mt: 2 }}>{t((pay.error as Error).message)}</Alert>}
</DialogContent>
<DialogActions>
<Stack direction="row" spacing={1}>
<Button onClick={onClose} disabled={pay.isPending}>{t('CLOSE')}</Button>
<Button variant="contained" disabled={pay.isPending || !s || empty} onClick={submit}>{t('PAY')}</Button>
</Stack>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,133 @@
import { useEffect, useMemo, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import {
Alert, Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, TextField,
} from '@mui/material';
import { ApiError, rpc, type Envelope } from '../../api/client';
import { useT } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
import { DateField } from '../../components/DateField';
const ENTITY = 'FLEET_PENDING_FINANCIAL_TRANSACTIONS';
type Opt = { CODE: string | number; CAPTION_CODE?: string; NAME?: string };
interface Last {
ACTIVATE_RECEIVABLES?: boolean;
ACTIVATION_DATE?: string;
ACTIVATION_TIME?: string;
RECEIVABLES_START_DATE?: string;
STAKEHOLDER_IDS?: string;
INDUSTRIAL_STATE?: string | number;
SERVICE_CODE?: string;
}
const iso = (yyyymmdd?: string) => (/^\d{8}/.test(String(yyyymmdd ?? '')) ? `${yyyymmdd!.slice(0, 4)}-${yyyymmdd!.slice(4, 6)}-${yyyymmdd!.slice(6, 8)}` : '');
const TIME = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/;
/**
* Overdue charges settings (Nafith side): switch the receivables on and choose from when they apply. The estate, stakeholder
* types and service are shown but fixed, exactly as in the old popup, where those three boxes were always disabled.
*/
export function PendingSettingsDialog({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
const t = useT();
const notify = useNotify();
const last = useQuery({ queryKey: ['pending-last-settings'], queryFn: () => rpc<Last>(ENTITY, 'GET_LAST_SETTINGS', {}), staleTime: 0 });
const estates = useQuery({ queryKey: ['pending-estates'], queryFn: () => rpc<Opt[]>('CONFIG', 'getINDUSTRIAL_STATE', {}), staleTime: 300_000 });
const kinds = useQuery({ queryKey: ['pending-kinds'], queryFn: () => rpc<Opt[]>('CONFIG', 'fillRELATED_ENTITY_ID', {}), staleTime: 300_000 });
const services = useQuery({ queryKey: ['pending-services'], queryFn: () => rpc<Opt[]>('CONFIG', 'getLT_SERVICES', {}), staleTime: 300_000 });
const [active, setActive] = useState(false);
const [date, setDate] = useState('');
const [time, setTime] = useState('');
const [start, setStart] = useState('');
const [touched, setTouched] = useState(false);
useEffect(() => {
const d = last.data;
if (!d) return;
setActive(!!d.ACTIVATE_RECEIVABLES);
setDate(iso(d.ACTIVATION_DATE));
setTime(String(d.ACTIVATION_TIME ?? ''));
setStart(iso(d.RECEIVABLES_START_DATE));
}, [last.data]);
const name = (list: Opt[] | undefined, code: unknown) => {
const o = list?.find((x) => String(x.CODE) === String(code));
return o ? o.NAME || t(o.CAPTION_CODE ?? String(o.CODE)) : String(code ?? '');
};
const kindIds = useMemo(() => {
const raw = String(last.data?.STAKEHOLDER_IDS ?? '');
return raw === 'ALL' || !raw ? ['ALL'] : raw.split(',').map((x) => x.trim()).filter(Boolean);
}, [last.data]);
const bad = { date: !date, time: !TIME.test(time), start: !start };
const save = useMutation({
meta: { loading: 'saving' },
mutationFn: async () => {
const d = last.data!;
const data = {
INDUSTRIAL_STATE: d.INDUSTRIAL_STATE,
// the backend counts the chosen types and stores "ALL" when every one is picked
STAKEHOLDER_IDS: kindIds,
SERVICE_CODE: d.SERVICE_CODE,
ACTIVATION_DATE: date.replace(/-/g, ''),
ACTIVATION_TIME: time,
RECEIVABLES_START_DATE: start.replace(/-/g, ''),
ACTIVATE_RECEIVABLES: active,
};
const r = await rpc<Envelope>(ENTITY, 'SETTINGS', { ID: 0, data }, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE || r.MESSAGECODE || 'ACTION_FAILED'), r.CODE, r.DATA);
return r;
},
onSuccess: (r) => {
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), t('SAVE'));
onDone();
},
onError: (e) => notify.error(e),
});
const readOnly = (label: string, value: string) => <TextField size="small" fullWidth label={label} value={value} slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }} />;
const loading = last.isPending || estates.isPending || kinds.isPending || services.isPending;
return (
<Dialog open onClose={() => !save.isPending && onClose()}>
<DialogTitle>{t('PENDING_FINANCIAL_TRANSACTIONS_SETTINGS')}</DialogTitle>
<DialogContent>
{loading && <Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}><CircularProgress size={28} /></Box>}
{last.error && <Alert severity="error">{t((last.error as Error).message)}</Alert>}
{last.data && !loading && (
<Stack spacing={1.75} sx={{ pt: 1 }}>
{readOnly(t('INDUSTRIAL_ESTATE'), name(estates.data, last.data.INDUSTRIAL_STATE))}
{readOnly(t('RELATED_ENTITY_ID'), kindIds.map((k) => (k === 'ALL' ? t('ALL') : name(kinds.data, k))).join('، '))}
{readOnly(t('SERVICE_NAME'), name(services.data, last.data.SERVICE_CODE))}
<DateField label={t('ACTIVATION_DATE')} value={date} onChange={setDate} fullWidth error={touched && bad.date} />
<TextField
size="small"
fullWidth
label={t('ACTIVATION_TIME')}
placeholder="HH:mm"
value={time}
onChange={(e) => setTime(e.target.value)}
error={touched && bad.time}
helperText={touched && bad.time ? t('TIME_PATTERN_HINT') : undefined}
slotProps={{ htmlInput: { dir: 'ltr', maxLength: 5 }, inputLabel: { shrink: true } }}
/>
<DateField label={t('RECEIVABLES_START_DATE')} value={start} onChange={setStart} fullWidth error={touched && bad.start} />
<FormControlLabel control={<Checkbox checked={active} onChange={(e) => setActive(e.target.checked)} />} label={t('PENDING_FINANCIAL_TRANSACTIONS_SETTINGS')} />
</Stack>
)}
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={save.isPending}>{t('CLOSE')}</Button>
<Button
variant="contained"
disabled={save.isPending || !last.data}
onClick={() => {
setTouched(true);
if (!bad.date && !bad.time && !bad.start) save.mutate();
}}
>
{t('SAVE')}
</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,137 @@
import { useMemo, useRef, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import { useAuth } from '../../auth/AuthContext';
import { rpc, ApiError, type Envelope } from '../../api/client';
import { uploadAttachment } from '../../api/attachments';
import { useLabel, useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
import { DateField } from '../../components/DateField';
import { resolveFields } from '../forms/fields';
import type { Option } from '../../api/entity';
/**
* Legacy "Upload file" popup of the reconciliation screens: one file, uploaded first to the server's temporary folder,
* then handed to RECONCILIATION_UPLOAD_FILE. The point-of-sale reconciliation also asks for the date and industrial estate.
*/
export function ReconciliationUpload({ entity, onClose, onDone }: { entity: 'RECONCILIATION' | 'RECONCILIATION_POS'; onClose: () => void; onDone: () => void }) {
const { config } = useAuth();
const t = useT();
const lab = useLabel();
const ui = useUi();
const notify = useNotify();
const pos = entity === 'RECONCILIATION_POS';
const input = useRef<HTMLInputElement>(null);
const [file, setFile] = useState<File | null>(null);
const [date, setDate] = useState('');
const [location, setLocation] = useState('');
const [touched, setTouched] = useState(false);
const [fileError, setFileError] = useState('');
const fields = useMemo(
() => (config && pos ? resolveFields(config, entity, 'CREATE', undefined, ['RECONCILE_DATE', 'LOCATION_IDS']) : []),
[config, entity, pos],
);
// the point-of-sale form has no estate field of its own in the role's metadata: use the estate list the other screens carry
const locOptions = useMemo(
() => (config?.ROLE_FIELD_STATUS_AUTHORITY_VIEW as unknown as { FIELD_NAME: string; DDL_VALUES?: Option[] }[] | undefined)?.find((r) => r.FIELD_NAME === 'LOCATION_IDS' && r.DDL_VALUES?.length)?.DDL_VALUES ?? [],
[config],
);
const dateField = fields.find((f) => f.name === 'RECONCILE_DATE');
const upload = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const serverFile = await uploadAttachment(file!);
const sent = [{ file: serverFile, name: file!.name }];
const args = pos
? { RECONCILIATION_POSEXCEL: { RECONCILIATION_POSEXCEL: sent, RECONCILE_DATE: date.replace(/\D/g, ''), LOCATION_IDS: location } }
: { reconciliationExcel: { reconciliationExcel: sent } };
const r = await rpc<Envelope>(entity, 'RECONCILIATION_UPLOAD_FILE', args, { post: true });
// a rejected file can come back with an empty MESSAGE: fall through to the code, then to a plain "wrong file" text
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE || r.MESSAGECODE || (typeof r.DATA === 'string' ? r.DATA : '') || 'WRONG_FILE_UPLOADED'), r.CODE, r.DATA);
return r;
},
onSuccess: (r) => {
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
onDone();
},
onError: (e) => notify.warning('WRONG_FILE_UPLOADED', failText(e as Error)),
});
// never an empty alert: an unknown / blank message reads as "wrong file"
const failText = (e: Error) => {
const m = (e.message ?? '').trim();
const shown = m ? t(m) : '';
return shown && !/^[A-Z0-9_.]+$/.test(shown) ? shown : ui('wrongFileType');
};
const missing =!file || (pos && (!date || !location));
return (
<Dialog open onClose={onClose} fullWidth maxWidth="xs">
<DialogTitle>{t('UPLOAD_GENERAL_FILE')}</DialogTitle>
<DialogContent>
<Stack spacing={1.5} sx={{ pt: 0.5 }}>
{pos && (
<>
<DateField
label={lab(dateField?.caption ?? 'RECONCILE_DATE')}
value={date}
onChange={setDate}
error={touched && !date}
fullWidth
/>
<TextField
select
label={lab('INDUSTRIAL_ESTATE')}
value={location}
onChange={(e) => setLocation(e.target.value)}
error={touched && !location}
fullWidth
>
{locOptions.map((o) => (
<MenuItem key={String(o.CODE)} value={String(o.CODE)}>{o.NAME || t(o.CAPTION_CODE ?? String(o.CODE))}</MenuItem>
))}
</TextField>
</>
)}
<input ref={input} type="file" hidden accept=".csv,.xls,.xlsx" onChange={(e) => {
const f = e.target.files?.[0] ?? null;
e.target.value = '';
if (f && !/\.(csv|xls|xlsx)$/i.test(f.name)) {
setFile(null);
setFileError(ui('wrongFileType'));
notify.warning('WRONG_FILE_TYPE_ONLY_CSV_XLS', ui('wrongFileType'));
return;
}
setFileError('');
setFile(f);
}} />
<Box
onClick={() => input.current?.click()}
sx={{ border: 2, borderStyle: 'dashed', borderColor: touched && !file ? 'error.main' : 'divider', borderRadius: 2, p: 3, textAlign: 'center', cursor: 'pointer' }}
>
<UploadFileIcon color="primary" />
<Typography fontSize={14}>{file ? file.name : t('MUST_UPLOAD_FILE')}</Typography>
</Box>
{fileError && <Alert severity="error">{fileError}</Alert>}
{upload.error && <Alert severity="error">{failText(upload.error as Error)}</Alert>}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('CLOSE')}</Button>
<Button
variant="contained"
disabled={upload.isPending}
onClick={() => {
setTouched(true);
if (!missing) upload.mutate();
}}
>
{t('UPLOAD_GENERAL_FILE')}
</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,142 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import DOMPurify from 'dompurify';
import {
Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Radio, RadioGroup, TextField, Typography,
} from '@mui/material';
import { ApiError, rpc, type Envelope } from '../../api/client';
import { validateReceipt } from '../../api/packages';
import { useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
const CARD_PAYMENT = 3;
const POS_PAYMENT = 6;
export interface RenewParams {
serviceGroupCode: string;
pacakgeCode: string; // (sic) the backend's spelling
durationID: string | number;
fleetData: string;
subscriptionServiceID: string;
}
interface Summary {
TOTALPRICE?: number;
SUBSCRIPTIONDETAILSCARD?: string;
PAYMENTMETHODS?: { ID: number; NAME: string }[];
}
/**
* Renew an expired fleet subscription. The old page first asked the backend whether the subscription may be renewed
* (renewSubscriptionValidation), then showed the order summary and the payment methods, then sent RENEW_SUBSCRIPTION.
*/
export function RenewSubscriptionDialog({ params, onClose, onDone }: { params: RenewParams; onClose: () => void; onDone: () => void }) {
const t = useT();
const ui = useUi();
const notify = useNotify();
const nav = useNavigate();
const [method, setMethod] = useState('');
const [receipt, setReceipt] = useState('');
const [error, setError] = useState('');
const summary = useQuery({
queryKey: ['renew-summary', params.subscriptionServiceID],
queryFn: async () => {
// the same check the old "Renew subscription" button made before opening the popup
const v = await rpc<{ RESPONSE_CODE?: string; MESSAGE?: string }>('CONFIG', 'renewSubscriptionValidation', { data: params, id: params.subscriptionServiceID });
if (v.RESPONSE_CODE !== 'SUCCESS') throw new ApiError(String(v.MESSAGE || 'ACTION_FAILED'));
return rpc<Summary>('CONFIG', 'getSubscriptionSummary', params as unknown as Record<string, unknown>);
},
staleTime: 0,
retry: false,
});
const s = summary.data;
const methods = s?.PAYMENTMETHODS ?? [];
const total = Number(s?.TOTALPRICE ?? 0);
useEffect(() => {
setMethod((m) => (m && methods.some((x) => String(x.ID) === m) ? m : methods.some((x) => x.ID === 1) ? '1' : ''));
}, [s]); // eslint-disable-line react-hooks/exhaustive-deps
const renew = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
if (method === String(POS_PAYMENT)) {
const ok = await validateReceipt(receipt.trim(), total);
if (ok !== 'VALID') throw new ApiError(String(ok));
}
const data = {
packageCode: params.pacakgeCode,
packageGroupCode: params.serviceGroupCode,
fleetArray: JSON.stringify([params.fleetData]),
paymentMethod: method,
subscriptionDetailsType: 'MULTI_TRIP',
packageGroupType: 'OWNED_FLEET',
approval_number_id: 0,
receipt_id: method === String(POS_PAYMENT) ? receipt.trim() : 0,
};
return rpc<Envelope & { RECEIVABLES?: string; PAYMENT_METHOD?: string }>('SUBSCRIPTIONS', 'RENEW_SUBSCRIPTION', { data, id: params.subscriptionServiceID }, { post: true });
},
onSuccess: (r) => {
// unpaid overdue charges must be settled first: the old page sent the user to that list
if (r.RECEIVABLES === 'true') {
notify.warning(String(r.MESSAGE ?? 'ACTION_FAILED'));
onClose();
nav('/e/FLEET_PENDING_FINANCIAL_TRANSACTIONS/grid?STATUS_CODE=WAITING_PAY');
return;
}
if (String(r.CODE) !== '000') {
notify.error(new ApiError(String(r.MESSAGE || 'ACTION_FAILED'), r.CODE));
return;
}
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
onDone();
},
onError: (e) => notify.error(e),
});
const submit = () => {
if (!method) return setError(t('PAYMENT_METHOD_NOT_SELECTED'));
if (method === String(POS_PAYMENT) && !receipt.trim()) return setError(t('PLEASE_ENTER_RECEIPT_NUMBER'));
setError('');
renew.mutate();
};
return (
<Dialog open onClose={() => !renew.isPending && onClose()} maxWidth="md">
<DialogTitle>{t('RENEW_SUBSCRIPTION')}</DialogTitle>
<DialogContent>
<Typography fontWeight={700} sx={{ mb: 1 }}>{t('ORDER_SUMMARY')}</Typography>
{summary.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}><CircularProgress size={28} /></Box>}
{summary.error && <Alert severity="warning">{t((summary.error as Error).message)}</Alert>}
{s && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Box
sx={{ '& .card': { border: 1, borderColor: 'divider', borderRadius: 1.5, p: 1.5 }, '& h4': { fontSize: 15, m: 0, mb: 1 }, '& h1': { fontSize: 20, m: 0 }, '& p': { m: 0, mb: 0.5 }, '& i': { display: 'none' } }}
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(s.SUBSCRIPTIONDETAILSCARD ?? '') }}
/>
<Box sx={{ border: 1, borderColor: 'divider', borderRadius: 1.5, p: 1.5 }}>
<Typography fontWeight={700} sx={{ mb: 0.5 }}>{t('PAYMENT_METHOD')}</Typography>
<RadioGroup value={method} onChange={(e) => setMethod(e.target.value)}>
{methods.map((m) => (
<Box key={m.ID}>
<FormControlLabel value={String(m.ID)} disabled={m.ID === CARD_PAYMENT} control={<Radio size="small" />} label={m.NAME} />
{m.ID === CARD_PAYMENT && <Typography variant="caption" color="text.secondary" sx={{ marginInlineStart: 4, display: 'block' }}>{ui('wizCardLater')}</Typography>}
{m.ID === POS_PAYMENT && method === String(POS_PAYMENT) && (
<TextField size="small" label={t('RECEIPT_NUMBER')} value={receipt} onChange={(e) => setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} />
)}
</Box>
))}
</RadioGroup>
</Box>
</Box>
)}
{error && <Alert severity="warning" sx={{ mt: 2 }} onClose={() => setError('')}>{error}</Alert>}
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={renew.isPending}>{t('CLOSE')}</Button>
<Button variant="contained" disabled={renew.isPending || !s} onClick={submit}>{t('PAY')}</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,94 @@
import { useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material';
import { rpc, ApiError, type Envelope } from '../../api/client';
import { useLabel, useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
/** Legacy "Withdraw balance" popup: shows the customer's available balance and withdraws an amount from it. */
export function WithdrawDialog({ id, onClose, onDone }: { id: string; onClose: () => void; onDone: () => void }) {
const t = useT();
const lab = useLabel();
const ui = useUi();
const notify = useNotify();
const [amount, setAmount] = useState('');
const [type, setType] = useState('Cash');
const [reason, setReason] = useState('');
const [touched, setTouched] = useState(false);
const balance = useQuery({
queryKey: ['withdraw-balance', id],
queryFn: () => rpc<{ NAME?: string; AVAILABLE_BALANCE?: string }>('config', 'getCustomerBalance', { NEW_ID: 0, DATA: { NEW_ID: id, search_data: {} } }),
staleTime: 0,
});
const available = Number(String(balance.data?.AVAILABLE_BALANCE ?? '0').trim()) || 0;
const valid = /^\d+(\.\d+)?$/.test(amount.trim()) && Number(amount) > 0 && Number(amount) <= available && !!reason.trim();
const withdraw = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const r = await rpc<Envelope>('CUSTOMER_BALANCES', 'WITHDRAW_BALANCE', { AMOUNT: amount.trim(), TYPE: type, REASON: reason.trim(), CUSTOMER_ID: id }, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE ?? 'ACTION_FAILED'), r.CODE, r.DATA);
return r;
},
onSuccess: (r) => {
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
onDone();
},
onError: (e) => notify.error(e),
});
return (
<Dialog open onClose={onClose} fullWidth maxWidth="xs">
<DialogTitle>{t('WITHDRAW_BALANCE')}</DialogTitle>
<DialogContent>
<Stack spacing={1.5} sx={{ pt: 0.5 }}>
{balance.error && <Alert severity="error">{t((balance.error as Error).message)}</Alert>}
<div>
<Typography variant="caption" color="text.secondary">{lab('RELATED_ENTITY_RECORD_ID')}</Typography>
<Typography fontWeight={700}>{balance.data?.NAME ?? '…'}</Typography>
</div>
<div>
<Typography variant="caption" color="text.secondary">{lab('AVAILABLE_BALANCE')}</Typography>
<Typography fontWeight={700}>{balance.data ? `${available.toFixed(3)} ${t('RO')}` : '…'}</Typography>
</div>
<TextField
label={lab('WITHDRAWAL_AMOUNT')}
value={amount}
onChange={(e) => setAmount(e.target.value)}
inputProps={{ inputMode: 'decimal' }}
error={touched && !(Number(amount) > 0 && Number(amount) <= available)}
helperText={touched && !(Number(amount) > 0 && Number(amount) <= available) ? t('CANT_WITHDRAW_BALANCE') : ' '}
fullWidth
/>
<TextField select label={lab('WITHDRAWAL_TYPE')} value={type} onChange={(e) => setType(e.target.value)} fullWidth>
<MenuItem value="Cash">{t('CASH')}</MenuItem>
<MenuItem value="Bank Transfer">{t('BANK_TRANSFER')}</MenuItem>
</TextField>
<TextField
label={lab('NON_APPROVAL_NOTES')}
value={reason}
onChange={(e) => setReason(e.target.value)}
multiline
minRows={2}
error={touched && !reason.trim()}
fullWidth
/>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('BACK')}</Button>
<Button
variant="contained"
disabled={withdraw.isPending || balance.isPending || available <= 0}
onClick={() => {
setTouched(true);
if (valid) withdraw.mutate();
}}
>
{t('WITHDRAW_BALANCE')}
</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,195 @@
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
Alert, Autocomplete, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle,
IconButton, Stack, TextField, Typography,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { useT, useUi } from '../../i18n';
import { ApiError } from '../../api/client';
import { getOptions, type Option } from '../../api/entity';
import { OTP_FIELDS, sendVerificationCode, verifySms, type OtpEntity } from '../../api/register';
type Step = 'form' | 'code';
/**
* The mobile-OTP pre-check OWNERS and FREEZONE_CLEARING_COMPANIES require before the full sign-up
* form: verify a mobile number by SMS, then hand the verified values back as the form's prefill.
*/
export function OtpDialog({
entity, open, onClose, onVerified, onExisting,
}: {
entity: OtpEntity;
open: boolean;
onClose: () => void;
/** the full create form opens pre-filled with these values */
onVerified: (prefill: Record<string, string>) => void;
/** the backend found an existing (returned) application for this ID: open it for editing instead */
onExisting: (id: string) => void;
}) {
const t = useT();
const ui = useUi();
const map = OTP_FIELDS[entity];
const [step, setStep] = useState<Step>('form');
const [mobile, setMobile] = useState('');
const [areaCode, setAreaCode] = useState<Option | null>(null);
const [nationality, setNationality] = useState<Option | null>(null);
const [docType, setDocType] = useState<Option | null>(null);
const [cn, setCn] = useState('');
const [code, setCode] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (!open) return;
setStep('form');
setMobile('');
setAreaCode(null);
setNationality(null);
setDocType(null);
setCn('');
setCode('');
setError('');
}, [open]);
const areaCodes = useQuery({ queryKey: ['otp-area-codes'], queryFn: () => getOptions('getAreaCode', {}), enabled: open, staleTime: 5 * 60_000 });
const nationalities = useQuery({ queryKey: ['otp-nationalities'], queryFn: () => getOptions('getNATIONALITYCODE', {}), enabled: open, staleTime: 5 * 60_000 });
const docTypes = useQuery({ queryKey: ['otp-doc-types'], queryFn: () => getOptions('getPERSONAL_DOCUMENT_TYPE', {}), enabled: open, staleTime: 5 * 60_000 });
const optLabel = (o: Option) => o.NAME || t(o.CAPTION_CODE ?? String(o.CODE));
const buildData = (): Record<string, string> => {
const data: Record<string, string> = {
[map.mobile]: mobile.trim(),
[map.areaCode]: String(areaCode?.CODE ?? ''),
[map.nationality]: String(nationality?.CODE ?? ''),
[map.docType]: String(docType?.CODE ?? ''),
};
if (map.cn) data[map.cn] = cn.trim();
return data;
};
const formFilled = mobile.trim() && areaCode && nationality && docType && (!map.cn || cn.trim());
const send = async () => {
setBusy(true);
setError('');
try {
const res = await sendVerificationCode(entity, buildData());
if (String(res.CODE) === '000' || res.CODE === 0 || res.MESSAGE === 'SMS.VERIFICATION') {
setStep('code');
} else {
setError(t(String(res.MESSAGE ?? res.MESSAGECODE ?? 'ACTION_FAILED')));
}
} catch (e) {
setError(e instanceof ApiError ? t(e.message) : t('ACTION_FAILED'));
} finally {
setBusy(false);
}
};
const verify = async () => {
setBusy(true);
setError('');
try {
const res = await verifySms(entity, { ...buildData(), VERIFICATION_CODE: code.trim() });
const codeNum = Number(res.CODE);
if (codeNum === 1) {
// an existing application (e.g. RETURNED) for this ID: continue it instead of creating a new one
const data = res.DATA as { ID?: string } | undefined;
if (data?.ID) onExisting(data.ID);
else setError(t('ACTION_FAILED'));
} else if (String(res.CODE) === '000' || codeNum === 0) {
const data = (res.DATA as Record<string, string>) ?? buildData();
onVerified(data);
} else {
setError(t(String(res.MESSAGE ?? res.MESSAGECODE ?? 'INVALID_VERIFICATION_CODE')));
}
} catch (e) {
setError(e instanceof ApiError ? t(e.message) : t('ACTION_FAILED'));
} finally {
setBusy(false);
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
{ui('otpTitle')}
<IconButton size="small" onClick={onClose}>
<CloseIcon fontSize="small" />
</IconButton>
</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ pt: 0.5 }}>
{error && <Alert severity="error">{error}</Alert>}
{step === 'form' ? (
<>
{map.cn && <TextField label={ui('otpNationalId')} fullWidth value={cn} onChange={(e) => setCn(e.target.value)} required autoFocus />}
<Autocomplete
fullWidth
options={nationalities.data ?? []}
loading={nationalities.isFetching}
getOptionLabel={optLabel}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
value={nationality}
onChange={(_, v) => setNationality(v)}
renderInput={(p) => <TextField {...p} label={ui('otpNationality')} required />}
/>
<Autocomplete
fullWidth
options={docTypes.data ?? []}
loading={docTypes.isFetching}
getOptionLabel={optLabel}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
value={docType}
onChange={(_, v) => setDocType(v)}
renderInput={(p) => <TextField {...p} label={ui('otpDocType')} required />}
/>
<Stack direction="row" spacing={1}>
<Autocomplete
options={areaCodes.data ?? []}
loading={areaCodes.isFetching}
getOptionLabel={optLabel}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
value={areaCode}
onChange={(_, v) => setAreaCode(v)}
sx={{ width: 160 }}
renderInput={(p) => <TextField {...p} label={ui('otpAreaCode')} required />}
/>
<TextField label={ui('otpMobile')} value={mobile} onChange={(e) => setMobile(e.target.value)} required fullWidth />
</Stack>
</>
) : (
<>
<Typography variant="body2" color="text.secondary">{ui('otpCodeHint')}</Typography>
<TextField
label={ui('otpCode')}
fullWidth
value={code}
onChange={(e) => setCode(e.target.value)}
autoFocus
required
slotProps={{ htmlInput: { maxLength: 5 } }}
/>
<Button size="small" onClick={() => setStep('form')} sx={{ alignSelf: 'flex-start' }}>
{ui('otpChangeNumber')}
</Button>
</>
)}
</Stack>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5 }}>
<Button onClick={onClose}>{ui('cancel')}</Button>
{step === 'form' ? (
<Button variant="contained" disabled={busy || !formFilled} onClick={() => void send()}>
{busy ? <CircularProgress size={20} color="inherit" /> : ui('otpSend')}
</Button>
) : (
<Button variant="contained" disabled={busy || !code.trim()} onClick={() => void verify()}>
{busy ? <CircularProgress size={20} color="inherit" /> : ui('otpVerify')}
</Button>
)}
</DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,82 @@
import { useEffect, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { Box, Button, CircularProgress, Paper, Stack, Typography } from '@mui/material';
import ArrowBack from '@mui/icons-material/ArrowBack';
import CheckCircleOutline from '@mui/icons-material/CheckCircleOutline';
import { useAuth } from '../../auth/AuthContext';
import { useT, useUi } from '../../i18n';
import { Logo } from '../../components/Logo';
import { EntityForm } from '../forms/EntityForm';
interface LocationState {
/** values the mobile-OTP pre-check already verified (OWNERS / FREEZONE_CLEARING_COMPANIES) */
prefill?: Record<string, string>;
/** an existing (e.g. RETURNED) application the OTP step found for this applicant: edit it instead of creating */
id?: string;
}
export function RegisterEntityPage() {
const { entity = '' } = useParams();
const { state } = useLocation() as { state: LocationState | null };
const { beginRegistration, registerReady } = useAuth();
const t = useT();
const ui = useUi();
const nav = useNavigate();
const [done, setDone] = useState(false);
useEffect(() => {
beginRegistration();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<Box sx={{ minHeight: '100vh', bgcolor: 'background.default', py: { xs: 3, md: 6 }, px: 2 }}>
<Box sx={{ maxWidth: 900, mx: 'auto' }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 4 }}>
<Logo height={34} />
{!done && (
<Stack
direction="row"
spacing={0.5}
alignItems="center"
component="button"
onClick={() => nav('/register')}
sx={{ border: 0, bgcolor: 'transparent', cursor: 'pointer', color: 'primary.main', font: 'inherit' }}
>
<ArrowBack fontSize="small" className="flip-rtl" />
<Typography variant="body2" fontWeight={600}>{ui('back')}</Typography>
</Stack>
)}
</Stack>
{done ? (
<Paper variant="outlined" sx={{ p: 5, textAlign: 'center', borderRadius: 3 }}>
<CheckCircleOutline color="success" sx={{ fontSize: 56, mb: 2 }} />
<Typography variant="h5" fontWeight={800} sx={{ mb: 1.5 }}>{ui('registerSuccessTitle')}</Typography>
<Typography color="text.secondary" sx={{ maxWidth: 480, mx: 'auto', mb: 3 }}>{ui('registerSuccessBody')}</Typography>
<Button variant="contained" onClick={() => nav('/login')}>{ui('backToLogin')}</Button>
</Paper>
) : (
<>
<Typography variant="h5" fontWeight={800} sx={{ mb: 3 }}>{t(entity)}</Typography>
{registerReady ? (
<EntityForm
key={entity}
entity={entity}
id={state?.id}
initialValues={state?.prefill}
publicMode
onPublicSuccess={() => setDone(true)}
/>
) : (
<Stack alignItems="center" spacing={2} sx={{ py: 10 }}>
<CircularProgress />
<Typography color="text.secondary">{ui('registerLoading')}</Typography>
</Stack>
)}
</>
)}
</Box>
</Box>
);
}

View File

@ -0,0 +1,91 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, Card, CardActionArea, CardContent, Stack, Typography } from '@mui/material';
import ArrowBack from '@mui/icons-material/ArrowBack';
import BusinessOutlined from '@mui/icons-material/BusinessOutlined';
import BusinessCenterOutlined from '@mui/icons-material/BusinessCenterOutlined';
import GroupsOutlined from '@mui/icons-material/GroupsOutlined';
import PersonOutline from '@mui/icons-material/PersonOutline';
import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined';
import { useAuth } from '../../auth/AuthContext';
import { useT, useUi } from '../../i18n';
import { Logo } from '../../components/Logo';
import { OtpDialog } from './OtpDialog';
import type { OtpEntity } from '../../api/register';
const CARDS: { entity: string; icon: typeof BusinessOutlined; desc: 'registerCompaniesDesc' | 'registerInvestorsDesc' | 'registerOtherStakeholdersDesc' | 'registerOwnersDesc' | 'registerFreezoneDesc'; otp?: boolean }[] = [
{ entity: 'COMPANIES', icon: BusinessOutlined, desc: 'registerCompaniesDesc' },
{ entity: 'INVESTORS', icon: BusinessCenterOutlined, desc: 'registerInvestorsDesc' },
{ entity: 'OTHER_STAKEHOLDERS', icon: GroupsOutlined, desc: 'registerOtherStakeholdersDesc' },
{ entity: 'OWNERS', icon: PersonOutline, desc: 'registerOwnersDesc', otp: true },
{ entity: 'FREEZONE_CLEARING_COMPANIES', icon: LocalShippingOutlined, desc: 'registerFreezoneDesc', otp: true },
];
export function RegisterHub() {
const { beginRegistration } = useAuth();
const t = useT();
const ui = useUi();
const nav = useNavigate();
const [otpEntity, setOtpEntity] = useState<OtpEntity | null>(null);
useEffect(() => {
beginRegistration();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const pick = (entity: string, otp?: boolean) => {
if (otp) setOtpEntity(entity as OtpEntity);
else nav(`/register/${entity}`);
};
return (
<Box sx={{ minHeight: '100vh', bgcolor: 'background.default', py: { xs: 3, md: 6 }, px: 2 }}>
<Box sx={{ maxWidth: 980, mx: 'auto' }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 4 }}>
<Logo height={34} />
<Stack direction="row" spacing={0.5} alignItems="center" component="button" onClick={() => nav('/login')}
sx={{ border: 0, bgcolor: 'transparent', cursor: 'pointer', color: 'primary.main', font: 'inherit' }}
>
<ArrowBack fontSize="small" className="flip-rtl" />
<Typography variant="body2" fontWeight={600}>{ui('backToLogin')}</Typography>
</Stack>
</Stack>
<Typography variant="h4" fontWeight={800} sx={{ mb: 1 }}>{ui('registerHubTitle')}</Typography>
<Typography color="text.secondary" sx={{ mb: 4, maxWidth: 640 }}>{ui('registerHubSubtitle')}</Typography>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', md: 'repeat(3, 1fr)' } }}>
{CARDS.map(({ entity, icon: Icon, desc, otp }) => (
<Card key={entity} variant="outlined" sx={{ borderRadius: 3 }}>
<CardActionArea onClick={() => pick(entity, otp)} sx={{ height: '100%', p: 0.5 }}>
<CardContent>
<Icon color="primary" sx={{ fontSize: 34, mb: 1.5 }} />
<Typography fontWeight={700} sx={{ mb: 0.5 }}>{t(entity)}</Typography>
<Typography variant="body2" color="text.secondary">{ui(desc)}</Typography>
</CardContent>
</CardActionArea>
</Card>
))}
</Box>
</Box>
{otpEntity && (
<OtpDialog
entity={otpEntity}
open={!!otpEntity}
onClose={() => setOtpEntity(null)}
onVerified={(prefill) => {
const entity = otpEntity;
setOtpEntity(null);
nav(`/register/${entity}`, { state: { prefill } });
}}
onExisting={(id) => {
const entity = otpEntity;
setOtpEntity(null);
nav(`/register/${entity}`, { state: { id } });
}}
/>
)}
</Box>
);
}

View File

@ -0,0 +1,190 @@
import { useMemo, useState } from 'react';
import {
Autocomplete, Badge, Box, Button, Chip, Drawer, IconButton, Paper, Stack, TextField, Typography,
} from '@mui/material';
import TuneIcon from '@mui/icons-material/Tune';
import CloseIcon from '@mui/icons-material/Close';
import { useT, useUi } from '../../i18n';
import type { Option } from '../../api/entity';
import { DateField } from '../../components/DateField';
import { rangeParts, toRange, type Filter, type SearchField } from './filters';
import { DEPENDENT_SEARCH, childrenOf, useDependentOptions } from './dependent';
const toInput = (v: string) => (v.length === 8 ? `${v.slice(0, 4)}-${v.slice(4, 6)}-${v.slice(6, 8)}` : '');
const fromInput = (v: string) => v.replace(/-/g, '');
const display = (v: string) => (v.length === 8 ? `${v.slice(6, 8)}/${v.slice(4, 6)}/${v.slice(0, 4)}` : v);
/** Quick search + status chips + a filters drawer, all driven by the backend's search metadata. */
export function SearchPanel({ entity, fields, filter, onChange }: { entity: string; fields: SearchField[]; filter: Filter; onChange: (f: Filter) => void }) {
const t = useT();
const ui = useUi();
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState<Filter>(filter);
// drop lists the old grids filled from another field (stakeholder type -> subscriptions, fleet type -> classes…)
const depDraft = useDependentOptions(entity, draft);
const depApplied = useDependentOptions(entity, filter);
// changing a field empties the ones that were filled from it
const setWithChildren = (f: Filter, id: string, v: string): Filter => childrenOf(entity, id).reduce((acc, c) => setKey(acc, c, ''), setKey(f, id, v));
const status = fields.find((f) => f.id === 'STATUS_CODE' && f.type === 'DROPDOWN');
// some modules (financial grids especially) flag a date range as a default search field, same as
// the legacy grid does — it belongs in the always-visible row next to status, not buried in "Filters"
const quickDates = useMemo(() => fields.filter((f) => f.quick && f.type === 'DATE'), [fields]);
const advanced = useMemo(
// there is no separate quick-search box, so the backend's default text field (usually the plate number)
// is an ordinary filter here; a plate number always sits right before its plate code
() => plateNumberFirst(fields.filter((f) => f.advanced && f.id !== status?.id && !quickDates.some((q) => q.id === f.id))),
[fields, status, quickDates],
);
// Enter inside any filter field runs the search, same as the Apply button
const apply = () => {
onChange(draft);
setOpen(false);
};
const openDrawer = () => {
setDraft(filter);
setOpen(true);
};
const activeAdvanced = advanced.filter((f) => filter[f.id]);
const label = (f: SearchField, v: string) => {
if (f.type === 'DROPDOWN') {
const o = (depApplied[f.id] ?? f.options)?.find((x) => String(x.CODE) === v);
return o ? o.NAME || t(o.CAPTION_CODE ?? String(o.CODE)) : v;
}
if (f.type === 'DATE') {
const [a, b] = rangeParts(v);
return a === b ? display(a) : `${display(a)} – ${display(b)}`;
}
return v;
};
const optLabel = (o: Option) => o.NAME || t(o.CAPTION_CODE ?? String(o.CODE));
return (
<Paper variant="outlined" sx={{ p: 1.25, mb: 1.5 }}>
<Stack direction={{ xs: 'column', md: 'row' }} spacing={1.5} alignItems={{ md: 'center' }}>
{status?.options && (
<Stack direction="row" spacing={0.75} useFlexGap flexWrap="wrap" sx={{ flex: 1 }}>
<Chip label={ui('all')} color={filter[status.id] ? 'default' : 'primary'} variant={filter[status.id] ? 'outlined' : 'filled'} onClick={() => onChange(setKey(filter, status.id, ''))} />
{status.options.map((o) => {
const on = filter[status.id] === String(o.CODE);
return (
<Chip key={String(o.CODE)} label={optLabel(o)} color={on ? 'primary' : 'default'} variant={on ? 'filled' : 'outlined'} onClick={() => onChange(setKey(filter, status.id, on ? '' : String(o.CODE)))} />
);
})}
</Stack>
)}
{quickDates.map((f) => {
const v = filter[f.id] ?? '';
const [a, b] = rangeParts(v);
return (
<Stack key={f.id} direction="row" spacing={1} alignItems="center">
<Typography variant="body2" color="text.secondary" sx={{ whiteSpace: 'nowrap' }}>{t(f.caption)}</Typography>
<DateField
size="small" label={ui('from')} value={toInput(a)}
onChange={(iso) => onChange(setKey(filter, f.id, toRange(fromInput(iso), b)))}
/>
<DateField
size="small" label={ui('to')} value={toInput(b)}
onChange={(iso) => onChange(setKey(filter, f.id, toRange(a, fromInput(iso))))}
/>
</Stack>
);
})}
{/* the filters button is always at the end of the row (right in English, left in Arabic). A Stack resets its
children's margins, so on pages with no status chips to fill the row a spacer pushes the button there. */}
{advanced.length > 0 && !status?.options && <Box sx={{ flex: 1, display: { xs: 'none', md: 'block' } }} />}
{advanced.length > 0 && (
<Badge badgeContent={activeAdvanced.length} color="secondary" sx={{ alignSelf: { xs: 'flex-end', md: 'center' } }}>
<Button variant="outlined" startIcon={<TuneIcon />} onClick={openDrawer}>{ui('filters')}</Button>
</Badge>
)}
</Stack>
{activeAdvanced.length > 0 && (
<Stack direction="row" spacing={0.75} useFlexGap flexWrap="wrap" sx={{ mt: 1.5 }}>
{activeAdvanced.map((f) => (
<Chip key={f.id} size="small" label={`${t(f.caption)}: ${label(f, filter[f.id])}`} onDelete={() => onChange(setWithChildren(filter, f.id, ''))} />
))}
<Button size="small" onClick={() => onChange(pick(filter, [status?.id, ...quickDates.map((f) => f.id)]))}>{ui('clear')}</Button>
</Stack>
)}
<Drawer anchor="right" open={open} onClose={() => setOpen(false)} slotProps={{ paper: { sx: { width: { xs: '100%', sm: 400 }, p: 3 } } }}>
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
<Typography variant="h6">{ui('filters')}</Typography>
<IconButton onClick={() => setOpen(false)}><CloseIcon /></IconButton>
</Stack>
<Box component="form" onSubmit={(e) => { e.preventDefault(); apply(); }} sx={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
{/* room for the scroll bar on its own side: Firefox draws it over the fields, Chrome beside them */}
<Stack spacing={2} sx={{ flex: 1, overflowY: 'auto', pt: 0.5, paddingInlineEnd: 1.5, scrollbarGutter: 'stable', scrollbarWidth: 'thin' }}>
{advanced.map((f) => {
const v = draft[f.id] ?? '';
const set = (nv: string) => setDraft((d) => setWithChildren(d, f.id, nv));
if (f.type === 'DROPDOWN') {
const choices = depDraft[f.id] ?? f.options ?? [];
// the list is being fetched for the chosen parent: say so instead of "no options"
const waiting = !!DEPENDENT_SEARCH[entity]?.[f.id] && !!draft[DEPENDENT_SEARCH[entity][f.id].parent] && !depDraft[f.id];
const sel = choices.find((o) => String(o.CODE) === v) ?? null;
return (
<Autocomplete key={f.id} fullWidth options={choices} value={sel} loading={waiting} getOptionLabel={optLabel} isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
onChange={(_, o) => set(o ? String(o.CODE) : '')} renderInput={(p) => <TextField {...p} label={t(f.caption)} />} />
);
}
if (f.type === 'DATE') {
const [a, b] = rangeParts(v);
return (
<Box key={f.id}>
<Typography variant="body2" color="text.secondary" sx={{ mb: 0.75 }}>{t(f.caption)}</Typography>
<Stack direction="row" spacing={1}>
<DateField label={ui('from')} value={toInput(a)} onChange={(iso) => set(toRange(fromInput(iso), b))} fullWidth />
<DateField label={ui('to')} value={toInput(b)} onChange={(iso) => set(toRange(a, fromInput(iso)))} fullWidth />
</Stack>
</Box>
);
}
return <TextField key={f.id} fullWidth label={t(f.caption)} value={v} onChange={(e) => set(e.target.value)} slotProps={{ htmlInput: { maxLength: f.maxLength } }} />;
})}
</Stack>
<Stack direction="row" spacing={1} sx={{ pt: 2 }}>
<Button type="submit" variant="contained" fullWidth>{ui('apply')}</Button>
<Button fullWidth onClick={() => setDraft((d) => pick(d, [status?.id, ...quickDates.map((f) => f.id)]))}>{ui('clear')}</Button>
</Stack>
</Box>
</Drawer>
</Paper>
);
}
function setKey(f: Filter, k: string, v: string): Filter {
const next = { ...f };
if (v) next[k] = v;
else delete next[k];
return next;
}
function pick(f: Filter, keys: (string | undefined)[]): Filter {
const out: Filter = {};
for (const k of keys) if (k && f[k]) out[k] = f[k];
return out;
}
/** Groups each plate number with its plate code (same prefix, e.g. TRAILER_), number first, at the spot of the earliest of them. */
function plateNumberFirst(list: SearchField[]): SearchField[] {
const kind = (id: string) => (/PLATE_NUMBER/.test(id) ? 0 : /PLATE_CODE/.test(id) ? 1 : -1);
const group = (id: string) => id.slice(0, id.indexOf('PLATE_'));
const placed = new Set<string>();
const out: SearchField[] = [];
for (const f of list) {
if (placed.has(f.id)) continue;
if (kind(f.id) < 0) {
out.push(f);
continue;
}
const mates = list.filter((x) => kind(x.id) >= 0 && group(x.id) === group(f.id)).sort((a, b) => kind(a.id) - kind(b.id));
for (const m of mates) {
placed.add(m.id);
out.push(m);
}
}
return out;
}

View File

@ -0,0 +1,56 @@
import { useQueries } from '@tanstack/react-query';
import { getOptions, type Option } from '../../api/entity';
import type { Filter } from './filters';
/**
* Search drop lists the legacy grids filled from another search field: pick a stakeholder type and the stakeholder names
* and the subscriptions that fit it are loaded; pick a fleet type and its classes and usages are loaded; pick an
* industrial estate and its investors are loaded. Until the parent has a value the child keeps the role's own list.
*/
interface Dependent {
parent: string;
load: (parentValue: string) => Promise<Option[]>;
}
const STAKEHOLDER_NAMES: Record<string, string> = { '7': 'INVESTORS', '10': 'OWNERS', '11': 'COMPANIES', '12': 'OTHER_STAKEHOLDERS' };
const fleetClass = (fleetType: string) => getOptions('getFleetSubscriptionClass', { fleetType });
const fleetUsage = (fleetType: string) => getOptions('getFleetSubscriptionUsage', { fleetType });
export const DEPENDENT_SEARCH: Record<string, Record<string, Dependent>> = {
SUBSCRIPTIONS: {
STAKEHOLDERNAMEAR: {
parent: 'RELATED_ENTITY_ID',
load: (id) => (STAKEHOLDER_NAMES[id] ? getOptions('getStakeHoldersList', { STAKEHOLDER_ID: id, STAKEHOLDER_NAME: STAKEHOLDER_NAMES[id] }) : Promise.resolve([])),
},
SUBSCRIPTION_NAME: { parent: 'RELATED_ENTITY_ID', load: (id) => getOptions('getSubscriptionDependsOnStakeholder', { stakeholderID: id }) },
FLEET_SUBSCRIPTION_CLASS: { parent: 'FLEET_SUBSCRIPTION_TYPE', load: fleetClass },
USAGE_TYPE: { parent: 'FLEET_SUBSCRIPTION_TYPE', load: fleetUsage },
},
PERMITS: {
FLEET_CATEGORY: { parent: 'FLEET_ENTITY_NAME', load: fleetClass },
INDUSTRIAL_ESTATE_STAKEHOLDER_ID: { parent: 'INDUSTRIAL_ESTATE_ID', load: (locationId) => getOptions('getInvestorsInLocation', { locationId }) },
},
};
/** The fields that depend on `parent` (cleared when the parent changes). */
export const childrenOf = (entity: string, parent: string): string[] =>
Object.entries(DEPENDENT_SEARCH[entity] ?? {}).filter(([, d]) => d.parent === parent).map(([child]) => child);
/** The options loaded for each dependent field whose parent has a value in `values` (others are left out). */
export function useDependentOptions(entity: string, values: Filter): Record<string, Option[]> {
const deps = Object.entries(DEPENDENT_SEARCH[entity] ?? {});
const results = useQueries({
queries: deps.map(([child, d]) => ({
queryKey: ['search-dependent', entity, child, values[d.parent] ?? ''],
queryFn: () => d.load(values[d.parent]),
enabled: !!values[d.parent],
staleTime: 5 * 60_000,
})),
});
const out: Record<string, Option[]> = {};
deps.forEach(([child, d], i) => {
if (values[d.parent] && Array.isArray(results[i].data)) out[child] = results[i].data as Option[];
});
return out;
}

View File

@ -0,0 +1,78 @@
import { useMemo } from 'react';
import { useAuth } from '../../auth/AuthContext';
import type { AppConfig } from '../../api/config';
import type { Option } from '../../api/entity';
/** Search metadata from getConfig (ROLE_SEARCH_FIELD_AUTHORITY_VIEW), per entity and role. */
export interface SearchField {
id: string;
type: 'TEXT' | 'DROPDOWN' | 'DATE' | string;
caption: string;
maxLength?: number;
options?: Option[];
/** shown in the quick search box */
quick: boolean;
advanced: boolean;
defaultValue?: string;
}
interface Row {
ENTITY_NAME: string;
HTML_ID: string;
FIELD_TYPE: string;
CAPTION_CODE: string;
LENGTH?: number | string;
DEFAULT_SEARCH_FIELD?: number;
APPEAR_IN_GRID_SEARCH?: number;
APPEAR_IN_ADVANCE_SEARCH?: number;
DEFAULT_VALUE?: string;
DDL_VALUES?: Option[];
}
export function useSearchFields(config: AppConfig | undefined, entity: string): SearchField[] {
const { lang } = useAuth();
return useMemo(() => {
// a grid page lists exactly the fields flagged APPEAR_IN_GRID_SEARCH — what the legacy grid's init_search renders.
// APPEAR_IN_ADVANCE_SEARCH belongs to the "advanced search" of the plan/letter create pages, not to grids.
const rows = ((config?.ROLE_SEARCH_FIELD_AUTHORITY_VIEW ?? []) as unknown as Row[]).filter(
(r) => r.ENTITY_NAME === entity && Number(r.APPEAR_IN_GRID_SEARCH) > 0,
);
// the plate code is searchable in both spellings (…_AR / …_EN); the old grids showed only the page language's one
const duplicate = lang === 'AR' ? 'IDX_PLATE_CODE_EN' : 'IDX_PLATE_CODE_AR';
return rows.filter((r) => r.HTML_ID !== duplicate).map((r) => ({
id: r.HTML_ID,
type: r.FIELD_TYPE,
caption: r.CAPTION_CODE,
maxLength: Number(r.LENGTH) > 0 ? Number(r.LENGTH) : undefined,
options: r.DDL_VALUES,
quick: Number(r.DEFAULT_SEARCH_FIELD) > 0,
advanced: true,
defaultValue: r.DEFAULT_VALUE || undefined,
}));
}, [config, entity, lang]);
}
export type Filter = Record<string, string>;
/** Filters live in the URL (?PLATE_NUMBER_GRID=10314&STATUS_CODE=REGISTERED) so back/forward and links keep them. */
export const filterFromParams = (p: URLSearchParams, fields: SearchField[]): Filter => {
const out: Filter = {};
for (const f of fields) {
const v = p.get(f.id);
if (v) out[f.id] = v;
}
return out;
};
export const filterToParams = (filter: Filter): Filter => filter;
// Date filters travel as yyyymmdd or a range yyyymmdd-yyyymmdd (what the legacy form posts).
export const toApiFilter = (filter: Filter): Record<string, string> => filter;
export const rangeParts = (v: string | undefined): [string, string] => {
if (!v) return ['', ''];
const [a, b] = v.split('-');
return [a ?? '', b ?? a ?? ''];
};
export const toRange = (from: string, to: string) =>
!from && !to ? '' : from && to ? `${from}-${to}` : from ? `${from}-${from}` : `${to}-${to}`;

View File

@ -0,0 +1,575 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
Alert, Autocomplete, Box, Button, Checkbox, CircularProgress, FormControlLabel, IconButton, Paper, Stack, Tab, Table, TableBody,
TableCell, TableHead, TableRow, Tabs, TextField, Typography,
} from '@mui/material';
import DeleteOutline from '@mui/icons-material/DeleteOutline';
import EditOutlined from '@mui/icons-material/EditOutlined';
import { useAuth } from '../../auth/AuthContext';
import { useNotify } from '../../notify/NotifyProvider';
import { useLabel, useT, useUi } from '../../i18n';
import type { PendingFile } from '../../api/attachments';
import { AttachmentField } from '../forms/AttachmentField';
import {
checkWaybillNumber, getOneTripData, validateApprovalNumber, validatePermit, type OneTripData,
} from '../../api/packages';
type Opt = { CODE: string | number; CAPTION_CODE?: string; NAME?: string };
/** packages whose approval number comes with the request (legacy: suhar / weighing bridge) */
const SPECIAL = ['ISD0001', 'ISW0001', 'IRM0001', 'IMA0001', 'IME0001', 'KRY0001', 'SID0001'];
const WEIGHING_BRIDGE = ['WBP001'];
export const FREE_ZONE = ['FZP0001'];
const DRIVER_ATT = ['DRIVER_FRONT_PER_DOC_ATT', 'DRIVER_BACK_PER_DOC_ATT', 'DRIVER_FRONT_LIC_ATT', 'DRIVER_BACK_LIC_ATT'] as const;
const DRIVER_ATT_CAPTION: Record<(typeof DRIVER_ATT)[number], string> = {
DRIVER_FRONT_PER_DOC_ATT: 'DRIVER_ID_FRONT',
DRIVER_BACK_PER_DOC_ATT: 'DRIVER_ID_BACK',
DRIVER_FRONT_LIC_ATT: 'DRIVER_LICENSE_FRONT',
DRIVER_BACK_LIC_ATT: 'DRIVER_LICENSE_BACK',
};
const GATE_PASS = 'GATE_PASS_ATT';
interface Form {
approval: string;
nationality: string;
truckNumber: string;
truckCode: string;
trailerNumber: string;
trailerCode: string;
trailerType: string;
cargo: string;
operation: string;
doubleMove: boolean;
discharge: string[];
waybill: string;
docNationality: string;
docType: string;
docNumber: string;
driverName: string;
driverNationality: string;
mobile: string;
areaCode: string;
}
const BLANK: Form = {
approval: '', nationality: '', truckNumber: '', truckCode: '', trailerNumber: '', trailerCode: '', trailerType: '', cargo: '', operation: '',
doubleMove: false, discharge: [], waybill: '', docNationality: '', docType: '', docNumber: '', driverName: '', driverNationality: '',
mobile: '', areaCode: '',
};
/** One accepted truck: what the backend receives, what the table shows, and what the form held (to edit it again). */
export interface OneTripEntry {
payload: Record<string, unknown>;
/** the permit is charged unless the backend answered with a warning */
fees: boolean;
form: Form;
files: Record<string, PendingFile>;
row: string[];
}
interface Props {
packageCode: string;
subscriptionCode: string;
packageGroupType: string;
entries: OneTripEntry[];
onEntries: (e: OneTripEntry[]) => void;
onApprovalId: (id: number) => void;
/** the industrial area the approval number belongs to (sent as the subscription's location) */
onEstate: (estate: string) => void;
}
function Pick({ label, options, value, onChange, disabled, required, error }: {
label: string; options: Opt[]; value: string; onChange: (v: string) => void; disabled?: boolean; required?: boolean; error?: boolean;
}) {
const t = useT();
const text = (o: Opt) => (o.CAPTION_CODE !== undefined ? t(o.CAPTION_CODE) : o.NAME ?? String(o.CODE));
const real = options.filter((o) => String(o.CODE) !== '');
return (
<Autocomplete
fullWidth
size="small"
disabled={disabled}
options={real}
value={real.find((o) => String(o.CODE) === value) ?? null}
getOptionLabel={text}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
onChange={(_, o) => onChange(o ? String(o.CODE) : '')}
renderInput={(p) => <TextField {...p} label={label} required={required} error={error} />}
/>
);
}
/** The one-trip permit step of the subscription wizard: enter each truck, trailer and driver, then continue to payment. */
export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, entries, onEntries, onApprovalId, onEstate }: Props) {
const { config, lang } = useAuth();
const t = useT();
const lab = useLabel();
const ui = useUi();
const notify = useNotify();
const [form, setForm] = useState<Form>(BLANK);
const [tab, setTab] = useState(0);
const [files, setFiles] = useState<Record<string, PendingFile>>({});
const [approvalOk, setApprovalOk] = useState(false);
const [approvalMsg, setApprovalMsg] = useState('PLEASE_ENTER_APPROVAL_NUMBER');
const [maxTrucks, setMaxTrucks] = useState(0);
const [estate, setEstate] = useState('');
const [stakeholder, setStakeholder] = useState('');
const [approvalLocked, setApprovalLocked] = useState(false);
const [driverFilesRequired, setDriverFilesRequired] = useState(false);
const [gatePassRequired, setGatePassRequired] = useState(false);
const [matching, setMatching] = useState(false);
const [busy, setBusy] = useState(false);
const [errors, setErrors] = useState<Record<string, boolean>>({});
const approvalId = useRef(0);
const entriesRef = useRef(entries);
entriesRef.current = entries;
const special = SPECIAL.includes(packageCode);
const fleetRequest: 0 | 1 = special || WEIGHING_BRIDGE.includes(packageCode) ? 1 : 0;
const sysVar = (name: string) => (config?.SYSTEM_VARIABLES as { NAME: string; VALUE: string }[] | undefined)?.find((v) => v.NAME === name)?.VALUE;
const baseUrl = sysVar('ATTACHMENT_URL') ?? '';
const maxMb = Number(sysVar('MAXFILESIZE')) || 8;
const waybillOn = String(sysVar('ENABLE_WAYBILL_NUMBER_FIELD')) === '1';
const side = lang === 'AR' ? 'AR' : 'EN';
const ctx = { packageCode, subscriptionCode, packageGroupType };
const data = useQuery<OneTripData>({ queryKey: ['wiz', 'onetrip', fleetRequest], queryFn: () => getOneTripData(fleetRequest), staleTime: 5 * 60_000 });
const d = data.data;
const omani = form.nationality === 'OMN';
const set = <K extends keyof Form>(k: K, v: Form[K]) => {
setForm((f) => ({ ...f, [k]: v }));
setErrors((e) => ({ ...e, [k]: false }));
};
const optionText = (list: Opt[] | undefined, code: string) => {
const o = list?.find((x) => String(x.CODE) === code);
return o ? (o.CAPTION_CODE !== undefined ? t(o.CAPTION_CODE) : o.NAME ?? String(o.CODE)) : '';
};
// first nationality / area code are pre-selected, like the old form did
useEffect(() => {
if (!d) return;
setForm((f) => ({
...f,
nationality: f.nationality || String(d.NATIONALITY?.find((o) => String(o.CODE) !== '')?.CODE ?? ''),
areaCode: f.areaCode || String(d.AREA_CODE?.find((o) => String(o.CODE) !== '')?.CODE ?? ''),
}));
}, [d]);
const applyApproval = async (num: string) => {
const r = await validateApprovalNumber(num);
const res = r.RESULT;
const fail = (msg: string) => {
notify.error(new Error(msg));
setEstate('');
onEstate('');
setStakeholder('');
setApprovalOk(false);
setApprovalMsg(msg);
setMaxTrucks(0);
approvalId.current = 0;
onApprovalId(0);
};
if (Number(res.CODE) === 0) return fail(String(res.MESSAGE ?? 'ACTION_FAILED'));
const est = String(res.INDUSTRIAL_ESTATE_ID ?? '');
if (!d?.INDUSTRIAL_ESTATE?.some((o) => String(o.CODE) === est)) return fail('APPROVAL_NUM_NOT_SUPPORT_LOCATION');
setEstate(est);
onEstate(est);
setStakeholder(String(res.INVESTOR_RECORD_ID ?? ''));
setApprovalOk(true);
approvalId.current = Number(res.REQUEST_ID ?? 0);
onApprovalId(approvalId.current);
setMaxTrucks(Number(res.TOTAL_FLEET_NO ?? 0) - Number(res.USED_FLEET_NO ?? 0));
};
const checkApproval = (num: string) => {
if (!num.trim() || Number.isNaN(Number(num))) return;
applyApproval(num.trim()).catch((e) => notify.error(e));
};
// the approval number can arrive with the request for the special packages; it then cannot be changed
const preset = useRef(false);
useEffect(() => {
if (!d || preset.current || d.APPROVAL_NUMBER === undefined || d.APPROVAL_NUMBER === '' || !fleetRequest) return;
preset.current = true;
const num = String(d.APPROVAL_NUMBER);
setForm((f) => ({ ...f, approval: num }));
setApprovalLocked(true);
if (special) setGatePassRequired(true);
checkApproval(num);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [d]);
const onApprovalChange = (v: string) => {
set('approval', v);
if (entries.length) {
notify.warning('CHANGE_APPROVAL_NUMBER_HINT', '');
onEntries([]);
}
};
const fillFromTruck = (r: Record<string, string>) => {
setForm((f) => {
const next = { ...f };
for (const [k, v] of Object.entries(r)) {
if (!v) continue;
if (k === 'TRAILER_PLATE_NUMBER') next.trailerNumber = v;
else if (k === 'DRIVER_NAME') next.driverName = v;
else if (k === 'TRAILER_PLATE_CODE_AR' || k === 'TRAILER_PLATE_CODE_EN') next.trailerCode = v;
else if (k === 'TRAILER_TYPE') next.trailerType = v;
else if (k === 'CARGO_TYPE') next.cargo = v;
else if (k === 'OPERATION_TYPE') next.operation = v;
else if (k === 'DRIVER_NATIONALITY') next.driverNationality = v;
else if (k === 'DRIVER_DOCUMENT_NATIONALITY') next.docNationality = v;
else if (k === 'DRIVER_DOCUMENT_TYPE') next.docType = v;
else if (k === 'DRIVER_DOCUMENT_NUMBER') next.docNumber = v;
else if (k === 'DRIVER_MOBILE_NUMBER') next.mobile = v;
else if (k === 'DRIVER_MOBILE_AREA_CODE') next.areaCode = v;
}
return next;
});
};
const checkTruck = async (f: Form = form) => {
if (!f.truckNumber.trim() || !f.nationality) return;
const own = f.nationality === 'OMN';
if (own && !f.truckCode) return;
const truck: Record<string, unknown> = {
FLEET_NATIONALITY: f.nationality,
FLEET_PLATE_NUMBER: f.truckNumber.trim(),
...(own ? { [`FLEET_PLATE_CODE_${side}`]: f.truckCode } : { FLEET_PLATE_CODE_AR: f.truckCode.trim() }),
};
try {
const r = await validatePermit([truck], { ...ctx, approvalNumberId: approvalId.current });
setMatching(Number(r.TRUCK_VALID_FOR_MATCHING_SERVICE) === 1);
const first = r.RESULTDATA?.[0] ?? {};
if (r.RESULTCODE === 'FAILED') return notify.error(new Error(first.response_error_codes ?? 'ACTION_FAILED'));
if (r.RESULTCODE === 'WARNING') notify.warning(first.response_error_codes ?? '', '');
const copy = { ...first };
// the backend answers in both languages; only the session's matters
if (side === 'AR') delete copy.TRAILER_PLATE_CODE_EN;
else delete copy.TRAILER_PLATE_CODE_AR;
fillFromTruck(copy);
} catch (e) {
notify.error(e);
}
};
const checkDriver = async (f: Form) => {
if (!f.docNationality || !f.docType || !f.docNumber.trim()) return;
try {
const r = await validatePermit(
[{ DRIVER_DOCUMENT_NATIONALITY: f.docNationality, DRIVER_DOCUMENT_TYPE: f.docType, DRIVER_DOCUMENT_NUMBER: f.docNumber.trim() }],
{ ...ctx, approvalNumberId: approvalId.current },
);
const first = r.RESULTDATA?.[0] ?? {};
if (r.RESULTCODE === 'FAILED') return notify.error(new Error(first.response_error_codes ?? 'ACTION_FAILED'));
if (first.DRIVER_NAME !== undefined) {
setForm((cur) => ({
...cur,
driverName: first.DRIVER_NAME,
driverNationality: first.DRIVER_NATIONALITY ?? cur.driverNationality,
mobile: first.DRIVER_MOBILE_NUMBER ?? cur.mobile,
areaCode: first.DRIVER_MOBILE_AREA_CODE ?? cur.areaCode,
}));
setDriverFilesRequired(false);
} else setDriverFilesRequired(true);
} catch (e) {
notify.error(e);
}
};
const showMatching = form.operation === 'DISCHARGE' && matching;
useEffect(() => {
if (!showMatching && (form.doubleMove || form.discharge.length)) setForm((f) => ({ ...f, doubleMove: false, discharge: [] }));
}, [showMatching, form.doubleMove, form.discharge.length]);
const clearForm = () => {
setForm((f) => ({ ...BLANK, approval: f.approval, nationality: f.nationality, areaCode: f.areaCode }));
setFiles({});
setErrors({});
setMatching(false);
setDriverFilesRequired(false);
};
const fail = (msg: string, tabIndex?: number) => {
if (tabIndex !== undefined) setTab(tabIndex);
notify.error(new Error(msg));
};
const add = async () => {
const need: (keyof Form)[] = [
'approval', 'nationality', 'truckNumber', 'trailerNumber', 'trailerType', 'cargo', 'operation',
'docNationality', 'docType', 'docNumber', 'driverName', 'driverNationality', 'mobile',
];
if (omani) need.push('truckCode', 'trailerCode');
if (waybillOn) need.push('waybill');
const missing = need.filter((k) => !String(form[k]).trim());
if (missing.length) {
setErrors(Object.fromEntries(missing.map((k) => [k, true])));
const driverFirst = missing.every((k) => ['docNationality', 'docType', 'docNumber', 'driverName', 'driverNationality', 'mobile'].includes(k));
return fail(t('VALIDATION.INVALID_INPUT'), driverFirst ? 1 : 0);
}
if (!approvalOk) return fail(t(approvalMsg));
if (entries.length >= maxTrucks) return fail(t('ENTERED_VEHICLE_EXCEED_ALLOW_NUMBER'));
if (form.doubleMove && !form.discharge.length) return fail(t('PLEASE_SELECT_DISCHARGING_LOCATIONS'));
if (waybillOn) {
const code = omani ? form.truckCode : form.truckCode.trim();
const w = await checkWaybillNumber({ plateNumber: form.truckNumber, plateCode: code, waybillNumber: form.waybill, nationality: form.nationality });
if (Number(w) !== 200 && Number(w) !== 1999) return fail(t('INVALIDWAYBILLNUMBER'));
}
const fileList: { fileType: string; file: string; attach_for: string }[] = [];
const pick = (types: readonly string[], attachFor: string) => types.forEach((ft) => files[ft] && fileList.push({ fileType: ft, file: files[ft].file, attach_for: attachFor }));
if (driverFilesRequired) {
if (DRIVER_ATT.some((k) => !files[k])) return fail(t('PLEASE_INSERT_DRIVER_ATTACHMENTS'), 2);
pick(DRIVER_ATT, 'DRIVER');
}
if (gatePassRequired) {
if (!files[GATE_PASS] && packageCode !== 'SID0001') return fail(t('PLEASE_INSERT_ALL_ATTACHMENTS'), 2);
pick([GATE_PASS], 'INVESTOR');
}
const truckCode = omani ? { FLEET_PLATE_CODE_AR: form.truckCode, FLEET_PLATE_CODE_EN: form.truckCode } : { FLEET_PLATE_CODE_AR: form.truckCode.trim() };
const trailerCode = omani ? { TRAILER_PLATE_CODE_AR: form.trailerCode, TRAILER_PLATE_CODE_EN: form.trailerCode } : { TRAILER_PLATE_CODE_AR: form.trailerCode.trim() };
const id = `${form.nationality}_${form.truckNumber}_${String(truckCode.FLEET_PLATE_CODE_AR).replace(/\s/g, '')}`;
const trailerId = `${form.trailerNumber}_${String(trailerCode.TRAILER_PLATE_CODE_AR).replace(/\s/g, '')}`;
const driverId = `${form.docNationality}_${form.docType}_${form.docNumber}`;
const same = (a: unknown, b: string) => String(a).toLowerCase() === b.toLowerCase();
if (entries.some((e) => same(e.payload.ID, id))) return fail(t('VEHICLE_PREVIOUSLY_ADDED'));
if (entries.some((e) => same(e.payload.TRAILER_DATA_ID, trailerId))) return fail(t('TRAILER_PREVIOUSLY_ADDED'));
if (entries.some((e) => same(e.payload.DRIVER_DATA_ID, driverId))) return fail(t('DRIVER_PREVIOUSLY_ADDED'));
const payload: Record<string, unknown> = {
FLEET_APPROVAL_NUMBER: form.approval,
INDUSTRIAL_ESTATE: estate,
STAKEHOLDER_NAME: stakeholder,
FLEET_NATIONALITY: form.nationality,
TRAILER_TYPE: form.trailerType,
FLEET_PLATE_NUMBER: form.truckNumber,
...truckCode,
CARGO_TYPE: form.cargo,
TRAILER_PLATE_NUMBER: form.trailerNumber,
...trailerCode,
OPERATION_TYPE: form.operation,
doubleMoveCheck: form.doubleMove,
DISCHARGE_LOCATIONS: form.discharge,
WAYBILL_NUMBER: form.waybill,
DRIVER_NAME: form.driverName,
DRIVER_DOCUMENT_NATIONALITY: form.docNationality,
DRIVER_DOCUMENT_TYPE: form.docType,
DRIVER_DOCUMENT_NUMBER: form.docNumber,
DRIVER_NATIONALITY: form.driverNationality,
DRIVER_MOBILE_NUMBER: form.mobile,
DRIVER_MOBILE_AREA_CODE: form.areaCode,
ID: id,
USER_LANGUAGE: side,
TRAILER_DATA_ID: trailerId,
DRIVER_DATA_ID: driverId,
};
setBusy(true);
try {
const r = await validatePermit([payload], { ...ctx, approvalNumberId: approvalId.current });
if (r.RESULTCODE === 'FAILED') {
const codes = String(r.RESULTDATA?.[0]?.response_error_codes ?? 'ACTION_FAILED').split(',');
return fail(codes.map((c) => t(c.trim())).join(' • '));
}
const plate = (n: string, code: string, list?: Opt[]) => `${n} ${omani ? optionText(list, code) || code : code}`.trim();
const row = [
optionText(d?.NATIONALITY, form.nationality),
plate(form.truckNumber, form.truckCode, d?.FLEET_PLATE_CODE),
plate(form.trailerNumber, form.trailerCode, d?.FLEET_PLATE_CODE),
optionText(d?.TRAILER_TYPES, form.trailerType),
optionText(d?.CARGO_TYPE, form.cargo),
optionText(d?.OPERATION_TYPES, form.operation),
optionText(d?.INDUSTRIAL_ESTATE, estate),
optionText(d?.INVESTORS_NAME, stakeholder),
optionText(d?.NATIONALITY, form.docNationality),
optionText(d?.PERSONAL_DOC_TYPE, form.docType),
form.docNumber,
form.driverName,
optionText(d?.NATIONALITY, form.driverNationality),
form.mobile,
];
onEntries([
...entries,
{ payload: { ...payload, FILES: fileList, FEES: r.RESULTCODE !== 'WARNING' }, fees: r.RESULTCODE !== 'WARNING', form: { ...form }, files: { ...files }, row },
]);
clearForm();
} catch (e) {
notify.error(e);
} finally {
setBusy(false);
}
};
const edit = (e: OneTripEntry) => {
setForm(e.form);
setFiles(e.files);
setErrors({});
setTab(0);
onEntries(entriesRef.current.filter((x) => x !== e));
};
const heads = useMemo(
() => ['TRUCK_NATIONALITY', 'TRUCK_NUMBER', 'TRAILER_NUMBER', 'TRAILER_TYPE', 'CARGO_TYPE', 'OPERATION_TYPE', 'INDUSTRIAL_ESTATE', 'RELATED_ENTITY_RECORD_ID',
'PERSONAL_DOC_NATIONALITY', 'PERSONAL_DOC_TYPE', 'NN', 'NAME_FROM_4_PARTS', 'DRIVER_NATIONALITY', 'MOBILE'],
[],
);
if (FREE_ZONE.includes(packageCode)) return <Alert severity="info">{ui('wizFreeZone')}</Alert>;
if (data.isPending) return <Box sx={{ display: 'grid', placeItems: 'center', py: 6 }}><CircularProgress /></Box>;
if (data.error || !d) return <Alert severity="error">{ui('loadError')}: {(data.error as Error | null)?.message}</Alert>;
const text = (k: keyof Form, label: string, extra?: { max?: number; onBlur?: () => void; disabled?: boolean; dir?: 'ltr' }) => (
<TextField
fullWidth size="small" label={label} required value={String(form[k])} error={!!errors[k]} disabled={extra?.disabled}
onChange={(e) => set(k, e.target.value as never)} onBlur={extra?.onBlur}
slotProps={{ htmlInput: { maxLength: extra?.max, dir: extra?.dir } }}
/>
);
const grid = { display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(3, 1fr)' } } as const;
const att = (field: string, caption: string) => (
<AttachmentField
key={field} field={field} label={lab(caption)} required readOnly={false} baseUrl={baseUrl} maxMb={maxMb} pending={files[field]}
onPending={(p) => setFiles((cur) => { const n = { ...cur }; if (p) n[field] = p; else delete n[field]; return n; })}
/>
);
return (
<Stack spacing={2}>
<Typography color="text.secondary" fontSize={13.5}>{lab('ONE_TRIP_PERMIT_ADD_HINT')}</Typography>
<Paper variant="outlined" sx={{ p: 2 }}>
<Tabs value={tab} onChange={(_, v: number) => setTab(v)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
<Tab label={lab('TRUCKS_INFO')} />
<Tab label={lab('OWNERS_INFO')} />
<Tab label={lab('ATTACHMENTS')} />
</Tabs>
{tab === 0 && (
<Box sx={grid}>
<TextField
fullWidth size="small" required label={lab('APPROVAL_NUMBER')} value={form.approval} error={!!errors.approval} disabled={approvalLocked}
onChange={(e) => onApprovalChange(e.target.value)} onBlur={() => checkApproval(form.approval)}
slotProps={{ htmlInput: { maxLength: 14 } }}
/>
<Pick label={lab('INDUSTRIAL_ESTATE')} options={d.INDUSTRIAL_ESTATE ?? []} value={estate} onChange={() => {}} disabled />
<Pick label={lab('RELATED_ENTITY_RECORD_ID')} options={d.INVESTORS_NAME ?? []} value={stakeholder} onChange={() => {}} disabled />
<Pick
label={lab('TRUCK_NATIONALITY')} required options={d.NATIONALITY ?? []} value={form.nationality} error={errors.nationality}
onChange={(v) => setForm((f) => ({ ...f, nationality: v, truckNumber: '', truckCode: '', trailerNumber: '', trailerCode: '' }))}
/>
<Stack direction="row" spacing={1}>
<Box sx={{ flex: 1 }}>{text('truckNumber', lab('TRUCK_NUMBER'), { max: 10, onBlur: () => void checkTruck() })}</Box>
<Box sx={{ flex: 1 }}>
{omani ? (
<Pick
label={lab('TRUCK_PLATE_ID')} required options={d.FLEET_PLATE_CODE ?? []} value={form.truckCode} error={errors.truckCode}
onChange={(v) => { set('truckCode', v); void checkTruck({ ...form, truckCode: v }); }}
/>
) : (
<TextField
fullWidth size="small" label={lab('TRUCK_PLATE_ID')} value={form.truckCode} onChange={(e) => set('truckCode', e.target.value)}
onBlur={() => form.truckCode.trim() && void checkTruck()} slotProps={{ htmlInput: { maxLength: 6 } }}
/>
)}
</Box>
</Stack>
<Stack direction="row" spacing={1}>
<Box sx={{ flex: 1 }}>{text('trailerNumber', lab('TRAILER_NUMBER'), { max: 10 })}</Box>
<Box sx={{ flex: 1 }}>
{omani ? (
<Pick label={lab('TRAILER_PLATE_ID')} required options={d.FLEET_PLATE_CODE ?? []} value={form.trailerCode} error={errors.trailerCode} onChange={(v) => set('trailerCode', v)} />
) : (
<TextField fullWidth size="small" label={lab('TRAILER_PLATE_ID')} value={form.trailerCode} onChange={(e) => set('trailerCode', e.target.value)} slotProps={{ htmlInput: { maxLength: 6 } }} />
)}
</Box>
</Stack>
<Pick label={lab('TRAILER_TYPE')} required options={d.TRAILER_TYPES ?? []} value={form.trailerType} error={errors.trailerType} onChange={(v) => set('trailerType', v)} />
<Pick label={lab('CARGO_TYPE')} required options={d.CARGO_TYPE ?? []} value={form.cargo} error={errors.cargo} onChange={(v) => set('cargo', v)} />
<Pick label={lab('OPERATION_TYPE')} required options={d.OPERATION_TYPES ?? []} value={form.operation} error={errors.operation} onChange={(v) => set('operation', v)} />
{showMatching && (
<FormControlLabel
control={<Checkbox checked={form.doubleMove} onChange={(e) => setForm((f) => ({ ...f, doubleMove: e.target.checked, discharge: e.target.checked ? f.discharge : [] }))} />}
label={lab('MATCHING_SERVICE_NOTE')}
/>
)}
{showMatching && form.doubleMove && (
<Autocomplete
multiple fullWidth size="small" options={d.GOVERNORATES ?? []}
value={(d.GOVERNORATES ?? []).filter((o) => form.discharge.includes(String(o.CODE)))}
getOptionLabel={(o) => (o.CAPTION_CODE !== undefined ? t(o.CAPTION_CODE) : o.NAME ?? String(o.CODE))}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
onChange={(_, v) => set('discharge', v.map((o) => String(o.CODE)))}
renderInput={(p) => <TextField {...p} label={lab('DISCHARGING_LOCATIONS')} required />}
/>
)}
{waybillOn && text('waybill', lab('WAYBILL_NUMBER'), { max: 20 })}
</Box>
)}
{tab === 1 && (
<Box sx={grid}>
<Pick label={lab('PERSONAL_DOC_NATIONALITY')} required options={d.NATIONALITY ?? []} value={form.docNationality} error={errors.docNationality}
onChange={(v) => { set('docNationality', v); void checkDriver({ ...form, docNationality: v }); }} />
<Pick label={lab('PERSONAL_DOC_TYPE')} required options={d.PERSONAL_DOC_TYPE ?? []} value={form.docType} error={errors.docType}
onChange={(v) => { set('docType', v); void checkDriver({ ...form, docType: v }); }} />
{text('docNumber', lab('NN'), { onBlur: () => void checkDriver(form) })}
{text('driverName', lab('NAME_FROM_4_PARTS'), { max: 50 })}
<Pick label={lab('DRIVER_NATIONALITY')} required options={d.NATIONALITY ?? []} value={form.driverNationality} error={errors.driverNationality} onChange={(v) => set('driverNationality', v)} />
<Stack direction="row" spacing={1}>
<Box sx={{ flex: 2 }}>{text('mobile', lab('MOBILE'), { max: 14, dir: 'ltr' })}</Box>
<Box sx={{ flex: 1 }}><Pick label={lab('AREA_CODE')} options={d.AREA_CODE ?? []} value={form.areaCode} onChange={(v) => set('areaCode', v)} /></Box>
</Stack>
</Box>
)}
{tab === 2 && (
<Box sx={grid}>
{driverFilesRequired
? DRIVER_ATT.map((f) => att(f, DRIVER_ATT_CAPTION[f]))
: <Typography color="text.secondary" fontSize={13.5} sx={{ gridColumn: '1 / -1' }}>{ui('wizNoDriverFiles')}</Typography>}
{gatePassRequired && att(GATE_PASS, packageCode === 'ISD0001' ? 'GATE_PASS_WAYBILL' : 'ATTACHMENT')}
</Box>
)}
<Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ mt: 2 }}>
<Button color="inherit" onClick={clearForm} disabled={busy}>{ui('clear')}</Button>
<Button variant="contained" color="success" onClick={() => void add()} disabled={busy}>{lab('ADD')}</Button>
</Stack>
</Paper>
<Paper variant="outlined" sx={{ p: 2 }}>
<Typography fontWeight={700} sx={{ mb: 1 }}>{lab('ADDED_VEHICLES')} ({entries.length}{maxTrucks ? ` / ${maxTrucks}` : ''})</Typography>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
{heads.map((h) => <TableCell key={h}>{lab(h)}</TableCell>)}
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{entries.length === 0 && (
<TableRow><TableCell colSpan={heads.length + 1}><Typography color="text.secondary">{lab('NO_INFO')}</Typography></TableCell></TableRow>
)}
{entries.map((e) => (
<TableRow key={String(e.payload.ID)}>
{e.row.map((c, i) => <TableCell key={i}>{c}</TableCell>)}
<TableCell sx={{ whiteSpace: 'nowrap' }}>
<IconButton size="small" title={lab('UPDATE')} onClick={() => edit(e)}><EditOutlined fontSize="small" /></IconButton>
<IconButton size="small" color="error" onClick={() => onEntries(entries.filter((x) => x !== e))}><DeleteOutline fontSize="small" /></IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Paper>
</Stack>
);
}

View File

@ -0,0 +1,484 @@
import { useMemo, useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Alert, Autocomplete, Box, Button, Card, CardActions, CardContent, Checkbox, Chip, CircularProgress, Dialog, DialogActions, DialogContent,
DialogTitle, FormControlLabel, List, ListItemButton, ListItemIcon, ListItemText, MenuItem, Paper, Radio, RadioGroup, Stack, Step,
StepLabel, Stepper, TextField, Typography,
} from '@mui/material';
import InfoOutlined from '@mui/icons-material/InfoOutlined';
import CalendarMonthOutlined from '@mui/icons-material/CalendarMonthOutlined';
import PaymentsOutlined from '@mui/icons-material/PaymentsOutlined';
import { useAuth } from '../../auth/AuthContext';
import { useNotify } from '../../notify/NotifyProvider';
import { isRtl, useT, useUi } from '../../i18n';
import {
createSubscription, getEmployees, getFilteredFleet, getFleet, getFleetClasses, getPackageGroups, getPackages, getPaymentMethods, getRiyadaCount, getServiceCategories,
getServiceSubscriptions, validateReceipt, type FleetResult, type FleetSearchField, type PackageCard, type Selectable,
} from '../../api/packages';
import { OneTripTrucks, type OneTripEntry } from './OneTripTrucks';
const ICON = { info: InfoOutlined, duration: CalendarMonthOutlined, price: PaymentsOutlined, text: InfoOutlined } as const;
// packages whose terms differ (the old wizard's "special packages" note)
const SPECIAL_NOTE = ['ISD0001', 'ISW0001', 'IRM0001', 'IMA0001', 'IME0001', 'KRY0001', 'SID0001'];
const RIYADA = 'RYD0001';
const CARD_PAYMENT = 3;
function Cards({ cards, action, onPick }: { cards: PackageCard[]; action: string; onPick: (c: PackageCard) => void }) {
return (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{cards.map((c) => (
<Card key={c.id} variant="outlined" sx={{ display: 'flex', flexDirection: 'column' }}>
<CardContent sx={{ flex: 1 }}>
<Typography fontWeight={700} fontSize={14.5} sx={{ mb: c.lines.length ? 1 : 0 }}>{c.title}</Typography>
<Stack spacing={0.5}>
{c.lines.map((l, i) => {
const Icon = ICON[l.kind];
return (
<Stack key={i} direction="row" spacing={0.75} alignItems="center" color={l.kind === 'price' ? 'primary.main' : 'text.secondary'}>
<Icon sx={{ fontSize: 16 }} />
<Typography fontSize={13} fontWeight={l.kind === 'price' ? 700 : 400}>{l.text}</Typography>
</Stack>
);
})}
</Stack>
</CardContent>
<CardActions sx={{ px: 2, pb: 1.5 }}>
<Button size="small" variant="outlined" onClick={() => onPick(c)}>{action}</Button>
</CardActions>
</Card>
))}
</Box>
);
}
/** Pick any number of items from a long list (the company's vehicles or employees). */
function Picker({ items, selected, onChange }: { items: Selectable[]; selected: string[]; onChange: (v: string[]) => void }) {
const ui = useUi();
const [q, setQ] = useState('');
const chosen = useMemo(() => new Set(selected), [selected]);
const filtered = useMemo(() => items.filter((i) => i.TEXT.toLowerCase().includes(q.trim().toLowerCase())), [items, q]);
const toggle = (v: string) => onChange(chosen.has(v) ? selected.filter((x) => x !== v) : [...selected, v]);
return (
<Paper variant="outlined" sx={{ p: 2 }}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} alignItems={{ sm: 'center' }} sx={{ mb: 1 }}>
<TextField size="small" label={ui('wizSearchList')} value={q} onChange={(e) => setQ(e.target.value)} sx={{ flex: 1 }} />
<Button size="small" onClick={() => onChange([...new Set([...selected, ...filtered.map((i) => i.VALUE)])])}>{ui('wizSelectShown')}</Button>
<Button size="small" color="inherit" disabled={!selected.length} onClick={() => onChange([])}>{ui('clear')}</Button>
<Chip color="primary" label={`${ui('wizSelected')}: ${selected.length} / ${items.length}`} />
</Stack>
<List dense sx={{ maxHeight: 340, overflow: 'auto', border: 1, borderColor: 'divider', borderRadius: 1 }}>
{filtered.slice(0, 200).map((i) => (
<ListItemButton key={i.VALUE} onClick={() => toggle(i.VALUE)}>
<ListItemIcon sx={{ minWidth: 36 }}><Checkbox edge="start" size="small" checked={chosen.has(i.VALUE)} tabIndex={-1} disableRipple /></ListItemIcon>
<ListItemText primary={i.TEXT} />
</ListItemButton>
))}
{filtered.length > 200 && <Typography variant="caption" color="text.secondary" sx={{ p: 1.5, display: 'block' }}>{ui('wizRefine')} ({filtered.length})</Typography>}
</List>
</Paper>
);
}
/** Staff search for vehicles (plate number/code, nationality, owner type, class) before choosing which to subscribe. */
function FleetSearch({ fields, busy, onSearch, onReset }: { fields: FleetSearchField[]; busy: boolean; onSearch: (f: Record<string, string>) => void; onReset: () => void }) {
const t = useT();
const notify = useNotify();
const ui = useUi();
const [values, setValues] = useState<Record<string, string>>({});
const [classes, setClasses] = useState<FleetSearchField['options'] | null>(null);
const set = (k: string, v: string) => setValues((cur) => ({ ...cur, [k]: v }));
const text = (o: FleetSearchField['options'][number]) => (o.CAPTION_CODE !== undefined ? t(o.CAPTION_CODE) : o.NAME ?? String(o.CODE));
// searching the whole fleet with no filter keeps the server busy for minutes, so at least one is required
const submit = () => {
const filters = Object.fromEntries(Object.entries(values).filter(([, v]) => v.trim() !== ''));
if (!Object.keys(filters).length) return notify.warning('', ui('wizNeedFilter'));
onSearch(filters);
};
const pickType = (v: string) => {
// the class list depends on the fleet type, as in the old form
setValues((cur) => ({ ...cur, ENTITY_NAME: v, TRUCK_TYPE: '' }));
setClasses(null);
if (v) getFleetClasses(v).then(setClasses).catch(() => setClasses([]));
};
return (
<Paper variant="outlined" component="form" onSubmit={(e: FormEvent) => { e.preventDefault(); submit(); }} sx={{ p: 2 }}>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(3, 1fr)' } }}>
{fields.map((f) => {
const options = f.name === 'TRUCK_TYPE' && classes ? classes : f.options;
if (f.kind === 'text') {
return (
<TextField key={f.name} fullWidth size="small" label={f.label} value={values[f.name] ?? ''} onChange={(e) => set(f.name, e.target.value)} slotProps={{ htmlInput: { maxLength: f.maxLength } }} />
);
}
return (
<Autocomplete
key={f.name}
fullWidth
size="small"
options={options.filter((o) => String(o.CODE) !== '')}
value={options.find((o) => String(o.CODE) === values[f.name] && String(o.CODE) !== '') ?? null}
getOptionLabel={text}
isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)}
onChange={(_, o) => (f.name === 'ENTITY_NAME' ? pickType(o ? String(o.CODE) : '') : set(f.name, o ? String(o.CODE) : ''))}
renderInput={(p) => <TextField {...p} label={f.label} />}
/>
);
})}
</Box>
<Stack direction="row" spacing={1} sx={{ mt: 2 }}>
<Button type="submit" variant="contained" disabled={busy}>{ui('search')}</Button>
<Button color="inherit" onClick={() => { setValues({}); setClasses(null); onReset(); }}>{ui('clear')}</Button>
</Stack>
</Paper>
);
}
interface Pick { id: string; title: string }
interface Sub extends Pick { type: string; price: number; platformPrice: number; lines: PackageCard['lines'] }
/** The subscription request wizard: service type → package → service → subscription → vehicles/employees → payment. */
export function SubscriptionWizard() {
const ui = useUi();
const t = useT();
const nav = useNavigate();
const qc = useQueryClient();
const notify = useNotify();
const { user, lang } = useAuth();
const rtl = isRtl(lang);
const [step, setStep] = useState(0);
const [group, setGroup] = useState<Pick | null>(null);
const [pkg, setPkg] = useState<Pick | null>(null);
const [service, setService] = useState<Pick | null>(null);
const [sub, setSub] = useState<Sub | null>(null);
const [estate, setEstate] = useState('');
const [error, setError] = useState('');
const [selected, setSelected] = useState<string[]>([]);
const [method, setMethod] = useState('');
const [receipt, setReceipt] = useState('');
const [agree, setAgree] = useState(false);
const [confirm, setConfirm] = useState(false);
const [entries, setEntries] = useState<OneTripEntry[]>([]);
const [approvalId, setApprovalId] = useState(0);
const [tripEstate, setTripEstate] = useState('');
const [found, setFound] = useState<Selectable[] | null>(null);
const [searching, setSearching] = useState(false);
const groups = useQuery({ queryKey: ['wiz', 'groups'], queryFn: getPackageGroups, enabled: step === 0 });
const packages = useQuery({ queryKey: ['wiz', 'packages', group?.id], queryFn: () => getPackages(group!.id), enabled: step === 1 && !!group });
const services = useQuery({
queryKey: ['wiz', 'services', pkg?.id, group?.id],
queryFn: () => getServiceCategories(pkg!.id, group!.id),
enabled: step === 2 && !!pkg && !!group,
});
const subs = useQuery({
queryKey: ['wiz', 'subs', pkg?.id, service?.id, group?.id],
queryFn: () => getServiceSubscriptions(pkg!.id, service!.id, group!.id),
enabled: step >= 3 && !!pkg && !!service && !!group,
});
const unowned = group?.id === 'UNOWNED_FLEET';
const estates = subs.data?.estates ?? [];
// a single industrial area is chosen for the user, as the old wizard did
const estateValue = estate || (estates.length === 1 ? String(estates[0].CODE) : '');
const listed = sub?.type === 'MULTI_TRIP' || sub?.type === 'EMPLOYEES';
const oneTrip = sub?.type === 'ONE_TRIP';
// one-trip permits are priced per truck that is charged; the platform service applies to every truck
const count = oneTrip ? entries.length : selected.length;
const items = useQuery({
queryKey: ['wiz', 'items', sub?.type, pkg?.id, service?.id, sub?.id, estateValue],
queryFn: (): Promise<FleetResult> =>
sub!.type === 'EMPLOYEES'
? getEmployees(pkg!.id).then((items) => ({ kind: 'list' as const, items }))
: getFleet({ packageCode: pkg!.id, service: service!.id, subscription: sub!.id, estate: estateValue }),
enabled: step >= 4 && !!sub && listed,
});
const listItems = items.data?.kind === 'list' ? items.data.items : items.data?.kind === 'search' ? found : undefined;
const riyada = useQuery({
queryKey: ['wiz', 'riyada'],
queryFn: () => getRiyadaCount(String(user?.related_entity_id ?? ''), String(user?.related_entity_record_id ?? '')),
enabled: step >= 4 && pkg?.id === RIYADA,
});
const methods = useQuery({ queryKey: ['wiz', 'methods', group?.id], queryFn: () => getPaymentMethods(group!.id), enabled: step === 5 && !!group });
const total = useMemo(() => {
if (!sub) return 0;
if (oneTrip) return sub.price * entries.filter((e) => e.fees).length + sub.platformPrice * entries.length;
return (sub.price + sub.platformPrice) * selected.length;
}, [sub, selected.length, oneTrip, entries]);
const pay = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const amount = total;
const chosen = method || (amount === 0 ? '0' : '');
if (chosen === '6') {
const verdict = await validateReceipt(receipt.trim(), amount);
if (String(verdict) !== 'VALID') throw new Error(String(verdict));
}
return createSubscription({
packageCode: pkg!.id,
packageGroupCode: [sub!.id],
fleetArray: JSON.stringify(oneTrip ? entries.map((e) => e.payload) : selected),
paymentMethod: Number(chosen),
subscriptionDetailsType: sub!.type,
packageGroupType: group!.id,
approval_number_id: oneTrip ? approvalId : 0,
periodicSubscriptionLocationID: oneTrip ? tripEstate : estateValue,
...(chosen === '6' ? { receipt_id: receipt.trim() } : {}),
});
},
onSuccess: (r) => {
setConfirm(false);
void qc.invalidateQueries({ queryKey: ['grid'] });
// one-trip requests report problems in RESULTCODE rather than throwing
if (r.RESULTCODE === 'FAILED') {
const failed = r.RESULTDATA?.find((x) => x.response_code === 'FAILED');
return notify.error(new Error(failed?.response_error_codes ?? 'ACTION_FAILED'));
}
if (r.RESULTCODE === 'FAILED_INCCORECT_APPROVAL_NUMBER_STATUS') return notify.error(new Error('APPROVAL_NUMBER_INCORRECT_STATUS'));
if (r.RESULTCODE === 'FAILED_NO_ENOUGH_BALANCE') return notify.error(new Error('FAILED_NO_ENOUGH_BALANCE'));
if (r.RECEIVABLES === 'true' || r.RESULTCODE === 'CANT_CREATE_DUE_TO_RECEIVABLES') {
// unpaid dues must be settled first; the backend says so
notify.warning(String(r.MESSAGE ?? ''), '');
nav('/e/FLEET_PENDING_FINANCIAL_TRANSACTIONS/grid');
return;
}
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
nav(sub?.type === 'EMPLOYEES' ? '/e/EMPLOYEES_SUBSCRIPTIONS/grid' : '/e/SUBSCRIPTIONS/grid');
},
onError: (e) => {
setConfirm(false);
notify.error(e);
},
});
const cap = (key: string, en: string, ar: string) => (t(key) !== key ? t(key) : rtl ? ar : en);
// the old wizard's step captions, in its own words: Available services, Categories, Service, Subscriptions, Details, Paying off
const labels = [
cap('AVAILABLE_SERVICES', 'Available Services', 'الخدمات المتاحة'),
cap('CATEGORIES', 'Categories', 'الفئات'),
cap('SERVICE_NAME', 'Service type', 'نوع الخدمة'),
cap('SUBSCRIPTIONS', 'Subscriptions', 'الإشتراكات'),
cap('DETAILS', 'Details', 'التفاصيل'),
cap('PAYING_OFF', 'Paying Off', 'الدفع'),
];
const current = [groups, packages, services, subs][step];
const empty = (cards?: PackageCard[]) =>
cards && !cards.length && <Typography variant="h6" color="text.secondary" textAlign="center" sx={{ py: 4 }}>{t('NO_AVAILABLE_SERVICES')}</Typography>;
const reset = (to: number) => {
if (to <= 1) setPkg(null);
if (to <= 2) setService(null);
if (to <= 3) setSub(null);
setSelected([]);
setEntries([]);
setApprovalId(0);
setTripEstate('');
setFound(null);
setMethod('');
setReceipt('');
setAgree(false);
};
const toPayment = () => {
if (!count) return setError(cap('WIZARD_SELECT_FLEET_ERROR_MSG', 'Please select at least one item', 'يرجى اختيار عنصر واحد على الأقل'));
if (pkg?.id === RIYADA && selected.length > 2 - Number(riyada.data ?? 0)) return setError(cap('RIYADA_EXCEEDED_QUOTA_LIMIT', 'Quota exceeded', 'تم تجاوز الحد المسموح'));
setError('');
setStep(5);
};
const submit = () => {
const chosen = method || (total === 0 ? '0' : '');
if (!chosen) return setError(cap('PAYMENT_METHOD_NOT_SELECTED', 'Select a payment method', 'يرجى اختيار طريقة الدفع'));
if (!agree) return setError(cap('MUST_CONFIRM', 'You must confirm to continue', 'يجب الموافقة للمتابعة'));
if (chosen === '6' && !receipt.trim()) return setError(cap('PLEASE_ENTER_RECEIPT_NUMBER', 'Enter the receipt number', 'يرجى إدخال رقم الإيصال'));
setError('');
setConfirm(true);
};
return (
<Stack spacing={2}>
<Paper variant="outlined" sx={{ p: 2 }}>
<Stepper activeStep={step} alternativeLabel>
{labels.map((l, i) => (
<Step key={i}>
<StepLabel>{l}</StepLabel>
</Step>
))}
</Stepper>
{(group || pkg || service) && step < 4 && (
<Stack direction="row" spacing={0.75} flexWrap="wrap" useFlexGap sx={{ mt: 2, justifyContent: 'center' }}>
{[group, pkg, service].filter(Boolean).map((p) => <Chip key={p!.id} size="small" label={p!.title} />)}
</Stack>
)}
</Paper>
{step < 4 && current?.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 8 }}><CircularProgress /></Box>}
{step < 4 && current?.error && <Alert severity="error">{ui('loadError')}: {(current.error as Error).message}</Alert>}
{error && <Alert severity="warning" onClose={() => setError('')}>{error}</Alert>}
{step === 0 && groups.data && (
<>
{empty(groups.data)}
<Cards cards={groups.data} action={ui('choose')} onPick={(c) => { reset(1); setGroup({ id: c.id, title: c.title }); setStep(1); }} />
</>
)}
{step === 1 && packages.data && (
<>
{empty(packages.data)}
<Cards cards={packages.data} action={ui('choose')} onPick={(c) => { reset(2); setPkg({ id: c.args[0] ?? c.id, title: c.title }); setStep(2); }} />
</>
)}
{step === 2 && services.data && (
<>
{empty(services.data)}
<Cards cards={services.data} action={ui('choose')} onPick={(c) => { reset(3); setService({ id: c.args[1] ?? c.id, title: c.title }); setEstate(''); setStep(3); }} />
</>
)}
{step === 3 && subs.data && (
<>
{!unowned && estates.length > 0 && (
<TextField select size="small" label={ui('wizEstate')} value={estateValue} onChange={(e) => setEstate(e.target.value)} sx={{ maxWidth: 320 }}>
{estates.map((e) => (
<MenuItem key={String(e.CODE)} value={String(e.CODE)}>{t(e.CAPTION_CODE ?? String(e.CODE))}</MenuItem>
))}
</TextField>
)}
{empty(subs.data.cards)}
<Cards
cards={subs.data.cards}
action={ui('subscribe')}
onPick={(c) => {
const type = c.args[3] ?? '';
// multi-trip subscriptions belong to one industrial area
if (type === 'MULTI_TRIP' && !unowned && !estateValue) return setError(ui('wizPickEstate'));
setError('');
reset(4);
const code = c.args[2] ?? c.id;
setSub({
id: code, title: c.title, type, lines: c.lines,
price: Number(subs.data.prices[`SUB_${code}`] ?? 0),
platformPrice: Number(subs.data.platformPrices[`SUB_${code}`] ?? 0),
});
setStep(4);
}}
/>
</>
)}
{step >= 4 && sub && (
<Paper variant="outlined" sx={{ p: 2 }}>
<Typography fontWeight={700} sx={{ mb: 1 }}>{ui('wizSummary')}</Typography>
<Stack spacing={0.5}>
{[group, pkg, service].filter(Boolean).map((p) => <Typography key={p!.id} fontSize={13.5}>{p!.title}</Typography>)}
<Typography fontSize={14} fontWeight={700}>{sub.title}</Typography>
{sub.lines.map((l, i) => <Typography key={i} fontSize={13} color="text.secondary">{l.text}</Typography>)}
{estateValue && !unowned && !oneTrip && (
<Typography fontSize={13} color="text.secondary">
{ui('wizEstate')}: {t(estates.find((e) => String(e.CODE) === estateValue)?.CAPTION_CODE ?? estateValue)}
</Typography>
)}
<Typography fontSize={14} color="primary.main" fontWeight={700}>{ui('wizPrice')}: {sub.price + sub.platformPrice} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')}</Typography>
</Stack>
</Paper>
)}
{step === 4 && sub && !listed && !oneTrip && <Alert severity="info">{ui('wizNext')}</Alert>}
{step === 4 && sub && oneTrip && (
<>
<OneTripTrucks
packageCode={pkg!.id}
subscriptionCode={sub.id}
packageGroupType={group!.id}
entries={entries}
onEntries={setEntries}
onApprovalId={setApprovalId}
onEstate={setTripEstate}
/>
<Box><Button variant="contained" disabled={!entries.length} onClick={toPayment}>{ui('wizContinue')}</Button></Box>
</>
)}
{step === 4 && sub && listed && (
<>
{items.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 6 }}><CircularProgress /></Box>}
{items.error && <Alert severity="error">{ui('loadError')}: {(items.error as Error).message}</Alert>}
{items.data?.kind === 'search' && (
<FleetSearch
fields={items.data.fields}
busy={searching}
onReset={() => { setFound(null); setSelected([]); }}
onSearch={(filters) => {
setSearching(true);
setSelected([]);
getFilteredFleet({ packageCode: pkg!.id, service: service!.id, subscription: sub!.id, estate: estateValue }, filters)
.then(setFound)
.catch((e) => notify.error(e))
.finally(() => setSearching(false));
}}
/>
)}
{listItems && !listItems.length && <Alert severity="info">{ui('wizNoItems')}</Alert>}
{items.data?.kind === 'search' && !found && <Alert severity="info">{ui('wizSearchFirst')}</Alert>}
{listItems && listItems.length > 0 && <Picker items={listItems} selected={selected} onChange={setSelected} />}
<Box><Button variant="contained" disabled={!selected.length} onClick={toPayment}>{ui('wizContinue')}</Button></Box>
</>
)}
{step === 5 && sub && (
<Paper variant="outlined" sx={{ p: 2 }}>
<Stack direction="row" spacing={4} sx={{ mb: 2 }} flexWrap="wrap" useFlexGap>
<Box><Typography color="text.secondary" fontSize={13}>{ui('wizCount')}</Typography><Typography variant="h5" color="primary">{count}</Typography></Box>
<Box>
<Typography color="text.secondary" fontSize={13}>{cap('TOTAL_PRICE', 'Total price', 'السعر الإجمالي')}</Typography>
<Typography variant="h5" color="primary">{total} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')}</Typography>
</Box>
</Stack>
<Typography fontWeight={700} sx={{ mb: 0.5 }}>{cap('PAYMENT_METHOD', 'Payment method', 'طريقة الدفع')}</Typography>
{methods.isPending && <CircularProgress size={20} />}
<RadioGroup value={method} onChange={(e) => setMethod(e.target.value)}>
{(methods.data ?? []).map((m) => (
<Box key={m.ID}>
<FormControlLabel value={String(m.ID)} disabled={m.ID === CARD_PAYMENT} control={<Radio size="small" />} label={m.NAME} />
{m.ID === CARD_PAYMENT && <Typography variant="caption" color="text.secondary" sx={{ marginInlineStart: 4, display: 'block' }}>{ui('wizCardLater')}</Typography>}
{m.ID === 6 && method === '6' && (
<TextField size="small" label={cap('RECEIPT_NUMBER', 'Receipt number', 'رقم الإيصال')} value={receipt} onChange={(e) => setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} />
)}
</Box>
))}
</RadioGroup>
<FormControlLabel
sx={{ mt: 1 }}
control={<Checkbox checked={agree} onChange={(e) => setAgree(e.target.checked)} />}
label={t(SPECIAL_NOTE.includes(pkg?.id ?? '') ? 'PACKAGES_NOTE' : 'AGREE_NOTE')}
/>
<Box sx={{ mt: 1 }}><Button variant="contained" onClick={submit}>{cap('PAY', 'Pay', 'دفع')}</Button></Box>
</Paper>
)}
{step > 0 && (
<Box>
<Button disabled={pay.isPending} onClick={() => { setError(''); setStep(step - 1); }}>{ui('back')}</Button>
</Box>
)}
<Dialog open={confirm} onClose={() => !pay.isPending && setConfirm(false)}>
<DialogTitle>{cap('PAY', 'Pay', 'دفع')}</DialogTitle>
<DialogContent>
<Typography>{sub?.title}</Typography>
<Typography color="text.secondary">{ui('wizCount')}: {count} · {total} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')}</Typography>
<Typography sx={{ mt: 1 }}>{t('CONFIRM_MSG')}</Typography>
</DialogContent>
<DialogActions>
<Button disabled={pay.isPending} onClick={() => setConfirm(false)}>{t('NO')}</Button>
<Button variant="contained" disabled={pay.isPending} onClick={() => pay.mutate()}>{t('YES')}</Button>
</DialogActions>
</Dialog>
</Stack>
);
}

View File

@ -0,0 +1,550 @@
import { useMemo, useState } from 'react';
import { SectionTitle, sectionFrame } from '../../components/SectionTitle';
import { Link as RouterLink } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Paper,
Stack, Tab, Table, TableBody, TableCell, TableHead, TablePagination, TableRow, Tabs, TextField, Typography,
} from '@mui/material';
import EditOutlined from '@mui/icons-material/EditOutlined';
import { useAuth } from '../../auth/AuthContext';
import { useNotify } from '../../notify/NotifyProvider';
import { isRtl, useLabel, useT, useUi } from '../../i18n';
import { PageHeader } from '../../components/PageHeader';
import { StatusChip } from '../../components/StatusChip';
import { getExtraFields, getView, runAction, type EntityAction, type ExtraSpec } from '../../api/entity';
import type { StoredAttachment } from '../../api/attachments';
import { resolveFields, toDisplayDate, toPayload, type ResolvedField } from '../forms/fields';
import { getLayout, VIEW_HIDDEN_FIELDS, VIEW_HIDDEN_SECTIONS, VIEW_LAST_FIELDS, type EntityLayout } from '../forms/layouts';
import { AttachmentField } from '../forms/AttachmentField';
import { ExtraFieldsDialog } from '../forms/ExtraFieldsDialog';
import { roleLabel } from '../../i18n/roles';
import { downloadReport } from '../../api/report';
import { getHeader } from './headers';
import { SubscriptionDetails } from './SubscriptionDetails';
import { actionNeedsEmail, isDangerous, isSimpleAction } from './actions';
import { FLEET_REQUEST_ORDER, fleetRequestView } from './fleetRequest';
import { PendingPayDialog } from '../gridActions/PendingPayDialog';
import { InvoiceSummary } from './InvoiceSummary';
import { RenewSubscriptionDialog } from '../gridActions/RenewSubscriptionDialog';
type Data = Record<string, unknown>;
/** One read-only value, resolved to the label the user would see in the form. */
function Value({ field, data, layout }: { field: ResolvedField; data: Data; layout: EntityLayout }) {
const { lang } = useAuth();
const t = useT();
const ui = useUi();
const raw = data[layout.alias?.[field.name] ?? field.name];
const dynamic = layout.dynamic?.[field.name];
const textKey = layout.viewText?.[field.name];
const humanize = useLabel();
const parent = dynamic ? String(data[dynamic.dependsOn] ?? '') : '';
const lookup = useQuery({
queryKey: ['lookup', field.name, parent],
queryFn: () => dynamic!.load(parent),
enabled: !!dynamic && !textKey && !!parent && !!raw,
staleTime: 5 * 60_000,
});
const empty = raw === undefined || raw === null || String(raw).trim() === '' || (Array.isArray(raw) && !raw.length);
const none = <Typography component="span" color="text.disabled">—</Typography>;
if (textKey && String(data[textKey] ?? '').trim()) return <>{String(data[textKey])}</>;
const forced = (data.__TEXT as Record<string, string> | undefined)?.[field.name];
if (forced) return <>{forced}</>;
// a stakeholder is stored as an id: show the name the backend sends beside it (investor names come in both languages)
const en = lang !== 'AR';
const named: Record<string, string[]> = {
STAKEHOLDER_ENTITY_RECORD_ID: ['STAKEHOLDER_ENTITY_RECORD_NAME'],
INDUSTRIAL_ESTATE_STAKEHOLDER_ID: [en ? 'INDUSTRIAL_INVESTOR_NAME_EN' : 'INDUSTRIAL_INVESTOR_NAME', 'INDUSTRIAL_INVESTOR_NAME'],
};
const nameText = (named[field.name] ?? []).map((k) => String(data[k] ?? '').trim()).find(Boolean);
if (nameText) return <>{nameText}</>;
// plate codes come as <FIELD>_AR / <FIELD>_EN when the plain field is empty
const coded = String(data[`${field.name}_${en ? 'EN' : 'AR'}`] ?? '').trim();
if (coded && /PLATE_CODE/.test(field.name)) return <>{coded}</>;
if (empty) return none;
// an affiliation's truck is stored as an id; the page should read as the plate number the user knows
if (field.name === 'TRUCK_ID') {
const side = lang === 'AR' ? 'AR' : 'EN';
const plate = [`PLATE_NUMBER_GRID_${side}`, 'PLATE_NUMBER_GRID_AR', 'PLATE_NUMBER_GRID_EN', 'PLATE_NUMBER']
.map((k) => String(data[k] ?? '').trim())
.find(Boolean);
if (plate) return <>{plate}</>;
}
// a job title the caption table has no entry for comes back as its role code; name it in the page's language
if (field.name === 'JOB_TITLE') return <>{roleLabel(String(raw), t, humanize, isRtl(lang))}</>;
if (field.type === 'DATE') return <>{toDisplayDate(raw)}</>;
if (field.type === 'DROPDOWN' || field.type === 'DROPDOWN_MULTI') {
const options = dynamic ? (lookup.data ?? []) : (field.options ?? []);
const label = (code: unknown) => {
const o = options.find((x) => String(x.CODE) === String(code).trim());
if (o) return o.NAME || t(o.CAPTION_CODE ?? String(o.CODE));
// a code the caption table does not know is shown in a readable form, never as RAW_UPPER_CASE
const c = String(code).trim();
return t(c) !== c ? t(c) : humanize(c);
};
return <>{Array.isArray(raw) ? raw.map(label).join('، ') : label(raw)}</>;
}
return <>{String(raw).trim() || ui('notProvided')}</>;
}
export function EntityView({ entity, id }: { entity: string; id: string }) {
const { config, lang, user } = useAuth();
const t = useT();
const ui = useUi();
const qc = useQueryClient();
const lab = useLabel();
const layout = useMemo(() => getLayout(entity, config), [entity, config]);
const [tab, setTab] = useState(0);
const [action, setAction] = useState<EntityAction | null>(null);
const [extra, setExtra] = useState<{ action: EntityAction; spec: ExtraSpec } | null>(null);
const [detPage, setDetPage] = useState(0);
const [vatOpen, setVatOpen] = useState(false);
const [vat, setVat] = useState('');
const [replyOpen, setReplyOpen] = useState(false);
const [payOpen, setPayOpen] = useState(false);
const [renewOpen, setRenewOpen] = useState(false);
const [replyText, setReplyText] = useState('');
const notify = useNotify();
const view = useQuery({ queryKey: ['view', entity, id], queryFn: () => getView(entity, id), staleTime: 0 });
// a ticket's DESCRIPTION arrives as { DESCRIPTION, REPLY: [...] }: the text stays a field, the replies get a table of their own
const raw: Data = useMemo(() => view.data?.data ?? {}, [view.data]);
const replies = useMemo(
() => ((raw.DESCRIPTION as { REPLY?: Record<string, unknown>[] } | undefined)?.REPLY ?? []),
[raw],
);
const fleetReq = useMemo(() => (entity === 'FLEET_REQUEST' ? fleetRequestView(raw, user, lang === 'AR') : null), [entity, raw, user, lang]);
const data: Data = useMemo(() => {
if (fleetReq) return fleetReq.data;
const d = raw.DESCRIPTION;
return d && typeof d === 'object' ? { ...raw, DESCRIPTION: (d as { DESCRIPTION?: unknown }).DESCRIPTION ?? '' } : raw;
}, [raw, fleetReq]);
const hiddenFields = useMemo(() => [...(VIEW_HIDDEN_FIELDS[entity] ?? []), ...(fleetReq?.hidden ?? [])], [entity, fleetReq]);
const status = String(data.STATUS_CODE ?? '').trim() || undefined;
const fieldNames = useMemo(() => layout?.sections.flatMap((s) => s.fields) ?? [], [layout]);
const fields = useMemo(
() => (config && layout ? resolveFields(config, entity, 'EDIT', status, fieldNames) : []),
[config, layout, entity, status, fieldNames],
);
const byName = useMemo(() => new Map(fields.map((f) => [f.name, f])), [fields]);
const run = useMutation({
meta: { loading: 'processing' },
mutationFn: async (v: { a: EntityAction; reason?: Record<string, string> }) => {
const values = { ...data, ...Object.fromEntries(Object.entries(layout?.alias ?? {}).map(([f, src]) => [f, data[src]])) };
return runAction(entity, v.a.ACTION_NAME, toPayload(fields, values), id, [], v.reason);
},
onSuccess: (res) => {
notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
// print / invoice actions answer with the generated file's location
const file = typeof res.DATA === 'string' ? res.DATA : (res.DATA as { FILE?: string } | undefined)?.FILE;
if (file && /downloadFiles/i.test(file)) void downloadReport(file).catch((e) => notify.error(e));
setAction(null);
setExtra(null);
void qc.invalidateQueries({ queryKey: ['grid', entity] });
void view.refetch();
},
onError: (e) => notify.error(e),
});
// UPDATE_VAT (stakeholders, finance role): only the VAT number is sent, with the commercial registration number
const vatMutation = useMutation({
meta: { loading: 'saving' },
mutationFn: () => runAction(entity, 'UPDATE_VAT', { VAT_NUMBER: vat.trim(), CRN: String(data.CRN ?? '').trim() }, id, []),
onSuccess: (res) => {
notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
setVatOpen(false);
void qc.invalidateQueries({ queryKey: ['grid', entity] });
void view.refetch();
},
onError: (e) => notify.error(e),
});
// ADD_REPLY (complaints and suggestions) carries the typed answer as REPLY, like the legacy reply box
const reply = useMutation({
meta: { loading: 'saving' },
mutationFn: () => runAction(entity, replyAction?.ACTION_NAME ?? 'ADD_REPLY', { REPLY: replyText.trim() }, id, []),
onSuccess: (res) => {
notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
setReplyOpen(false);
setReplyText('');
void qc.invalidateQueries({ queryKey: ['grid', entity] });
void view.refetch();
},
onError: (e) => notify.error(e),
});
// actions that need a reason open that popup first; the others just ask for confirmation
const askAction = async (a: EntityAction) => {
run.reset();
if (actionNeedsEmail(a.ACTION_NAME) && !String(data.EMAIL ?? '').trim()) {
notify.warning('EMAIL_REQUIRED_FOR_ACTION', ui('emailRequiredForAction'));
return;
}
// printing only produces a file: no confirmation, like the old page
if (a.ACTION_NAME === 'PRINT' || a.ACTION_NAME === 'GET_INVOICE') {
run.mutate({ a });
return;
}
try {
const spec = await getExtraFields(entity, a.ACTION_NAME);
if (spec) setExtra({ action: a, spec });
else setAction(a);
} catch (e) {
notify.error(e);
}
};
if (!layout) return <Alert severity="info">{t(entity)}</Alert>;
if (view.isPending) return <Box sx={{ display: 'grid', placeItems: 'center', py: 10 }}><CircularProgress /></Box>;
if (view.error) return <Alert severity="error">{t((view.error as Error).message)}</Alert>;
const label = (field: string, code: unknown) => {
const c = String(code ?? '').trim();
if (!c) return '';
const o = byName.get(field)?.options?.find((x) => String(x.CODE) === c);
return o ? o.NAME || t(o.CAPTION_CODE ?? String(o.CODE)) : t(c);
};
const header = getHeader(entity, data, isRtl(lang), label, t(entity));
const actions = view.data!.actions;
// legacy shows the trailers section only when the affiliated truck is a truck head
const trailers = view.data!.trailers;
const isTruckHead = String(data.USE_DESCRIPTION ?? '').trim() === 'TRUCK_HEAD_LORRY';
// the support role's action is OPOFF_ADD_REPLY: same box, the action name is whatever the backend listed
const replyAction = actions.find((a) => /(^|_)ADD_REPLY$/.test(a.ACTION_NAME));
const vatAction = actions.find((a) => a.ACTION_NAME === 'UPDATE_VAT');
const canEdit = actions.some((a) => a.ACTION_NAME === 'UPDATE');
const stored = (data.ATTACHMENTS as StoredAttachment[] | undefined) ?? [];
const sysVar = (name: string) => (config?.SYSTEM_VARIABLES as { NAME: string; VALUE: string }[] | undefined)?.find((v) => v.NAME === name)?.VALUE;
const baseUrl = sysVar('ATTACHMENT_URL') ?? '';
const layoutDocs = layout.sections.flatMap((s) => s.fields).map((n) => byName.get(n)).filter((f): f is ResolvedField => !!f && f.type === 'ATTACHMENT');
// a subscription's files are not form fields: the old page always had the driver's four, the gate pass for the
// Suhar packages and the reference document for the free-zone package
const pkg = String(data.CODE ?? '').trim();
const docFields: { name: string; caption: string }[] =
entity === 'SUBSCRIPTIONS'
? [
{ name: 'DRIVER_FRONT_PER_DOC_ATT', caption: 'DRIVER_ID_FRONT' },
{ name: 'DRIVER_BACK_PER_DOC_ATT', caption: 'DRIVER_ID_BACK' },
{ name: 'DRIVER_FRONT_LIC_ATT', caption: 'DRIVER_LICENSE_FRONT' },
{ name: 'DRIVER_BACK_LIC_ATT', caption: 'DRIVER_LICENSE_BACK' },
...(['ISD0001', 'ISW0001', 'IRM0001', 'IMA0001', 'IME0001', 'SID0001'].includes(pkg)
? [{ name: 'GATE_PASS_ATT', caption: pkg === 'ISD0001' ? 'GATE_PASS_WAYBILL' : 'ATTACHMENT' }]
: []),
...(pkg === 'FZP0001' ? [{ name: 'REFERENCE_DOCUMENT_ATT', caption: 'REFERENCE_DOCUMENT_ATT' }] : []),
]
: layoutDocs.filter((f) => !hiddenFields.includes(f.name)).map((f) => ({ name: f.name, caption: f.caption }));
// the old pages kept their attachments in titled groups (sender / support side, driver / vehicle…): keep the same groups
const docGroups: { title: string; fields: { name: string; caption: string }[] }[] =
entity === 'SUBSCRIPTIONS'
? [{ title: '', fields: docFields }]
: layout.sections
.map((s) => ({ title: s.title, fields: docFields.filter((d) => s.fields.includes(d.name)) }))
.filter((g) => g.fields.length);
return (
<>
<PageHeader
backTo={`/e/${entity}/grid`}
// every record page: the entity's name on top in the accent colour, under it the record's own value in a smaller
// font (a plate badge where the entity is a vehicle), and the status beside it
title={t(entity)}
subtitle={
<Stack direction="row" spacing={1} alignItems="center" flexWrap="wrap" useFlexGap>
{header.lead}
{header.title && header.title !== t(entity) && (
<Typography component="span" fontSize={16} fontWeight={700} color="text.primary">{header.title}</Typography>
)}
{header.status && <StatusChip status={header.status} />}
{header.subtitle && header.subtitle !== t(entity) && <span>{header.subtitle}</span>}
</Stack>
}
actions={
<>
{actions
.filter(isSimpleAction)
.map((a) => (
<Button key={a.ACTION_NAME} variant="outlined" color={isDangerous(a.ACTION_NAME) ? 'error' : 'primary'} onClick={() => void askAction(a)}>
{t(String(a.ACTION_CAPTION_CODE ?? a.ACTION_NAME))}
</Button>
))}
{vatAction && (
<Button variant="contained" onClick={() => { vatMutation.reset(); setVat(String(data.VAT_NUMBER ?? '').trim()); setVatOpen(true); }}>
{t(String(vatAction.ACTION_CAPTION_CODE ?? 'UPDATE_VAT'))}
</Button>
)}
{entity === 'SUBSCRIPTIONS' && actions.some((a) => a.ACTION_NAME === 'RENEW_SUBSCRIPTION') && (
<Button variant="contained" color="success" onClick={() => setRenewOpen(true)}>{t('RENEW_SUBSCRIPTION')}</Button>
)}
{entity === 'FLEET_PENDING_FINANCIAL_TRANSACTIONS' && actions.some((a) => a.ACTION_NAME === 'PAY') && (
<Button variant="contained" color="success" onClick={() => setPayOpen(true)}>{t('PAY')}</Button>
)}
{replyAction && (
<Button variant="contained" onClick={() => { reply.reset(); setReplyOpen(true); }}>
{t(String(replyAction.ACTION_CAPTION_CODE ?? replyAction.ACTION_NAME))}
</Button>
)}
{canEdit && (
<Button variant="contained" startIcon={<EditOutlined />} component={RouterLink} to={`/e/${entity}/create/${id}`}>
{ui('edit')}
</Button>
)}
</>
}
/>
{docFields.length > 0 && (
<Tabs value={tab} onChange={(_, v: number) => setTab(v)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
<Tab label={ui('details')} />
<Tab label={`${ui('documents')} (${stored.length})`} />
</Tabs>
)}
{tab === 0 && (
<Stack spacing={1.5}>
{entity === 'SUBSCRIPTIONS' && <SubscriptionDetails data={data} label={label} />}
{entity !== 'SUBSCRIPTIONS' && layout.sections.map((s) => {
if (VIEW_HIDDEN_SECTIONS[entity]?.includes(s.title)) return null;
const last = VIEW_LAST_FIELDS[entity] ?? [];
const base = [...s.fields.filter((n) => !last.includes(n)), ...s.fields.filter((n) => last.includes(n))];
const rank = (n: string) => { const i = FLEET_REQUEST_ORDER.indexOf(n); return i < 0 ? 99 : i; };
const ordered = entity === 'FLEET_REQUEST' ? [...base].sort((a, b) => rank(a) - rank(b)) : base;
const shown = ordered
.filter((n) => !hiddenFields.includes(n))
// the form swaps a plate-code dropdown and a free-text box by nationality; a record page shows the code once
.filter((n) => !(n === 'PLATE_CODE_AR' && (s.fields.includes('PLATE_CODE') || s.fields.includes('FLEET_PLATE_CODE'))))
.map((n) => byName.get(n))
.filter((f): f is ResolvedField => !!f && !f.hidden && f.type !== 'ATTACHMENT');
if (!shown.length) return null;
return (
<Paper key={s.title} variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<SectionTitle view code={s.title}>{lab(s.title)}</SectionTitle>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{shown.map((f) => (
<Box key={f.name} sx={{ minWidth: 0 }}>
<Typography component="div" fontSize={13.5} fontWeight={600} color="primary.main" lineHeight={1.4}>{lab(f.caption)}</Typography>
<Typography fontSize={14} sx={{ wordBreak: 'break-word' }}><Value field={f} data={data} layout={layout} /></Typography>
</Box>
))}
</Box>
</Paper>
);
})}
{entity === 'INVOICES' && <InvoiceSummary id={id} data={raw} />}
{replies.length > 0 && (
<Paper variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<SectionTitle view code="REPLY">{lab('REPLY_DETAILS')}</SectionTitle>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
{['NAME', 'USER_TYPE', 'REPLY_DATE', 'REPLY_DETAILS'].map((c) => (
<TableCell key={c} align="center">{lab(c)}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{replies.map((r, i) => {
const d = String(r.CREATION_DATE ?? '');
const when = /^\d{14}$/.test(d) ? `${d.slice(6, 8)}/${d.slice(4, 6)}/${d.slice(0, 4)} ${d.slice(8, 10)}:${d.slice(10, 12)}:${d.slice(12)}` : d;
return (
<TableRow key={i}>
<TableCell align="center">{String(r.CREATED_BY_NAME ?? '')}</TableCell>
<TableCell align="center">{String(r.CREATED_BY_ROLE_CODE ?? '')}</TableCell>
<TableCell align="center" dir="ltr">{when}</TableCell>
<TableCell align="center" sx={{ whiteSpace: 'pre-wrap' }}>{String(r.DESCRIPTION ?? '')}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Box>
</Paper>
)}
{(view.data!.details ?? []).length > 0 && (
<Paper variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<SectionTitle view code="RECONCILIATION">{ui('reconciliationLines')}</SectionTitle>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
{['SERIAL', 'CARD_HOLDER_NAME', 'CARD_NUMBER', 'MERCHANT_TRACK_ID', 'AMOUNT_OMANI_RIALS', 'TRANSACTION_TYPE', 'STATUS_CODE'].map((c) => (
<TableCell key={c} align="center">{lab(c)}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{(view.data!.details ?? []).slice(detPage * 25, detPage * 25 + 25).map((r, i) => (
<TableRow key={String(r.ID ?? i)}>
<TableCell align="center">{String(r.S_NO ?? '')}</TableCell>
<TableCell align="center">{String(r.CARD_HOLDER_NAME ?? '')}</TableCell>
<TableCell align="center" dir="ltr">{String(r.CARD_NUMBER ?? '')}</TableCell>
<TableCell align="center">{String(r.MERCHANT_TRACK_ID ?? '')}</TableCell>
<TableCell align="center">{String(r.TERMINAL_AMOUNT ?? '')}</TableCell>
<TableCell align="center">{String(r.ACTION_CODE ?? '')}</TableCell>
<TableCell align="center">{String(r.STATUS_CODE ?? '')}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
<TablePagination
component="div"
count={(view.data!.details ?? []).length}
page={detPage}
rowsPerPage={25}
rowsPerPageOptions={[25]}
labelDisplayedRows={({ from, to, count }) => `${from}–${to} ${ui('pagerOf')} ${count}`}
onPageChange={(_, p) => setDetPage(p)}
/>
</Paper>
)}
{(trailers.length > 0 || isTruckHead) && (
<Paper variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<SectionTitle view code="TRAILER">{lab('TRAILERS_INFO')}</SectionTitle>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
{['PLATE_NUMBER', 'EQUIPMENT_DESCRIPTION', 'EXTREME_CAPACITY', 'EMPTY_WEIGHT', 'AXES_NUMBER'].map((c) => (
<TableCell key={c} align="center">{lab(c)}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{trailers.map((r, i) => (
<TableRow key={String(r.ID ?? i)}>
<TableCell align="center" dir="ltr">{String(r.PLATE_NUMBER ?? '')}</TableCell>
<TableCell align="center">{t(String(r.USE_DESCRIPTION ?? '').trim())}</TableCell>
<TableCell align="center">{String(r.EXTREME_CAPACITY ?? '')}</TableCell>
<TableCell align="center">{String(r.EMPTY_WEIGHT ?? '')}</TableCell>
<TableCell align="center">{String(r.AXES_NUMBER ?? '')}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Paper>
)}
</Stack>
)}
{tab === 1 && (
<Stack spacing={1.5}>
{docGroups.map((g) => (
<Paper key={g.title || 'docs'} variant="outlined" sx={{ p: 2, ...sectionFrame }}>
{g.title && <SectionTitle view code={g.title}>{lab(g.title)}</SectionTitle>}
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>
{g.fields.map((f) => (
<AttachmentField
key={f.name}
field={f.name}
label={lab(f.caption)}
required={false}
readOnly
stored={stored.find((a) => a.FILE_BUSINESS_TYPE.trim() === f.name)}
baseUrl={baseUrl}
maxMb={0}
onPending={() => {}}
/>
))}
</Box>
</Paper>
))}
</Stack>
)}
<Dialog open={!!action} onClose={() => setAction(null)}>
<DialogTitle>{t(String(action?.ACTION_CAPTION_CODE ?? action?.ACTION_NAME ?? ''))}</DialogTitle>
<DialogContent>
<Typography>{t('CONFIRM_MSG')}</Typography>
{run.error && <Alert severity="error" sx={{ mt: 2 }}>{t((run.error as Error).message)}</Alert>}
</DialogContent>
<DialogActions>
<Button onClick={() => setAction(null)}>{t('NO')}</Button>
<Button variant="contained" disabled={run.isPending} onClick={() => action && run.mutate({ a: action })}>{t('YES')}</Button>
</DialogActions>
</Dialog>
<Dialog open={vatOpen} onClose={() => setVatOpen(false)} fullWidth maxWidth="xs">
<DialogTitle>{t(String(vatAction?.ACTION_CAPTION_CODE ?? 'UPDATE_VAT'))}</DialogTitle>
<DialogContent>
<TextField autoFocus fullWidth margin="dense" label={lab(byName.get('VAT_NUMBER')?.caption ?? 'VAT_NUMBER')} value={vat} onChange={(e) => setVat(e.target.value)} />
{vatMutation.error && <Alert severity="error" sx={{ mt: 2 }}>{t((vatMutation.error as Error).message)}</Alert>}
</DialogContent>
<DialogActions>
<Button onClick={() => setVatOpen(false)}>{t('BACK')}</Button>
<Button variant="contained" disabled={vatMutation.isPending} onClick={() => vatMutation.mutate()}>{t(String(vatAction?.ACTION_CAPTION_CODE ?? 'UPDATE_VAT'))}</Button>
</DialogActions>
</Dialog>
<Dialog open={replyOpen} onClose={() => setReplyOpen(false)} fullWidth maxWidth="sm">
<DialogTitle>{t(String(replyAction?.ACTION_CAPTION_CODE ?? 'ADD_REPLY'))}</DialogTitle>
<DialogContent>
<TextField
autoFocus
fullWidth
multiline
minRows={4}
margin="dense"
label={lab(byName.get('REPLY')?.caption ?? 'REPLY')}
value={replyText}
onChange={(e) => setReplyText(e.target.value)}
/>
{reply.error && <Alert severity="error" sx={{ mt: 2 }}>{t((reply.error as Error).message)}</Alert>}
</DialogContent>
<DialogActions>
<Button onClick={() => setReplyOpen(false)}>{t('BACK')}</Button>
<Button variant="contained" disabled={reply.isPending || !replyText.trim()} onClick={() => reply.mutate()}>
{t(String(replyAction?.ACTION_CAPTION_CODE ?? 'ADD_REPLY'))}
</Button>
</DialogActions>
</Dialog>
{renewOpen && (
<RenewSubscriptionDialog
params={{
serviceGroupCode: String(raw.SERVICE_GROUP_CODE ?? ''),
pacakgeCode: String(raw.CODE ?? ''),
durationID: String(raw.DURATION_ID ?? ''),
fleetData: `${raw.FLEET_ENTITY_ID ?? ''}_${raw.FLEET_ENTITY_RECORD_ID ?? ''}`,
subscriptionServiceID: id,
}}
onClose={() => setRenewOpen(false)}
onDone={() => {
setRenewOpen(false);
void qc.invalidateQueries({ queryKey: ['grid', entity] });
void view.refetch();
}}
/>
)}
{payOpen && (
<PendingPayDialog
id={id}
data={raw}
onClose={() => setPayOpen(false)}
onDone={() => {
setPayOpen(false);
void qc.invalidateQueries({ queryKey: ['grid', entity] });
void view.refetch();
}}
/>
)}
{extra && (
<ExtraFieldsDialog
spec={extra.spec}
title={t(String(extra.action.ACTION_CAPTION_CODE ?? extra.action.ACTION_NAME))}
onCancel={() => setExtra(null)}
onSubmit={(reason) => run.mutate({ a: extra.action, reason })}
/>
)}
</>
);
}

View File

@ -0,0 +1,164 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
Alert, Box, Button, Chip, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Paper, Table, TableBody, TableCell, TableFooter,
TableHead, TableRow, Typography,
} from '@mui/material';
import ReceiptLongOutlined from '@mui/icons-material/ReceiptLongOutlined';
import { rpc } from '../../api/client';
import { useLabel, useT, useUi } from '../../i18n';
type Row = (string | number)[];
interface Grid { DATA?: Row[]; CODE?: string | number; MESSAGE?: string }
const money = (v: unknown) => (Number.isFinite(Number(v)) ? Number(v).toFixed(3) : '0.000');
/** One figure of the summary: a caption over a big number with the currency. */
function Tile({ caption, value, unit, strong, tone }: { caption: string; value: string; unit: string; strong?: boolean; tone?: 'neg' }) {
return (
<Box
sx={{
flex: '1 1 150px',
p: 1.5,
borderRadius: 2,
border: 1,
borderColor: strong ? 'primary.main' : 'divider',
bgcolor: strong ? 'primary.main' : 'transparent',
color: strong ? 'primary.contrastText' : 'text.primary',
}}
>
<Typography fontSize={12.5} sx={{ opacity: strong ? 0.85 : 1 }} color={strong ? 'inherit' : 'text.secondary'}>{caption}</Typography>
<Typography fontSize={22} fontWeight={800} lineHeight={1.3} color={tone === 'neg' && !strong ? 'error.main' : 'inherit'}>
<bdi dir="ltr">{value}</bdi> <Typography component="span" fontSize={12.5} fontWeight={600} color="inherit" sx={{ opacity: 0.8 }}>{unit}</Typography>
</Typography>
</Box>
);
}
/**
* The legacy invoice page's "Invoice summary": the subscriptions and services the invoice bills, with their amounts and how
* many subscriptions each covers, closed by the total, the tax, the discount and the net amount. Clicking a count lists them.
*/
export function InvoiceSummary({ id, data }: { id: string; data: Record<string, unknown> }) {
const t = useT();
const lab = useLabel();
const ui = useUi();
const [open, setOpen] = useState<{ row: Row; title: string } | null>(null);
const unit = t('RO') !== 'RO' ? t('RO') : 'OMR';
const lines = useQuery({
queryKey: ['invoice-summary', id],
queryFn: () => rpc<Grid>('INVOICES', 'getTransactionPackage', { DATA: { invoice_ID: id } }),
staleTime: 0,
});
const rows = lines.data?.DATA ?? [];
const sum = rows.reduce((a, r) => a + Number(r[3] ?? 0), 0);
const count = rows.reduce((a, r) => a + Number(r[4] ?? 0), 0);
const tax = Number(data.TAX || 0);
const discount = Number(data.DISCOUNT || 0);
const net = Number(data.NET_AMOUNT ?? data.AMOUNT ?? 0);
return (
<Paper variant="outlined" sx={{ p: 2 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.5 }}>
<ReceiptLongOutlined color="primary" fontSize="small" />
<Typography component="h2" fontWeight={700} fontSize={14.5}>{ui('invoiceSummary')}</Typography>
</Box>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1.25, mb: 2 }}>
<Tile caption={t('TOTAL')} value={money(sum)} unit={unit} />
<Tile caption={t('TAX')} value={money(tax)} unit={unit} />
<Tile caption={t('DISCOUNT')} value={money(discount)} unit={unit} />
<Tile caption={lab('NET_AMOUNT')} value={money(net)} unit={unit} strong tone={net < 0 ? 'neg' : undefined} />
</Box>
{lines.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 3 }}><CircularProgress size={26} /></Box>}
{lines.error && <Alert severity="error">{t((lines.error as Error).message)}</Alert>}
{lines.data && !rows.length && <Typography color="text.secondary" textAlign="center" sx={{ py: 2 }}>{t('NO_INFO')}</Typography>}
{rows.length > 0 && (
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>{t('SUBSCRIPTION_NAME')}</TableCell>
<TableCell>{t('SERVICE_NAME')}</TableCell>
<TableCell align="right">{t('AMOUNT')}</TableCell>
<TableCell align="center">{t('NUMBER_OF_SUBSCRIPTIONS')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((r, i) => (
<TableRow key={i} hover>
<TableCell>{String(r[1] || r[6] || '—')}</TableCell>
<TableCell>{String(r[2] ?? '')}</TableCell>
<TableCell align="right"><bdi dir="ltr">{money(r[3])}</bdi></TableCell>
<TableCell align="center">
<Chip size="small" color="primary" variant="outlined" label={String(r[4] ?? 0)} onClick={() => setOpen({ row: r, title: String(r[2] ?? '') })} />
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow sx={{ '& td': { fontWeight: 800, fontSize: 13.5 } }}>
<TableCell colSpan={2}>{t('TOTAL')}</TableCell>
<TableCell align="right"><bdi dir="ltr">{money(sum)}</bdi></TableCell>
<TableCell align="center">{count}</TableCell>
</TableRow>
</TableFooter>
</Table>
</Box>
)}
{open && <TransactionsDialog invoiceId={id} row={open.row} title={open.title} unit={unit} onClose={() => setOpen(null)} />}
</Paper>
);
}
/** The subscriptions (financial transactions) behind one line of the summary. */
function TransactionsDialog({ invoiceId, row, title, unit, onClose }: { invoiceId: string; row: Row; title: string; unit: string; onClose: () => void }) {
const t = useT();
const list = useQuery({
queryKey: ['invoice-lines', invoiceId, row[0], row[5], row[6]],
queryFn: () =>
rpc<Grid>('INVOICES', 'GETGRIDFINANCIAILTRANSACTIONS', {
DATA1: { PackageID: row[0], invoices_ID: invoiceId, code: row[5], group_code: row[6] },
page: 1,
rows: 200,
}),
staleTime: 0,
});
const data = list.data?.DATA ?? [];
return (
<Dialog open onClose={onClose} maxWidth="md">
<DialogTitle>{title}</DialogTitle>
<DialogContent>
{list.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}><CircularProgress size={26} /></Box>}
{list.error && <Alert severity="error">{t((list.error as Error).message)}</Alert>}
{list.data && !data.length && <Typography color="text.secondary">{t('NO_INFO')}</Typography>}
{data.length > 0 && (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>{t('CREATION_DATE')}</TableCell>
<TableCell>{t('SERVICE_NAME')}</TableCell>
<TableCell align="center">{t('NUMBER')}</TableCell>
<TableCell align="right">{`${t('AMOUNT')} (${unit})`}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map((r, i) => (
<TableRow key={String(r[0] ?? i)}>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{String(r[1] ?? '')}</TableCell>
<TableCell>{String(r[2] ?? '')}</TableCell>
<TableCell align="center"><bdi dir="ltr">{String(r[3] ?? '')}</bdi></TableCell>
<TableCell align="right"><bdi dir="ltr">{money(r[4])}</bdi></TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</DialogContent>
<DialogActions><Button onClick={onClose}>{t('CLOSE')}</Button></DialogActions>
</Dialog>
);
}

View File

@ -0,0 +1,158 @@
import { useQuery } from '@tanstack/react-query';
import { SectionTitle, sectionFrame } from '../../components/SectionTitle';
import DOMPurify from 'dompurify';
import { Box, Checkbox, FormControlLabel, Paper, Stack, Typography } from '@mui/material';
import { useAuth } from '../../auth/AuthContext';
import { useLabel, useT, useUi } from '../../i18n';
import { PlateBadge } from '../../components/PlateBadge';
import { getOptions } from '../../api/entity';
import { rpc } from '../../api/client';
type Data = Record<string, unknown>;
const s = (v: unknown) => String(v ?? '').trim();
const FINANCE_ROLES = ['OPOFF', 'SHIFT_SUPERVISOR', 'LOP_CC'];
const SHOW_FINANCE = (role: string) => FINANCE_ROLES.includes(role);
function Group({ title, code, children }: { title: string; code?: string; children: React.ReactNode }) {
return (
<Paper variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<SectionTitle view code={code ?? 'DETAILS'}>{title}</SectionTitle>
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)', lg: 'repeat(3, 1fr)' } }}>{children}</Box>
</Paper>
);
}
function Item({ caption, children }: { caption: string; children: React.ReactNode }) {
const empty = children === undefined || children === null || children === '';
return (
<Box sx={{ minWidth: 0 }}>
<Typography component="div" fontSize={13.5} fontWeight={600} color="primary.main" lineHeight={1.4}>{caption}</Typography>
<Typography component="div" fontSize={14} sx={{ wordBreak: 'break-word' }}>
{empty ? <Typography component="span" color="text.disabled">—</Typography> : children}
</Typography>
</Box>
);
}
/** The old subscription page: package line, service data, the vehicle / permit / stakeholder block, stakeholder info and the invoice. */
export function SubscriptionDetails({ data, label }: { data: Data; label: (field: string, code: unknown) => string }) {
const { user, lang } = useAuth();
const lab = useLabel();
const t = useT();
const ui = useUi();
const L = lang === 'AR' ? 'AR' : 'EN';
const rtl = L === 'AR';
const role = String(user?.role_code ?? '');
const unowned = s(data.DRIVER_DOCUMENT_NATIONALITY) !== '';
const category = s(data.TARGETED_CATEGORY);
const nonOmani = s(data.FLEET_NATIONALITY) !== 'OMN';
const plateCode = (prefix: string) => s(data[`${prefix}PLATE_CODE_${nonOmani ? 'AR' : L}`]) || s(data[`${prefix}PLATE_CODE_AR`]);
const plate = (prefix: string) => {
const n = s(data[`${prefix}PLATE_NUMBER`]);
return n ? <PlateBadge text={`${n} ${plateCode(prefix)}`.trim()} /> : '';
};
const title = `${s(data.CODE)} - ${s(data[`DESCRIPTION_${L}`])} / ${s(data.SERVICE_GROUP_CODE)} - ${s(data[`SERVICE_GROUP_NAME_${L}`])}`;
const estateId = s(data.PERIODIC_SUBSCRIPTION_LOCATION_ID);
const contractual = Number(data.CONTRACTUAL_SUBSCRIPTION) === 1;
const investors = useQuery({
queryKey: ['sub-investors', estateId],
queryFn: () => getOptions('getInvestorsInLocation', { locationId: estateId }),
enabled: contractual && !!estateId,
staleTime: 5 * 60_000,
});
const investorName = (() => {
const id = s(data.INDUSTRIAL_ESTATE_STAKEHOLDER_ID);
const o = (investors.data ?? []).find((x) => String(x.CODE) === id);
return o?.NAME || (o?.CAPTION_CODE ? t(o.CAPTION_CODE) : '');
})();
const billing = s(data.BILLING_CODE);
const finance = useQuery({
queryKey: ['sub-finance', billing],
queryFn: async () => {
const r = await rpc<{ DATA?: { FINANCIAL_TRANSACTION_INFO?: string } }>('SUBSCRIPTIONS', 'FINANCIAL_TRANSACTION_INFO', { billing_code: billing });
return r.DATA?.FINANCIAL_TRANSACTION_INFO ?? '';
},
enabled: SHOW_FINANCE(role) && !!billing,
staleTime: 60_000,
});
const mobile = s(data.DRIVER_MOBILE_NUMBER);
return (
<Stack spacing={1.5}>
<Group title={title}>
<Item caption={lab('SERVICE_NAME')}>{s(data[`SERVICE_DESCRIPTION_${L}`])}</Item>
<Item caption={lab('SUBSCRIPTION_ACTIVATION_DATE')}>{s(data.ACTIVATION_DATE_GRID)}</Item>
<Item caption={lab('SUBSCRIPTION_DURATION')}>{s(data[`DURATION_${L}`])}</Item>
<Item caption={lab('SUBSCRIPTION_EXPIRY_DATE')}>{s(data.EXPIRY_DATE_GRID)}</Item>
{/* the old page always listed the estate for a fleet's own subscription: the periodic one, else the package's */}
{!unowned && (
<Item caption={lab('INDUSTRIAL_ESTATE')}>
{(estateId && label('INDUSTRIAL_ESTATE_ID', estateId)) || s(data.SUBSCRIPTION_LOCATION_NAME) || label('INDUSTRIAL_ESTATE_ID', data.PACKAGE_LOCATION_ID)}
</Item>
)}
</Group>
{unowned ? (
<>
<Group title={lab('TRUCKS_INFO')} code="TRUCK">
<Item caption={lab('FLEET_NATIONALITY')}>{label('FLEET_NATIONALITY', data.FLEET_NATIONALITY)}</Item>
<Item caption={lab('TRAILER_TYPE')}>{label('TRAILER_TYPE', data.TRAILER_TYPE)}</Item>
<Item caption={lab('PLATE_NUMBER')}>{plate('')}</Item>
<Item caption={lab('CARGO_TYPE')}>{label('CARGO_TYPE', data.CARGO_TYPE)}</Item>
<Item caption={lab('TRAILER_PLATE_NUMBER')}>{plate('TRAILER_')}</Item>
<Item caption={lab('OPERATION_TYPE')}>{label('OPERATION_TYPE', data.OPERATION_TYPE)}</Item>
</Group>
<Group title={lab('OWNERS_INFO')} code="OWNER">
<Item caption={lab('DRIVER_DOCUMENT_NATIONALITY')}>{label('DRIVER_DOCUMENT_NATIONALITY', data.DRIVER_DOCUMENT_NATIONALITY)}</Item>
<Item caption={lab('DRIVER_NAME')}>{s(data.DRIVER_NAME)}</Item>
<Item caption={lab('DRIVER_DOCUMENT_TYPE')}>{label('DRIVER_DOCUMENT_TYPE', data.DRIVER_DOCUMENT_TYPE)}</Item>
<Item caption={lab('DRIVER_NATIONALITY')}>{label('DRIVER_NATIONALITY', data.DRIVER_NATIONALITY)}</Item>
<Item caption={lab('DRIVER_DOCUMENT_NUMBER')}>{s(data.DRIVER_DOCUMENT_NUMBER)}</Item>
<Item caption={lab('DRIVER_MOBILE_NUMBER')}>
{mobile && <bdi dir="ltr">{[label('DRIVER_MOBILE_AREA_CODE', data.DRIVER_MOBILE_AREA_CODE), mobile].filter(Boolean).join(' ')}</bdi>}
</Item>
</Group>
</>
) : category === 'PERMITS' ? (
<Group title={lab('PERMITS_INFO')} code="PERMIT">
<Item caption={lab('PN')}>{s(data.PERMIT_NUMBER)}</Item>
</Group>
) : category === 'STAKEHOLDERS' ? (
<Group title={lab('STAKEHOLDER_INFO')} code="STAKEHOLDER_INFO">
<Item caption={lab('CRN')}>{s(data.STAKEHOLDER_CRN)}</Item>
</Group>
) : (
<Group title={lab('VEHICLE_INFO')} code="VEHICLE">
<Item caption={lab('PLATE_NUMBER')}>{plate('')}</Item>
</Group>
)}
<Paper variant="outlined" sx={{ px: 2, py: 0.5, ...sectionFrame }}>
<FormControlLabel
sx={{ m: 0 }}
control={<Checkbox checked={contractual} disabled />}
label={lab('CONTRACTUAL_SUBSCRIPTION')}
/>
</Paper>
{contractual && (
<Group title={lab('STAKEHOLDER_INFO')} code="STAKEHOLDER_INFO">
<Item caption={lab('INDUSTRIAL_ESTATE')}>{label('INDUSTRIAL_ESTATE_ID', estateId) || s(data.SUBSCRIPTION_LOCATION_NAME)}</Item>
<Item caption={lab('INDUSTRIAL_ESTATE_STAKEHOLDER_ID')}>{investorName}</Item>
</Group>
)}
{finance.data && (
<Paper variant="outlined" sx={{ p: 2, overflowX: 'auto', ...sectionFrame }} dir={rtl ? 'rtl' : 'ltr'}>
<SectionTitle view code="FINANCIAL">{ui('financialInfo')}</SectionTitle>
<Box dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(finance.data) }} />
</Paper>
)}
</Stack>
);
}

View File

@ -0,0 +1,32 @@
import type { EntityAction } from '../../api/entity';
/**
* Entity actions that are plain state changes: the backend needs only the record and, at most, a reason.
* Everything else the backend lists for a role (payments, settings, helper lookups, one-off wizards) has
* its own screen in the legacy app, so no generic button is offered for it.
*/
const SIMPLE = new Set([
'ACCEPT', 'REJECT', 'REGISTER', 'COMPLETE', 'DEACTIVATE', 'ACTIVATE', 'DELETE', 'CANCEL', 'SUSPEND',
'RETURN_OPOFF', 'APPROVAL', 'NON_APPROVAL', 'FINISH', 'FINISH_SANCTION', 'UNDER_CHECK', 'STOPPED',
'DESCHEDULE', 'UNTIE_THE_WAIT', 'MARK_LETTER_READ', 'RESEND_EMAIL', 'RESEND_COMPLETE_SMS',
'RESEND_EMAIL_REGISTER_USER', 'RESET_PASSWORD', 'RESET_PASSWORD_IMMEDIATELY',
// finance: accept / revoke a payment, deposit or revoke a deposit request, publish an invoice
'ACCEPT_PAYMENT', 'REVOKE_PAYMENT', 'DEPOSIT', 'REVOKE', 'PUBLISH',
// reconcile a file; print / invoice produce a file that is downloaded
'RECONCILE', 'PRINT', 'GET_INVOICE',
// customer service: the support role finishes a ticket
'OPOFF_COMPLETE',
]);
export const isSimpleAction = (a: EntityAction) => SIMPLE.has(a.ACTION_NAME);
export const isDangerous = (name: string) => /DELETE|DEACTIVATE|REJECT|CANCEL|SUSPEND|NON_APPROVAL|REVOKE/.test(name);
/**
* These actions have the backend email the user (a reset link, a registration link…). Without an
* address on file the backend fails deep in its mail step with an opaque JSON-parsing error, so the
* front end checks first and explains the real problem instead of surfacing that.
* RESET_PASSWORD_IMMEDIATELY does NOT need an email: the backend generates a new password and
* returns it directly in the response message, without sending anything.
*/
const NEEDS_EMAIL = new Set(['RESET_PASSWORD', 'RESEND_EMAIL_REGISTER_USER', 'RESEND_EMAIL']);
export const actionNeedsEmail = (name: string) => NEEDS_EMAIL.has(name);

View File

@ -0,0 +1,66 @@
import type { SessionUser } from '../../api/session';
type Data = Record<string, unknown>;
const WEB_ONLY = [
'LOCAL_VEHICLE_GRID', 'DRIVER_CN', 'DRIVER_NAME', 'DRIVER_AREA_CODE', 'DRIVER_MOBILE_NUMBER', 'OMANI_DRIVER_GRID',
'PLATE_NUMBER', 'PLATE_CODE_AR', 'FLEET_PLATE_CODE', 'TRAILER_TYPE', 'TRAILER_PLATE_NUMBER', 'TRAILER_PLATE_CODE', 'TRAILER_PLATE_CODE_AR',
'DRIVER_ID_FRONT', 'DRIVER_ID_BACK', 'TRUCK_LICENSE_FRONT', 'TRUCK_LICENSE_BACK',
];
const APP_ONLY = ['RECEIVER_RELATED_ENTITY_ID', 'LOCATION_IDS', 'NOTES', 'RECEIVER_RELATED_ENTITY_RECORD_ID', 'ATTACHMENT_1', 'ATTACHMENT_2'];
/**
* The legacy entry-permit-request page (FLEET_REQUEST_HIDE) shows one of two shapes:
* - a request an external driver subscription made from the mobile app: the driver, the vehicle and the licence photos;
* - every other request: the other party, the industrial estate, the notes and the two attachments.
* It also names the *other* side: when the receiver is the signed-in user's own entity it shows the sender instead.
*/
export function fleetRequestView(data: Data, user: SessionUser | null, ar: boolean) {
const driverRequest = String(data.CREATION_SOURCE ?? '') === 'FROM_MOBILE' && String(data.ROLE_CODE ?? '') === 'EXTERNAL_SUBSCRIPTION';
const hidden = driverRequest ? APP_ONLY : WEB_ONLY;
const mine =
String(data.RECEIVER_RELATED_ENTITY_ID ?? '') === String(user?.related_entity_id ?? '#') &&
String(data.RECEIVER_RELATED_ENTITY_RECORD_ID ?? '') === String(user?.related_entity_record_id ?? '#');
const party = mine
? { RECEIVER_RELATED_ENTITY_ID: data.SENDER_RELATED_ENTITY_ID, RECEIVER_RELATED_ENTITY_RECORD_ID: data.SENDER_RELATED_ENTITY_RECORD_ID }
: {};
const entity = String(party.RECEIVER_RELATED_ENTITY_ID ?? data.RECEIVER_RELATED_ENTITY_ID ?? '');
const location =
entity === '12'
? data.OTHER_STAKEHOLDERS_LOCATION_ID
: (entity === '7' || entity === '11' || entity === '10') && String(user?.location_ids ?? '#') === String(data.LOCATION_IDS ?? '')
? data.SENDER_LOCATION_ID
: data.LOCATION_IDS;
// one plate-code field is shown, in the page's language (the other spelling when only one was stored)
const code = (base: string) => {
const a = String(data[`${base}_AR`] ?? '').trim();
const e = String(data[`${base}_EN`] ?? '').trim();
return (ar ? a || e : e || a) || '';
};
const text: Record<string, string> = {};
// the backend sends the party's name beside its id (RECEIVER_COMPANY_NAME, or COMPANY_NAME for the sender)
const nameOf = (base: string) => (ar ? String(data[base] ?? '').trim() : String(data[`${base}_EN`] ?? '').trim() || String(data[base] ?? '').trim());
const partyName = nameOf(mine ? 'COMPANY_NAME' : 'RECEIVER_COMPANY_NAME');
if (partyName) text.RECEIVER_RELATED_ENTITY_RECORD_ID = partyName;
if (code('PLATE_CODE')) text.FLEET_PLATE_CODE = code('PLATE_CODE');
if (code('TRAILER_PLATE_CODE')) text.TRAILER_PLATE_CODE = code('TRAILER_PLATE_CODE');
return {
hidden: [...hidden, 'PLATE_CODE_AR', 'TRAILER_PLATE_CODE_AR'],
data: { ...data, ...party, LOCATION_IDS: location, __TEXT: text } as Data,
};
}
/** Legacy column order, so the three-column grid reads like the old page (driver / vehicle / trailer blocks line up). */
export const FLEET_REQUEST_ORDER = [
'FLEET_REQUEST_NUMBER',
'RECEIVER_RELATED_ENTITY_ID', 'LOCATION_IDS', 'RECEIVER_RELATED_ENTITY_RECORD_ID',
'DRIVER_NATIONALITY_CODE', 'OMANI_DRIVER_GRID', 'DRIVER_NAME',
'DRIVER_MOBILE_NUMBER', 'DRIVER_CN', 'LOCAL_VEHICLE_GRID',
'DRIVER_AREA_CODE', 'FLEET_NATIONALITY_CODE', 'PLATE_NUMBER',
'TRUCK_TYPE', 'NUMBER_OF_FLEET', 'FLEET_PLATE_CODE',
'TRAILER_TYPE', 'TRAILER_PLATE_NUMBER', 'TRAILER_PLATE_CODE',
'NOTES',
];

View File

@ -0,0 +1,73 @@
import type { ReactNode } from 'react';
import { Avatar } from '@mui/material';
import { PlateBadge } from '../../components/PlateBadge';
export interface Header {
title: string;
subtitle?: string;
lead?: ReactNode;
status?: string;
}
type Data = Record<string, unknown>;
const s = (v: unknown) => String(v ?? '').trim();
const join = (...parts: unknown[]) => parts.map(s).filter(Boolean).join(' · ');
/** Entity-specific page headers; anything not listed falls back to the entity caption. */
/** label(field, code): the translated dropdown label of a field value, as the form shows it */
type Label = (field: string, code: unknown) => string;
/**
* The plate as the user reads it ("5759 و ك"): the backend's ready-made grid text when the record has one, else the number
* with its code, whatever the screen calls the fields. Blacklist records keep it as "<code> <number>" in ENTITY_VALUE.
*/
export function plateOf(d: Data, rtl: boolean): string {
const L = rtl ? 'AR' : 'EN';
const O = rtl ? 'EN' : 'AR';
const ready = [`PLATE_NUMBER_GRID_${L}`, `FLEET_PLATE_NUMBER_GRID_${L}`, `PLATE_NO_GRID_${L}`, `PLATE_NUMBER_GRID_${O}`, `FLEET_PLATE_NUMBER_GRID_${O}`, `PLATE_NO_GRID_${O}`]
.map((k) => s(d[k]))
.find(Boolean);
if (ready) return ready;
const num = s(d.PLATE_NUMBER) || s(d.FLEET_PLATE_NUMBER);
const code = [`PLATE_CODE_${L}`, `FLEET_PLATE_CODE_${L}`, 'PLATE_CODE', 'PLATE_CODE_AR', 'PLATE_CODE_EN', 'FLEET_PLATE_CODE_AR'].map((k) => s(d[k])).find(Boolean) ?? '';
if (num) return `${num} ${code}`.trim();
return s(d.ENTITY_VALUE);
}
/** Vehicle records and the records about a vehicle lead with the plate badge instead of a name or an id. */
const plateHeader = (d: Data, rtl: boolean, fallback: string): Header | null => {
const plate = plateOf(d, rtl);
return plate ? { lead: <PlateBadge text={plate} />, title: fallback, status: s(d.STATUS_CODE) } : null;
};
const PLATE_ENTITIES = ['RFID_TAGS', 'TRAILERS', 'EQUIPMENTS', 'BUSES', 'CARS', 'AFFILIATION', 'RENTED_TRUCK', 'SUBSCRIPTIONS', 'TROUBLE_SHOOTING', 'SANCTIONS', 'VIOLATIONS', 'BLACKLISTS', 'PARKING_YARD', 'FLEET_PENDING_FINANCIAL_TRANSACTIONS'];
const HEADERS: Record<string, (d: Data, rtl: boolean, label: Label) => Header> = {
TRUCKS: (d, rtl, label) => ({
lead: <PlateBadge text={s(rtl ? d.PLATE_NUMBER_GRID_AR : d.PLATE_NUMBER_GRID_EN) || s(d.PLATE_NUMBER)} />,
title: s(d.OWNER_NAME) || s(d.COMPANY_NAME),
subtitle: join(label('TRUCK_TYPE', d.TRUCK_TYPE), label('USE_DESCRIPTION', d.USE_DESCRIPTION)),
status: s(d.STATUS_CODE),
}),
// the request number identifies it; the company name on these records is often "unknown"
FLEET_REQUEST: (d) => ({ title: s(d.FLEET_REQUEST_NUMBER), status: s(d.STATUS_CODE) }),
USERS: (d) => ({
lead: <Avatar sx={{ width: 56, height: 56, bgcolor: 'primary.main' }}>{s(d.NAME).slice(0, 1).toUpperCase()}</Avatar>,
title: s(d.NAME),
subtitle: join(d.EMAIL, d.MOBILE),
status: s(d.STATUS_CODE),
}),
};
// for entities without a custom header: the first name-like value the record has
const NAME_KEYS = ['NAME', 'NAME_AR', 'FULL_NAME', 'COMPANY_NAME', 'OWNER_NAME', 'SUBJECT', 'TITLE', 'LETTER_TITLE', 'PLATE_NUMBER', 'PERMIT_NUMBER', 'VIOLATION_NUM', 'CODE'];
/** Page titles that differ from the module's menu caption. */
const VIEW_TITLE: Record<string, { en: string; ar: string }> = { DEPOSITS: { en: 'Deposit request', ar: 'طلب الإيداع' } };
export const getHeader = (entity: string, d: Data, rtl: boolean, label: Label, fallbackTitle: string): Header => {
const fallback = VIEW_TITLE[entity] ? (rtl ? VIEW_TITLE[entity].ar : VIEW_TITLE[entity].en) : fallbackTitle;
const custom = HEADERS[entity]?.(d, rtl, label) ?? (PLATE_ENTITIES.includes(entity) ? plateHeader(d, rtl, fallback) : null);
if (custom) return custom;
const name = NAME_KEYS.map((k) => s(d[k])).find(Boolean);
return { title: name || fallback, subtitle: name ? fallback : undefined, status: s(d.STATUS_CODE) };
};

54
src/i18n/index.tsx Normal file
View File

@ -0,0 +1,54 @@
import { createContext, useContext, useMemo, type ReactNode } from 'react';
import { useAuth } from '../auth/AuthContext';
import { SECTION_TITLES, UI, type UiKey } from './ui';
type Dict = Record<string, string>;
const I18nCtx = createContext<(key: string) => string>((k) => k);
/** Captions come from getConfig (LT_CAPTIONS_VIEW[lang][key]); fall back to Arabic, then the key. */
export function I18nProvider({ children }: { children: ReactNode }) {
const { config, lang } = useAuth();
const t = useMemo(() => {
const all = config?.LT_CAPTIONS_VIEW ?? {};
const cur: Dict = all[lang] ?? {};
const ar: Dict = all.AR ?? {};
// two caption defects reported by QA: a wrong plural ("12 خانه") and a Latin token whose brackets flip in RTL
const fix = (text: string) =>
text.includes('RRN')
? text
.replace(/\(\s*(\d+)\s+خانه\s*\)/g, '($1 خانات)')
.replace(/\(\s*RRN\s*\)/g, '⁦(RRN)⁩')
: text;
return (key: string) => {
const found = cur[key] || ar[key];
return found ? fix(found) : key;
};
}, [config, lang]);
return <I18nCtx.Provider value={t}>{children}</I18nCtx.Provider>;
}
export const useT = () => useContext(I18nCtx);
export const isRtl = (lang: string) => lang === 'AR' || lang === 'URD';
/** A caption, or — when the system has none for the code — a readable version of the code itself. */
export function useLabel() {
const t = useT();
const { lang } = useAuth();
return (key: string) => {
const c = t(key);
if (c !== key) return c;
const base = key.replace(/-TAB$/, '');
const own = SECTION_TITLES[key] ?? SECTION_TITLES[base];
if (own) return isRtl(lang) ? own.ar : own.en;
// last resort: a readable form of the code ("OWNERINFO" -> "Owner info")
const words = base.replace(/(?<=[A-Z])(INFORMATION|INFO|DETAILS|OPTIONS)$/, '_$1').replace(/[_-]+/g, ' ').trim().toLowerCase();
return words.charAt(0).toUpperCase() + words.slice(1);
};
}
/** Strings owned by the new UI (see ui.ts), in the current language. */
export function useUi() {
const { lang } = useAuth();
return (key: UiKey) => (isRtl(lang) ? UI[key].ar : UI[key].en);
}

19
src/i18n/roles.ts Normal file
View File

@ -0,0 +1,19 @@
// Role / job-title codes the backend returns as plain codes because its caption table has no entry for them
// (the Users grid's profession column and a user's job title). Anything unknown still gets a readable form.
const ROLES: Record<string, { en: string; ar: string }> = {
MADAYN_FIN: { en: 'Madayn finance', ar: 'مدائن - المالية' },
FIN_MANAGER: { en: 'Finance manager', ar: 'مدير مالي' },
OPADMIN: { en: 'Operations administrator', ar: 'مسؤول العمليات' },
OPOFF: { en: 'Operations officer', ar: 'موظف العمليات' },
};
const looksLikeCode = (s: string) => /^[A-Z][A-Z0-9_]{2,}$/.test(s);
/** The caption when the system has one, else our own bilingual name, else a readable form of the code. */
export function roleLabel(raw: string, caption: (k: string) => string, humanize: (k: string) => string, rtl: boolean) {
const code = raw.trim();
if (!looksLikeCode(code)) return raw;
if (caption(code) !== code) return caption(code);
const own = ROLES[code];
return own ? (rtl ? own.ar : own.en) : humanize(code);
}

191
src/i18n/ui.ts Normal file
View File

@ -0,0 +1,191 @@
// Strings the legacy caption table does not have. Everything else comes from the backend captions.
export const UI = {
home: { en: 'Home', ar: 'الرئيسية' },
search: { en: 'Search', ar: 'بحث' },
quickSearch: { en: 'Search by plate number…', ar: 'ابحث برقم اللوحة…' },
searchEverything: { en: 'Search pages…', ar: 'ابحث في الصفحات…' },
noResults: { en: 'No results', ar: 'لا توجد نتائج' },
filters: { en: 'Filters', ar: 'تصفية' },
apply: { en: 'Apply', ar: 'تطبيق' },
clear: { en: 'Clear all', ar: 'مسح الكل' },
new: { en: 'New', ar: 'جديد' },
view: { en: 'View', ar: 'عرض' },
edit: { en: 'Edit', ar: 'تعديل' },
details: { en: 'Details', ar: 'التفاصيل' },
documents: { en: 'Documents', ar: 'المستندات' },
from: { en: 'From', ar: 'من' },
to: { en: 'To', ar: 'إلى' },
all: { en: 'All', ar: 'الكل' },
records: { en: 'records', ar: 'سجل' },
collapse: { en: 'Collapse menu', ar: 'طي القائمة' },
expand: { en: 'Expand menu', ar: 'توسيع القائمة' },
darkMode: { en: 'Dark mode', ar: 'الوضع الداكن' },
lightMode: { en: 'Light mode', ar: 'الوضع الفاتح' },
noFile: { en: 'No file', ar: 'لا يوجد ملف' },
notProvided: { en: 'Not provided', ar: 'غير مدخل' },
invoiceSummary: { en: 'Invoice summary', ar: 'ملخص الفاتورة' },
wrongFileType: { en: 'Wrong file type. Choose a CSV or Excel file (.csv, .xls, .xlsx).', ar: 'نوع الملف غير صحيح. اختر ملف CSV أو Excel (‎.csv، ‎.xls، ‎.xlsx).' },
jumpTo: { en: 'Jump to…', ar: 'انتقل إلى…' },
actions: { en: 'Actions', ar: 'الإجراءات' },
needsInfo: { en: 'This action needs extra information that is not supported yet.', ar: 'يتطلب هذا الإجراء معلومات إضافية غير مدعومة بعد.' },
loadError: { en: 'Could not load data', ar: 'تعذر تحميل البيانات' },
exportExcel: { en: 'Export to Excel', ar: 'تصدير إلى Excel' },
exporting: { en: 'Preparing file…', ar: 'جاري تجهيز الملف…' },
exportTitle: { en: 'Export to Excel', ar: 'تصدير إلى Excel' },
exportBody: { en: 'Export the records that match the current search to an Excel file?', ar: 'هل تريد تصدير السجلات المطابقة للبحث الحالي إلى ملف Excel؟' },
exportAll: { en: 'No filters are applied: every record will be exported.', ar: 'لا توجد عوامل تصفية: سيتم تصدير جميع السجلات.' },
exportReady: { en: 'The file is ready and is downloading', ar: 'الملف جاهز ويجري تنزيله' },
saved: { en: 'Saved successfully', ar: 'تم الحفظ بنجاح' },
cancel: { en: 'Cancel', ar: 'إلغاء' },
notAvailableYet: { en: 'Not available in the new screen yet', ar: 'غير متاح في الشاشة الجديدة بعد' },
blockedForm: {
en: 'This form needs fields that are not migrated yet, so saving is disabled here. Use the previous system for this record.',
ar: 'يحتاج هذا النموذج إلى حقول لم يتم نقلها بعد، لذلك تم تعطيل الحفظ هنا. استخدم النظام السابق لهذا السجل.',
},
choose: { en: 'Choose', ar: 'اختيار' },
subscribe: { en: 'Subscribe', ar: 'اشتراك' },
back: { en: 'Back', ar: 'رجوع' },
wizGroup: { en: 'Service type', ar: 'نوع الخدمة' },
wizPackage: { en: 'Package', ar: 'الباقة' },
wizService: { en: 'Service', ar: 'الخدمة' },
wizSubscription: { en: 'Subscription', ar: 'الاشتراك' },
wizFleet: { en: 'Vehicles / employees', ar: 'المركبات / الموظفون' },
wizEstate: { en: 'Industrial area', ar: 'المنطقة الصناعية' },
wizPickEstate: { en: 'Please select the industrial area first', ar: 'يرجى اختيار المنطقة الصناعية أولاً' },
wizSummary: { en: 'Your selection', ar: 'اختيارك' },
wizPrice: { en: 'Price per vehicle', ar: 'السعر لكل مركبة' },
wizOmr: { en: 'OMR', ar: 'ر.ع' },
wizPay: { en: 'Payment', ar: 'الدفع' },
wizSearchList: { en: 'Search the list', ar: 'ابحث في القائمة' },
wizSelectShown: { en: 'Select all shown', ar: 'تحديد كل المعروض' },
wizSelected: { en: 'Selected', ar: 'المحدد' },
wizRefine: { en: 'Showing the first 200; refine the search to see more', ar: 'يتم عرض أول 200؛ حسّن البحث لعرض المزيد' },
wizNoItems: { en: 'Nothing is available to add to this subscription.', ar: 'لا توجد عناصر متاحة للإضافة إلى هذا الاشتراك.' },
wizContinue: { en: 'Continue to payment', ar: 'المتابعة إلى الدفع' },
wizCount: { en: 'Number of items', ar: 'العدد' },
wizCardLater: { en: 'Card payment is not available in the new screen yet.', ar: 'الدفع بالبطاقة غير متاح في الشاشة الجديدة بعد.' },
wizFreeZone: { en: 'One-trip permits for the free-zone package are entered in the previous system for now. Nothing has been submitted.', ar: 'تصاريح الرحلة الواحدة لباقة المنطقة الحرة تُدخل حالياً في النظام السابق. لم يتم إرسال أي طلب.' },
wizSearchFirst: { en: 'Search for the vehicles by plate number, plate code, nationality, owner type or class, then pick the ones to subscribe.', ar: 'ابحث عن المركبات برقم اللوحة أو ترميزها أو الجنسية أو نوع المالك أو الفئة، ثم اختر ما تريد الاشتراك به.' },
wizNeedFilter: { en: 'Enter at least one search filter (for example the plate number).', ar: 'أدخل معياراً واحداً على الأقل للبحث (مثل رقم اللوحة).' },
gridLoading: { en: 'Loading the list from the system…', ar: 'جاري تحميل القائمة من النظام…' },
gridSearching: { en: 'Updating the results…', ar: 'جاري تحديث النتائج…' },
gridLoadingSlow: { en: 'Large lists can take a few more seconds. Please wait.', ar: 'قد تستغرق القوائم الكبيرة بضع ثوانٍ إضافية. يرجى الانتظار.' },
fleetOwnerNote: { en: 'The vehicle belongs to the selected stakeholder', ar: 'المركبة مملوكة للجهة المختارة' },
datePlaceholder: { en: 'dd/mm/yyyy', ar: 'يوم/شهر/سنة' },
pickDate: { en: 'Choose a date', ar: 'اختر تاريخاً' },
rowsPerPage: { en: 'Rows per page', ar: 'عدد الصفوف في الصفحة' },
pagerOf: { en: 'of', ar: 'من' },
prevPage: { en: 'Previous page', ar: 'الصفحة السابقة' },
nextPage: { en: 'Next page', ar: 'الصفحة التالية' },
firstPage: { en: 'First page', ar: 'الصفحة الأولى' },
lastPage: { en: 'Last page', ar: 'الصفحة الأخيرة' },
loginFailed: { en: 'The username or password is incorrect.', ar: 'اسم المستخدم أو كلمة المرور غير صحيحة.' },
loginRequired: { en: 'This field is required.', ar: 'هذا الحقل مطلوب.' },
notAuthorizedTitle: { en: 'You are not authorized to open this page', ar: 'غير مصرّح لك بفتح هذه الصفحة' },
notAuthorizedText: { en: 'Your role does not include this screen. If you need access, contact the system administrator.', ar: 'صلاحياتك لا تشمل هذه الشاشة. إذا كنت بحاجة إلى الوصول، يرجى التواصل مع مسؤول النظام.' },
openMenu: { en: 'Open the menu', ar: 'فتح القائمة' },
wizNoDriverFiles: { en: 'This driver is already registered, so no driver documents are needed.', ar: 'هذا السائق مسجل مسبقاً، لذا لا حاجة إلى مستندات السائق.' },
wizNext: {
en: 'This subscription type (visitors) needs its own entry form, which is not in the new screen yet. Nothing has been submitted; complete this request in the previous system.',
ar: 'هذا النوع من الاشتراكات (الزوار) يحتاج إلى نموذج إدخال خاص غير متاح في الشاشة الجديدة بعد. لم يتم إرسال أي طلب؛ أكمل هذا الطلب في النظام السابق.',
},
loginUsername: { en: 'Username', ar: 'اسم المستخدم' },
loginPassword: { en: 'Password', ar: 'كلمة المرور' },
loginSubmit: { en: 'Sign in', ar: 'تسجيل الدخول' },
loginWelcome: { en: 'Welcome back', ar: 'مرحباً بعودتك' },
loginTitle: { en: 'Sign in to Nafith@Madayn', ar: 'تسجيل الدخول إلى نافذ@مدائن' },
loginTagline: {
en: 'One place to manage fleet subscriptions, permits and trucking services across Madayn industrial estates.',
ar: 'مكان واحد لإدارة اشتراكات الأسطول والتصاريح وخدمات النقل في جميع المناطق الصناعية لمدائن.',
},
rememberMe: { en: 'Remember me', ar: 'تذكرني' },
followUs: { en: 'Follow us', ar: 'تابعنا' },
allRightsReserved: { en: 'All rights reserved.', ar: 'جميع الحقوق محفوظة.' },
showPassword: { en: 'Show password', ar: 'إظهار كلمة المرور' },
hidePassword: { en: 'Hide password', ar: 'إخفاء كلمة المرور' },
forgotPassword: { en: 'Forgot password?', ar: 'نسيت كلمة المرور؟' },
myProfile: { en: 'My profile', ar: 'ملفي الشخصي' },
reconciliationLines: { en: 'Transactions in the file', ar: 'الحركات في الملف' },
selectAll: { en: 'Select all rows', ar: 'تحديد كل الصفوف' },
selectRow: { en: 'Select row', ar: 'تحديد الصف' },
selectedCount: { en: 'selected', ar: 'محدد' },
moreActions: { en: 'More actions', ar: 'إجراءات أخرى' },
financialInfo: { en: 'Financial transaction', ar: 'معلومات الحركة المالية' },
companyProfile: { en: 'Company profile', ar: 'ملف الشركة' },
emailRequiredForAction: {
en: 'This user has no email on file. Add one before using this action.',
ar: 'لا يوجد بريد إلكتروني مسجل لهذا المستخدم. يرجى إضافته قبل استخدام هذا الإجراء.',
},
total: { en: 'Total', ar: 'الإجمالي' },
newToNafith: { en: 'New to Nafith@Madayn?', ar: 'جديد في نافذ@مدائن؟' },
signUp: { en: 'Sign up', ar: 'إنشاء حساب' },
signUpNotAvailable: {
en: 'Self-registration is not in the new screen yet. Please use the previous system to create an account.',
ar: 'إنشاء حساب جديد غير متاح في الشاشة الجديدة بعد. يرجى استخدام النظام السابق لإنشاء حساب.',
},
saving: { en: 'Saving your changes…', ar: 'جاري حفظ التغييرات…' },
processing: { en: 'Processing your request…', ar: 'جاري تنفيذ الطلب…' },
pleaseWait: { en: 'Please wait, this can take a few seconds', ar: 'يرجى الانتظار، قد يستغرق هذا بضع ثوانٍ' },
loadingWorkspace: { en: 'Preparing your workspace…', ar: 'جاري تجهيز مساحة العمل…' },
firstLoad: { en: 'The first load takes a little longer', ar: 'التحميل الأول يستغرق وقتاً أطول قليلاً' },
stillWorking: { en: 'Still working, thanks for your patience…', ar: 'ما زلنا نعمل، شكراً لصبرك…' },
agreeToTerms: { en: 'I agree to the terms and conditions', ar: 'أوافق على الشروط والأحكام' },
backToLogin: { en: 'Back to login', ar: 'العودة لتسجيل الدخول' },
registerHubTitle: { en: 'Create an account', ar: 'إنشاء حساب جديد' },
registerHubSubtitle: {
en: 'Choose the type of account that matches you. We will ask for a few details and any supporting documents.',
ar: 'اختر نوع الحساب الذي يناسبك. سنطلب بعض البيانات والمستندات المؤيدة.',
},
registerCompaniesDesc: { en: 'A transport or logistics company operating in Madayn estates.', ar: 'شركة نقل أو خدمات لوجستية تعمل في مناطق مدائن الصناعية.' },
registerInvestorsDesc: { en: 'An investor running a facility inside a Madayn estate.', ar: 'مستثمر يدير منشأة داخل منطقة مدائن الصناعية.' },
registerOtherStakeholdersDesc: { en: 'Any other stakeholder dealing with Madayn.', ar: 'أي جهة أخرى ذات صلة بمدائن.' },
registerOwnersDesc: { en: 'An individual truck or vehicle owner.', ar: 'مالك شاحنة أو مركبة فردية.' },
registerFreezoneDesc: { en: 'A clearing company operating inside the free zone.', ar: 'شركة تخليص تعمل داخل المنطقة الحرة.' },
registerStart: { en: 'Start', ar: 'ابدأ' },
registerLoading: { en: 'Preparing the registration form…', ar: 'جاري تجهيز نموذج التسجيل…' },
otpTitle: { en: 'Verify your mobile number', ar: 'تحقق من رقم جوالك' },
otpMobile: { en: 'Mobile number', ar: 'رقم الجوال' },
otpAreaCode: { en: 'Country code', ar: 'رمز الدولة' },
otpNationality: { en: 'Nationality', ar: 'الجنسية' },
otpDocType: { en: 'ID document type', ar: 'نوع وثيقة الهوية' },
otpNationalId: { en: 'ID / national number', ar: 'رقم الهوية الوطنية' },
otpSend: { en: 'Send verification code', ar: 'إرسال رمز التحقق' },
otpCode: { en: 'Verification code', ar: 'رمز التحقق' },
otpCodeHint: { en: 'Enter the code sent to your mobile number', ar: 'أدخل الرمز المرسل إلى رقم جوالك' },
otpVerify: { en: 'Verify', ar: 'تحقق' },
otpChangeNumber: { en: 'Change number', ar: 'تغيير الرقم' },
registerSuccessTitle: { en: 'Application submitted', ar: 'تم إرسال الطلب' },
registerSuccessBody: {
en: 'Thank you. We sent a confirmation link to the email you provided — open it to continue. Our team will review your application afterwards.',
ar: 'شكراً لك. أرسلنا رابط تأكيد إلى البريد الإلكتروني الذي أدخلته — افتحه للمتابعة. سيقوم فريقنا بمراجعة طلبك بعد ذلك.',
},
registerReturnedExisting: {
en: 'An application for this ID already exists and needs your attention. Continuing to that application…',
ar: 'يوجد طلب سابق بهذا الرقم يحتاج إلى متابعتك. جاري الانتقال إلى ذلك الطلب…',
},
} as const;
export type UiKey = keyof typeof UI;
// Section headings the old pages used but the caption table has no Arabic for (found by comparing every generated layout).
export const SECTION_TITLES: Record<string, { en: string; ar: string }> = {
// the trailer's plate code is captioned "Plate Code" in the metadata, which reads as a duplicate of the truck's
TRAILER_PLATE_CODE: { en: 'Trailer Plate Code', ar: 'ترميز لوحة المقطورة' },
BLACKLISTSINFO: { en: 'Blacklist details', ar: 'تفاصيل القائمة السوداء' },
OWNERINFO: { en: 'Owner details', ar: 'بيانات المالك' },
INSURANCEINFO: { en: 'Insurance', ar: 'التأمين' },
CAPACITY_OPTIONS: { en: 'Capacity options', ar: 'خيارات الطاقة الاستيعابية' },
DRIVERS_INFO: { en: 'Driver details', ar: 'بيانات السائق' },
FAMILY_MEMBERSINFO: { en: 'Family member details', ar: 'بيانات أفراد الأسرة' },
FLEET_PENDING_FINANCIAL_TRANSACTIONSINFO: { en: 'Transaction details', ar: 'تفاصيل المعاملة' },
CAPACITYINFO: { en: 'Capacity details', ar: 'تفاصيل الطاقة الاستيعابية' },
MAININFO: { en: 'Main information', ar: 'المعلومات الأساسية' },
SETTING: { en: 'Settings', ar: 'الإعدادات' },
NOTIFICATION_LOGINFO: { en: 'Notification details', ar: 'تفاصيل الإشعار' },
OWNERSINFO: { en: 'Personal information', ar: 'المعلومات الشخصية' },
LICENSEINFO: { en: 'License information', ar: 'معلومات الرخصة' },
POS_TRANSACTIONSINFO: { en: 'Transaction details', ar: 'تفاصيل المعاملة' },
RFID_TAGSINFO: { en: 'Tag details', ar: 'تفاصيل البطاقة' },
SANCTION_DETAILS: { en: 'Sanction details', ar: 'تفاصيل العقوبة' },
WORKINFO: { en: 'Work information', ar: 'معلومات العمل' },
};

222
src/layout/AppShell.tsx Normal file
View File

@ -0,0 +1,222 @@
import { useEffect, useState } from 'react';
import { Link as RouterLink, Outlet, useLocation } from 'react-router-dom';
import {
AppBar, Avatar, Box, Breadcrumbs, ButtonBase, Divider, Drawer, GlobalStyles, IconButton, Link, ListItemIcon,
Menu, MenuItem, Toolbar, Tooltip, Typography, useMediaQuery, useTheme,
} from '@mui/material';
import MenuIcon from '@mui/icons-material/Menu';
import SearchIcon from '@mui/icons-material/Search';
import DarkModeOutlined from '@mui/icons-material/DarkModeOutlined';
import LightModeOutlined from '@mui/icons-material/LightModeOutlined';
import TranslateIcon from '@mui/icons-material/Translate';
import LogoutIcon from '@mui/icons-material/Logout';
import PersonOutline from '@mui/icons-material/PersonOutline';
import BusinessOutlined from '@mui/icons-material/BusinessOutlined';
import LockOutlined from '@mui/icons-material/LockOutlined';
import NavigateNext from '@mui/icons-material/NavigateNext';
import { useAuth } from '../auth/AuthContext';
import { ChangePasswordDialog } from '../auth/ChangePasswordDialog';
import { isRtl, useLabel, useT, useUi } from '../i18n';
import { roleLabel } from '../i18n/roles';
import { useColorMode } from '../theme';
import { NavProvider, useNav } from './NavContext';
import { RAIL_WIDTH, SIDEBAR_WIDTH, Sidebar } from './Sidebar';
import { CommandPalette } from './CommandPalette';
import { GlobalLoading } from '../components/GlobalLoading';
const COLLAPSE_KEY = 'mams.sidebar';
function Crumbs() {
const { pathname, search } = useLocation();
const ui = useUi();
const { sectionOf, title, labelOf } = useNav();
const dash = /^\/dashboard\/([^/]+)/.exec(pathname)?.[1];
if (dash) {
const key = `DASHBOARD:${dash}`;
const section = sectionOf(key);
return (
<Breadcrumbs separator={<NavigateNext fontSize="small" className="flip-rtl" />} sx={{ '& .MuiBreadcrumbs-li': { fontSize: 13.5 } }}>
<Link component={RouterLink} to="/" color="text.secondary" underline="hover">{ui('home')}</Link>
{section && <Typography color="text.secondary" fontSize="inherit">{title(section)}</Typography>}
<Typography fontSize="inherit" fontWeight={600}>{labelOf(key)}</Typography>
</Breadcrumbs>
);
}
const m = /^\/e\/([^/]+)\/([^/]+)(?:\/([^/]+))?/.exec(pathname);
if (!m) return null;
// the profile page has no breadcrumb trail, like the legacy one
if (new URLSearchParams(search).get('profile') === '1') return null;
const [, entity, view, id] = m;
const section = sectionOf(entity);
const leaf = view === 'view' ? ui('view') : view === 'create' ? (id ? ui('edit') : ui('new')) : null;
return (
<Breadcrumbs separator={<NavigateNext fontSize="small" className="flip-rtl" />} sx={{ '& .MuiBreadcrumbs-li': { fontSize: 13.5 } }}>
<Link component={RouterLink} to="/" color="text.secondary" underline="hover">{ui('home')}</Link>
{section && <Typography color="text.secondary" fontSize="inherit">{title(section)}</Typography>}
{leaf ? (
<Link component={RouterLink} to={`/e/${entity}/grid`} color="text.secondary" underline="hover">{labelOf(entity)}</Link>
) : (
<Typography fontSize="inherit" fontWeight={600}>{labelOf(entity)}</Typography>
)}
{leaf && <Typography fontSize="inherit" fontWeight={600}>{leaf}</Typography>}
</Breadcrumbs>
);
}
function Shell() {
const { user, config, lang, setLang } = useAuth();
const ui = useUi();
const t = useT();
const humanize = useLabel();
const { mode, toggle } = useColorMode();
const theme = useTheme();
const wide = useMediaQuery(theme.breakpoints.up('md'));
const [drawer, setDrawer] = useState(false);
const [palette, setPalette] = useState(false);
const [menuEl, setMenuEl] = useState<HTMLElement | null>(null);
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
// legacy: a user tied to a company or stakeholder (other than the operations officer) also gets that record's page
const relatedName = String(user?.related_entity_name ?? '').toUpperCase();
const companyEntity =
relatedName && user?.encrypted_related_entity_record_id && user?.role_code !== 'OPOFF' && config?.AUTHORITY.some((a) => a.ENTITY_NAME === relatedName && a.ACTION_NAME === 'GETVIEW')
? relatedName
: '';
const can = (action: string) => !!config?.AUTHORITY.some((a) => a.ENTITY_NAME === 'USERS' && a.ACTION_NAME === action);
const [collapsed, setCollapsed] = useState(() => {
try {
return localStorage.getItem(COLLAPSE_KEY) === '1';
} catch {
return false;
}
});
const toggleCollapsed = () =>
setCollapsed((c) => {
try {
localStorage.setItem(COLLAPSE_KEY, c ? '0' : '1');
} catch {
/* ignore */
}
return !c;
});
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
setPalette(true);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);
const width = collapsed ? RAIL_WIDTH : SIDEBAR_WIDTH;
return (
<Box sx={{ display: 'flex', minHeight: '100vh' }}>
<GlobalStyles styles={{ '[dir=rtl] .flip-rtl': { transform: 'scaleX(-1)' } }} />
{wide ? (
<Drawer variant="permanent" sx={{ width, flexShrink: 0, '& .MuiDrawer-paper': { width, boxSizing: 'border-box', borderInlineEnd: 1, borderColor: 'divider', transition: 'width .2s', overflowX: 'hidden' } }}>
<Sidebar collapsed={collapsed} onToggle={toggleCollapsed} />
</Drawer>
) : (
<Drawer open={drawer} onClose={() => setDrawer(false)} sx={{ '& .MuiDrawer-paper': { width: SIDEBAR_WIDTH } }}>
<Sidebar collapsed={false} onNavigate={() => setDrawer(false)} />
</Drawer>
)}
<Box sx={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
<AppBar position="sticky" color="inherit" elevation={0} sx={{ borderBottom: 1, borderColor: 'divider', bgcolor: 'background.paper' }}>
<Toolbar variant="dense" sx={{ gap: 1.25, minHeight: 52 }}>
{!wide && <IconButton edge="start" aria-label={ui('openMenu')} onClick={() => setDrawer(true)}><MenuIcon /></IconButton>}
<Box sx={{ flex: 1, minWidth: 0 }}><Crumbs /></Box>
<ButtonBase
onClick={() => setPalette(true)}
sx={{ display: { xs: 'none', sm: 'flex' }, gap: 1, alignItems: 'center', px: 1.25, py: 0.4, minWidth: 220, border: 1, borderColor: 'divider', borderRadius: 2.5, color: 'text.secondary', justifyContent: 'flex-start' }}
>
<SearchIcon sx={{ fontSize: 16 }} />
<Typography sx={{ flex: 1, textAlign: 'start', fontSize: 13.5 }}>{ui('jumpTo')}</Typography>
<Box component="kbd" sx={{ fontSize: 11, px: 0.75, border: 1, borderColor: 'divider', borderRadius: 1 }}>Ctrl K</Box>
</ButtonBase>
<IconButton sx={{ display: { sm: 'none' } }} aria-label={ui('searchEverything')} onClick={() => setPalette(true)}><SearchIcon sx={{ fontSize: 18 }} /></IconButton>
<Tooltip title={mode === 'dark' ? ui('lightMode') : ui('darkMode')}>
<IconButton onClick={toggle}>{mode === 'dark' ? <LightModeOutlined /> : <DarkModeOutlined />}</IconButton>
</Tooltip>
<Tooltip title={lang === 'AR' ? 'English' : 'العربية'}>
<IconButton onClick={() => setLang(lang === 'AR' ? 'EN' : 'AR')}><TranslateIcon /></IconButton>
</Tooltip>
<IconButton onClick={(e) => setMenuEl(e.currentTarget)} aria-label={ui('myProfile')} sx={{ p: 0.5 }}>
<Avatar sx={{ width: 34, height: 34, bgcolor: 'primary.main' }}>
<PersonOutline fontSize="small" />
</Avatar>
</IconButton>
</Toolbar>
</AppBar>
<Menu anchorEl={menuEl} open={!!menuEl} onClose={() => setMenuEl(null)} slotProps={{ paper: { sx: { minWidth: 220 } } }}>
<Box sx={{ px: 2, py: 1 }}>
<Typography fontWeight={700}>{user?.name}</Typography>
<Typography variant="caption" color="text.secondary">{roleLabel(String(user?.job_title ?? user?.role_code ?? ''), t, humanize, isRtl(lang))}</Typography>
</Box>
<Divider />
{can('GETVIEW') && user && (
<MenuItem component={RouterLink} to={`/e/USERS/create/${user.user_id}?profile=1`} onClick={() => setMenuEl(null)} sx={{ minHeight: 44 }}>
<ListItemIcon><PersonOutline fontSize="small" /></ListItemIcon>
{ui('myProfile')}
</MenuItem>
)}
{companyEntity && (
<MenuItem component={RouterLink} to={`/e/${companyEntity}/create/${user?.encrypted_related_entity_record_id}`} onClick={() => setMenuEl(null)} sx={{ minHeight: 44 }}>
<ListItemIcon><BusinessOutlined fontSize="small" /></ListItemIcon>
{ui('companyProfile')}
</MenuItem>
)}
{can('CHANGE_PASSWORD') && (
<MenuItem
sx={{ minHeight: 44 }}
onClick={() => {
setMenuEl(null);
setChangePasswordOpen(true);
}}
>
<ListItemIcon><LockOutlined fontSize="small" /></ListItemIcon>
{t('CHANGE_PASSWORD')}
</MenuItem>
)}
<Divider />
<LogoutItem onDone={() => setMenuEl(null)} />
</Menu>
<ChangePasswordDialog open={changePasswordOpen} onClose={() => setChangePasswordOpen(false)} />
<Box component="main" sx={{ flex: 1, p: { xs: 1.5, md: 2.5 }, width: '100%', maxWidth: 1560, mx: 'auto' }}>
<Outlet />
</Box>
</Box>
<CommandPalette open={palette} onClose={() => setPalette(false)} />
<GlobalLoading />
</Box>
);
}
function LogoutItem({ onDone }: { onDone: () => void }) {
const { signOut } = useAuth();
const t = useT();
return (
<MenuItem sx={{ minHeight: 44 }} onClick={() => { onDone(); void signOut(); }}>
<ListItemIcon><LogoutIcon fontSize="small" /></ListItemIcon>
{t('LOGOUT')}
</MenuItem>
);
}
export function AppShell() {
return (
<NavProvider>
<Shell />
</NavProvider>
);
}

View File

@ -0,0 +1,79 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, Dialog, IconButton, InputAdornment, List, ListItemButton, ListItemText, TextField, Tooltip, Typography } from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import { useUi } from '../i18n';
import AddCircleOutline from '@mui/icons-material/AddCircleOutline';
import { newRecordSx } from '../components/newRecordSx';
import { useNav } from './NavContext';
/** Ctrl/⌘+K: jump to any page the user's role can open. */
export function CommandPalette({ open, onClose }: { open: boolean; onClose: () => void }) {
const { sections, title, labelOf } = useNav();
const ui = useUi();
const nav = useNavigate();
const [q, setQ] = useState('');
const [cursor, setCursor] = useState(0);
const list = useRef<HTMLUListElement>(null);
const entries = useMemo(
() =>
sections.flatMap((s) =>
s.items.map((i) => ({ key: i.entity, label: labelOf(i.entity), group: title(s), to: i.to, create: i.canCreate ? `/e/${i.entity}/create` : undefined })),
),
[sections, labelOf, title],
);
const results = useMemo(() => {
const n = q.trim().toLowerCase();
return n ? entries.filter((e) => `${e.label} ${e.key} ${e.group}`.toLowerCase().includes(n)) : entries;
}, [entries, q]);
useEffect(() => setCursor(0), [q, open]);
useEffect(() => {
list.current?.children[cursor]?.scrollIntoView({ block: 'nearest' });
}, [cursor]);
const go = (to: string) => {
onClose();
setQ('');
nav(to);
};
return (
<Dialog open={open} onClose={onClose} fullWidth maxWidth="sm" slotProps={{ paper: { sx: { position: 'absolute', top: '12vh', m: 0, borderRadius: 3 } } }}>
<Box sx={{ p: 1.5 }}>
<TextField
autoFocus
fullWidth
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder={ui('searchEverything')}
onKeyDown={(e) => {
if (e.key === 'ArrowDown') { e.preventDefault(); setCursor((c) => Math.min(c + 1, results.length - 1)); }
else if (e.key === 'ArrowUp') { e.preventDefault(); setCursor((c) => Math.max(c - 1, 0)); }
else if (e.key === 'Enter' && results[cursor]) go(results[cursor].to);
}}
slotProps={{ input: { startAdornment: <InputAdornment position="start"><SearchIcon sx={{ fontSize: 18 }} /></InputAdornment> } }}
/>
</Box>
<List ref={list} sx={{ maxHeight: '50vh', overflowY: 'auto', pt: 0, px: 1, pb: 1 }}>
{results.map((r, i) => (
<Box key={r.key} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<ListItemButton selected={i === cursor} onMouseMove={() => setCursor(i)} onClick={() => go(r.to)} sx={{ flex: 1 }}>
<ListItemText primary={r.label} secondary={r.group} />
</ListItemButton>
{/* the same "new record" shortcut the menu shows beside a module that can create records */}
{r.create && (
<Tooltip title={ui('new')}>
<IconButton size="small" sx={newRecordSx} aria-label={`${ui('new')} · ${r.label}`} onClick={() => go(r.create!)}>
<AddCircleOutline sx={{ fontSize: 16 }} />
</IconButton>
</Tooltip>
)}
</Box>
))}
{!results.length && <Typography color="text.secondary" sx={{ p: 2 }}>{ui('noResults')}</Typography>}
</List>
</Dialog>
);
}

45
src/layout/NavContext.tsx Normal file
View File

@ -0,0 +1,45 @@
import { createContext, useContext, useMemo, type ReactNode } from 'react';
import { useAuth } from '../auth/AuthContext';
import { isRtl, useT } from '../i18n';
import { parseMenu } from './menu';
import { buildDashboardSection, buildNav, buildTopBarSection, WIZARD_KEY, type NavSection } from './nav';
interface NavState {
sections: NavSection[];
/** section title in the current language */
title: (s: NavSection) => string;
headingTitle: (h: { en: string; ar: string; text?: string }) => string;
/** menu caption of an entity: the server's when it has one, else the entity caption */
labelOf: (entity: string) => string;
sectionOf: (entity: string) => NavSection | undefined;
}
const Ctx = createContext<NavState>({ sections: [], title: () => '', headingTitle: () => '', labelOf: (e) => e, sectionOf: () => undefined });
export const useNav = () => useContext(Ctx);
export function NavProvider({ children }: { children: ReactNode }) {
const { config, lang } = useAuth();
const t = useT();
const { user } = useAuth();
const rtl = isRtl(lang);
const sections = useMemo(() => {
const menu = buildNav(parseMenu(config?.MENU_STRUCTURE_VIEW ?? ''));
const dash = buildDashboardSection(user?.dashboard_name, rtl);
const extra = buildTopBarSection(config?.AUTHORITY ?? [], new Set(menu.flatMap((s) => s.items.map((i) => i.entity))));
const all = extra ? [...menu, extra] : menu;
return dash ? [dash, ...all] : all;
}, [config, user, rtl]);
const value = useMemo<NavState>(
() => ({
sections,
title: (s) => s.serverTitle || (rtl ? s.title.ar : s.title.en),
headingTitle: (h) => h.text || (rtl ? h.ar : h.en),
labelOf: (entity) =>
sections.flatMap((s) => s.items).find((i) => i.entity === entity)?.label ||
(entity === WIZARD_KEY ? (rtl ? 'طلب اشتراك اسطول' : 'Request fleet subscription') : t(entity)),
sectionOf: (entity) => sections.find((s) => s.items.some((i) => i.entity === entity)),
}),
[sections, rtl, t],
);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

194
src/layout/Sidebar.tsx Normal file
View File

@ -0,0 +1,194 @@
import { useEffect, useState } from 'react';
import { Link as RouterLink, useLocation, useNavigate } from 'react-router-dom';
import {
alpha, Box, Collapse, Divider, IconButton, List, ListItemButton, ListItemIcon, ListItemText, Menu, MenuItem,
Stack, Tooltip, Typography,
} from '@mui/material';
import ExpandMore from '@mui/icons-material/ExpandMore';
import HomeOutlined from '@mui/icons-material/HomeOutlined';
import ChevronLeft from '@mui/icons-material/ChevronLeft';
import ChevronRight from '@mui/icons-material/ChevronRight';
import AddCircleOutline from '@mui/icons-material/AddCircleOutline';
import { newRecordSx } from '../components/newRecordSx';
import { useUi } from '../i18n';
import { useNav } from './NavContext';
import type { NavSection } from './nav';
import { Logo, LogoIcon } from '../components/Logo';
export const SIDEBAR_WIDTH = 272;
export const RAIL_WIDTH = 76;
const entityFromPath = (p: string) => {
const e = /^\/e\/([^/]+)/.exec(p)?.[1];
if (e) return e;
const d = /^\/dashboard\/([^/]+)/.exec(p)?.[1];
return d ? `DASHBOARD:${d}` : undefined;
};
export function Sidebar({ collapsed, onToggle, onNavigate }: { collapsed: boolean; onToggle?: () => void; onNavigate?: () => void }) {
const { sections, title, headingTitle, labelOf } = useNav();
const ui = useUi();
const { pathname } = useLocation();
const nav = useNavigate();
const active = entityFromPath(pathname);
const [open, setOpen] = useState<string | null>(null);
const [pop, setPop] = useState<{ el: HTMLElement; section: NavSection } | null>(null);
// keep the section that contains the current page open
useEffect(() => {
const s = sections.find((x) => x.items.some((i) => i.entity === active));
if (s) setOpen(s.key);
}, [active, sections]);
const renderRows = (s: NavSection, inMenu: boolean) =>
s.rows.map((r, i) =>
'heading' in r ? (
<Box key={`h${i}`} sx={{ px: inMenu ? 1 : 1.5, pt: i === 0 ? 0.5 : 1.25, pb: 0.5 }}>
{i > 0 && <Divider sx={{ mb: 1 }} />}
<Typography
variant="caption"
fontWeight={800}
sx={{
display: 'block',
px: 1.25,
py: 0.5,
borderRadius: 1.5,
bgcolor: alpha(s.color, 0.14),
color: s.color,
textTransform: 'uppercase',
letterSpacing: '.04em',
}}
>
{headingTitle(r.heading)}
</Typography>
</Box>
) : inMenu ? (
<MenuItem
key={r.item.entity}
component={RouterLink}
to={r.item.to}
selected={active === r.item.entity}
onClick={() => { setPop(null); onNavigate?.(); }}
sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 1 }}
>
{labelOf(r.item.entity)}
{r.item.canCreate && (
<Tooltip title={ui('new')}>
<IconButton
sx={newRecordSx}
aria-label={`${ui('new')} · ${labelOf(r.item.entity)}`}
onClick={(e) => { e.preventDefault(); e.stopPropagation(); setPop(null); onNavigate?.(); nav(`/e/${r.item.entity}/create`); }}
>
<AddCircleOutline sx={{ fontSize: 16 }} />
</IconButton>
</Tooltip>
)}
</MenuItem>
) : (
<ListItemButton
key={r.item.entity}
component={RouterLink}
to={r.item.to}
selected={active === r.item.entity}
onClick={onNavigate}
sx={{ py: 0.6, ps: 2.5, pe: 1, mx: 1, justifyContent: 'space-between' }}
>
<ListItemText primary={labelOf(r.item.entity)} slotProps={{ primary: { fontSize: 14 } }} />
{r.item.canCreate && (
<Tooltip title={ui('new')}>
<IconButton
sx={newRecordSx}
aria-label={`${ui('new')} · ${labelOf(r.item.entity)}`}
// not a link of its own: the whole row is already a link, and one link inside another is invalid HTML
onClick={(e) => { e.preventDefault(); e.stopPropagation(); onNavigate?.(); nav(`/e/${r.item.entity}/create`); }}
>
<AddCircleOutline sx={{ fontSize: 16 }} />
</IconButton>
</Tooltip>
)}
</ListItemButton>
),
);
return (
<Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<Box sx={{ display: 'flex', alignItems: 'center', height: 53, px: collapsed ? 1 : 2.5, justifyContent: collapsed ? 'center' : 'space-between', flexShrink: 0 }}>
{collapsed ? <LogoIcon size={28} /> : <Logo height={30} />}
{onToggle && (
<Tooltip title={collapsed ? ui('expand') : ui('collapse')}>
<IconButton size="small" onClick={onToggle}>
{collapsed ? <ChevronRight className="flip-rtl" /> : <ChevronLeft className="flip-rtl" />}
</IconButton>
</Tooltip>
)}
</Box>
<Divider />
<Box sx={{ flex: 1, overflowY: 'auto', py: 1.5, px: collapsed ? 1 : 0 }}>
<List disablePadding sx={{ px: collapsed ? 0 : 1 }}>
<Tooltip title={collapsed ? ui('home') : ''} placement="right">
<ListItemButton component={RouterLink} to="/" selected={pathname === '/'} onClick={onNavigate} sx={{ mb: 0.5, justifyContent: collapsed ? 'center' : 'flex-start' }}>
<ListItemIcon sx={{ minWidth: 0, width: 28, justifyContent: 'center', marginInlineEnd: collapsed ? 0 : 1.5, color: 'inherit' }}><HomeOutlined sx={{ fontSize: 19 }} /></ListItemIcon>
{!collapsed && <ListItemText primary={ui('home')} slotProps={{ primary: { fontWeight: 600 } }} />}
</ListItemButton>
</Tooltip>
{sections.map((s) => {
const Icon = s.icon;
const isActive = s.items.some((i) => i.entity === active);
const expanded = open === s.key;
return (
<Box key={s.key}>
<Tooltip title={collapsed ? title(s) : ''} placement="right">
<ListItemButton
selected={collapsed && isActive}
onClick={(e) => (collapsed ? setPop({ el: e.currentTarget, section: s }) : setOpen(expanded ? null : s.key))}
sx={{
mb: 0.25,
justifyContent: collapsed ? 'center' : 'flex-start',
color: isActive ? 'primary.main' : 'text.primary',
...(collapsed && { '&.Mui-selected': { bgcolor: alpha(s.color, 0.16), '&:hover': { bgcolor: alpha(s.color, 0.24) } } }),
}}
>
<ListItemIcon
sx={{
minWidth: 0,
color: s.color,
width: 28, height: 28, borderRadius: '50%', display: 'grid', placeItems: 'center',
// a small gap between the icon and the caption
marginInlineEnd: collapsed ? 0 : 1.5,
bgcolor: alpha(s.color, isActive ? 0.28 : 0.14),
}}
>
<Icon sx={{ fontSize: 17 }} />
</ListItemIcon>
{!collapsed && (
<>
<ListItemText primary={title(s)} slotProps={{ primary: { fontWeight: 600, fontSize: 14.5 } }} />
<ExpandMore sx={{ transition: 'transform .2s', transform: expanded ? 'rotate(180deg)' : 'none', opacity: 0.6 }} />
</>
)}
</ListItemButton>
</Tooltip>
{!collapsed && (
<Collapse in={expanded} unmountOnExit>
<List disablePadding sx={{ pb: 0.5 }}>{renderRows(s, false)}</List>
</Collapse>
)}
</Box>
);
})}
</List>
</Box>
<Menu anchorEl={pop?.el} open={!!pop} onClose={() => setPop(null)} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} slotProps={{ paper: { sx: { minWidth: 220, maxHeight: '70vh' } } }}>
{pop && (
<Stack direction="row" alignItems="center" spacing={1} sx={{ px: 2, py: 1, bgcolor: alpha(pop.section.color, 0.12) }}>
<pop.section.icon sx={{ fontSize: 18, color: pop.section.color }} />
<Typography variant="subtitle2" fontWeight={800} sx={{ color: pop.section.color }}>{title(pop.section)}</Typography>
</Stack>
)}
{pop && renderRows(pop.section, true)}
</Menu>
</Box>
);
}

37
src/layout/menu.ts Normal file
View File

@ -0,0 +1,37 @@
// The server renders the role-based menu as HTML. We turn it into a typed tree and drop
// the javascript: hrefs; each leaf becomes a router path /e/<ENTITY>/<grid|create>.
export interface MenuNode {
label: string;
icon: string;
to?: string;
entity?: string;
children: MenuNode[];
}
const LEAF = /ui\.loadPage\('([A-Z0-9_]+)'\s*,\s*'([A-Z_]+)'\)/i;
/** `label` is the caption the server rendered into the menu (empty when the server has none). */
export function parseMenu(html: string): MenuNode[] {
const doc = new DOMParser().parseFromString(`<ul>${html}</ul>`, 'text/html');
const walk = (ul: Element): MenuNode[] =>
[...ul.children]
.filter((li) => li.tagName === 'LI')
.map((li) => {
const a = li.querySelector(':scope > a');
const m = LEAF.exec(a?.getAttribute('href') ?? '');
const sub = li.querySelector(':scope > ul');
const entity = m?.[1].toUpperCase();
const action = m?.[2].toLowerCase();
const text = a?.textContent?.trim() ?? '';
return {
label: text,
icon: a?.querySelector('i')?.getAttribute('class') ?? '',
entity,
to: entity ? `/e/${entity}/${action}` : undefined,
children: sub ? walk(sub) : [],
} satisfies MenuNode;
});
const root = doc.body.firstElementChild;
return root ? walk(root) : [];
}

246
src/layout/nav.ts Normal file
View File

@ -0,0 +1,246 @@
import type { ElementType } from 'react';
import MapOutlined from '@mui/icons-material/MapOutlined';
import PaymentsOutlined from '@mui/icons-material/PaymentsOutlined';
import EventNoteOutlined from '@mui/icons-material/EventNoteOutlined';
import BlockOutlined from '@mui/icons-material/BlockOutlined';
import GavelOutlined from '@mui/icons-material/GavelOutlined';
import LightbulbOutlined from '@mui/icons-material/LightbulbOutlined';
import LocalParkingOutlined from '@mui/icons-material/LocalParkingOutlined';
import LinkOutlined from '@mui/icons-material/LinkOutlined';
import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined';
import MailOutline from '@mui/icons-material/MailOutline';
import AppRegistrationOutlined from '@mui/icons-material/AppRegistrationOutlined';
import CardMembershipOutlined from '@mui/icons-material/CardMembershipOutlined';
import FolderOutlined from '@mui/icons-material/FolderOutlined';
import DashboardOutlined from '@mui/icons-material/DashboardOutlined';
import SupportAgentOutlined from '@mui/icons-material/SupportAgentOutlined';
import type { MenuNode } from './menu';
/**
* The server renders a role-based menu whose group labels are mostly empty, so group titles and
* icons are decided here, keyed by the first entity in the group. Entities (not GRID/CREATE
* pairs) are the menu items: the list page has the "New" button.
*/
interface GroupMeta { en: string; ar: string; icon: ElementType; color: string }
const GROUPS: Record<string, GroupMeta> = {
FLEET_TRACKING_SERVICES: { en: 'Tracking', ar: 'التتبع', icon: MapOutlined, color: '#2c98d4' },
POS_TRANSACTIONS: { en: 'Finance', ar: 'المالية', icon: PaymentsOutlined, color: '#2e8b4f' },
WAITING_PLAN: { en: 'Planning', ar: 'التخطيط', icon: EventNoteOutlined, color: '#e2a93b' },
TROUBLE_SHOOTING: { en: 'Incidents & blacklist', ar: 'البلاغات والقوائم السوداء', icon: BlockOutlined, color: '#c6484b' },
VIOLATIONS: { en: 'Violations', ar: 'المخالفات', icon: GavelOutlined, color: '#9c3a53' },
COMPLAINTS_SUGGESTIONS: { en: 'Feedback', ar: 'الشكاوى والمقترحات', icon: LightbulbOutlined, color: '#7c6fd1' },
PARKING_YARD: { en: 'Parking', ar: 'المواقف', icon: LocalParkingOutlined, color: '#00897b' },
AFFILIATION: { en: 'Affiliation', ar: 'الإنتساب', icon: LinkOutlined, color: '#3f51b5' },
RENTED_TRUCK: { en: 'Rented trucks', ar: 'الشاحنات المستأجرة', icon: LocalShippingOutlined, color: '#1565c0' },
LETTERS_DETAILS: { en: 'Letters', ar: 'المراسلات', icon: MailOutline, color: '#d16475' },
PERSONNEL: { en: 'Registry', ar: 'السجلات', icon: AppRegistrationOutlined, color: '#0097a7' },
SUBSCRIPTIONS: { en: 'Subscriptions & permits', ar: 'الاشتراكات والتصاريح', icon: CardMembershipOutlined, color: '#6a3fa0' },
};
// sections the server's own menu groups that have no entry above (a fallback "More" group, or a role-specific
// one we haven't named) still get a distinct colour, cycled by position, instead of all looking the same grey
const FALLBACK_COLORS = ['#2c98d4', '#d16475', '#2e8b4f', '#e2a93b', '#7c6fd1', '#0097a7', '#c6484b', '#a5894f'];
// the business's requested menu order (Dashboard is handled separately, always first)
const SECTION_ORDER = [
'PERSONNEL', // Registration
'SUBSCRIPTIONS',
'POS_TRANSACTIONS', // Financial system
'TROUBLE_SHOOTING', // Troubleshooting
'VIOLATIONS', // Violations and Sanctions
'AFFILIATION', // Fleet Affiliations
'RENTED_TRUCK', // Rented Trucks Affiliation
'PARKING_YARD',
'COMPLAINTS_SUGGESTIONS', // Complaint and suggestion
'LETTERS_DETAILS', // messages
'WAITING_PLAN', // capacity management
];
// sub-headings inside a big group, keyed by their first entity
const HEADINGS: Record<string, { en: string; ar: string }> = {
TRUCKS: { en: 'Fleet', ar: 'المركبات' },
INVESTORS: { en: 'Stakeholders', ar: 'الجهات' },
};
export interface NavItem {
entity: string;
to: string;
canCreate: boolean;
/** caption from the server's menu, when it has one */
label?: string;
}
export interface NavSection {
key: string;
title: { en: string; ar: string };
/** group caption from the server's menu, when it has one (wins over `title`) */
serverTitle?: string;
icon: ElementType;
/** a distinct tint for this section's icon, mainly to tell sections apart when the sidebar is collapsed */
color: string;
/** items and optional headings, in menu order */
rows: ({ item: NavItem } | { heading: { en: string; ar: string; text?: string } })[];
items: NavItem[];
/** the group's first entity, used to sort sections into the business's requested menu order */
groupEntity?: string;
}
/** Menu entries the business asked to hide (the goods-tracking service). */
export const HIDDEN_ENTITIES = new Set(['FLEET_TRACKING_SERVICES', 'WAITING_PLAN', 'SCHEDULING_PLAN', 'CAPACITY_PLAN_DETAILS']);
/** Entities that leave their own group and sit right after another entity: Permits status (CAPACITY) goes under Fleet permits. */
const MOVE_AFTER: Record<string, string> = { CAPACITY: 'PERMITS' };
const isEntityContainer = (n: MenuNode) => n.children.length > 0 && n.children.every((c) => c.entity);
/** Turn the legacy GRID/CREATE leaves of one container into one item per entity. */
function toItems(leaves: MenuNode[], containerLabel = ''): NavItem[] {
const by = new Map<string, { grid: boolean; create: boolean; label: string; createLabel: string }>();
for (const l of leaves) {
const e = l.entity!;
const cur = by.get(e) ?? { grid: false, create: false, label: '', createLabel: '' };
if (l.to?.endsWith('/grid')) {
cur.grid = true;
cur.label = l.label || cur.label;
} else {
cur.create = true;
cur.createLabel = l.label || cur.createLabel;
}
by.set(e, cur);
}
// the entity's own caption sits on its container; the GRID leaf caption is the fallback
const items: NavItem[] = [];
for (const [entity, f] of by) {
items.push({
entity,
to: `/e/${entity}/${f.grid ? 'grid' : 'create'}`,
canCreate: f.create,
label: containerLabel || f.label || undefined,
});
// the subscription request wizard is reached from the "+" beside Fleet subscriptions, not from its own menu entry
}
return items;
}
export const WIZARD_KEY = 'SUBSCRIPTIONS:new';
export function buildNav(menu: MenuNode[]): NavSection[] {
const sections: NavSection[] = [];
menu.forEach((top, i) => {
const rows: NavSection['rows'] = [];
const leavesDirect = top.children.filter((c) => c.entity);
if (leavesDirect.length) toItems(leavesDirect, '').forEach((item) => rows.push({ item }));
for (const c of top.children) {
if (c.entity) continue;
if (isEntityContainer(c)) {
toItems(c.children, c.label).forEach((item) => rows.push({ item }));
} else {
const first = c.children.flatMap((x) => (isEntityContainer(x) ? x.children : []))[0]?.entity;
if (first && (HEADINGS[first] || c.label)) {
rows.push({ heading: { en: HEADINGS[first]?.en ?? c.label, ar: HEADINGS[first]?.ar ?? c.label, text: c.label || undefined } });
}
for (const x of c.children) if (isEntityContainer(x)) toItems(x.children, x.label).forEach((item) => rows.push({ item }));
}
}
const visible = rows.filter((r) => !('item' in r) || !HIDDEN_ENTITIES.has(r.item.entity));
const items = visible.flatMap((r) => ('item' in r ? [r.item] : []));
if (!items.length) return;
const meta = GROUPS[items[0].entity];
sections.push({
key: `${i}:${items[0].entity}`,
title: meta ?? { en: 'More', ar: 'المزيد' },
serverTitle: top.label || undefined,
icon: meta?.icon ?? FolderOutlined,
color: meta?.color ?? FALLBACK_COLORS[sections.length % FALLBACK_COLORS.length],
rows: visible,
items,
groupEntity: items[0].entity,
});
});
for (const [moved, after] of Object.entries(MOVE_AFTER)) {
const from = sections.find((s) => s.items.some((i) => i.entity === moved));
const to = sections.find((s) => s.items.some((i) => i.entity === after));
if (!from || !to || from === to) continue;
const row = from.rows.find((r) => 'item' in r && r.item.entity === moved);
if (!row || !('item' in row)) continue;
from.rows = from.rows.filter((r) => r !== row);
from.items = from.items.filter((i) => i !== row.item);
const at = to.rows.findIndex((r) => 'item' in r && r.item.entity === after);
to.rows.splice(at + 1, 0, row);
to.items.splice(to.items.findIndex((i) => i.entity === after) + 1, 0, row.item);
}
for (let i = sections.length - 1; i >= 0; i--) if (!sections[i].items.length) sections.splice(i, 1);
// the server returns groups in its own (role-dependent) order; re-sort to the business's requested order,
// keeping any unlisted/custom group after the known ones, in the order the server sent them
const rank = (s: NavSection) => {
const i = SECTION_ORDER.indexOf(s.groupEntity ?? '');
return i === -1 ? SECTION_ORDER.length : i;
};
return sections
.map((s, i) => ({ s, i }))
.sort((a, b) => rank(a.s) - rank(b.s) || a.i - b.i)
.map(({ s }) => s);
}
/**
* The old UI showed two modules as icons in its top bar instead of in the menu: the customer service screen (tickets)
* and the entry permit requests screen. Here they get a menu group of their own, for the roles allowed to list them
* and only when the server's menu does not already carry them.
*/
const TOP_BAR_MODULES = ['TICKETS', 'FLEET_REQUEST'];
export function buildTopBarSection(authority: { ENTITY_NAME?: string; ACTION_NAME: string }[], inMenu: Set<string>): NavSection | null {
const items: NavItem[] = TOP_BAR_MODULES.filter(
(e) => !inMenu.has(e) && !HIDDEN_ENTITIES.has(e) && authority.some((a) => a.ENTITY_NAME === e && a.ACTION_NAME === 'GETGRID'),
).map((entity) => ({
entity,
to: `/e/${entity}/grid`,
canCreate: authority.some((a) => a.ENTITY_NAME === entity && a.ACTION_NAME === 'CREATE'),
}));
if (!items.length) return null;
return {
key: 'top-bar-modules',
title: { en: 'Requests & support', ar: 'الطلبات والدعم' },
icon: SupportAgentOutlined,
color: '#e07a3f',
rows: items.map((item) => ({ item })),
items,
};
}
/** The old home page's dashboards and infographics, now a menu of their own. */
export const DASHBOARDS: Record<string, { en: string; ar: string; slug: string }> = {
_stkhDashboard: { en: 'Stakeholders dashboard', ar: 'إحصائية الجهات', slug: 'stakeholders' },
_fleetDashboard: { en: 'Fleet dashboard', ar: 'إحصائية المركبات', slug: 'fleet' },
_personnelDashboard: { en: 'Personnel dashboard', ar: 'إحصائية العاملين والسائقين', slug: 'personnel' },
_fleetInfographic: { en: 'Fleet infographic', ar: 'إنفوجرافيك المركبات', slug: 'fleet-infographic' },
_personnelInfographic: { en: 'Personnel infographic', ar: 'إنفوجرافيك العاملين', slug: 'personnel-infographic' },
_stakeholdersinfographic: { en: 'Stakeholders infographic', ar: 'إنفوجرافيك الجهات', slug: 'stakeholders-infographic' },
};
/** Build the Dashboard section from the user's `dashboard_name` list (a JSON string in the session). */
export function buildDashboardSection(raw: unknown, rtl: boolean): NavSection | null {
let list: { NAME?: string; ORDER?: number }[] = [];
try {
list = typeof raw === 'string' ? (JSON.parse(raw) as typeof list) : [];
} catch {
list = [];
}
const known = list
.filter((d) => d.NAME && DASHBOARDS[d.NAME])
.sort((a, b) => (a.ORDER ?? 0) - (b.ORDER ?? 0));
if (!known.length) return null;
const items: NavItem[] = known.map((d) => ({
entity: `DASHBOARD:${DASHBOARDS[d.NAME!].slug}`,
to: `/dashboard/${DASHBOARDS[d.NAME!].slug}`,
canCreate: false,
label: rtl ? DASHBOARDS[d.NAME!].ar : DASHBOARDS[d.NAME!].en,
}));
return {
key: 'dashboard',
title: { en: 'Dashboard', ar: 'الاحصائيات' },
icon: DashboardOutlined,
color: '#d1a233',
rows: items.map((item) => ({ item })),
items,
};
}

28
src/main.tsx Normal file
View File

@ -0,0 +1,28 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AuthProvider } from './auth/AuthContext';
import { I18nProvider } from './i18n';
import { AppTheme } from './theme';
import { NotifyProvider } from './notify/NotifyProvider';
import { App } from './App';
const queryClient = new QueryClient({
defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 1 } },
});
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<AppTheme>
<I18nProvider>
<NotifyProvider>
<App />
</NotifyProvider>
</I18nProvider>
</AppTheme>
</AuthProvider>
</QueryClientProvider>
</StrictMode>,
);

View File

@ -0,0 +1,73 @@
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';
import { Alert, Snackbar, type AlertColor } from '@mui/material';
import { useT } from '../i18n';
interface Note {
id: number;
severity: AlertColor;
text: string;
}
interface Notifier {
/** `code` is a backend message code (a caption key); `fallback` is shown when there is no caption for it */
success: (code: string, fallback?: string) => void;
warning: (code: string, fallback?: string) => void;
info: (code: string, fallback?: string) => void;
/** show any thrown error: backend business messages are caption codes and get translated */
error: (e: unknown) => void;
}
const Ctx = createContext<Notifier>({ success() {}, warning() {}, error() {}, info() {} });
export const useNotify = () => useContext(Ctx);
let seq = 0;
/** Toasts for what the backend says: "saved successfully", validation failures, report ready… */
export function NotifyProvider({ children }: { children: ReactNode }) {
const t = useT();
const [notes, setNotes] = useState<Note[]>([]);
const push = useCallback((severity: AlertColor, text: string) => {
const id = ++seq;
setNotes((n) => [...n.slice(-2), { id, severity, text }]);
}, []);
const close = (id: number) => setNotes((n) => n.filter((x) => x.id !== id));
const api = useMemo<Notifier>(() => {
const say = (code: string, fallback?: string) => {
if (!code) return fallback ?? '';
const text = t(code);
if (text !== code) return text; // a real caption translation was found
// no translation: if `code` is itself an opaque caption key (e.g. "SUCCESSFUL.OPERATION"),
// show the nicer fallback; otherwise it's already a human-readable message straight from
// the backend (e.g. "Password has been reset successfully, new password is p392890"), so show it as-is
return /^[A-Z0-9_.]+$/.test(code) && fallback ? fallback : code;
};
return {
success: (code, fb) => push('success', say(code, fb)),
warning: (code, fb) => push('warning', say(code, fb)),
info: (code, fb) => push('info', say(code, fb)),
error: (e) => push('error', t(e instanceof Error ? e.message : String(e))),
};
}, [push, t]);
return (
<Ctx.Provider value={api}>
{children}
{notes.map((n, i) => (
<Snackbar
key={n.id}
open
autoHideDuration={n.severity === 'error' ? 8000 : 4500}
onClose={(_, reason) => reason !== 'clickaway' && close(n.id)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
sx={{ bottom: { xs: 16 + i * 58, sm: 24 + i * 58 } }}
>
<Alert severity={n.severity} variant="filled" onClose={() => close(n.id)} sx={{ minWidth: 280, maxWidth: 560, alignItems: 'center' }}>
{n.text}
</Alert>
</Snackbar>
))}
</Ctx.Provider>
);
}

242
src/pages.tsx Normal file
View File

@ -0,0 +1,242 @@
import { useState, type FormEvent } from 'react';
import { Link as RouterLink, Navigate, useParams } from 'react-router-dom';
import {
Alert, Box, Button, Checkbox, CircularProgress, Divider, FormControlLabel, IconButton,
InputAdornment, Paper, Stack, TextField, Tooltip, Typography,
} from '@mui/material';
import LanguageIcon from '@mui/icons-material/Language';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import FacebookIcon from '@mui/icons-material/Facebook';
import YouTubeIcon from '@mui/icons-material/YouTube';
import PublicIcon from '@mui/icons-material/Public';
import { useAuth } from './auth/AuthContext';
import { ForgotPasswordDialog } from './auth/ForgotPasswordDialog';
import { useT, useUi } from './i18n';
import { Logo, LogoIcon } from './components/Logo';
import { LoginArt } from './components/LoginArt';
import { EntityRoute } from './features/EntityRoute';
import { HomeLauncher } from './features/HomeLauncher';
const SOCIAL_LINKS = [
{ icon: FacebookIcon, label: 'Facebook', href: 'https://www.facebook.com/NafithOman/?_rdc=2&_rdr' },
{ icon: YouTubeIcon, label: 'YouTube', href: 'https://www.youtube.com/channel/UCilALKPs7PnVIlEPF28TFkQ' },
{ icon: PublicIcon, label: 'nafith.om', href: 'http://nafith.om/' },
];
export function LoginPage() {
const { user, signIn, lang, setLang } = useAuth();
const t = useT();
const ui = useUi();
const [u, setU] = useState('');
const [p, setP] = useState('');
const [remember, setRemember] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [err, setErr] = useState('');
const [touched, setTouched] = useState(false);
const [busy, setBusy] = useState(false);
const [forgotOpen, setForgotOpen] = useState(false);
if (user) return <Navigate to="/" replace />;
// no caption table exists before sign-in, so backend login codes are shown through our own text; wrong user
// and wrong password read the same, which also stops the page from telling which usernames exist
const loginMessage = (code: string) =>
/^LOGIN\.(USER_NOT_FOUND|INVALID_PASSWORD)$/.test(code) || /^WRONG_INFO$/.test(code) || t(code) === code ? ui('loginFailed') : t(code);
const submit = async (e: FormEvent) => {
e.preventDefault();
// the browser's own "please fill out this field" bubble is in the browser's language, so the form
// validates itself (noValidate) and says it in the page's language
setTouched(true);
if (!u.trim() || !p) return;
setBusy(true);
setErr('');
try {
await signIn(u, p, remember);
} catch (x) {
setErr(x instanceof Error ? x.message : 'LOGIN_FAILED');
} finally {
setBusy(false);
}
};
return (
<Box sx={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1.1fr 1fr' } }}>
{/* brand panel */}
<Box
sx={{
display: { xs: 'none', md: 'flex' },
position: 'relative',
overflow: 'hidden',
flexDirection: 'column',
justifyContent: 'space-between',
p: 6,
color: '#fff',
background: 'linear-gradient(135deg, #0b3a5c 0%, #0b6ea8 55%, #1a8fc9 100%)',
}}
>
<LoginArt />
<LogoIcon
size={520}
sx={{
position: 'absolute',
insetInlineEnd: -140,
bottom: -140,
opacity: 0.1,
filter: 'grayscale(1) brightness(5)',
pointerEvents: 'none',
}}
/>
<Box
sx={{
position: 'absolute',
insetInlineStart: -80,
top: -80,
width: 260,
height: 260,
borderRadius: '50%',
background: 'radial-gradient(circle, rgba(255,255,255,.18), transparent 70%)',
pointerEvents: 'none',
}}
/>
<Box sx={{ position: 'relative' }}>
<Logo height={52} on="dark" />
</Box>
<Box sx={{ position: 'relative', maxWidth: 440 }}>
<Typography variant="h4" fontWeight={800} sx={{ mb: 2 }}>
{ui('loginWelcome')}
</Typography>
<Typography sx={{ opacity: 0.9, fontSize: 16, lineHeight: 1.8 }}>{ui('loginTagline')}</Typography>
</Box>
<Stack direction="row" spacing={1.5} sx={{ position: 'relative' }}>
{SOCIAL_LINKS.map(({ icon: Icon, label, href }) => (
<Tooltip key={label} title={label}>
<IconButton
component="a"
href={href}
target="_blank"
rel="noopener noreferrer"
size="small"
sx={{ color: '#fff', bgcolor: 'rgba(255,255,255,.12)', '&:hover': { bgcolor: 'rgba(255,255,255,.22)' } }}
>
<Icon fontSize="small" />
</IconButton>
</Tooltip>
))}
</Stack>
</Box>
{/* form panel */}
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', p: 3, bgcolor: 'background.default' }}>
<Paper
elevation={0}
sx={{ width: 400, maxWidth: '100%', p: { xs: 3, sm: 4.5 }, border: '1px solid', borderColor: 'divider', borderRadius: 3 }}
>
<Stack component="form" noValidate spacing={2.25} onSubmit={submit}>
<Box sx={{ display: { xs: 'flex', md: 'none' }, justifyContent: 'center', mb: 0.5 }}>
<Logo height={36} />
</Box>
<Box>
<Typography variant="h5" component="h1" fontWeight={800}>
{ui('loginTitle')}
</Typography>
</Box>
{err && <Alert severity="error">{loginMessage(err)}</Alert>}
<TextField
label={ui('loginUsername')}
placeholder={ui('loginUsername')}
value={u}
onChange={(e) => setU(e.target.value)}
autoComplete="username"
required
autoFocus
error={touched && !u.trim()}
helperText={touched && !u.trim() ? ui('loginRequired') : undefined}
/>
<TextField
label={ui('loginPassword')}
placeholder={ui('loginPassword')}
type={showPassword ? 'text' : 'password'}
value={p}
onChange={(e) => setP(e.target.value)}
autoComplete="current-password"
required
error={touched && !p}
helperText={touched && !p ? ui('loginRequired') : undefined}
slotProps={{
input: {
endAdornment: (
<InputAdornment position="end">
<IconButton
size="small"
edge="end"
tabIndex={-1}
aria-label={showPassword ? ui('hidePassword') : ui('showPassword')}
onClick={() => setShowPassword((v) => !v)}
>
{showPassword ? <VisibilityOff fontSize="small" /> : <Visibility fontSize="small" />}
</IconButton>
</InputAdornment>
),
},
}}
/>
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mt: -1 }}>
<FormControlLabel
control={<Checkbox size="small" checked={remember} onChange={(e) => setRemember(e.target.checked)} />}
label={ui('rememberMe')}
sx={{ color: 'text.secondary' }}
/>
<Button size="small" onClick={() => setForgotOpen(true)}>
{ui('forgotPassword')}
</Button>
</Stack>
<Button type="submit" variant="contained" disabled={busy} size="large">
{busy ? <CircularProgress size={22} color="inherit" /> : ui('loginSubmit')}
</Button>
<Stack direction="row" spacing={0.5} justifyContent="center" alignItems="center">
<Typography variant="body2" color="text.secondary">
{ui('newToNafith')}
</Typography>
<Button size="small" component={RouterLink} to="/register">
{ui('signUp')}
</Button>
</Stack>
<Button size="small" startIcon={<LanguageIcon fontSize="small" />} onClick={() => setLang(lang === 'AR' ? 'EN' : 'AR')}>
{lang === 'AR' ? 'English' : 'العربية'}
</Button>
<Divider sx={{ pt: 1 }}>
<Typography variant="caption" color="text.secondary">
{ui('followUs')}
</Typography>
</Divider>
<Stack direction="row" spacing={1} justifyContent="center">
{SOCIAL_LINKS.map(({ icon: Icon, label, href }) => (
<Tooltip key={label} title={label}>
<IconButton component="a" href={href} target="_blank" rel="noopener noreferrer" size="small" color="primary">
<Icon fontSize="small" />
</IconButton>
</Tooltip>
))}
</Stack>
<Typography variant="caption" color="text.secondary" textAlign="center">
© {new Date().getFullYear()} Nafith@Madayn — {ui('allRightsReserved')}
</Typography>
</Stack>
</Paper>
</Box>
<ForgotPasswordDialog open={forgotOpen} onClose={() => setForgotOpen(false)} />
</Box>
);
}
export function HomePage() {
return <HomeLauncher />;
}
export function EntityPage() {
const { entity = '', view = 'grid', id } = useParams();
return <EntityRoute key={`${entity}/${view}/${id ?? ''}`} entity={entity} view={view} id={id} />;
}

144
src/theme.tsx Normal file
View File

@ -0,0 +1,144 @@
import { createContext, useContext, useMemo, useState, type ReactNode } from 'react';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';
import { CssBaseline, ThemeProvider, createTheme, type PaletteMode } from '@mui/material';
import { useAuth } from './auth/AuthContext';
import { isRtl } from './i18n';
const ltrCache = createCache({ key: 'mui' });
const rtlCache = createCache({ key: 'muirtl', stylisPlugins: [prefixer, rtlPlugin] });
const MODE_KEY = 'mams.mode';
const readMode = (): PaletteMode => {
try {
const saved = localStorage.getItem(MODE_KEY);
if (saved === 'dark' || saved === 'light') return saved;
} catch {
/* storage can be blocked */
}
// light unless the user chose dark themselves
return 'light';
};
const ModeCtx = createContext<{ mode: PaletteMode; toggle: () => void }>({ mode: 'light', toggle: () => {} });
export const useColorMode = () => useContext(ModeCtx);
// Design tokens: calm blue-grey surfaces, the Nafith blue as primary, a rose accent used sparingly.
const tokens = {
light: { bg: '#f4f6fa', paper: '#ffffff', border: '#e2e8f0', primary: '#0b6ea8', text: '#0b3a5c', sub: '#5b6b7d', accent: '#d6336c' },
dark: { bg: '#0d1520', paper: '#141f2d', border: '#243245', primary: '#5fb4ea', text: '#e6edf5', sub: '#9aabbd', accent: '#f06595' },
};
export function AppTheme({ children }: { children: ReactNode }) {
const { lang } = useAuth();
const rtl = isRtl(lang);
const [mode, setMode] = useState<PaletteMode>(readMode);
const toggle = () =>
setMode((m) => {
const next = m === 'light' ? 'dark' : 'light';
try {
localStorage.setItem(MODE_KEY, next);
} catch {
/* ignore */
}
return next;
});
const theme = useMemo(() => {
const k = tokens[mode];
return createTheme({
direction: rtl ? 'rtl' : 'ltr',
palette: {
mode,
primary: { main: k.primary },
secondary: { main: k.accent },
background: { default: k.bg, paper: k.paper },
text: { primary: k.text, secondary: k.sub },
divider: k.border,
},
shape: { borderRadius: 12 },
typography: {
// Cairo covers both Arabic and Latin text in one family — same font nafith.eg's own login page uses.
fontFamily: '"Cairo", "Segoe UI", Tahoma, system-ui, sans-serif',
h4: { fontWeight: 700, letterSpacing: '-0.01em' },
h5: { fontWeight: 700, letterSpacing: '-0.01em', fontSize: '1.3rem' },
h6: { fontWeight: 700 },
button: { textTransform: 'none', fontWeight: 600 },
},
components: {
MuiPaper: { defaultProps: { elevation: 0 }, styleOverrides: { outlined: { borderColor: k.border } } },
MuiButton: { defaultProps: { disableElevation: true, size: 'small' }, styleOverrides: { root: { borderRadius: 8 } } },
// every popup (confirmations, reason / reply / VAT forms) shares one width, title size and text size
MuiDialog: {
defaultProps: { fullWidth: true, maxWidth: 'xs' },
styleOverrides: { paper: { borderRadius: 12 } },
},
MuiDialogTitle: { styleOverrides: { root: { fontSize: '1.05rem', fontWeight: 700, lineHeight: 1.4 } } },
MuiDialogContent: {
styleOverrides: { root: { fontSize: '0.9rem', '& .MuiTypography-root:not(.MuiTypography-caption)': { fontSize: '0.9rem' } } },
},
MuiDialogActions: { styleOverrides: { root: { padding: '8px 24px 16px', gap: 4 } } },
MuiTable: { defaultProps: { size: 'small' } },
MuiTextField: { defaultProps: { size: 'small' } },
// MUI's own texts ("No options", "Loading…") follow the page language
MuiAutocomplete: {
defaultProps: {
size: 'small',
noOptionsText: rtl ? 'لا توجد خيارات' : 'No options',
loadingText: rtl ? 'جارٍ التحميل…' : 'Loading…',
clearText: rtl ? 'مسح' : 'Clear',
openText: rtl ? 'فتح' : 'Open',
closeText: rtl ? 'إغلاق' : 'Close',
},
styleOverrides: { option: { fontSize: 13.5 }, noOptions: { fontSize: 13.5 } },
},
// field text, placeholders and labels are the same size as the grid cells and the menu (13.5px)
MuiInputBase: { styleOverrides: { root: { fontSize: 13.5 } } },
// the values inside an opened drop list
MuiMenuItem: { styleOverrides: { root: { fontSize: 13.5 } } },
MuiInputLabel: { styleOverrides: { root: { fontSize: 13.5 } } },
MuiFormHelperText: { styleOverrides: { root: { fontSize: 12 } } },
MuiChip: { styleOverrides: { root: { fontWeight: 600 } } },
MuiTableCell: {
styleOverrides: {
// dense rows; the header is a quiet tint of the surface, not a bright band
root: { borderColor: k.border, padding: '5px 12px', fontSize: 13.5, lineHeight: 1.35 },
head: {
backgroundColor: mode === 'light' ? '#eaf2fc' : '#13263b',
color: mode === 'light' ? '#1f3a5f' : '#bcd4ea',
fontWeight: 700,
fontSize: 13,
padding: '9px 12px',
lineHeight: 1.3,
borderBottomColor: mode === 'light' ? '#cfe0f5' : '#24405e',
},
},
},
MuiListItemButton: {
styleOverrides: {
root: {
borderRadius: 8,
paddingTop: 5,
paddingBottom: 5,
'&.Mui-selected': { backgroundColor: mode === 'light' ? '#e6f2fa' : '#17324a', color: k.primary },
'&.Mui-selected:hover': { backgroundColor: mode === 'light' ? '#dbeaf6' : '#1b3a56' },
},
},
},
},
});
}, [mode, rtl]);
return (
<ModeCtx.Provider value={{ mode, toggle }}>
<CacheProvider value={rtl ? rtlCache : ltrCache}>
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
</CacheProvider>
</ModeCtx.Provider>
);
}

18
tsconfig.json Normal file
View File

@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"skipLibCheck": true,
"isolatedModules": true,
"resolveJsonModule": true,
"noEmit": true,
"types": ["vite/client", "node"]
},
"include": ["src", "vite.config.ts"]
}

36
vite.config.ts Normal file
View File

@ -0,0 +1,36 @@
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
// The ColdFusion backend is unchanged. In dev it is proxied so the browser sees one origin
// (session cookies work, no CORS). In production IIS serves /mams next to /OmanTCS_stg.
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
const target = env.VITE_BACKEND_ORIGIN || 'http://192.168.6.46';
const proxy = { '/OmanTCS_stg': { target, changeOrigin: true } };
return {
base: env.VITE_BASE || '/mams/',
plugins: [react()],
server: { port: 5173, proxy },
// `npm start` serves the production build from your PC with the same backend proxy
preview: { port: 4173, proxy },
build: {
// staging builds go to their own folder so they never overwrite (or get deployed as) the production build
outDir: mode === 'staging' ? 'dist-staging' : 'dist',
sourcemap: false,
target: 'es2022',
rollupOptions: {
output: {
// libraries change rarely: keep them in their own files so the browser can cache them across releases
manualChunks: (id) => {
if (!id.includes('node_modules')) return undefined;
if (/node_modules\/(react|react-dom|react-router|react-router-dom|scheduler)\//.test(id)) return 'react';
if (id.includes('@mui/icons-material')) return 'mui-icons';
if (/node_modules\/(@mui|@emotion)\//.test(id)) return 'mui';
if (id.includes('@tanstack')) return 'query';
return undefined;
},
},
},
},
};
});