Permit view fields/actions/weights, ask-for-filter grids, blacklist view, optional non-Omani plate code, hide investor/company info, LOP_CC filters

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-16 13:56:28 +03:00
parent e41bcfa279
commit 0f1c6ab3eb
11 changed files with 176 additions and 21 deletions

View File

@ -1,7 +1,7 @@
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { Link as RouterLink, Navigate, useSearchParams } from 'react-router-dom';
import { HIDDEN_ENTITIES, WIZARD_KEY } from '../layout/nav';
import { Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Stack, Typography } from '@mui/material';
import { Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Stack, Typography } from '@mui/material';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { rpc } from '../api/client';
import { useNotify } from '../notify/NotifyProvider';
@ -45,6 +45,12 @@ function dynamicDefaults(entity: string): Record<string, string> {
const PENDING_ENTITY = 'FLEET_PENDING_FINANCIAL_TRANSACTIONS';
/**
* Big lists that open with no records and no default status: the user enters a search filter first (fleet subscriptions,
* entry permit requests, users, stickers, blacklist, rented trucks affiliation, fleet permits).
*/
const ASK_FOR_FILTER = new Set(['SUBSCRIPTIONS', 'FLEET_REQUEST', 'USERS', 'RFID_TAGS', 'BLACKLISTS', 'RENTED_TRUCK', 'PERMITS']);
/** "05/11/2026 - 16/10/2023" (either order) -> "20231016-20261105" */
function receivablesRange(range: string): string {
const ds = range.split('-').map((p) => p.trim().split('/'));
@ -104,6 +110,8 @@ function GridPage({ entity, extraDefaults }: { entity: string; extraDefaults?: R
// otherwise every clear would silently snap back to the default instead of showing everything.
// plus the two defaults the old pages set in script rather than in the metadata (see dynamicDefaults)
const defaultFilter = useMemo(() => {
// these lists open on "All" and wait for the user's own search filter
if (ASK_FOR_FILTER.has(entity)) return {} as Record<string, string>;
const out: Record<string, string> = Object.fromEntries(fields.filter((f) => f.defaultValue).map((f) => [f.id, f.defaultValue!]));
for (const [id, v] of Object.entries({ ...dynamicDefaults(entity), ...extraDefaults })) if (fields.some((f) => f.id === id)) out[id] = v;
return out;
@ -195,7 +203,11 @@ function GridPage({ entity, extraDefaults }: { entity: string; extraDefaults?: R
{t('TOTAL_BALANCE')} : <bdi dir="ltr">{totalBalance.toFixed(3)}</bdi> {t('RO')}
</Typography>
)}
{ASK_FOR_FILTER.has(entity) && !Object.values(filter).some((v) => String(v ?? '').trim() !== '') ? (
<Alert severity="info">{ui('enterSearchFilter')}</Alert>
) : (
<EntityGrid entity={entity} filter={toApiFilter(filter)} canEdit={can('UPDATE')} onTotal={onTotal} onFilterRequired={onFilterRequired} selectable={selectable} selected={selected} onSelectedChange={setSelected} onTotalBalance={setTotalBalance} />
)}
{uploadOpen && (entity === 'RECONCILIATION' || entity === 'RECONCILIATION_POS') && (
<ReconciliationUpload entity={entity} onClose={() => setUploadOpen(false)} onDone={() => { setUploadOpen(false); void qc.invalidateQueries({ queryKey: ['grid', entity] }); }} />
)}

View File

@ -15,7 +15,7 @@ import { fetchRecaptchaSiteKey } from '../../api/session';
import { useRecaptcha } from '../../auth/recaptcha';
import { fromInputDate, resolveFields, toDisplayDate, toInputDate, toPayload, type Mode, type ResolvedField } from './fields';
import { RecordActionButtons } from '../view/RecordActionButtons';
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 { CONFIRM_ENTITIES, CREATE_DEFAULTS, CREATE_HIDDEN_SECTIONS, 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';
@ -307,6 +307,7 @@ export function EntityForm({
(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 === 'CREATE' && !!layout?.sections.some((s) => CREATE_HIDDEN_SECTIONS[entity]?.includes(s.title) && s.fields.includes(name))) ||
(mode === 'EDIT' && !!layout?.sections.some((s) => EDIT_HIDDEN_SECTIONS[entity]?.includes(s.title) && s.fields.includes(name))) ||
(!!nonOmaniOnly?.fields.includes(name) && !isNonOmani) ||
(!!riyadaDoc && name === riyadaDoc && !riyadaRole) ||
@ -314,6 +315,9 @@ export function EntityForm({
(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));
// fleet pages: the free-text plate code (non-Omani documents) is optional, the Omani dropdown stays mandatory
const plateOptional = (name: string) => FLEET_ENTITIES.includes(entity) && plateRules.some((r) => r.text === name);
const plateRequired = (name: string) => isPlateField(name) && !plateOptional(name);
// fields that become mandatory because of what was chosen
const conditionallyRequired = (name: string) =>
(mode === 'CREATE' && !!CREATE_REQUIRED[entity]?.includes(name)) ||
@ -395,7 +399,7 @@ export function EntityForm({
const v = values[f.name];
const empty = v === undefined || v === null || v === '' || (Array.isArray(v) && !v.length);
// whichever of the plate-code pair is showing is the one that must be filled
const required = isPlateField(f.name) || conditionallyRequired(f.name) ? true : f.required;
const required = plateRequired(f.name) || conditionallyRequired(f.name) ? true : plateOptional(f.name) ? false : f.required;
if (required && empty) errs[f.name] = t('REQUIRED_FIELD');
else if (!empty && f.regex && typeof v === 'string') {
// date patterns are written for the display format dd/mm/yyyy, values are stored as yyyymmdd
@ -482,7 +486,7 @@ export function EntityForm({
const visible = s.fields
.map((n) => byName.get(n))
.filter((f): f is ResolvedField => !!f && !f.hidden && !formHidden(f.name))
.map((f) => (isPlateField(f.name) || conditionallyRequired(f.name) ? { ...f, required: true } : f))
.map((f) => (plateRequired(f.name) || conditionallyRequired(f.name) ? { ...f, required: true } : plateOptional(f.name) ? { ...f, required: false } : f))
.map((f) => (ownerLocked(f.name) || profileLocked(f.name) ? { ...f, readOnly: true } : f))
.map((f) => (trailerPlateAsSelect(f) ? { ...f, type: 'DROPDOWN', options: byName.get('FLEET_PLATE_CODE')!.options } : f));
if (!visible.length) return null;

View File

@ -1037,6 +1037,8 @@
"fields": [
"FIRST_WEIGHT",
"FIRST_WEIGHT_DATE",
"SECOND_WEIGHT",
"SECOND_WEIGHT_DATE",
"NET_WEIGHT"
]
},

View File

@ -143,6 +143,8 @@ export const VIEW_HIDDEN_SECTIONS: Record<string, string[]> = {
PERSONNEL: ['LICENSEINFO', 'PERSONNEL_INFO'],
// the reply box is a popup here; the answers are listed in their own table
TICKETS: ['ADD_REPLY'],
// the extra backend fields (type, severity, expiry) are not on the legacy blacklist page
BLACKLISTS: ['BLACKLISTS_INFO'],
};
/** Fields that only apply to a non-Omani nationality (passport details), and the nationality field that decides it. */
@ -151,6 +153,12 @@ export const NON_OMANI_ONLY: Record<string, { nationality: string; fields: strin
PERSONNEL: { nationality: 'NATIONALITY_CODE', fields: ['PASSPORT_NUMBER', 'PASSPORT_EXPIRY_DATE', 'PASSPORT_NOT_OMANI'], attachment: 'PASSPORT_NOT_OMANI', notRequiredWith: 'NN' },
};
/** Whole groups left out of the create form (heading and fields): the extra backend fields the legacy create page never asked for. */
export const CREATE_HIDDEN_SECTIONS: Record<string, string[]> = {
INVESTORS: ['INVESTORS_INFO'],
COMPANIES: ['COMPANIES_INFO'],
};
/** Sections whose heading is left out of the create form (the fields stay). */
export const HIDDEN_CREATE_TITLES: Record<string, string> = { BLACKLISTS: 'BLACKLISTSINFO' };
@ -185,7 +193,7 @@ export const VIEW_HIDDEN_FIELDS: Record<string, string[]> = {
...Object.fromEntries(FLEET_ENTITIES.map((e) => [e, ['NATIONALITY_LICENCE', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER']])),
USERS: ['LOCATION_IDS'],
};
export const VIEW_LAST_FIELDS: Record<string, string[]> = { DEPOSITS: ['NOTES'] };
export const VIEW_LAST_FIELDS: Record<string, string[]> = { DEPOSITS: ['NOTES'], BLACKLISTS: ['NOTES'] };
/** Heading of the group that holds an entity's extra backend-required fields, when "<ENTITY>_INFO" would read wrongly. */
const EXTRA_TITLE: Record<string, string> = { PERMITS: 'TRUCKS_INFO' };
@ -264,9 +272,14 @@ function build(entity: string, config: AppConfig): EntityLayout | undefined {
if (names.has(field) && !dynamic[field]) dynamic[field] = lookup;
}
return { ...hand, sections, dynamic, alias };
return { ...hand, sections, dynamic, alias, viewText: { ...(hand?.viewText ?? {}), ...(VIEW_TEXT[entity] ?? {}) } };
}
/** Record-page values the backend sends ready formatted under another key (the *_GRID ones carry the time of day). */
const VIEW_TEXT: Record<string, Record<string, string>> = {
PERMITS: { CREATION_DATE: 'CREATION_DATE_GRID', FIRST_WEIGHT_DATE: 'FIRST_WEIGHT_DATE_GRID', SECOND_WEIGHT_DATE: 'SECOND_WEIGHT_DATE_GRID' },
};
const ENTITY_LOOKUPS: Record<string, Record<string, DynamicLookup>> = {
// investors that hold the chosen industrial area
RENTED_TRUCK: {

View File

@ -75,7 +75,8 @@ export function PendingPayDialog({ id, data, onClose, onDone }: { id: string; da
if (nafith) {
Object.assign(params, {
depts_transcation_ids: data.ID,
stakeholder_entity_id: data.STAKEHOLDER_ENTITY_ID,
// legacy: ticking "include the Nafith service" makes the payer's own entity the stakeholder
stakeholder_entity_id: withNafith ? ((user as Record<string, unknown> | null)?.related_entity_id ?? data.STAKEHOLDER_ENTITY_ID) : data.STAKEHOLDER_ENTITY_ID,
stakeholder_entity_Record_id: data.STAKEHOLDER_ENTITY_RECORD_ID,
fleet_entity_id: data.FLEET_ENTITY_ID,
fleet_entity_record_id: data.FLEET_ENTITY_RECORD_ID,

View File

@ -32,7 +32,7 @@ interface Row {
/** 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<string, { roles: string[]; ids: string[] }> = {
FLEET_REQUEST: {
roles: ['SHIFT_SUPERVISOR', 'OPOFF'],
roles: ['SHIFT_SUPERVISOR', 'OPOFF', 'LOP_CC'],
ids: ['SENDER_RELATED_ENTITY_ID', 'SENDER_RELATED_ENTITY_RECORD_ID', 'RECEIVER_RELATED_ENTITY_ID', 'RECEIVER_RELATED_ENTITY_RECORD_ID'],
},
};

View File

@ -11,6 +11,7 @@ import { rpc, type Envelope } from '../../api/client';
import { useAuth } from '../../auth/AuthContext';
import { useLabel, useT, useUi } from '../../i18n';
import { sectionFrame } from '../../components/SectionTitle';
import { DateField } from '../../components/DateField';
/**
* The old record pages ended with a collapsed "Events" card: who did what to the record and when, with a popup that
@ -24,7 +25,14 @@ 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];
/**
* A log row is [id, action, user, date, details]; the permit log (and a few others) also carries the kiosk the action
* was made at, between the user and the date: [id, action, user, kiosk, date, details].
*/
type Row = string[];
const hasKiosk = (r: Row) => r.length >= 6;
const rowDate = (r: Row) => (hasKiosk(r) ? r[4] : r[3]);
const rowDetails = (r: Row) => String(r[r.length - 1] ?? '');
/** 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<string, unknown>; newData: Record<string, unknown> } | null {
@ -82,6 +90,9 @@ export function EntityEvents({ entity, id }: { entity: string; id: string }) {
const reset = () => { setPage(0); setDraft(EMPTY); setApplied(EMPTY); };
const rows = events.data?.rows ?? [];
const count = events.data?.records ?? 0;
// the permit log always has the kiosk column, as the old page did, even when a page of rows is empty
const kiosk = entity === 'PERMITS' || rows.some(hasKiosk);
const cols = kiosk ? 5 : 4;
return (
<Paper variant="outlined" sx={{ p: 2, ...sectionFrame }}>
@ -113,8 +124,8 @@ export function EntityEvents({ entity, id }: { entity: string; id: string }) {
{actions.map((a) => <MenuItem key={a.ACTION_CODE} value={a.ACTION_CODE}>{t(a.CAPTION_CODE)}</MenuItem>)}
</TextField>
<TextField size="small" label={t('USERNAME')} value={draft.login} onChange={(e) => setDraft({ ...draft, login: e.target.value })} />
<TextField size="small" type="date" label={ui('from')} value={draft.from} onChange={(e) => setDraft({ ...draft, from: e.target.value })} slotProps={{ inputLabel: { shrink: true } }} />
<TextField size="small" type="date" label={ui('to')} value={draft.to} onChange={(e) => setDraft({ ...draft, to: e.target.value })} slotProps={{ inputLabel: { shrink: true } }} />
<DateField size="small" label={ui('from')} value={draft.from} onChange={(iso) => setDraft((d) => ({ ...d, from: iso }))} />
<DateField size="small" label={ui('to')} value={draft.to} onChange={(iso) => setDraft((d) => ({ ...d, to: iso }))} />
<Button variant="contained" onClick={search}>{t('SEARCH')}</Button>
<Button onClick={reset}>{t('CANCEL_SEARCH')}</Button>
</Stack>
@ -128,19 +139,21 @@ export function EntityEvents({ entity, id }: { entity: string; id: string }) {
<TableRow>
<TableCell align="center">{t('ACTION_CODE')}</TableCell>
<TableCell align="center">{t('USERNAME')}</TableCell>
{kiosk && <TableCell align="center">{t('KIOSK_NUMBER')}</TableCell>}
<TableCell align="center">{t('CREATION_DATE')}</TableCell>
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{rows.length === 0 && <TableRow><TableCell colSpan={4} align="center" sx={{ color: 'text.secondary' }}>{t('NO_INFO')}</TableCell></TableRow>}
{rows.length === 0 && <TableRow><TableCell colSpan={cols} align="center" sx={{ color: 'text.secondary' }}>{t('NO_INFO')}</TableCell></TableRow>}
{rows.map((r) => {
const d = parseDetails(String(r[4] ?? ''));
const d = parseDetails(rowDetails(r));
return (
<TableRow key={r[0]}>
<TableCell align="center">{r[1]}</TableCell>
<TableCell align="center">{r[2]}</TableCell>
<TableCell align="center" dir="ltr">{r[3]}</TableCell>
{kiosk && <TableCell align="center">{hasKiosk(r) ? r[3] : ''}</TableCell>}
<TableCell align="center" dir="ltr">{rowDate(r)}</TableCell>
<TableCell align="center">
{d && Object.keys(d.newData).length + Object.keys(d.oldData).length > 0 && (
<Tooltip title={t('EVENTS_DETAILS')}>

View File

@ -1,6 +1,7 @@
import { useMemo, useState } from 'react';
import { SectionTitle, sectionFrame } from '../../components/SectionTitle';
import { Link as RouterLink } from 'react-router-dom';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { WeighingDialog } from './WeighingDialog';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Paper,
@ -53,7 +54,11 @@ function Value({ field, data, layout }: { field: ResolvedField; data: Data; layo
const none = <Typography component="span" sx={{
color: "text.disabled"
}}>—</Typography>;
if (textKey && String(data[textKey] ?? '').trim()) return <>{String(data[textKey])}</>;
if (textKey && String(data[textKey] ?? '').trim()) {
const text = String(data[textKey]);
// a date with a time (29/07/2026 11:38:48) must read date first in the right-to-left page too
return /^\d{2}\/\d{2}\/\d{4}/.test(text) ? <span dir="ltr">{text}</span> : <>{text}</>;
}
const forced = (data.__TEXT as Record<string, string> | undefined)?.[field.name];
if (forced) return <>{forced}</>;
// a stakeholder is stored as an id: show the name the backend sends beside it (investor names come in both languages)
@ -109,6 +114,8 @@ export function EntityView({ entity, id }: { entity: string; id: string }) {
const [detPage, setDetPage] = useState(0);
const [vatOpen, setVatOpen] = useState(false);
const [vat, setVat] = useState('');
const nav = useNavigate();
const [wimOpen, setWimOpen] = useState(false);
const [replyOpen, setReplyOpen] = useState(false);
const [payOpen, setPayOpen] = useState(false);
const [renewOpen, setRenewOpen] = useState(false);
@ -148,10 +155,17 @@ export function EntityView({ entity, id }: { entity: string; id: string }) {
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'));
else if (v.a.ACTION_NAME !== 'MFZ_EXIT_INQUIRY') 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));
if (file && (/downloadFiles/i.test(file) || v.a.ACTION_NAME === 'PRINT_WEIGHING_BRIDGE_DATA')) void downloadReport(file).catch((e) => notify.error(e));
// free-zone exit inquiry: the result says whether the truck may leave (the old page's messages)
if (v.a.ACTION_NAME === 'MFZ_EXIT_INQUIRY') {
const result = String((res.DATA as { INTEGRATION_RESULT?: string } | undefined)?.INTEGRATION_RESULT ?? '');
const msg: Record<string, string> = { True: 'ALLOWED_EXIT_MFZ', Partially: 'ALLOWED_TEMP_EXIT_MFZ', False: 'NOT_ALLOWED_EXIT_MFZ', ERROR: 'ERROR_WITH_EDAA' };
if (msg[result]) (result === 'True' || result === 'Partially' ? notify.success : notify.warning)(msg[result], t(msg[result]));
if (result === 'True' || result === 'Partially') nav(`/e/${entity}/grid`);
}
setAction(null);
setExtra(null);
void qc.invalidateQueries({ queryKey: ['grid', entity] });
@ -195,7 +209,7 @@ export function EntityView({ entity, id }: { entity: string; id: string }) {
return;
}
// printing only produces a file: no confirmation, like the old page
if (a.ACTION_NAME === 'PRINT' || a.ACTION_NAME === 'GET_INVOICE') {
if (a.ACTION_NAME === 'PRINT' || a.ACTION_NAME === 'GET_INVOICE' || a.ACTION_NAME === 'PRINT_WEIGHING_BRIDGE_DATA') {
run.mutate({ a });
return;
}
@ -295,6 +309,11 @@ export function EntityView({ entity, id }: { entity: string; id: string }) {
{t(String(a.ACTION_CAPTION_CODE ?? a.ACTION_NAME))}
</Button>
))}
{actions.some((a) => a.ACTION_NAME === 'VIEW_WIM') && (
<Button variant="outlined" onClick={() => setWimOpen(true)}>
{t(String(actions.find((a) => a.ACTION_NAME === 'VIEW_WIM')?.ACTION_CAPTION_CODE ?? 'VIEW_WIM'))}
</Button>
)}
{vatAction && (
<Button variant="contained" onClick={() => { vatMutation.reset(); setVat(String(data.VAT_NUMBER ?? '').trim()); setVatOpen(true); }}>
{t(String(vatAction.ACTION_CAPTION_CODE ?? 'UPDATE_VAT'))}
@ -573,6 +592,7 @@ export function EntityView({ entity, id }: { entity: string; id: string }) {
)}
<NewPasswordDialog message={newPassword} onClose={() => setNewPassword(null)} />
{entity === 'PERMITS' && <WeighingDialog entity={entity} id={id} open={wimOpen} onClose={() => setWimOpen(false)} />}
{extra && (
<ExtraFieldsDialog

View File

@ -0,0 +1,86 @@
import { useQuery } from '@tanstack/react-query';
import { Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Table, TableBody, TableCell, TableRow, Typography } from '@mui/material';
import { runAction } from '../../api/entity';
import { useAuth } from '../../auth/AuthContext';
import { isRtl, useT } from '../../i18n';
/**
* The permit's "weighing readings" (VIEW_WIM): what the bridge measured when the truck entered and when it left the
* estate: total weight, speed and the weight on every axle. The old page drew a truck with the axles; here they are a table.
*/
type Reading = Record<string, unknown>;
const AXLES = [1, 2, 3, 4, 5, 6, 7, 8, 9];
/** a reading worth showing: not empty, not the bridge's "--------" placeholder and not zero (an axle the truck does not have) */
const has = (v: unknown) => {
const s = String(v ?? '').trim();
return s !== '' && !/^-+$/.test(s) && !(Number.isFinite(Number(s)) && Number(s) === 0);
};
// the caption table has no entries for these readings, so the dialog carries its own names
const NAMES = {
total: { en: 'Total weight', ar: 'الوزن الكلي' },
speed: { en: 'Speed', ar: 'السرعة' },
axle: { en: 'Axle', ar: 'المحور' },
};
export function WeighingDialog({ entity, id, open, onClose }: { entity: string; id: string; open: boolean; onClose: () => void }) {
const t = useT();
const { lang } = useAuth();
const ar = isRtl(lang);
const name = (k: keyof typeof NAMES) => (ar ? NAMES[k].ar : NAMES[k].en);
const q = useQuery({
queryKey: ['weighing', entity, id],
enabled: open,
staleTime: 0,
retry: false,
queryFn: async () => (await runAction(entity, 'VIEW_WIM', {}, id, [])).DATA as Reading,
});
const d = q.data ?? {};
const side = (title: string, key: 'ENTRY' | 'EXIT') => {
const rows: [string, unknown][] = [
[name('total'), d[`TOTAL_WEIGHT_${key}`]],
[name('speed'), d[`SPEED_${key}`]],
...AXLES.map((n) => [`${name('axle')} ${n}`, d[`AXIAL_WEIGHT_AXLE_${n}_${key}`]] as [string, unknown]),
].filter(([, v]) => has(v)) as [string, unknown][];
return (
<Box sx={{ flex: 1, minWidth: 260 }}>
<Typography sx={{ fontWeight: 800, mb: 1 }}>{title}</Typography>
{rows.length === 0 ? (
<Typography variant="body2" sx={{ color: 'text.secondary' }}>{t('NO_RECORD_EXIST')}</Typography>
) : (
<Table size="small">
<TableBody>
{rows.map(([label, v]) => (
<TableRow key={label}>
<TableCell sx={{ color: 'text.secondary' }}>{label}</TableCell>
<TableCell dir="ltr" align="right" sx={{ fontWeight: 700 }}>{String(v)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</Box>
);
};
return (
<Dialog open={open} onClose={onClose} fullWidth maxWidth="md">
<DialogTitle>{t('WEIGHTS')}</DialogTitle>
<DialogContent>
{q.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}><CircularProgress size={26} /></Box>}
{q.error && <Alert severity="error">{t((q.error as Error).message)}</Alert>}
{q.data && (
<Box sx={{ display: 'flex', gap: 3, flexWrap: 'wrap', pt: 1 }}>
{side(t('WEIGHTS_ENTRY_INDUSTRIAL_ESTATE'), 'ENTRY')}
{side(t('WEIGHTS_EXITING_INDUSTRIAL_ESTATE'), 'EXIT')}
</Box>
)}
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('CLOSE')}</Button>
</DialogActions>
</Dialog>
);
}

View File

@ -16,6 +16,9 @@ const SIMPLE = new Set([
'RECONCILE', 'PRINT', 'GET_INVOICE',
// customer service: the support role finishes a ticket
'OPOFF_COMPLETE',
// permits: gate-in / gate-out, release, return to review, extend validity, free-zone exit, weighing slip
'GIN_EVENT', 'GOUT_EVENT', 'RELEASED', 'MFZ_TEMPORARY_EXIT', 'RETURN_TO_UNDER_REVIEW', 'MFZ_EXTEND_VALIDITY_PERIOD',
'MFZ_EXIT_INQUIRY', 'PRINT_WEIGHING_BRIDGE_DATA',
]);
export const isSimpleAction = (a: EntityAction) => SIMPLE.has(a.ACTION_NAME);

View File

@ -87,6 +87,7 @@ export const UI = {
wizFreeZone: { en: 'One-trip permits for the free-zone package are entered in the previous system for now. Nothing has been submitted.', ar: 'تصاريح الرحلة الواحدة لباقة المنطقة الحرة تُدخل حالياً في النظام السابق. لم يتم إرسال أي طلب.' },
wizSearchFirst: { en: 'Search for the vehicles by plate number, plate code, nationality, owner type or class, then pick the ones to subscribe.', ar: 'ابحث عن المركبات برقم اللوحة أو ترميزها أو الجنسية أو نوع المالك أو الفئة، ثم اختر ما تريد الاشتراك به.' },
wizNeedFilter: { en: 'Enter at least one search filter (for example the plate number).', ar: 'أدخل معياراً واحداً على الأقل للبحث (مثل رقم اللوحة).' },
enterSearchFilter: { en: 'Choose a status or enter a search filter above to list the records.', ar: 'اختر حالة أو أدخل معياراً للبحث أعلاه لعرض السجلات.' },
gridLoading: { en: 'Loading the list from the system…', ar: 'جاري تحميل القائمة من النظام…' },
gridSearching: { en: 'Updating the results…', ar: 'جاري تحديث النتائج…' },
gridLoadingSlow: { en: 'Large lists can take a few more seconds. Please wait.', ar: 'قد تستغرق القوائم الكبيرة بضع ثوانٍ إضافية. يرجى الانتظار.' },
@ -191,7 +192,7 @@ export type UiKey = keyof typeof UI;
export const SECTION_TITLES: Record<string, { en: string; ar: string }> = {
// the trailer's plate code is captioned "Plate Code" in the metadata, which reads as a duplicate of the truck's
TRAILER_PLATE_CODE: { en: 'Trailer Plate Code', ar: 'ترميز لوحة المقطورة' },
BLACKLISTSINFO: { en: 'Blacklist details', ar: 'تفاصيل القائمة السوداء' },
BLACKLISTSINFO: { en: 'Blacklist details', ar: 'معلومات المنع' },
OWNERINFO: { en: 'Owner details', ar: 'بيانات المالك' },
INSURANCEINFO: { en: 'Insurance', ar: 'التأمين' },
CAPACITY_OPTIONS: { en: 'Capacity options', ar: 'خيارات الطاقة الاستيعابية' },