diff --git a/src/api/client.ts b/src/api/client.ts index 1953c25..1bfabdc 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -54,7 +54,13 @@ export function parseBackendJson(raw: string): T { let value: unknown = JSON.parse(text); if (typeof value === 'string') { text = clean(value); - value = JSON.parse(text); + // some answers are just a word inside the JSON string (the receipt check says "VALID" or "RECEIPT_NUMBER_…"): + // keep it as the text it is when it is not JSON itself + try { + value = JSON.parse(text); + } catch { + value = text; + } } return value as T; } @@ -67,6 +73,12 @@ export interface Envelope { [k: string]: unknown; } +/** Called once when the backend says the session has ended (code 405 / SESSION_ENDED); the auth provider signs the user out of the app. */ +let sessionEndedHandler: (() => void) | undefined; +export const onSessionEnded = (fn: (() => void) | undefined) => { + sessionEndedHandler = fn; +}; + export async function rpc( entity: string, method: string, @@ -90,7 +102,10 @@ export async function rpc( 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 === 405 || env.CODE === 405 || env.MESSAGE === 'SESSION_ENDED' || env.MESSAGECODE === 'SESSION_ENDED') { + sessionEndedHandler?.(); + throw new ApiError('SESSION_ENDED', 405); + } if (env.code === 470) throw new ApiError('ACCESS_DENIED', 470); } return data; diff --git a/src/api/packages.ts b/src/api/packages.ts index 163b9ee..09ab36e 100644 --- a/src/api/packages.ts +++ b/src/api/packages.ts @@ -8,7 +8,7 @@ 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 }[]; + lines: { kind: 'info' | 'duration' | 'price' | 'text' | 'hint'; text: string }[]; /** arguments of the button's click handler, e.g. getServiceSubscriptions('MT0003','ACCESS',title,'FLEET') */ args: string[]; } @@ -28,9 +28,11 @@ function parseColumn(html: unknown): PackageCard[] { 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) => { + // the description / duration / price lines, plus the coloured ("pink") hint paragraphs some services carry (container hints) + const lines = [...card.querySelectorAll('p.card-text, p.pink')].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() ?? '' }; + const kind = p.classList.contains('pink') ? 'hint' : KIND.find(([c]) => icon.includes(c))?.[1] ?? 'text'; + return { kind, text: p.textContent?.replace(/\s+/g, ' ').trim() ?? '' }; }); return { id: card.id.replace(/_card$|_serviceCard$/, ''), @@ -184,7 +186,10 @@ export interface CreateResult { /** The request the old wizard's "Pay" button sends. */ export async function createSubscription(p: SubscriptionRequest) { - const r = await rpc('subscriptions', 'CREATE', p as unknown as Record, { post: true }); + // the old request layer sent every array argument as a comma list ("A,B"), and the backend reads the group codes as a + // list (listLen): a real array makes it fail with "…cannot be converted to a simple value" + const args: Record = { ...p, packageGroupCode: Array.isArray(p.packageGroupCode) ? p.packageGroupCode.join(',') : p.packageGroupCode }; + const r = await rpc('subscriptions', 'CREATE', args, { 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; diff --git a/src/auth/AuthContext.tsx b/src/auth/AuthContext.tsx index 6a03a2a..db6f6d1 100644 --- a/src/auth/AuthContext.tsx +++ b/src/auth/AuthContext.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'; -import { rpc } from '../api/client'; +import { onSessionEnded, 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'; @@ -88,6 +88,22 @@ export function AuthProvider({ children }: { children: ReactNode }) { document.documentElement.dir = lang === 'AR' || lang === 'URD' ? 'rtl' : 'ltr'; }, [lang]); + // the backend ended the session (timeout, signed in elsewhere, server restart): leave the app and go to the login page, + // exactly like a sign-out. Nothing happens when nobody is signed in (public sign-up pages, the login page itself). + useEffect(() => { + onSessionEnded(() => { + if (!qc.getQueryData(['session'])) return; + try { + sessionStorage.setItem('mams.sessionEnded', '1'); + } catch { + /* storage can be blocked */ + } + qc.setQueryData(['session'], null); + qc.removeQueries({ predicate: (q) => q.queryKey[0] !== 'session' }); + }); + return () => onSessionEnded(undefined); + }, [qc]); + const signIn = async (u: string, p: string, rememberMe = false) => { await apiLogin(u, p, LANG_IDS[lang] ?? 1, rememberMe); await qc.invalidateQueries({ queryKey: ['session'] }); diff --git a/src/components/EntityGrid.tsx b/src/components/EntityGrid.tsx index f3f2982..51b6605 100644 --- a/src/components/EntityGrid.tsx +++ b/src/components/EntityGrid.tsx @@ -16,6 +16,7 @@ import { isRtl, useLabel, useT, useUi } from '../i18n'; import { roleLabel } from '../i18n/roles'; import { useMutation } from '@tanstack/react-query'; import { useNotify } from '../notify/NotifyProvider'; +import { NewPasswordDialog, findNewPassword, isPasswordReset } from './NewPasswordDialog'; import { WithdrawDialog } from '../features/gridActions/WithdrawDialog'; import { CONFIRM_ROW_ACTIONS, DIALOG_ROW_ACTIONS, parseRowActions, runRowAction, type RowAction } from '../api/gridActions'; import { StatusChip } from './StatusChip'; @@ -30,11 +31,31 @@ function GridLoading({ text }: { text: string }) { return () => clearTimeout(h); }, []); return ( - + - {text} - {slow && {ui('gridLoadingSlow')}} + {text} + {slow && {ui('gridLoadingSlow')}} ); @@ -74,11 +95,13 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, const [menu, setMenu] = useState<{ el: HTMLElement; actions: RowAction[] } | null>(null); const [confirmAction, setConfirmAction] = useState(null); const [withdrawId, setWithdrawId] = useState(null); + const [newPassword, setNewPassword] = useState(null); const doAction = useMutation({ meta: { loading: 'processing' }, mutationFn: (a: RowAction) => runRowAction(entity, a, filter), - onSuccess: (msg) => { - notify.success(msg, ui('saved')); + onSuccess: (msg, a) => { + if (isPasswordReset(a.name) && findNewPassword(msg)) setNewPassword(msg); + else notify.success(msg, ui('saved')); void data.refetch(); }, onError: (e) => notify.error(e), @@ -161,7 +184,6 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, 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) => { @@ -172,6 +194,9 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, } onSelectedChange?.(next); }} + slotProps={{ + input: { 'aria-label': ui('selectAll') } + }} /> )} @@ -216,7 +241,6 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, e.stopPropagation()}> { const next = { ...selected }; @@ -224,6 +248,9 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, else delete next[rowId(r)]; onSelectedChange?.(next); }} + slotProps={{ + input: { 'aria-label': ui('selectRow') } + }} /> )} @@ -255,7 +282,13 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, {!loading && !list.length && ( - + {ui('noResults')} @@ -294,6 +327,7 @@ export function EntityGrid({ entity, filter, canEdit, onTotal, onFilterRequired, ))} {withdrawId && setWithdrawId(null)} onDone={() => { setWithdrawId(null); void data.refetch(); }} />} + setNewPassword(null)} /> setConfirmAction(null)}> {confirmAction?.label || t(confirmAction?.name ?? '')} {t('CONFIRM_MSG')} diff --git a/src/components/GlobalLoading.tsx b/src/components/GlobalLoading.tsx index fc90157..b41a6a4 100644 --- a/src/components/GlobalLoading.tsx +++ b/src/components/GlobalLoading.tsx @@ -37,10 +37,16 @@ export function GlobalLoading() { {bar && t.zIndex.tooltip + 2 }} />} t.zIndex.modal + 10, bgcolor: 'rgba(8, 16, 28, 0.45)', backdropFilter: 'blur(2px)' }}> - + - {ui(pending[0] ?? 'processing')} - {slow ? ui('stillWorking') : ui('pleaseWait')} + {ui(pending[0] ?? 'processing')} + {slow ? ui('stillWorking') : ui('pleaseWait')} diff --git a/src/components/LoadingScreen.tsx b/src/components/LoadingScreen.tsx index 2c94035..94b8851 100644 --- a/src/components/LoadingScreen.tsx +++ b/src/components/LoadingScreen.tsx @@ -13,12 +13,26 @@ export function LoadingScreen() { }, []); return ( - + - {ui('loadingWorkspace')} - + {ui('loadingWorkspace')} + {ui('firstLoad')} diff --git a/src/components/NewPasswordDialog.tsx b/src/components/NewPasswordDialog.tsx new file mode 100644 index 0000000..714b296 --- /dev/null +++ b/src/components/NewPasswordDialog.tsx @@ -0,0 +1,66 @@ +import { useState } from 'react'; +import { Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip, Typography } from '@mui/material'; +import ContentCopyOutlined from '@mui/icons-material/ContentCopyOutlined'; +import CheckOutlined from '@mui/icons-material/CheckOutlined'; +import { useT, useUi } from '../i18n'; + +/** The "reset password immediately" action answers with the new password inside its message (the generated one: "p" + 6 digits). */ +export const isPasswordReset = (action: string) => action === 'RESET_PASSWORD_IMMEDIATELY'; +export const findNewPassword = (message: string) => message.match(/\bp\d{6}\b/)?.[0]; + +export function NewPasswordDialog({ message, onClose }: { message: string | null; onClose: () => void }) { + const t = useT(); + const ui = useUi(); + const [copied, setCopied] = useState(false); + const password = message ? findNewPassword(message) : undefined; + + const copy = async () => { + if (!password) return; + try { + await navigator.clipboard.writeText(password); + } catch { + // clipboard blocked (plain http): fall back to selecting a hidden text box + const el = document.createElement('textarea'); + el.value = password; + document.body.appendChild(el); + el.select(); + document.execCommand('copy'); + el.remove(); + } + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + + return ( + + {t('SUCCESSFUL.OPERATION')} + + {message ? t(message) : ''} + {password && ( + + {password} + + void copy()} aria-label={ui('copy')}> + {copied ? : } + + + + )} + + + + + + ); +} diff --git a/src/components/PageHeader.tsx b/src/components/PageHeader.tsx index 1800763..c60f938 100644 --- a/src/components/PageHeader.tsx +++ b/src/components/PageHeader.tsx @@ -33,17 +33,41 @@ export function PageHeader({ backTo?: string; }) { return ( - - + + {backTo && } {lead} {/* the page's one h1: a screen reader's outline starts from it */} - {title} - {subtitle && {subtitle}} + {title} + {subtitle && {subtitle}} - {actions && {actions}} + {actions && {actions}} ); } diff --git a/src/components/sectionIcons.tsx b/src/components/sectionIcons.tsx index 139864a..c52b49a 100644 --- a/src/components/sectionIcons.tsx +++ b/src/components/sectionIcons.tsx @@ -1,7 +1,7 @@ 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 PersonOutline from '@mui/icons-material/PersonOutlineOutlined'; import BadgeOutlined from '@mui/icons-material/BadgeOutlined'; import AttachFileOutlined from '@mui/icons-material/AttachFileOutlined'; import VerifiedUserOutlined from '@mui/icons-material/VerifiedUserOutlined'; @@ -9,7 +9,7 @@ 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 WorkOutline from '@mui/icons-material/WorkOutlineOutlined'; import ForumOutlined from '@mui/icons-material/ForumOutlined'; import ReceiptLongOutlined from '@mui/icons-material/ReceiptLongOutlined'; import BusinessOutlined from '@mui/icons-material/BusinessOutlined'; diff --git a/src/features/EntityRoute.tsx b/src/features/EntityRoute.tsx index d71d12a..49d0eaf 100644 --- a/src/features/EntityRoute.tsx +++ b/src/features/EntityRoute.tsx @@ -167,7 +167,6 @@ function GridPage({ entity, extraDefaults }: { entity: string; extraDefaults?: R <> {can('GETREPORT') && } @@ -187,7 +186,12 @@ function GridPage({ entity, extraDefaults }: { entity: string; extraDefaults?: R /> setParams(filterToParams(f), { replace: true })} /> {totalBalance !== undefined && ( - + {t('TOTAL_BALANCE')} : {totalBalance.toFixed(3)} {t('RO')} )} @@ -223,10 +227,19 @@ function NotAuthorized() { const ui = useUi(); return ( - + - {ui('notAuthorizedTitle')} - {ui('notAuthorizedText')} + {ui('notAuthorizedTitle')} + {ui('notAuthorizedText')} diff --git a/src/features/HomeLauncher.tsx b/src/features/HomeLauncher.tsx index ded8716..674d686 100644 --- a/src/features/HomeLauncher.tsx +++ b/src/features/HomeLauncher.tsx @@ -1,6 +1,6 @@ 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 AddCircleOutline from '@mui/icons-material/AddCircleOutlineOutlined'; import { newRecordSx } from '../components/newRecordSx'; import { useAuth } from '../auth/AuthContext'; import { useNav } from '../layout/NavContext'; @@ -17,20 +17,47 @@ export function HomeLauncher() { return ( <> {user?.name} - {roleLabel(String(user?.job_title ?? user?.role_code ?? ''), t, humanize, isRtl(lang))} + {roleLabel(String(user?.job_title ?? user?.role_code ?? ''), t, humanize, isRtl(lang))} {sections.map((s) => { const Icon = s.icon; return ( - + - {title(s)} + {title(s)} {s.items.map((i) => ( - - + + {labelOf(i.entity)} {/* the same "+" the menu shows beside a module that can create records */} diff --git a/src/features/dashboard/DashboardPage.tsx b/src/features/dashboard/DashboardPage.tsx index 0318737..10f9a46 100644 --- a/src/features/dashboard/DashboardPage.tsx +++ b/src/features/dashboard/DashboardPage.tsx @@ -91,8 +91,21 @@ function Tiles({ items }: { items: Item[] }) { - {fmt(i.value)} - {i.label} + {fmt(i.value)} + {i.label} ); @@ -120,7 +133,14 @@ function Pie({ items }: { items: Item[] }) { : theme.palette.action.hover; return ( - + - {fmt(items.reduce((a, i) => a + i.value, 0))} - {ui('total')} + {fmt(items.reduce((a, i) => a + i.value, 0))} + {ui('total')} {stops.map((s) => ( - + {s.label} - {fmt(s.value)} - + {fmt(s.value)} + {Math.round((s.value / total) * 100)}% @@ -157,9 +194,16 @@ function Bars({ items }: { items: Item[] }) { {items.map((i) => ( - + {i.label} - {fmt(i.value)} + {fmt(i.value)} @@ -188,19 +232,32 @@ function Stacked({ items }: { items: Item[] }) { const max = Math.max(1, ...items.map((i) => i.value)); return ( - + {keys.map((k) => ( - + - {labels.get(k)} + {labels.get(k)} ))} {items.map((i) => ( - + {i.label} - {fmt(i.value)} + {fmt(i.value)} {i.segments?.filter((s) => s.value > 0).map((s) => ( @@ -223,13 +280,24 @@ function BlockCard({ block }: { block: Block }) { const tint = blockIcon(block.key); return ( - + {tint && ( )} - {block.title} + {block.title} {body} @@ -287,7 +355,14 @@ export function DashboardPage() { <> {page.locations && estates.length > 0 && ( - + setLocation(0)} /> {estates.map((e) => ( setLocation(Number(e.CODE))} /> @@ -295,7 +370,14 @@ export function DashboardPage() { )} {model.nats.length > 0 && ( - + {model.nats.map((n) => ( setNat(n)} /> ))} diff --git a/src/features/dashboard/icons.tsx b/src/features/dashboard/icons.tsx index b20a173..7bc4ecd 100644 --- a/src/features/dashboard/icons.tsx +++ b/src/features/dashboard/icons.tsx @@ -11,7 +11,7 @@ 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 CheckCircleOutline from '@mui/icons-material/CheckCircleOutlineOutlined'; import ScheduleOutlined from '@mui/icons-material/ScheduleOutlined'; import ErrorOutlineOutlined from '@mui/icons-material/ErrorOutlineOutlined'; import UndoOutlined from '@mui/icons-material/UndoOutlined'; @@ -20,7 +20,7 @@ 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 WorkOutline from '@mui/icons-material/WorkOutlineOutlined'; import DashboardOutlined from '@mui/icons-material/DashboardOutlined'; import CategoryOutlined from '@mui/icons-material/CategoryOutlined'; diff --git a/src/features/forms/AttachmentField.tsx b/src/features/forms/AttachmentField.tsx index f0a8935..e80bc6a 100644 --- a/src/features/forms/AttachmentField.tsx +++ b/src/features/forms/AttachmentField.tsx @@ -70,13 +70,24 @@ export function AttachmentField(props: { bgcolor: over ? 'action.selected' : 'action.hover', }} > - + {label} {required ? ' *' : ''} {shown && ( - + {isImage(shown) && !broken ? ( + {pending.name} onPending(undefined)} aria-label={t('DELETE')}> diff --git a/src/features/forms/EntityForm.tsx b/src/features/forms/EntityForm.tsx index 90ba185..68d8e8d 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 { CREATE_HIDDEN, EDIT_HIDDEN_SECTIONS, FLEET_ENTITIES, HIDDEN_CREATE_TITLES, NON_OMANI_ONLY, getLayout, type DynamicLookup } from './layouts'; +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 { AttachmentField } from './AttachmentField'; import { DateField } from '../../components/DateField'; import { ExtraFieldsDialog } from './ExtraFieldsDialog'; @@ -141,15 +141,17 @@ function FieldInput(props: { error={!!error} helperText={error ?? (unavailable ? ui('notAvailableYet') : undefined)} slotProps={{ + ...p.slotProps, + input: { - ...p.InputProps, + ...p.slotProps.input, endAdornment: ( <> {dyn.isFetching && } - {p.InputProps.endAdornment} + {p.slotProps.input.endAdornment} ), - }, + } }} /> )} @@ -239,9 +241,9 @@ export function EntityForm({ useEffect(() => { if (!view.data) return; const d = view.data.data; - const aliased = Object.fromEntries(Object.entries(layout?.alias ?? {}).map(([f, src]) => [f, d[src]])); + const aliased = Object.fromEntries(Object.entries(layout?.alias ?? {}).map(([f, src]) => [f, d[aliasSource(src, lang)]])); setValues({ ...d, ...aliased }); - }, [view.data, layout]); + }, [view.data, layout, lang]); const status = view.data ? String(view.data.data.STATUS_CODE ?? '').trim() : undefined; const fieldNames = useMemo(() => layout?.sections.flatMap((s) => s.fields) ?? [], [layout]); @@ -297,9 +299,14 @@ export function EntityForm({ plateHidden(name) || (ownerToggle && (name === 'IS_OWNER' || (isOwner && OWNER_DOC.includes(name)))) || (mode === 'CREATE' && !!CREATE_HIDDEN[entity]?.includes(name)) || + (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); + (entity === 'OWNERS' && name === 'OWNER_RIYADAH_CARD_HOLDER_DOC' && !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) => (!!nonOmaniOnly?.fields.includes(name) && isNonOmani && !(nonOmaniOnly.notRequiredWith && String(values[nonOmaniOnly.notRequiredWith] ?? '').trim() && name !== nonOmaniOnly.attachment)) || @@ -361,8 +368,16 @@ export function EntityForm({ setErrors((e) => ({ ...e, [name]: '' })); }; + // legacy: non-Nafith users confirm the data is correct before saving (role 45 is ticked for them and not shown) + const confirmBox = !publicMode && !profile && CONFIRM_ENTITIES.includes(entity) && !!user && user.role_group !== 'NAFITH' && String(user.role_id ?? '') !== '45'; + const [confirmed, setConfirmed] = useState(false); + const validate = () => { const errs: Record = {}; + if (confirmBox && !confirmed) { + notify.error(new ApiError('MUST_CONFIRM')); + return false; + } 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'); @@ -559,6 +574,10 @@ export function EntityForm({ {blocked && {ui('blockedForm')}} + {confirmBox && ( + setConfirmed(e.target.checked)} />} label={t('AGREE_NOTE')} /> + )} + {publicMode && ( diff --git a/src/features/forms/generated-layouts.json b/src/features/forms/generated-layouts.json index 4face03..40a8ce5 100644 --- a/src/features/forms/generated-layouts.json +++ b/src/features/forms/generated-layouts.json @@ -214,7 +214,10 @@ "CHASSES_NUMBER", "PASSENGER_NUMBER", "AXES_NUMBER", - "ENGINE_NUMBER" + "ENGINE_NUMBER", + "CREATED_BY_NAME", + "UPDATED_BY_NAME", + "LAST_UPDATE_DATE_GRID" ] }, { @@ -343,7 +346,6 @@ "STAKEHOLDER_ENTITY_NUMBER", "STAKEHOLDER_ENTITY_RECORD_NAME", "STAKEHOLDER_ENTITY_ID", - "NOTES", "DEPOSIT_REQUEST_NUMBER", "VOUCHER_NUMBER", "TRANSACTION_TYPE", @@ -351,7 +353,8 @@ "DEPOSIT_AMOUNT", "DEPOSIT_DATE", "REFERENCE_NUMBER", - "RECEIPT_ID" + "RECEIPT_ID", + "NOTES" ] }, { @@ -417,7 +420,10 @@ "USE_DESCRIPTION", "MODEL_YEAR", "EXTREME_CAPACITY", - "AXES_NUMBER" + "AXES_NUMBER", + "CREATED_BY_NAME", + "UPDATED_BY_NAME", + "LAST_UPDATE_DATE_GRID" ] }, { @@ -502,7 +508,6 @@ "RECEIVER_RELATED_ENTITY_ID", "LOCATION_IDS", "RECEIVER_RELATED_ENTITY_RECORD_ID", - "NOTES", "DRIVER_NATIONALITY_CODE", "OMANI_DRIVER_GRID", "DRIVER_NAME", @@ -519,7 +524,8 @@ "NUMBER_OF_FLEET", "TRAILER_PLATE_NUMBER", "TRAILER_PLATE_CODE", - "TRAILER_PLATE_CODE_AR" + "TRAILER_PLATE_CODE_AR", + "NOTES" ] }, { @@ -1336,7 +1342,10 @@ "PASSENGER_NUMBER", "AXES_NUMBER", "CHASSES_NUMBER", - "ENGINE_NUMBER" + "ENGINE_NUMBER", + "CREATED_BY_NAME", + "UPDATED_BY_NAME", + "LAST_UPDATE_DATE_GRID" ] }, { diff --git a/src/features/forms/layouts.ts b/src/features/forms/layouts.ts index a370407..3698724 100644 --- a/src/features/forms/layouts.ts +++ b/src/features/forms/layouts.ts @@ -46,11 +46,11 @@ export const layouts: Record = { // 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: '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'] }, - { title: 'INSURANCEINFO', fields: ['INSURANCE_DOCUMENT_NUMBER', 'INSURANCE_TYPE', 'INSURANCE_COMPANY'] }, - { title: 'ADDRESS', fields: ['GOVERNORATE_CODE', 'STATE_CODE', 'CITY_CODE', 'ADDRESS', 'NATIONALITY_CODE', 'NOTES'] }, + { 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' }, @@ -89,11 +89,35 @@ export const CREATE_HIDDEN: Record = { 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) + // a new entry permit request is the "stakeholder" shape: the driver and vehicle-plate fields and the driver / truck + // licence attachments belong to the mobile-app shape and the legacy create page hides them + FLEET_REQUEST: [ + 'OMANI_DRIVER_GRID', 'DRIVER_NAME', 'DRIVER_MOBILE_NUMBER', 'DRIVER_AREA_CODE', 'DRIVER_CN', 'LOCAL_VEHICLE_GRID', 'TRAILER_TYPE', + 'PLATE_NUMBER', 'FLEET_PLATE_CODE', 'PLATE_CODE_AR', 'TRAILER_PLATE_NUMBER', 'TRAILER_PLATE_CODE', 'TRAILER_PLATE_CODE_AR', + 'DRIVER_ID_FRONT', 'DRIVER_ID_BACK', 'TRUCK_LICENSE_FRONT', 'TRUCK_LICENSE_BACK', + ], + // 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'], 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'], }; +/** Legacy pages that carry the "I confirm the data is correct" tick box for every user outside Nafith. */ +export const CONFIRM_ENTITIES = [ + 'DEPOSITS', 'BUSES', 'CARS', 'COMPANIES', 'EQUIPMENTS', 'FAMILY_MEMBERS', 'FREEZONE_CLEARING_COMPANIES', 'FREEZONE_DEPOSITORS', 'INVESTORS', + 'INVOICES', 'MFZ_PERMITS', 'NOTIFICATION_LOG', 'OTHER_STAKEHOLDERS', 'OWNERS', 'PARKING_YARD', 'PERMITS', 'PERSONNEL', 'RENTED_TRUCK', + 'RFID_TAGS', 'TRAILERS', 'TRUCKS', 'VIOLATIONS', 'VISITORS_PERMITS', 'AVAILABLE_ON_PLATFORM', 'AVAILABLE_ON_PLATFORM_SEARCH', +]; + /** Groups left out of the edit form (the record keeps its values; nothing in them is asked again). */ -export const EDIT_HIDDEN_SECTIONS: Record = { COMPANIES: ['COMPANIES_INFO'] }; +export const EDIT_HIDDEN_SECTIONS: Record = { + COMPANIES: ['COMPANIES_INFO'], + OWNERS: ['OWNERS_INFO'], + // employees: the driver-licence group and the backend-required "Employee info" extras are not shown + PERSONNEL: ['LICENSEINFO', 'PERSONNEL_INFO'], +}; + +/** 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'] }; /** Whole groups the legacy record page does not show (driver info; investor capacity and investor info). */ export const VIEW_HIDDEN_SECTIONS: Record = { @@ -102,6 +126,7 @@ export const VIEW_HIDDEN_SECTIONS: Record = { OTHER_STAKEHOLDERS: ['OTHER_STAKEHOLDERS_INFO'], FREEZONE_DEPOSITORS: ['FREEZONE_DEPOSITORS_INFO'], COMPANIES: ['COMPANIES_INFO'], + PERSONNEL: ['LICENSEINFO', 'PERSONNEL_INFO'], // the reply box is a popup here; the answers are listed in their own table TICKETS: ['ADD_REPLY'], }; @@ -115,6 +140,13 @@ export const NON_OMANI_ONLY: Record = { BLACKLISTS: 'BLACKLISTSINFO' }; +/** + * The value a form field takes from the record when the backend names it differently (see `alias`). The backend returns + * language pairs (PLATE_CODE_EN / PLATE_CODE_AR) and the option lists carry the code in the session language, so the + * pair member of the session language is the one that matches an option. + */ +export const aliasSource = (src: string, lang: string) => (lang.toUpperCase() === 'AR' && src.endsWith('_EN') ? `${src.slice(0, -3)}_AR` : src); + export const hasLayout =(entity: string) => entity in layouts; // --------------------------------------------------------------------------------------------- @@ -133,7 +165,10 @@ const ENTITY_ALIAS: Record> = { POS_TRANSACTIONS: const SECTION_AFTER: Record = { 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 = { DEPOSITS: ['RECEIPT_ID'] }; +export const VIEW_HIDDEN_FIELDS: Record = { + DEPOSITS: ['RECEIPT_ID'], + USERS: ['LOCATION_IDS'], +}; export const VIEW_LAST_FIELDS: Record = { DEPOSITS: ['NOTES'] }; /** Heading of the group that holds an entity's extra backend-required fields, when "_INFO" would read wrongly. */ diff --git a/src/features/gridActions/PendingPayDialog.tsx b/src/features/gridActions/PendingPayDialog.tsx index fe33f1d..26404e1 100644 --- a/src/features/gridActions/PendingPayDialog.tsx +++ b/src/features/gridActions/PendingPayDialog.tsx @@ -110,7 +110,11 @@ export function PendingPayDialog({ id, data, onClose, onDone }: { id: string; da !pay.isPending && onClose()} maxWidth="md"> {t('PAY_OFF_DEBIT_BALANCE')} - {t('ORDER_SUMMARY')} + {t('ORDER_SUMMARY')} {nafith && ( { setWithNafith(e.target.checked); setMethod(''); }} />} @@ -127,12 +131,22 @@ export function PendingPayDialog({ id, data, onClose, onDone }: { id: string; da - {t('PAYMENT_METHOD')} + {t('PAYMENT_METHOD')} setMethod(e.target.value)}> {methods.map((m) => ( } label={m.NAME} /> - {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} + {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} {m.ID === POS_PAYMENT && method === String(POS_PAYMENT) && ( setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} /> )} diff --git a/src/features/gridActions/ReconciliationUpload.tsx b/src/features/gridActions/ReconciliationUpload.tsx index b20e3cf..814541f 100644 --- a/src/features/gridActions/ReconciliationUpload.tsx +++ b/src/features/gridActions/ReconciliationUpload.tsx @@ -113,7 +113,9 @@ export function ReconciliationUpload({ entity, onClose, onDone }: { entity: 'REC sx={{ border: 2, borderStyle: 'dashed', borderColor: touched && !file ? 'error.main' : 'divider', borderRadius: 2, p: 3, textAlign: 'center', cursor: 'pointer' }} > - {file ? file.name : t('MUST_UPLOAD_FILE')} + {file ? file.name : t('MUST_UPLOAD_FILE')} {fileError && {fileError}} {upload.error && {failText(upload.error as Error)}} diff --git a/src/features/gridActions/RenewSubscriptionDialog.tsx b/src/features/gridActions/RenewSubscriptionDialog.tsx index 4e0bee7..aec26ed 100644 --- a/src/features/gridActions/RenewSubscriptionDialog.tsx +++ b/src/features/gridActions/RenewSubscriptionDialog.tsx @@ -106,7 +106,11 @@ export function RenewSubscriptionDialog({ params, onClose, onDone }: { params: R !renew.isPending && onClose()} maxWidth="md"> {t('RENEW_SUBSCRIPTION')} - {t('ORDER_SUMMARY')} + {t('ORDER_SUMMARY')} {summary.isPending && } {summary.error && {t((summary.error as Error).message)}} {s && ( @@ -116,12 +120,22 @@ export function RenewSubscriptionDialog({ params, onClose, onDone }: { params: R dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(s.SUBSCRIPTIONDETAILSCARD ?? '') }} /> - {t('PAYMENT_METHOD')} + {t('PAYMENT_METHOD')} setMethod(e.target.value)}> {methods.map((m) => ( } label={m.NAME} /> - {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} + {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} {m.ID === POS_PAYMENT && method === String(POS_PAYMENT) && ( setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} /> )} diff --git a/src/features/gridActions/WithdrawDialog.tsx b/src/features/gridActions/WithdrawDialog.tsx index 6152146..9647a7e 100644 --- a/src/features/gridActions/WithdrawDialog.tsx +++ b/src/features/gridActions/WithdrawDialog.tsx @@ -45,21 +45,31 @@ export function WithdrawDialog({ id, onClose, onDone }: { id: string; onClose: ( {balance.error && {t((balance.error as Error).message)}}
- {lab('RELATED_ENTITY_RECORD_ID')} - {balance.data?.NAME ?? '…'} + {lab('RELATED_ENTITY_RECORD_ID')} + {balance.data?.NAME ?? '…'}
- {lab('AVAILABLE_BALANCE')} - {balance.data ? `${available.toFixed(3)} ${t('RO')}` : '…'} + {lab('AVAILABLE_BALANCE')} + {balance.data ? `${available.toFixed(3)} ${t('RO')}` : '…'}
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 + slotProps={{ + htmlInput: { inputMode: 'decimal' } + }} /> setType(e.target.value)} fullWidth> {t('CASH')} diff --git a/src/features/register/OtpDialog.tsx b/src/features/register/OtpDialog.tsx index 164a743..c62ece9 100644 --- a/src/features/register/OtpDialog.tsx +++ b/src/features/register/OtpDialog.tsx @@ -161,7 +161,9 @@ export function OtpDialog({ ) : ( <> - {ui('otpCodeHint')} + {ui('otpCodeHint')} - + {!done && ( nav('/register')} - sx={{ border: 0, bgcolor: 'transparent', cursor: 'pointer', color: 'primary.main', font: 'inherit' }} - > + sx={{ + alignItems: "center", + border: 0, + bgcolor: 'transparent', + cursor: 'pointer', + color: 'primary.main', + font: 'inherit' + }}> - {ui('back')} + {ui('back')} )} @@ -52,13 +65,29 @@ export function RegisterEntityPage() { {done ? ( - {ui('registerSuccessTitle')} - {ui('registerSuccessBody')} + {ui('registerSuccessTitle')} + {ui('registerSuccessBody')} ) : ( <> - {t(entity)} + {t(entity)} {registerReady ? ( setDone(true)} /> ) : ( - + - {ui('registerLoading')} + {ui('registerLoading')} )} diff --git a/src/features/register/RegisterHub.tsx b/src/features/register/RegisterHub.tsx index b321e57..e902760 100644 --- a/src/features/register/RegisterHub.tsx +++ b/src/features/register/RegisterHub.tsx @@ -5,7 +5,7 @@ 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 PersonOutline from '@mui/icons-material/PersonOutlineOutlined'; import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined'; import { useAuth } from '../../auth/AuthContext'; import { useT, useUi } from '../../i18n'; @@ -41,18 +41,46 @@ export function RegisterHub() { return ( - + - nav('/login')} - sx={{ border: 0, bgcolor: 'transparent', cursor: 'pointer', color: 'primary.main', font: 'inherit' }} - > + nav('/login')} + sx={{ + alignItems: "center", + border: 0, + bgcolor: 'transparent', + cursor: 'pointer', + color: 'primary.main', + font: 'inherit' + }}> - {ui('backToLogin')} + {ui('backToLogin')} - {ui('registerHubTitle')} - {ui('registerHubSubtitle')} + {ui('registerHubTitle')} + {ui('registerHubSubtitle')} {CARDS.map(({ entity, icon: Icon, desc, otp }) => ( @@ -60,8 +88,14 @@ export function RegisterHub() { pick(entity, otp)} sx={{ height: '100%', p: 0.5 }}> - {t(entity)} - {ui(desc)} + {t(entity)} + {ui(desc)} diff --git a/src/features/search/SearchPanel.tsx b/src/features/search/SearchPanel.tsx index b465b70..2b35dca 100644 --- a/src/features/search/SearchPanel.tsx +++ b/src/features/search/SearchPanel.tsx @@ -62,9 +62,18 @@ export function SearchPanel({ entity, fields, filter, onChange }: { entity: stri return ( - + {status?.options && ( - + onChange(setKey(filter, status.id, ''))} /> {status.options.map((o) => { const on = filter[status.id] === String(o.CODE); @@ -78,8 +87,15 @@ export function SearchPanel({ entity, fields, filter, onChange }: { entity: stri const v = filter[f.id] ?? ''; const [a, b] = rangeParts(v); return ( - - {t(f.caption)} + + {t(f.caption)} onChange(setKey(filter, f.id, toRange(fromInput(iso), b)))} @@ -102,7 +118,14 @@ export function SearchPanel({ entity, fields, filter, onChange }: { entity: stri {activeAdvanced.length > 0 && ( - + {activeAdvanced.map((f) => ( onChange(setWithChildren(filter, f.id, ''))} /> ))} @@ -111,7 +134,13 @@ export function SearchPanel({ entity, fields, filter, onChange }: { entity: stri )} setOpen(false)} slotProps={{ paper: { sx: { width: { xs: '100%', sm: 400 }, p: 3 } } }}> - + {ui('filters')} setOpen(false)}> @@ -135,7 +164,12 @@ export function SearchPanel({ entity, fields, filter, onChange }: { entity: stri const [a, b] = rangeParts(v); return ( - {t(f.caption)} + {t(f.caption)} set(toRange(fromInput(iso), b))} fullWidth /> set(toRange(a, fromInput(iso)))} fullWidth /> diff --git a/src/features/search/dependent.ts b/src/features/search/dependent.ts index 78974f6..81376f2 100644 --- a/src/features/search/dependent.ts +++ b/src/features/search/dependent.ts @@ -14,7 +14,9 @@ interface Dependent { const STAKEHOLDER_NAMES: Record = { '7': 'INVESTORS', '10': 'OWNERS', '11': 'COMPANIES', '12': 'OTHER_STAKEHOLDERS' }; -const fleetClass = (fleetType: string) => getOptions('getFleetSubscriptionClass', { fleetType }); +const stakeholders = (id: string) => + STAKEHOLDER_NAMES[id] ? getOptions('getStakeHoldersList', { STAKEHOLDER_ID: id, STAKEHOLDER_NAME: STAKEHOLDER_NAMES[id] }) : Promise.resolve([]); +const fleetClass =(fleetType: string) => getOptions('getFleetSubscriptionClass', { fleetType }); const fleetUsage = (fleetType: string) => getOptions('getFleetSubscriptionUsage', { fleetType }); export const DEPENDENT_SEARCH: Record> = { @@ -27,6 +29,11 @@ export const DEPENDENT_SEARCH: Record> = { FLEET_SUBSCRIPTION_CLASS: { parent: 'FLEET_SUBSCRIPTION_TYPE', load: fleetClass }, USAGE_TYPE: { parent: 'FLEET_SUBSCRIPTION_TYPE', load: fleetUsage }, }, + // entry permit requests: the sender / receiver names are those of the chosen sender / receiver type + FLEET_REQUEST: { + SENDER_RELATED_ENTITY_RECORD_ID: { parent: 'SENDER_RELATED_ENTITY_ID', load: (id) => stakeholders(id) }, + RECEIVER_RELATED_ENTITY_RECORD_ID: { parent: 'RECEIVER_RELATED_ENTITY_ID', load: (id) => stakeholders(id) }, + }, PERMITS: { FLEET_CATEGORY: { parent: 'FLEET_ENTITY_NAME', load: fleetClass }, INDUSTRIAL_ESTATE_STAKEHOLDER_ID: { parent: 'INDUSTRIAL_ESTATE_ID', load: (locationId) => getOptions('getInvestorsInLocation', { locationId }) }, diff --git a/src/features/search/filters.ts b/src/features/search/filters.ts index b33066e..f8a2203 100644 --- a/src/features/search/filters.ts +++ b/src/features/search/filters.ts @@ -29,9 +29,20 @@ interface Row { DDL_VALUES?: Option[]; } +/** Filters only some roles get: entry permit requests offer the sender / receiver pickers to the shift supervisor and the operations office. */ +const ROLE_ONLY_FILTERS: Record = { + FLEET_REQUEST: { + roles: ['SHIFT_SUPERVISOR', 'OPOFF'], + ids: ['SENDER_RELATED_ENTITY_ID', 'SENDER_RELATED_ENTITY_RECORD_ID', 'RECEIVER_RELATED_ENTITY_ID', 'RECEIVER_RELATED_ENTITY_RECORD_ID'], + }, +}; + export function useSearchFields(config: AppConfig | undefined, entity: string): SearchField[] { - const { lang } = useAuth(); + const { lang, user } = useAuth(); + const roleCode = user?.role_code; return useMemo(() => { + const only = ROLE_ONLY_FILTERS[entity]; + const hidden = only && !only.roles.includes(roleCode ?? '') ? only.ids : []; // 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( @@ -39,7 +50,7 @@ export function useSearchFields(config: AppConfig | undefined, entity: string): ); // 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) => ({ + return rows.filter((r) => r.HTML_ID !== duplicate && !hidden.includes(r.HTML_ID)).map((r) => ({ id: r.HTML_ID, type: r.FIELD_TYPE, caption: r.CAPTION_CODE, @@ -49,7 +60,7 @@ export function useSearchFields(config: AppConfig | undefined, entity: string): advanced: true, defaultValue: r.DEFAULT_VALUE || undefined, })); - }, [config, entity, lang]); + }, [config, entity, lang, roleCode]); } export type Filter = Record; diff --git a/src/features/subscriptions/OneTripTrucks.tsx b/src/features/subscriptions/OneTripTrucks.tsx index 2e2d7a6..b18a346 100644 --- a/src/features/subscriptions/OneTripTrucks.tsx +++ b/src/features/subscriptions/OneTripTrucks.tsx @@ -4,7 +4,7 @@ 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 DeleteOutline from '@mui/icons-material/DeleteOutlineOutlined'; import EditOutlined from '@mui/icons-material/EditOutlined'; import { useAuth } from '../../auth/AuthContext'; import { useNotify } from '../../notify/NotifyProvider'; @@ -118,6 +118,8 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, const [stakeholder, setStakeholder] = useState(''); const [approvalLocked, setApprovalLocked] = useState(false); const [driverFilesRequired, setDriverFilesRequired] = useState(false); + // set only when the backend's driver check found the driver registered; until then the driver documents can be attached + const [driverRegistered, setDriverRegistered] = useState(false); const [gatePassRequired, setGatePassRequired] = useState(false); const [matching, setMatching] = useState(false); const [busy, setBusy] = useState(false); @@ -264,7 +266,10 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, { ...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 (r.RESULTCODE === 'FAILED') { + setDriverRegistered(false); + return notify.error(new Error(first.response_error_codes ?? 'ACTION_FAILED')); + } if (first.DRIVER_NAME !== undefined) { setForm((cur) => ({ ...cur, @@ -274,7 +279,11 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, areaCode: first.DRIVER_MOBILE_AREA_CODE ?? cur.areaCode, })); setDriverFilesRequired(false); - } else setDriverFilesRequired(true); + setDriverRegistered(true); + } else { + setDriverFilesRequired(true); + setDriverRegistered(false); + } } catch (e) { notify.error(e); } @@ -291,6 +300,7 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, setErrors({}); setMatching(false); setDriverFilesRequired(false); + setDriverRegistered(false); }; const fail = (msg: string, tabIndex?: number) => { @@ -439,7 +449,11 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, return ( - {lab('ONE_TRIP_PERMIT_ADD_HINT')} + {lab('ONE_TRIP_PERMIT_ADD_HINT')} setTab(v)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}> @@ -530,21 +544,36 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, {tab === 2 && ( - {driverFilesRequired + {!driverRegistered ? DRIVER_ATT.map((f) => att(f, DRIVER_ATT_CAPTION[f])) - : {ui('wizNoDriverFiles')}} + : {ui('wizNoDriverFiles')}} {gatePassRequired && att(GATE_PASS, packageCode === 'ISD0001' ? 'GATE_PASS_WAYBILL' : 'ATTACHMENT')} )} - + - {lab('ADDED_VEHICLES')} ({entries.length}{maxTrucks ? ` / ${maxTrucks}` : ''}) + {lab('ADDED_VEHICLES')} ({entries.length}{maxTrucks ? ` / ${maxTrucks}` : ''}) @@ -555,7 +584,9 @@ export function OneTripTrucks({ packageCode, subscriptionCode, packageGroupType, {entries.length === 0 && ( - {lab('NO_INFO')} + {lab('NO_INFO')} )} {entries.map((e) => ( diff --git a/src/features/subscriptions/SubscriptionWizard.tsx b/src/features/subscriptions/SubscriptionWizard.tsx index afed9af..f760ae1 100644 --- a/src/features/subscriptions/SubscriptionWizard.tsx +++ b/src/features/subscriptions/SubscriptionWizard.tsx @@ -30,14 +30,40 @@ function Cards({ cards, action, onPick }: { cards: PackageCard[]; action: string {cards.map((c) => ( - {c.title} + {c.title} {c.lines.map((l, i) => { + // the legacy cards print service hints in the accent colour ("pink"), without an icon + if (l.kind === 'hint') return ( + {l.text} + ); const Icon = ICON[l.kind]; return ( - + - {l.text} + {l.text} ); })} @@ -61,7 +87,13 @@ function Picker({ items, selected, onChange }: { items: Selectable[]; selected: const toggle = (v: string) => onChange(chosen.has(v) ? selected.filter((x) => x !== v) : [...selected, v]); return ( - + setQ(e.target.value)} sx={{ flex: 1 }} /> @@ -74,7 +106,13 @@ function Picker({ items, selected, onChange }: { items: Selectable[]; selected: ))} - {filtered.length > 200 && {ui('wizRefine')} ({filtered.length})} + {filtered.length > 200 && {ui('wizRefine')} ({filtered.length})} ); @@ -268,7 +306,13 @@ export function SubscriptionWizard() { ]; const current = [groups, packages, services, subs][step]; const empty = (cards?: PackageCard[]) => - cards && !cards.length && {t('NO_AVAILABLE_SERVICES')}; + cards && !cards.length && {t('NO_AVAILABLE_SERVICES')}; const reset = (to: number) => { if (to <= 1) setPkg(null); @@ -311,7 +355,15 @@ export function SubscriptionWizard() { ))} {(group || pkg || service) && step < 4 && ( - + {[group, pkg, service].filter(Boolean).map((p) => )} )} @@ -372,17 +424,38 @@ export function SubscriptionWizard() { {step >= 4 && sub && ( - {ui('wizSummary')} + {ui('wizSummary')} - {[group, pkg, service].filter(Boolean).map((p) => {p!.title})} - {sub.title} - {sub.lines.map((l, i) => {l.text})} + {[group, pkg, service].filter(Boolean).map((p) => {p!.title})} + {sub.title} + {sub.lines.map((l, i) => {l.text})} {estateValue && !unowned && !oneTrip && ( - + {ui('wizEstate')}: {t(estates.find((e) => String(e.CODE) === estateValue)?.CAPTION_CODE ?? estateValue)} )} - {ui('wizPrice')}: {sub.price + sub.platformPrice} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')} + {ui('wizPrice')}: {sub.price + sub.platformPrice} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')} )} @@ -430,21 +503,46 @@ export function SubscriptionWizard() { {step === 5 && sub && ( - - {ui('wizCount')}{count} + + {ui('wizCount')}{count} - {cap('TOTAL_PRICE', 'Total price', 'السعر الإجمالي')} + {cap('TOTAL_PRICE', 'Total price', 'السعر الإجمالي')} {total} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')} - {cap('PAYMENT_METHOD', 'Payment method', 'طريقة الدفع')} + {cap('PAYMENT_METHOD', 'Payment method', 'طريقة الدفع')} {methods.isPending && } setMethod(e.target.value)}> {(methods.data ?? []).map((m) => ( } label={m.NAME} /> - {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} + {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} {m.ID === 6 && method === '6' && ( setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} /> )} @@ -471,7 +569,9 @@ export function SubscriptionWizard() { {cap('PAY', 'Pay', 'دفع')} {sub?.title} - {ui('wizCount')}: {count} · {total} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')} + {ui('wizCount')}: {count} · {total} {t('RO') !== 'RO' ? t('RO') : ui('wizOmr')} {t('CONFIRM_MSG')} diff --git a/src/features/view/EntityEvents.tsx b/src/features/view/EntityEvents.tsx new file mode 100644 index 0000000..b6ef0e7 --- /dev/null +++ b/src/features/view/EntityEvents.tsx @@ -0,0 +1,199 @@ +import { useMemo, useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { + Alert, Box, Button, CircularProgress, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, MenuItem, Paper, Stack, Table, TableBody, + TableCell, TableHead, TablePagination, TableRow, TextField, Tooltip, +} from '@mui/material'; +import ExpandMore from '@mui/icons-material/ExpandMore'; +import OpenInNewOutlined from '@mui/icons-material/OpenInNewOutlined'; +import HistoryOutlined from '@mui/icons-material/HistoryOutlined'; +import { rpc, type Envelope } from '../../api/client'; +import { useAuth } from '../../auth/AuthContext'; +import { useLabel, useT, useUi } from '../../i18n'; +import { sectionFrame } from '../../components/SectionTitle'; + +/** + * The old record pages ended with a collapsed "Events" card: who did what to the record and when, with a popup that + * compares the old and the new values. It loads only when it is opened. + */ +const ROWS = 5; + +interface Filters { action: string; login: string; from: string; to: string } +const EMPTY: Filters = { action: '', login: '', from: '', to: '' }; + +/** yyyy-mm-dd (date box) -> yyyymmdd (what the backend's "from-to" date range compares) */ +const yyyymmdd = (d: string) => d.replace(/-/g, ''); + +type Row = [id: string, action: string, user: string, date: string, details: string]; + +/** The details icon carries the old / new data as base64 JSON inside its click handler; read it, never run it. */ +function parseDetails(html: string): { oldData: Record; newData: Record } | null { + const b64 = html.match(/"logModal",\s*0,\s*\\?"([A-Za-z0-9+/=]+)\\?"/)?.[1]; + if (!b64) return null; + try { + const bin = atob(b64); + const text = new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))); + const outer = JSON.parse(text.replace(/^\/\//, '')) as { OLD?: string; NEW?: string }; + const inner = (s?: string) => (s ? (JSON.parse(s.replace(/^\/\//, '')) as Record) : {}); + return { oldData: inner(outer.OLD), newData: inner(outer.NEW) }; + } catch { + return null; + } +} + +export function EntityEvents({ entity, id }: { entity: string; id: string }) { + const { config } = useAuth(); + const t = useT(); + const ui = useUi(); + const lab = useLabel(); + const [open, setOpen] = useState(false); + const [draft, setDraft] = useState(EMPTY); + const [applied, setApplied] = useState(EMPTY); + const [page, setPage] = useState(0); + const [detail, setDetail] = useState<{ oldData: Record; newData: Record } | null>(null); + + const allowed = !!config?.AUTHORITY.some((a) => a.ENTITY_NAME === entity && a.ACTION_NAME === 'GETLOG'); + const actions = useMemo( + () => ((config?.LOG_ACTION_LIST as { ENTITY_NAME: string; ACTION_CODE: string; CAPTION_CODE: string }[] | undefined) ?? []).filter((a) => a.ENTITY_NAME === entity), + [config, entity], + ); + + const events = useQuery({ + queryKey: ['events', entity, id, applied, page], + enabled: open && allowed, + queryFn: async () => { + const r = await rpc & { RECORDS?: number }>(entity, 'GETLOG', { + data: { + ENTITY_ID: id, + ACTION_CODE: applied.action, + LOGIN: applied.login, + ...(applied.from && applied.to ? { CREATION_DATE: `${yyyymmdd(applied.from)}-${yyyymmdd(applied.to)}` } : {}), + }, + page: page + 1, + rows: ROWS, + }); + return { rows: (r.DATA ?? []) as Row[], records: Number(r.RECORDS ?? 0), total: Number(r.TOTAL ?? 0) }; + }, + }); + + if (!allowed) return null; + + const search = () => { setPage(0); setApplied(draft); }; + const reset = () => { setPage(0); setDraft(EMPTY); setApplied(EMPTY); }; + const rows = events.data?.rows ?? []; + const count = events.data?.records ?? 0; + + return ( + + setOpen((o) => !o)} + aria-expanded={open} + sx={{ + all: 'unset', boxSizing: 'border-box', width: '100%', display: 'flex', alignItems: 'center', gap: 1, cursor: 'pointer', + fontSize: 15, fontWeight: 800, color: 'text.primary', pb: open ? 0.75 : 0, borderBottom: open ? 1 : 0, borderColor: 'divider', + }} + > + + {t('EVENT_TABLE')} + + + + + + setDraft({ ...draft, action: e.target.value })} sx={{ minWidth: 200 }}> + --- + {actions.map((a) => {t(a.CAPTION_CODE)})} + + setDraft({ ...draft, login: e.target.value })} /> + setDraft({ ...draft, from: e.target.value })} slotProps={{ inputLabel: { shrink: true } }} /> + setDraft({ ...draft, to: e.target.value })} slotProps={{ inputLabel: { shrink: true } }} /> + + + + + {events.isPending && } + {events.error && {t((events.error as Error).message)}} + {events.data && ( + +
+ + + {t('ACTION_CODE')} + {t('USERNAME')} + {t('CREATION_DATE')} + + + + + {rows.length === 0 && {t('NO_INFO')}} + {rows.map((r) => { + const d = parseDetails(String(r[4] ?? '')); + return ( + + {r[1]} + {r[2]} + {r[3]} + + {d && Object.keys(d.newData).length + Object.keys(d.oldData).length > 0 && ( + + setDetail(d)} aria-label={t('EVENTS_DETAILS')}> + + )} + + + ); + })} + +
+ `${from}–${to}`} + onPageChange={(_, p) => setPage(p)} + /> +
+ )} + + + setDetail(null)} fullWidth maxWidth="md"> + {t('EVENTS_DETAILS')} + + + + + + {t('INFO_TYPE')} + {t('OLD_DATA')} + {t('NEW_DATA')} + + + + {detail && Object.entries(detail.newData).map(([k, v]) => ( + + {lab(k)} + {detail.oldData[k] === undefined ? '' : String(detail.oldData[k])} + {String(v)} + + ))} + +
+
+
+ + + +
+
+ ); +} diff --git a/src/features/view/EntityView.tsx b/src/features/view/EntityView.tsx index e65b495..c249c76 100644 --- a/src/features/view/EntityView.tsx +++ b/src/features/view/EntityView.tsx @@ -15,7 +15,7 @@ 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 { aliasSource, 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'; @@ -26,6 +26,8 @@ import { actionNeedsEmail, isDangerous, isSimpleAction } from './actions'; import { FLEET_REQUEST_ORDER, fleetRequestView } from './fleetRequest'; import { PendingPayDialog } from '../gridActions/PendingPayDialog'; import { InvoiceSummary } from './InvoiceSummary'; +import { EntityEvents } from './EntityEvents'; +import { NewPasswordDialog, findNewPassword, isPasswordReset } from '../../components/NewPasswordDialog'; import { RenewSubscriptionDialog } from '../gridActions/RenewSubscriptionDialog'; type Data = Record; @@ -35,7 +37,7 @@ function Value({ field, data, layout }: { field: ResolvedField; data: Data; layo const { lang } = useAuth(); const t = useT(); const ui = useUi(); - const raw = data[layout.alias?.[field.name] ?? field.name]; + const raw = data[aliasSource(layout.alias?.[field.name] ?? field.name, lang)]; const dynamic = layout.dynamic?.[field.name]; const textKey = layout.viewText?.[field.name]; const humanize = useLabel(); @@ -48,7 +50,9 @@ function Value({ field, data, layout }: { field: ResolvedField; data: Data; layo }); const empty = raw === undefined || raw === null || String(raw).trim() === '' || (Array.isArray(raw) && !raw.length); - const none = —; + const none = —; if (textKey && String(data[textKey] ?? '').trim()) return <>{String(data[textKey])}; const forced = (data.__TEXT as Record | undefined)?.[field.name]; if (forced) return <>{forced}; @@ -132,14 +136,17 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { ); const byName = useMemo(() => new Map(fields.map((f) => [f.name, f])), [fields]); + const [newPassword, setNewPassword] = useState(null); const run = useMutation({ meta: { loading: 'processing' }, mutationFn: async (v: { a: EntityAction; reason?: Record }) => { - const values = { ...data, ...Object.fromEntries(Object.entries(layout?.alias ?? {}).map(([f, src]) => [f, data[src]])) }; + const values = { ...data, ...Object.fromEntries(Object.entries(layout?.alias ?? {}).map(([f, src]) => [f, data[aliasSource(src, lang)]])) }; return runAction(entity, v.a.ACTION_NAME, toPayload(fields, values), id, [], v.reason); }, - onSuccess: (res) => { - notify.success(String(res.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved')); + onSuccess: (res, v) => { + // the new password is shown in a box with a copy button, not in a toast that disappears + if (isPasswordReset(v.a.ACTION_NAME) && findNewPassword(String(res.MESSAGE ?? ''))) setNewPassword(String(res.MESSAGE)); + else 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)); @@ -255,10 +262,23 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { // font (a plate badge where the entity is a vehicle), and the status beside it title={t(entity)} subtitle={ - + {header.lead} {header.title && header.title !== t(entity) && ( - {header.title} + {header.title} )} {header.status && } {header.subtitle && header.subtitle !== t(entity) && {header.subtitle}} @@ -327,8 +347,19 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { {shown.map((f) => ( - {lab(f.caption)} - + {lab(f.caption)} + ))} @@ -459,6 +490,8 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { )} + + setAction(null)}> {t(String(action?.ACTION_CAPTION_CODE ?? action?.ACTION_NAME ?? ''))} @@ -537,6 +570,8 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { /> )} + setNewPassword(null)} /> + {extra && ( - {caption} - - {value} {unit} + {caption} + + {value} {unit}
); @@ -62,7 +80,12 @@ export function InvoiceSummary({ id, data }: { id: string; data: Record - {ui('invoiceSummary')} + {ui('invoiceSummary')} @@ -74,7 +97,12 @@ export function InvoiceSummary({ id, data }: { id: string; data: Record} {lines.error && {t((lines.error as Error).message)}} - {lines.data && !rows.length && {t('NO_INFO')}} + {lines.data && !rows.length && {t('NO_INFO')}} {rows.length > 0 && ( @@ -134,7 +162,9 @@ function TransactionsDialog({ invoiceId, row, title, unit, onClose }: { invoiceI {list.isPending && } {list.error && {t((list.error as Error).message)}} - {list.data && !data.length && {t('NO_INFO')}} + {list.data && !data.length && {t('NO_INFO')}} {data.length > 0 && (
diff --git a/src/features/view/SubscriptionDetails.tsx b/src/features/view/SubscriptionDetails.tsx index 127ace0..35eea21 100644 --- a/src/features/view/SubscriptionDetails.tsx +++ b/src/features/view/SubscriptionDetails.tsx @@ -27,9 +27,23 @@ function Item({ caption, children }: { caption: string; children: React.ReactNod const empty = children === undefined || children === null || children === ''; return ( - {caption} - - {empty ? — : children} + {caption} + + {empty ? — : children} ); diff --git a/src/i18n/ui.ts b/src/i18n/ui.ts index c6193a5..d08e1e3 100644 --- a/src/i18n/ui.ts +++ b/src/i18n/ui.ts @@ -22,6 +22,7 @@ export const UI = { darkMode: { en: 'Dark mode', ar: 'الوضع الداكن' }, lightMode: { en: 'Light mode', ar: 'الوضع الفاتح' }, noFile: { en: 'No file', ar: 'لا يوجد ملف' }, + sessionEnded: { en: 'Your session has ended. Please sign in again.', 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).' }, @@ -36,6 +37,9 @@ export const UI = { 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: 'تم الحفظ بنجاح' }, + copy: { en: 'Copy', ar: 'نسخ' }, + copied: { en: 'Copied', ar: 'تم النسخ' }, + close: { en: 'Close', 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 45bccc2..d0f2aa3 100644 --- a/src/layout/AppShell.tsx +++ b/src/layout/AppShell.tsx @@ -10,7 +10,7 @@ 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 PersonOutline from '@mui/icons-material/PersonOutlineOutlined'; import BusinessOutlined from '@mui/icons-material/BusinessOutlined'; import LockOutlined from '@mui/icons-material/LockOutlined'; import NavigateNext from '@mui/icons-material/NavigateNext'; @@ -36,9 +36,19 @@ function Crumbs() { const section = sectionOf(key); return ( } sx={{ '& .MuiBreadcrumbs-li': { fontSize: 13.5 } }}> - {ui('home')} - {section && {title(section)}} - {labelOf(key)} + {ui('home')} + {section && {title(section)}} + {labelOf(key)} ); } @@ -51,14 +61,30 @@ function Crumbs() { const leaf = view === 'view' ? ui('view') : view === 'create' ? (id ? ui('edit') : ui('new')) : null; return ( } sx={{ '& .MuiBreadcrumbs-li': { fontSize: 13.5 } }}> - {ui('home')} - {section && {title(section)}} + {ui('home')} + {section && {title(section)}} {leaf ? ( - {labelOf(entity)} + {labelOf(entity)} ) : ( - {labelOf(entity)} + {labelOf(entity)} )} - {leaf && {leaf}} + {leaf && {leaf}} ); } @@ -158,8 +184,12 @@ function Shell() { setMenuEl(null)} slotProps={{ paper: { sx: { minWidth: 220 } } }}> - {user?.name} - {roleLabel(String(user?.job_title ?? user?.role_code ?? ''), t, humanize, isRtl(lang))} + {user?.name} + {roleLabel(String(user?.job_title ?? user?.role_code ?? ''), t, humanize, isRtl(lang))} {can('GETVIEW') && user && ( diff --git a/src/layout/CommandPalette.tsx b/src/layout/CommandPalette.tsx index 96d9fd6..5f9bd26 100644 --- a/src/layout/CommandPalette.tsx +++ b/src/layout/CommandPalette.tsx @@ -3,7 +3,7 @@ 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 AddCircleOutline from '@mui/icons-material/AddCircleOutlineOutlined'; import { newRecordSx } from '../components/newRecordSx'; import { useNav } from './NavContext'; @@ -72,7 +72,11 @@ export function CommandPalette({ open, onClose }: { open: boolean; onClose: () = )} ))} - {!results.length && {ui('noResults')}} + {!results.length && {ui('noResults')}} ); diff --git a/src/layout/NavContext.tsx b/src/layout/NavContext.tsx index ee6f2f6..ce64cbd 100644 --- a/src/layout/NavContext.tsx +++ b/src/layout/NavContext.tsx @@ -26,7 +26,16 @@ export function NavProvider({ children }: { children: ReactNode }) { 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; + // the entry permit requests screen is the last item of the Permits group + const permits = menu.find((s) => s.items.some((i) => i.entity === 'PERMITS')); + const entry = extra?.items.find((i) => i.entity === 'FLEET_REQUEST'); + if (permits && extra && entry) { + permits.rows.push({ item: entry }); + permits.items.push(entry); + extra.rows = extra.rows.filter((r) => !('item' in r) || r.item !== entry); + extra.items = extra.items.filter((i) => i !== entry); + } + const all = extra?.items.length ? [...menu, extra] : menu; return dash ? [dash, ...all] : all; }, [config, user, rtl]); const value = useMemo( diff --git a/src/layout/Sidebar.tsx b/src/layout/Sidebar.tsx index 1a324a1..542058d 100644 --- a/src/layout/Sidebar.tsx +++ b/src/layout/Sidebar.tsx @@ -8,7 +8,7 @@ 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 AddCircleOutline from '@mui/icons-material/AddCircleOutlineOutlined'; import { newRecordSx } from '../components/newRecordSx'; import { useUi } from '../i18n'; import { useNav } from './NavContext'; @@ -47,8 +47,8 @@ export function Sidebar({ collapsed, onToggle, onNavigate }: { collapsed: boolea {i > 0 && } + letterSpacing: '.04em' + }}> {headingTitle(r.heading)} @@ -93,7 +92,7 @@ export function Sidebar({ collapsed, onToggle, onNavigate }: { collapsed: boolea onClick={onNavigate} sx={{ py: 0.6, ps: 2.5, pe: 1, mx: 1, justifyContent: 'space-between' }} > - + {r.item.canCreate && ( - {!collapsed && } + {!collapsed && } @@ -163,7 +162,7 @@ export function Sidebar({ collapsed, onToggle, onNavigate }: { collapsed: boolea {!collapsed && ( <> - + )} @@ -182,9 +181,22 @@ export function Sidebar({ collapsed, onToggle, onNavigate }: { collapsed: boolea setPop(null)} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} slotProps={{ paper: { sx: { minWidth: 220, maxHeight: '70vh' } } }}> {pop && ( - + - {title(pop.section)} + {title(pop.section)} )} {pop && renderRows(pop.section, true)} diff --git a/src/layout/nav.ts b/src/layout/nav.ts index e46f3ce..e487955 100644 --- a/src/layout/nav.ts +++ b/src/layout/nav.ts @@ -8,7 +8,7 @@ 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 MailOutline from '@mui/icons-material/MailOutlineOutlined'; import AppRegistrationOutlined from '@mui/icons-material/AppRegistrationOutlined'; import CardMembershipOutlined from '@mui/icons-material/CardMembershipOutlined'; import FolderOutlined from '@mui/icons-material/FolderOutlined'; @@ -85,8 +85,8 @@ export interface NavSection { 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']); +/** Menu entries the business asked to hide (the goods-tracking service and the logistics platform). */ +export const HIDDEN_ENTITIES = new Set(['FLEET_TRACKING_SERVICES', 'WAITING_PLAN', 'SCHEDULING_PLAN', 'CAPACITY_PLAN_DETAILS', 'AVAILABLE_ON_PLATFORM', 'AVAILABLE_ON_PLATFORM_SEARCH']); /** Entities that leave their own group and sit right after another entity: Permits status (CAPACITY) goes under Fleet permits. */ const MOVE_AFTER: Record = { CAPACITY: 'PERMITS' }; diff --git a/src/pages.tsx b/src/pages.tsx index 3540771..c227374 100644 --- a/src/pages.tsx +++ b/src/pages.tsx @@ -36,6 +36,16 @@ export function LoginPage() { const [touched, setTouched] = useState(false); const [busy, setBusy] = useState(false); const [forgotOpen, setForgotOpen] = useState(false); + // the backend ended the session while the user was working: say so once on the login page + const [ended] = useState(() => { + try { + const v = sessionStorage.getItem('mams.sessionEnded') === '1'; + sessionStorage.removeItem('mams.sessionEnded'); + return v; + } catch { + return false; + } + }); 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 @@ -102,7 +112,12 @@ export function LoginPage() { - + {ui('loginWelcome')} {ui('loginTagline')} @@ -136,10 +151,13 @@ export function LoginPage() { - + {ui('loginTitle')} + {ended && !err && {ui('sessionEnded')}} {err && {loginMessage(err)}} - + setRemember(e.target.checked)} />} label={ui('rememberMe')} @@ -194,8 +218,16 @@ export function LoginPage() { {busy ? : ui('loginSubmit')} - - + + {ui('newToNafith')} - + {ui('followUs')} - + {SOCIAL_LINKS.map(({ icon: Icon, label, href }) => ( @@ -221,7 +257,12 @@ export function LoginPage() { ))} - + © {new Date().getFullYear()} Nafith@Madayn — {ui('allRightsReserved')}