From e631b3c12bb245da6b067bf67ad05bdfcd2e40cb Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Thu, 12 Nov 2026 11:17:45 +0300 Subject: [PATCH] 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 --- src/App.tsx | 13 +- src/features/EntityRoute.tsx | 5 +- src/features/HomeLauncher.tsx | 5 +- src/features/admin/CachingPage.tsx | 179 ++++++++++++++++++++++ src/features/admin/cachingAccess.ts | 6 + src/features/forms/EntityForm.tsx | 44 ++++-- src/features/forms/generated-layouts.json | 1 + src/features/forms/layouts.ts | 24 ++- src/features/view/EntityView.tsx | 2 + src/i18n/ui.ts | 12 ++ src/layout/AppShell.tsx | 14 +- src/layout/nav.ts | 2 +- src/pages.tsx | 7 +- 13 files changed, 282 insertions(+), 32 deletions(-) create mode 100644 src/features/admin/CachingPage.tsx create mode 100644 src/features/admin/cachingAccess.ts diff --git a/src/App.tsx b/src/App.tsx index 9774353..56a5b0c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 ; +} + export function App() { const { user, ready } = useAuth(); if (!ready) return ; @@ -21,10 +29,11 @@ export function App() { } /> } /> } /> - : }> + : }> } /> } /> } /> + } /> } /> diff --git a/src/features/EntityRoute.tsx b/src/features/EntityRoute.tsx index 49d0eaf..515692b 100644 --- a/src/features/EntityRoute.tsx +++ b/src/features/EntityRoute.tsx @@ -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 ( @@ -275,7 +275,8 @@ export function EntityRoute({ entity, view, id }: { entity: string; view: string const profile = entity === 'USERS' && !!id && params.get('profile') === '1'; return ( <> - + {/* the company profile (opened from the user menu with ?own=1) has no back button */} + }> diff --git a/src/features/HomeLauncher.tsx b/src/features/HomeLauncher.tsx index 674d686..25e9a2e 100644 --- a/src/features/HomeLauncher.tsx +++ b/src/features/HomeLauncher.tsx @@ -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 }}> - + {/* the section's own colour, the same soft badge the menu uses */} + {title(s)} diff --git a/src/features/admin/CachingPage.tsx b/src/features/admin/CachingPage.tsx new file mode 100644 index 0000000..6f1ba99 --- /dev/null +++ b/src/features/admin/CachingPage.tsx @@ -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®ionsSTR={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; + tables: Set; + objects: Set; +} + +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, 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(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 = {}; + const OBJECT: Record = {}; + 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®ionsSTR=${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 ; + + const nothing = Object.keys(payload.KEY).length === 0; + + return ( + <> + } /> + + {ui('cachingNote')} + {REGIONS.map((r) => ( + + + setSel((s) => ({ ...s, regions: toggle(s.regions, r.name) }))} />} + label={r.name} + /> + + + + {ui('cachingTables')} + + {r.tables.map((k) => ( + setSel((s) => ({ ...s, tables: toggle(s.tables, `${r.name}/${k}`) }))} />} + label={{k}} + /> + ))} + + + {r.objects && ( + + {ui('cachingObjects')} + {r.objects.map((k) => ( + setSel((s) => ({ ...s, objects: toggle(s.objects, `${r.name}/${k}`) }))} />} + label={{k}} + /> + ))} + + )} + + + ))} + + + + + + + + setConfirm(false)}> + {ui('cachingRun')} + + {ui('cachingConfirm')} + + + + + + + + ); +} diff --git a/src/features/admin/cachingAccess.ts b/src/features/admin/cachingAccess.ts new file mode 100644 index 0000000..2b23130 --- /dev/null +++ b/src/features/admin/cachingAccess.ts @@ -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())); diff --git a/src/features/forms/EntityForm.tsx b/src/features/forms/EntityForm.tsx index 68d8e8d..b67ad86 100644 --- a/src/features/forms/EntityForm.tsx +++ b/src/features/forms/EntityForm.tsx @@ -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; +/** 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 = { OWNERS: 'OWNER_RIYADAH_CARD_HOLDER_DOC', COMPANIES: 'RIYADAH_CARD_HOLDER_DOC' }; +const RIYADA_SECTION: Record = { 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(() => initialValues ?? {}); + const [values, setValues] = useState(() => ({ ...(id ? {} : CREATE_DEFAULTS[entity]), ...initialValues })); const [errors, setErrors] = useState>({}); const [confirm, setConfirm] = useState(false); const [pending, setPending] = useState>({}); @@ -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) => { 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({ ), )} - {riyadaRole && sectionIndex === 0 && ( + {riyadaRole && s.title === RIYADA_SECTION[entity] && ( set('RIYADA_CARD_HOLDER', e.target.checked)} />} @@ -589,14 +596,17 @@ export function EntityForm({ )} - - {!publicMode && } + {/* 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) && ( + + )} + {!publicMode && search.get('own') !== '1' && } setToDelete(null)}> diff --git a/src/features/forms/generated-layouts.json b/src/features/forms/generated-layouts.json index 40a8ce5..e8913ab 100644 --- a/src/features/forms/generated-layouts.json +++ b/src/features/forms/generated-layouts.json @@ -292,6 +292,7 @@ "MOBILE_NUMBER", "AREA_CODE", "PRIMARY_EMAIL", + "RIYADA_CARD_HOLDER", "NOTES" ] }, diff --git a/src/features/forms/layouts.ts b/src/features/forms/layouts.ts index 3698724..1fe8893 100644 --- a/src/features/forms/layouts.ts +++ b/src/features/forms/layouts.ts @@ -47,10 +47,11 @@ export const layouts: Record = { // 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 = { /** 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> = 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 = { TROUBLE_SHOOTING: ['TS_NUMBER', 'GATE_ID', 'CREATION_DATE', 'PERMIT_NUMBER', 'PERMIT_STATUS_CODE'], @@ -98,6 +104,7 @@ export const CREATE_HIDDEN: Record = { ], // 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 = { }; /** Single fields left out of the edit form (and the record page, see VIEW_HIDDEN_FIELDS). */ -export const EDIT_HIDDEN_FIELDS: Record = { USERS: ['LOCATION_IDS'] }; +export const EDIT_HIDDEN_FIELDS: Record = { + 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 = { 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 = { @@ -167,6 +181,8 @@ const SECTION_AFTER: Record = { PERMITS: ['TRUCKS_INFO /** Fields the record page does not show, and fields it puts last in their group. */ export const VIEW_HIDDEN_FIELDS: Record = { 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 = { DEPOSITS: ['NOTES'] }; diff --git a/src/features/view/EntityView.tsx b/src/features/view/EntityView.tsx index c249c76..eb53ac8 100644 --- a/src/features/view/EntityView.tsx +++ b/src/features/view/EntityView.tsx @@ -67,6 +67,8 @@ function Value({ field, data, layout }: { field: ResolvedField; data: Data; layo // plate codes come as _AR / _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 diff --git a/src/i18n/ui.ts b/src/i18n/ui.ts index d08e1e3..7c95f03 100644 --- a/src/i18n/ui.ts +++ b/src/i18n/ui.ts @@ -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: { diff --git a/src/layout/AppShell.tsx b/src/layout/AppShell.tsx index d0f2aa3..4715b0b 100644 --- a/src/layout/AppShell.tsx +++ b/src/layout/AppShell.tsx @@ -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() { )} {companyEntity && ( - setMenuEl(null)} sx={{ minHeight: 44 }}> + setMenuEl(null)} sx={{ minHeight: 44 }}> {ui('companyProfile')} )} + {canUseCaching(user) && ( + setMenuEl(null)} sx={{ minHeight: 44 }}> + + {ui('cachingTitle')} + + )} {can('CHANGE_PASSWORD') && ( = { 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' }, }; diff --git a/src/pages.tsx b/src/pages.tsx index c227374..1d9830b 100644 --- a/src/pages.tsx +++ b/src/pages.tsx @@ -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 ; + // 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 ; // 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) =>