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