Truck layouts, company Riyada value, cache tool, sign-in return and Home colors

- Trucks: truck info in legacy column order, owner section like the trailer's, new vehicles default to Omani document nationality
- Fleet record pages hide the owner's identity-document fields; save button hidden when the role cannot update
- Companies: Riyada card value on the record page and the tick box for the operations office
- Customer Service: ticket type and subject mandatory on create
- System cache page (/caching) for the system administrator role and the "system" user, with a user-menu entry
- Signing in returns to the page that was asked for before the login page
- Home page section icons use the menu colors; Registration system color changed
- Company profile page has no back button or breadcrumb

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-12 11:17:45 +03:00
parent a01c9324c3
commit e631b3c12b
13 changed files with 282 additions and 32 deletions

View File

@ -1,5 +1,5 @@
import { lazy, Suspense } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom';
import { LoadingScreen } from './components/LoadingScreen';
import { useAuth } from './auth/AuthContext';
import { AppShell } from './layout/AppShell';
@ -7,10 +7,18 @@ 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 cache tool (the old caching.cfm) is for staff and rarely opened
const CachingPage = lazy(() => import('./features/admin/CachingPage').then((m) => ({ default: m.CachingPage })));
// 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 })));
/** Not signed in: go to the login page and remember the page that was asked for, so signing in lands there. */
function ToLogin() {
const { pathname, search } = useLocation();
return <Navigate to="/login" replace state={pathname === '/' ? undefined : { from: `${pathname}${search}` }} />;
}
export function App() {
const { user, ready } = useAuth();
if (!ready) return <LoadingScreen />;
@ -21,10 +29,11 @@ export function App() {
<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 element={user ? <AppShell /> : <ToLogin />}>
<Route index element={<HomePage />} />
<Route path="e/:entity/:view/:id?" element={<EntityPage />} />
<Route path="dashboard/:slug" element={<DashboardPage />} />
<Route path="caching" element={<CachingPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>

View File

@ -223,7 +223,7 @@ function GridPage({ entity, extraDefaults }: { entity: string; extraDefaults?: R
}
/** A whole-page "not authorized" — no grid chrome, no filters, just what happened and the way out. */
function NotAuthorized() {
export function NotAuthorized() {
const ui = useUi();
return (
<Box sx={{ display: 'grid', placeItems: 'center', py: 10, textAlign: 'center' }}>
@ -275,7 +275,8 @@ export function EntityRoute({ entity, view, id }: { entity: string; view: string
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)}`} />
{/* the company profile (opened from the user menu with ?own=1) has no back button */}
<PageHeader backTo={params.get('own') === '1' ? undefined : profile ? '/' : `/e/${entity}/grid`} title={profile ? ui('myProfile') : `${id ? ui('edit') : ui('new')} · ${labelOf(entity)}`} />
<Suspense fallback={<PageLoading />}>
<EntityForm entity={entity} id={id} />
</Suspense>

View File

@ -1,5 +1,5 @@
import { Link as RouterLink } from 'react-router-dom';
import { Box, IconButton, Paper, Stack, Tooltip, Typography } from '@mui/material';
import { alpha, Box, IconButton, Paper, Stack, Tooltip, Typography } from '@mui/material';
import AddCircleOutline from '@mui/icons-material/AddCircleOutlineOutlined';
import { newRecordSx } from '../components/newRecordSx';
import { useAuth } from '../auth/AuthContext';
@ -34,7 +34,8 @@ export function HomeLauncher() {
alignItems: "center",
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>
{/* the section's own colour, the same soft badge the menu uses */}
<Box sx={{ display: 'grid', placeItems: 'center', width: 30, height: 30, borderRadius: 1.5, bgcolor: alpha(s.color, 0.14), color: s.color }}><Icon sx={{ fontSize: 18 }} /></Box>
<Typography component="h2" sx={{
fontWeight: 700
}}>{title(s)}</Typography>

View File

@ -0,0 +1,179 @@
import { useMemo, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Paper, Stack, Typography } from '@mui/material';
import StorageOutlined from '@mui/icons-material/StorageOutlined';
import { useAuth } from '../../auth/AuthContext';
import { useNotify } from '../../notify/NotifyProvider';
import { useT, useUi } from '../../i18n';
import { PageHeader } from '../../components/PageHeader';
import { SectionTitle, sectionFrame } from '../../components/SectionTitle';
import { API_BASE, ApiError } from '../../api/client';
import { NotAuthorized } from '../EntityRoute';
import { canUseCaching } from './cachingAccess';
/**
* The old caching.cfm: choose which cached regions (and, inside them, which tables and objects) the backend should
* rebuild, then press Cache. The backend call is
* `cashing.cfc?method=cacheTables&regionsSTR={KEY:{region:[tables]},OBJECT:{region:[objects]}}`.
*/
interface Region {
name: string;
tables: string[];
objects?: string[];
}
const REGIONS: Region[] = [
{
name: 'AUTHORITY',
tables: [
'ROLE_AUTHORITY_VIEW', 'ROLE_AUTHORITY_OWNERSHIP_VIEW', 'ROLE_GRID_AUTHORITY', 'ROLE_SEARCH_FIELD_AUTHORITY_VIEW', 'ROLE_REPORT_AUTHORITY',
'NOTIFICATION_TEMPLATE_VIEW', 'ROLE_FIELD_STATUS_AUTHORITY_VIEW', 'ROLE_ACTION_EXTRA_FIELD_VIEW',
],
},
{
name: 'ENTITY',
tables: [
'ENTITY', 'ENTITY_ACTION', 'ENTITY_FIELD_VIEW', 'ENTITY_FIELD', 'ENTITY_STATUS_VIEW', 'ENTITY_WORKFLOW_VIEW', 'ENTITY_FIELD_VALIDATION_VIEW',
'ENTITY_ACTION_EXTRA_FIELD_VIEW', 'ENTITY_MOBILE_FIELDS_VIEW', 'ENTITY_MOBILE_SEARCH_FIELDS_VIEW', 'ENTITY_MOBILE_GUIDE_SEARCH_FIELDS_VIEW',
'MOBILE_FIRESTORE_DOCUMENTS', 'PACKAGES',
],
objects: ['ENTITY_STATUS_VIEW'],
},
{
name: 'LOCKUP',
tables: [
'LOCATION', 'LT_AUTHORITY_ROLE', 'LT_JOB_TITLE', 'LT_CAPTIONS_VIEW', 'LT_LANGUAGE', 'LT_VALIDATION', 'LT_Country_VIEW', 'LT_Governorate', 'LT_States',
'LT_City', 'lt_fleet', 'LT_BLACKLIST_TYPE', 'LT_VIOLATIONS_GROUP', 'MENU_STRUCTURE_VIEW', 'INFORMATION_SCHEMA.COLUMNS', 'LT_PUBLIC', 'LT_REASONS',
'LT_FLEET_PLATE_CODES', 'LT_PAYMENT_METHODS', 'LT_CARGO_TYPE', 'LT_SERVICES', 'LT_AFFILIATION_STAKEHOLDERS_VIEW', 'LT_DURATIONS_SETUP',
],
objects: ['LT_PUBLIC', 'LT_REASONS', 'LT_CAPTIONS_VIEW', 'LT_JOB_TITLE', 'LT_Country_VIEW'],
},
{ name: 'SYSTEM_CONFIG', tables: ['SYSTEM_VARIABLES'] },
];
interface Selection {
regions: Set<string>;
tables: Set<string>;
objects: Set<string>;
}
const everything = (): Selection => ({
regions: new Set(REGIONS.map((r) => r.name)),
tables: new Set(REGIONS.flatMap((r) => r.tables.map((k) => `${r.name}/${k}`))),
objects: new Set(REGIONS.flatMap((r) => (r.objects ?? []).map((k) => `${r.name}/${k}`))),
});
const toggle = (set: Set<string>, key: string) => {
const next = new Set(set);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
};
export function CachingPage() {
const { user } = useAuth();
const t = useT();
const ui = useUi();
const notify = useNotify();
const [sel, setSel] = useState<Selection>(everything);
const [confirm, setConfirm] = useState(false);
// the old page was open to anyone who knew its address; here it is for the system administrator role only
const allowed = canUseCaching(user);
const payload = useMemo(() => {
const KEY: Record<string, string[]> = {};
const OBJECT: Record<string, string[]> = {};
for (const r of REGIONS) {
if (!sel.regions.has(r.name)) continue;
KEY[r.name] = r.tables.filter((k) => sel.tables.has(`${r.name}/${k}`));
const objs = (r.objects ?? []).filter((k) => sel.objects.has(`${r.name}/${k}`));
if (objs.length) OBJECT[r.name] = objs;
}
return { KEY, OBJECT };
}, [sel]);
const run = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const url = `${API_BASE}/backend/core/common/cashing.cfc?method=cacheTables&regionsSTR=${encodeURIComponent(JSON.stringify(payload))}`;
const res = await fetch(url, { credentials: 'same-origin' });
if (!res.ok) throw new ApiError(`HTTP ${res.status}`, res.status);
},
onSuccess: () => {
setConfirm(false);
notify.success('SUCCESSFUL.OPERATION', ui('cachingDone'));
},
onError: (e) => {
setConfirm(false);
notify.error(e);
},
});
if (!allowed) return <NotAuthorized />;
const nothing = Object.keys(payload.KEY).length === 0;
return (
<>
<PageHeader title={ui('cachingTitle')} lead={<StorageOutlined sx={{ color: 'primary.main' }} />} />
<Stack spacing={1.5}>
<Alert severity="info">{ui('cachingNote')}</Alert>
{REGIONS.map((r) => (
<Paper key={r.name} variant="outlined" sx={{ p: 2, ...sectionFrame }}>
<SectionTitle view code={r.name}>
<FormControlLabel
sx={{ m: 0 }}
control={<Checkbox size="small" checked={sel.regions.has(r.name)} onChange={() => setSel((s) => ({ ...s, regions: toggle(s.regions, r.name) }))} />}
label={r.name}
/>
</SectionTitle>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: r.objects ? '2fr 1fr' : '1fr' }, opacity: sel.regions.has(r.name) ? 1 : 0.5 }}>
<Box>
<Typography sx={{ fontSize: 13.5, fontWeight: 700, color: 'primary.main', mb: 0.5 }}>{ui('cachingTables')}</Typography>
<Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)' }, columnGap: 2 }}>
{r.tables.map((k) => (
<FormControlLabel
key={k}
control={<Checkbox size="small" checked={sel.tables.has(`${r.name}/${k}`)} onChange={() => setSel((s) => ({ ...s, tables: toggle(s.tables, `${r.name}/${k}`) }))} />}
label={<Typography dir="ltr" sx={{ fontSize: 13.5 }}>{k}</Typography>}
/>
))}
</Box>
</Box>
{r.objects && (
<Box>
<Typography sx={{ fontSize: 13.5, fontWeight: 700, color: 'primary.main', mb: 0.5 }}>{ui('cachingObjects')}</Typography>
{r.objects.map((k) => (
<FormControlLabel
key={k}
sx={{ display: 'flex' }}
control={<Checkbox size="small" checked={sel.objects.has(`${r.name}/${k}`)} onChange={() => setSel((s) => ({ ...s, objects: toggle(s.objects, `${r.name}/${k}`) }))} />}
label={<Typography dir="ltr" sx={{ fontSize: 13.5 }}>{k}</Typography>}
/>
))}
</Box>
)}
</Box>
</Paper>
))}
<Stack direction="row" spacing={1}>
<Button variant="contained" disabled={nothing || run.isPending} onClick={() => setConfirm(true)}>{ui('cachingRun')}</Button>
<Button onClick={() => setSel(everything())}>{ui('cachingAll')}</Button>
<Button onClick={() => setSel({ regions: new Set(), tables: new Set(), objects: new Set() })}>{ui('cachingNone')}</Button>
</Stack>
</Stack>
<Dialog open={confirm} onClose={() => setConfirm(false)}>
<DialogTitle>{ui('cachingRun')}</DialogTitle>
<DialogContent>
<Typography>{ui('cachingConfirm')}</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setConfirm(false)}>{t('NO')}</Button>
<Button variant="contained" disabled={run.isPending} onClick={() => run.mutate()}>{t('YES')}</Button>
</DialogActions>
</Dialog>
</>
);
}

View File

@ -0,0 +1,6 @@
/** Who may rebuild the backend caches: the system administrator role, and the built-in user named "system". */
export const CACHING_ROLES = ['SYSTEM_ADMIN'];
export const CACHING_LOGINS = ['system'];
export const canUseCaching = (user: { role_code?: string; login?: string } | null | undefined) =>
!!user && (CACHING_ROLES.includes(String(user.role_code ?? '')) || CACHING_LOGINS.includes(String(user.login ?? '').trim().toLowerCase()));

View File

@ -14,7 +14,7 @@ import { getExtraFields, getView, runAction, type ExtraSpec, type Option } from
import { fetchRecaptchaSiteKey } from '../../api/session';
import { useRecaptcha } from '../../auth/recaptcha';
import { fromInputDate, resolveFields, toDisplayDate, toInputDate, toPayload, type Mode, type ResolvedField } from './fields';
import { CONFIRM_ENTITIES, CREATE_HIDDEN, EDIT_HIDDEN_FIELDS, aliasSource, EDIT_HIDDEN_SECTIONS, FLEET_ENTITIES, HIDDEN_CREATE_TITLES, NON_OMANI_ONLY, getLayout, type DynamicLookup } from './layouts';
import { CONFIRM_ENTITIES, CREATE_DEFAULTS, CREATE_HIDDEN, CREATE_REQUIRED, EDIT_HIDDEN_FIELDS, aliasSource, 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';
@ -22,6 +22,10 @@ import { deleteAttachment, type PendingFile, type StoredAttachment } from '../..
type Values = Record<string, unknown>;
/** The Riyada card document field per entity, and the section that carries the tick box (the manager's info for a company). */
const RIYADA_DOC: Record<string, string> = { OWNERS: 'OWNER_RIYADAH_CARD_HOLDER_DOC', COMPANIES: 'RIYADAH_CARD_HOLDER_DOC' };
const RIYADA_SECTION: Record<string, string> = { OWNERS: 'OWNERSINFO', COMPANIES: 'MANAGER_INFORMATION' };
const PROFILE_SECTIONS = [
{ title: 'MAININFO', fields: ['NAME', 'EMAIL', 'LOGIN', 'MOBILE', 'AREA_CODE', 'JOB_TITLE', 'LAST_LOGIN_DATE'] },
{ title: 'SETTING', fields: ['LANGUAGE'] },
@ -225,7 +229,7 @@ export function EntityForm({
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 [values, setValues] = useState<Values>(() => ({ ...(id ? {} : CREATE_DEFAULTS[entity]), ...initialValues }));
const [errors, setErrors] = useState<Record<string, string>>({});
const [confirm, setConfirm] = useState(false);
const [pending, setPending] = useState<Record<string, PendingFile>>({});
@ -284,8 +288,10 @@ export function EntityForm({
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';
// the Riyada card tick box (driver-owner and trucking company) is only offered to the operations office, like the old page;
// ticking it makes the card document mandatory
const riyadaDoc = RIYADA_DOC[entity];
const riyadaRole = !!riyadaDoc && 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';
@ -302,15 +308,16 @@ export function EntityForm({
(mode === 'EDIT' && !!EDIT_HIDDEN_FIELDS[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) ||
(!!riyadaDoc && name === riyadaDoc && !riyadaRole) ||
// legacy asks for the POS receipt number only for the POS transaction type (6)
(entity === 'DEPOSITS' && name === 'RECEIPT_ID' && String(values.TRANSACTION_TYPE ?? '').trim() !== '6') ||
// stakeholder users deposit for themselves: the stakeholder picker is not shown to them
(entity === 'DEPOSITS' && mode === 'CREATE' && user?.role_group === 'STAKEHOLDER' && ['STAKEHOLDER_ENTITY_NUMBER', 'STAKEHOLDER_ENTITY_RECORD_NAME', 'STAKEHOLDER_ENTITY_ID'].includes(name));
// fields that become mandatory because of what was chosen
const conditionallyRequired = (name: string) =>
(mode === 'CREATE' && !!CREATE_REQUIRED[entity]?.includes(name)) ||
(!!nonOmaniOnly?.fields.includes(name) && isNonOmani && !(nonOmaniOnly.notRequiredWith && String(values[nonOmaniOnly.notRequiredWith] ?? '').trim() && name !== nonOmaniOnly.attachment)) ||
(name === 'OWNER_RIYADAH_CARD_HOLDER_DOC' && riyadaChecked);
(!!riyadaDoc && name === riyadaDoc && riyadaChecked);
const stakeholderKey = `${values.RELATED_ENTITY_ID ?? ''}_${values.RELATED_ENTITY_RECORD_ID ?? ''}`;
const fillOwner = async () => {
@ -406,7 +413,7 @@ export function EntityForm({
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 (riyadaDoc) 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');
@ -418,7 +425,7 @@ export function EntityForm({
}
notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
void qc.invalidateQueries({ queryKey: ['grid', entity] });
nav(profile ? '/' : `/e/${entity}/grid`);
nav(profile || search.get('own') === '1' ? '/' : `/e/${entity}/grid`);
},
onError: (e) => {
setExtraSpec(null);
@ -561,7 +568,7 @@ export function EntityForm({
),
)}
</Box>
{riyadaRole && sectionIndex === 0 && (
{riyadaRole && s.title === RIYADA_SECTION[entity] && (
<FormControlLabel
sx={{ mt: 1 }}
control={<Checkbox checked={riyadaChecked} onChange={(e) => set('RIYADA_CARD_HOLDER', e.target.checked)} />}
@ -589,6 +596,8 @@ export function EntityForm({
)}
<Stack direction="row" spacing={1}>
{/* a vehicle the role may not change (no UPDATE in its actions for this status) has no save button at all, not a disabled one */}
{!(FLEET_ENTITIES.includes(entity) && !allowed) && (
<Button
type="submit"
variant="contained"
@ -596,7 +605,8 @@ export function EntityForm({
>
{t(action)}
</Button>
{!publicMode && <Button onClick={() => nav(profile ? '/' : `/e/${entity}/grid`)}>{t('BACK')}</Button>}
)}
{!publicMode && search.get('own') !== '1' && <Button onClick={() => nav(profile ? '/' : `/e/${entity}/grid`)}>{t('BACK')}</Button>}
</Stack>
<Dialog open={!!toDelete} onClose={() => setToDelete(null)}>

View File

@ -292,6 +292,7 @@
"MOBILE_NUMBER",
"AREA_CODE",
"PRIMARY_EMAIL",
"RIYADA_CARD_HOLDER",
"NOTES"
]
},

View File

@ -47,10 +47,11 @@ export const layouts: Record<string, EntityLayout> = {
// 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', 'OPERATING_CARD_NO', 'CARD_EXPIRY_DATE', 'NOTES'] },
{ 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', 'CREATED_BY_NAME', 'UPDATED_BY_NAME', 'LAST_UPDATE_DATE_GRID'] },
{ title: 'OWNERINFO', fields: ['RELATED_ENTITY_ID', 'RELATED_ENTITY_RECORD_ID', 'LOCATION_IDS', 'OWNER_NAME', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER', 'NATIONALITY_LICENCE'] },
// legacy column order (three columns read row by row): stakeholder type / industrial area / stakeholder name first, then the vehicle data
{ title: 'TRUCKS_INFO', fields: ['RELATED_ENTITY_ID', 'LOCATION_IDS', 'RELATED_ENTITY_RECORD_ID', 'PLATE_NUMBER', 'FLEET_PLATE_CODE', 'PLATE_CODE_AR', 'USE_DESCRIPTION', 'PLATE_TYPE_CODE', 'TRUCK_TYPE', 'MODEL_YEAR', 'VEHICLE_TYPE', 'COLOR_CODE', 'SUBCOLOR', 'EXTREME_CAPACITY', 'ENGINE_CAPACITY', 'ORIGIN_COUNTRY_CODE', 'AXES_NUMBER', 'MANUFACTURING_YEAR', 'EMPTY_WEIGHT', 'ENGINE_NUMBER', 'CHASSES_NUMBER', 'PASSENGER_NUMBER', 'CREATED_BY_NAME', 'UPDATED_BY_NAME', 'LAST_UPDATE_DATE_GRID'] },
// the owner group is the same as the trailer's
{ title: 'OWNERINFO', fields: ['OWNER_NAME', 'NATIONALITY_CODE', 'GOVERNORATE_CODE', 'STATE_CODE', 'CITY_CODE', 'ADDRESS', 'NATIONALITY_LICENCE', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER'] },
{ title: 'INSURANCEINFO', fields: ['INSURANCE_DOCUMENT_NUMBER', 'INSURANCE_TYPE', 'INSURANCE_COMPANY', 'LICENSE_AUTHORITY', 'FIRST_REGISTRATION_DATE'] },
{ title: 'ADDRESS', fields: ['GOVERNORATE_CODE', 'STATE_CODE', 'CITY_CODE', 'ADDRESS', 'NATIONALITY_CODE'] },
{ 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' },
@ -72,6 +73,11 @@ export const layouts: Record<string, EntityLayout> = {
/** 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'];
/** Values a new record starts with. A new vehicle's document nationality is Oman (the plate-code rule follows it). */
export const CREATE_DEFAULTS: Record<string, Record<string, string>> = Object.fromEntries(
FLEET_ENTITIES.map((e) => [e, { LICENCE_NATIONALITY: 'OMN' }]),
);
/** 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'],
@ -98,6 +104,7 @@ export const CREATE_HIDDEN: Record<string, string[]> = {
],
// a new user: no status yet, and the industrial area and language are not asked on the create page
USERS: ['STATUS_CODE', 'LOCATION_IDS', 'LANGUAGE'],
COMPANIES: ['RIYADA_CARD_HOLDER'],
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'],
};
@ -117,7 +124,14 @@ export const EDIT_HIDDEN_SECTIONS: Record<string, string[]> = {
};
/** Single fields left out of the edit form (and the record page, see VIEW_HIDDEN_FIELDS). */
export const EDIT_HIDDEN_FIELDS: Record<string, string[]> = { USERS: ['LOCATION_IDS'] };
export const EDIT_HIDDEN_FIELDS: Record<string, string[]> = {
USERS: ['LOCATION_IDS'],
// the Riyada card value is a tick box of its own on the company form (operations office only)
COMPANIES: ['RIYADA_CARD_HOLDER'],
};
/** Fields that are mandatory on the create page although the role metadata does not flag them. */
export const CREATE_REQUIRED: Record<string, string[]> = { TICKETS: ['TICKET_TYPE', 'SUBJECT'] };
/** Whole groups the legacy record page does not show (driver info; investor capacity and investor info). */
export const VIEW_HIDDEN_SECTIONS: Record<string, string[]> = {
@ -167,6 +181,8 @@ const SECTION_AFTER: Record<string, [string, string]> = { PERMITS: ['TRUCKS_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'],
// a vehicle's record page does not repeat the owner's identity document in the owner details
...Object.fromEntries(FLEET_ENTITIES.map((e) => [e, ['NATIONALITY_LICENCE', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER']])),
USERS: ['LOCATION_IDS'],
};
export const VIEW_LAST_FIELDS: Record<string, string[]> = { DEPOSITS: ['NOTES'] };

View File

@ -67,6 +67,8 @@ function Value({ field, data, layout }: { field: ResolvedField; data: Data; layo
// 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}</>;
// the Riyada card tick box comes back as 1 / 0: read it as Yes / No
if (field.name === 'RIYADA_CARD_HOLDER') return <>{t(['1', 'YES', 'TRUE'].includes(String(raw ?? '').trim().toUpperCase()) ? 'YES' : 'NO')}</>;
if (empty) return none;
// an affiliation's truck is stored as an id; the page should read as the plate number the user knows

View File

@ -40,6 +40,18 @@ export const UI = {
copy: { en: 'Copy', ar: 'نسخ' },
copied: { en: 'Copied', ar: 'تم النسخ' },
close: { en: 'Close', ar: 'إغلاق' },
cachingTitle: { en: 'System cache', ar: 'ذاكرة النظام المؤقتة' },
cachingNote: {
en: 'Pick the cached regions, tables and objects the system should rebuild from the database. Use it after changing settings, captions, menus or permissions directly in the database.',
ar: 'اختر المناطق والجداول والعناصر المخزنة مؤقتاً التي يجب أن يعيد النظام بناءها من قاعدة البيانات. استخدمها بعد تغيير الإعدادات أو التسميات أو القوائم أو الصلاحيات مباشرة في قاعدة البيانات.',
},
cachingTables: { en: 'Tables inside the region', ar: 'الجداول داخل المنطقة' },
cachingObjects: { en: 'Objects inside the region', ar: 'العناصر داخل المنطقة' },
cachingRun: { en: 'Cache', ar: 'تحديث الذاكرة المؤقتة' },
cachingAll: { en: 'Select all', ar: 'تحديد الكل' },
cachingNone: { en: 'Clear selection', ar: 'إلغاء التحديد' },
cachingConfirm: { en: 'Rebuild the selected cache now? Screens may be slower for a moment.', ar: 'هل تريد إعادة بناء الذاكرة المؤقتة المحددة الآن؟ قد تكون الشاشات أبطأ للحظات.' },
cachingDone: { en: 'The cache was rebuilt', ar: 'تمت إعادة بناء الذاكرة المؤقتة' },
cancel: { en: 'Cancel', ar: 'إلغاء' },
notAvailableYet: { en: 'Not available in the new screen yet', ar: 'غير متاح في الشاشة الجديدة بعد' },
blockedForm: {

View File

@ -10,6 +10,8 @@ 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 { canUseCaching } from '../features/admin/cachingAccess';
import StorageOutlined from '@mui/icons-material/StorageOutlined';
import PersonOutline from '@mui/icons-material/PersonOutlineOutlined';
import BusinessOutlined from '@mui/icons-material/BusinessOutlined';
import LockOutlined from '@mui/icons-material/LockOutlined';
@ -55,7 +57,9 @@ function Crumbs() {
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 own = new URLSearchParams(search);
// the user's own profile and the company profile (?own=1) have no breadcrumb trail
if (own.get('profile') === '1' || own.get('own') === '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;
@ -199,11 +203,17 @@ function Shell() {
</MenuItem>
)}
{companyEntity && (
<MenuItem component={RouterLink} to={`/e/${companyEntity}/create/${user?.encrypted_related_entity_record_id}`} onClick={() => setMenuEl(null)} sx={{ minHeight: 44 }}>
<MenuItem component={RouterLink} to={`/e/${companyEntity}/create/${user?.encrypted_related_entity_record_id}?own=1`} onClick={() => setMenuEl(null)} sx={{ minHeight: 44 }}>
<ListItemIcon><BusinessOutlined fontSize="small" /></ListItemIcon>
{ui('companyProfile')}
</MenuItem>
)}
{canUseCaching(user) && (
<MenuItem component={RouterLink} to="/caching" onClick={() => setMenuEl(null)} sx={{ minHeight: 44 }}>
<ListItemIcon><StorageOutlined fontSize="small" /></ListItemIcon>
{ui('cachingTitle')}
</MenuItem>
)}
{can('CHANGE_PASSWORD') && (
<MenuItem
sx={{ minHeight: 44 }}

View File

@ -34,7 +34,7 @@ const GROUPS: Record<string, GroupMeta> = {
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' },
PERSONNEL: { en: 'Registry', ar: 'السجلات', icon: AppRegistrationOutlined, color: '#8d6e63' },
SUBSCRIPTIONS: { en: 'Subscriptions & permits', ar: 'الاشتراكات والتصاريح', icon: CardMembershipOutlined, color: '#6a3fa0' },
};

View File

@ -1,5 +1,5 @@
import { useState, type FormEvent } from 'react';
import { Link as RouterLink, Navigate, useParams } from 'react-router-dom';
import { Link as RouterLink, Navigate, useLocation, useParams } from 'react-router-dom';
import {
Alert, Box, Button, Checkbox, CircularProgress, Divider, FormControlLabel, IconButton,
InputAdornment, Paper, Stack, TextField, Tooltip, Typography,
@ -31,6 +31,7 @@ export function LoginPage() {
const [u, setU] = useState('');
const [p, setP] = useState('');
const [remember, setRemember] = useState(false);
const location = useLocation();
const [showPassword, setShowPassword] = useState(false);
const [err, setErr] = useState('');
const [touched, setTouched] = useState(false);
@ -46,7 +47,9 @@ export function LoginPage() {
return false;
}
});
if (user) return <Navigate to="/" replace />;
// after signing in, go to the page that was asked for before the login page (an in-app path only)
const asked = (location.state as { from?: string } | null)?.from;
if (user) return <Navigate to={asked && /^\/(?!\/)/.test(asked) ? asked : '/'} 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) =>