diff --git a/src/api/packages.ts b/src/api/packages.ts index 09ab36e..1239cce 100644 --- a/src/api/packages.ts +++ b/src/api/packages.ts @@ -179,6 +179,8 @@ export interface CreateResult { MESSAGE?: string; RECEIVABLES?: string; PAYMENT_METHOD?: string; + /** for a card payment: what the bank's payment page (payment.cfm) needs */ + DATA?: { BILLING_CODE?: string; AMOUNT?: string | number; PARAMS?: unknown }; /** one-trip requests answer with a RESULTCODE instead of CODE */ RESULTCODE?: string; RESULTDATA?: { response_code?: string; response_error_codes?: string }[]; diff --git a/src/api/session.ts b/src/api/session.ts index c3b1d00..45964c8 100644 --- a/src/api/session.ts +++ b/src/api/session.ts @@ -30,10 +30,16 @@ export async function fetchSessionUser(lang: string): Promise('CONFIG', 'login', { - // the backend reads DATA.REMEMBER_ME unconditionally on a successful login, even though it does nothing with it here - data: { USERNAME: username, PASSWORD: password, LANGUAGE: languageId, REMEMBER_ME: rememberMe }, - }); + // POST, so the password travels in the request body and never in the URL (web-server logs, proxies, browser history) + const res = await rpc( + 'CONFIG', + 'login', + { + // the backend reads DATA.REMEMBER_ME unconditionally on a successful login, even though it does nothing with it here + data: { USERNAME: username, PASSWORD: password, LANGUAGE: languageId, REMEMBER_ME: rememberMe }, + }, + { post: true }, + ); if (String(res.CODE) !== '000' && res.CODE !== 0) { throw new ApiError(String(res.MESSAGECODE ?? res.MESSAGE ?? 'LOGIN_FAILED'), res.CODE); } diff --git a/src/features/forms/EntityForm.tsx b/src/features/forms/EntityForm.tsx index e7340fd..a6bfaa3 100644 --- a/src/features/forms/EntityForm.tsx +++ b/src/features/forms/EntityForm.tsx @@ -15,8 +15,9 @@ 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_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 { CONFIRM_ENTITIES, CREATE_DEFAULTS, CREATE_HIDDEN_SECTIONS, CREATE_OPTION_ONLY, 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 { LetterReceivers, LetterTexts, lettersPayload, type LetterText, type Receiver } from './LetterLists'; import { DateField } from '../../components/DateField'; import { ExtraFieldsDialog } from './ExtraFieldsDialog'; import { deleteAttachment, type PendingFile, type StoredAttachment } from '../../api/attachments'; @@ -55,6 +56,8 @@ const PLATE_RULES: { select: string; text: string; nat?: string[] }[] = [ // 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']; +/** a new message keeps these in lists of their own: the fields themselves are not posted */ +const LETTER_LIST_FIELDS = ['LANGUAGE', 'SUBJECT', 'DETAILS', 'LETTERS_STAKEHOLDERS', 'ENTITY_ROLE', 'CATEGORY']; 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']; @@ -302,6 +305,10 @@ export function EntityForm({ (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 lettersCreate = entity === 'LETTERS' && mode === 'CREATE'; + const isLetter = String(values.MESSAGE_CATEGORY ?? '').trim() === 'LETTER'; + const [letterTexts, setLetterTexts] = useState([]); + const [receivers, setReceivers] = useState([]); const formHidden = (name: string) => plateHidden(name) || (ownerToggle && (name === 'IS_OWNER' || (isOwner && OWNER_DOC.includes(name)))) || @@ -314,7 +321,9 @@ export function EntityForm({ // 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)); + (entity === 'DEPOSITS' && mode === 'CREATE' && user?.role_group === 'STAKEHOLDER' && ['STAKEHOLDER_ENTITY_NUMBER', 'STAKEHOLDER_ENTITY_RECORD_NAME', 'STAKEHOLDER_ENTITY_ID'].includes(name)) || + // a new message: the texts and the receivers are two lists of their own (see LetterLists); number and "mandatory" are for letters only + (lettersCreate && (LETTER_LIST_FIELDS.includes(name) || (!isLetter && ['LETTER_NUMBER', 'IS_MANDETORY'].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); @@ -322,7 +331,8 @@ export function EntityForm({ 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); + (!!riyadaDoc && name === riyadaDoc && riyadaChecked) || + (lettersCreate && isLetter && ['LETTER_NUMBER', 'IS_MANDETORY'].includes(name)); const stakeholderKey = `${values.RELATED_ENTITY_ID ?? ''}_${values.RELATED_ENTITY_RECORD_ID ?? ''}`; const fillOwner = async () => { @@ -344,6 +354,42 @@ export function EntityForm({ if (isOwner && mode === 'CREATE') void fillOwner(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [isOwner, mode, stakeholderKey]); + // rented truck: typing the plate looks the truck up and fills in its owner (legacy vehicleSearchByPlateCode on blur / code change); + // the truck's id travels with the save + const [truckInfo, setTruckInfo] = useState<{ TRUCK_ID?: unknown; FLEET_ENTITY_ID?: unknown } | null>(null); + const rentedOmani = String(values.TRUCK_NATIONALITY ?? '').trim().toUpperCase() === 'OMN'; + const rentedNumber = String(values.PLATE_NUMBER ?? '').trim(); + const rentedCode = String((rentedOmani ? values.PLATE_CODE : values.PLATE_CODE_AR) ?? '').trim(); + useEffect(() => { + if (entity !== 'RENTED_TRUCK' || mode !== 'CREATE' || !rentedNumber || !rentedCode) return; + let cancelled = false; + const h = setTimeout(async () => { + try { + const res = await rpc('CONFIG', 'vehicleSearchByPlateCode', { PLATE_NUMBER: rentedNumber, PLATE_CODE: rentedCode }); + if (cancelled) return; + const [row, count] = (Array.isArray(res) ? res : []) as [Record | undefined, unknown]; + if (Number(count) !== 1 || !row) { + setTruckInfo(null); + notify.error(new ApiError('INCORRECT_ENTERED_PLATE_NUMBER_OR_PLATE_CODE')); + } else if (String(row.STAKEHOLDER_ENTITY_ID) === '7') { + // an investor's own truck cannot be rented out + setTruckInfo(null); + setValues((cur) => ({ ...cur, PLATE_NUMBER: '', PLATE_CODE: '', PLATE_CODE_AR: '', STAKEHOLDER_ENTITY_ID: '', STAKEHOLDER_ENTITY_RECORD_ID: '' })); + notify.error(new ApiError('CANT_RENTED_TRUCK_BY_INV')); + } else { + setTruckInfo({ TRUCK_ID: row.TRUCK_ID, FLEET_ENTITY_ID: row.FLEET_ENTITY_ID }); + setValues((cur) => ({ ...cur, STAKEHOLDER_ENTITY_ID: String(row.STAKEHOLDER_ENTITY_ID ?? ''), STAKEHOLDER_ENTITY_RECORD_ID: String(row.STAKEHOLDER_ENTITY_RECORD_ID ?? '') })); + } + } catch (e) { + if (!cancelled) notify.error(e); + } + }, 500); + return () => { + cancelled = true; + clearTimeout(h); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [entity, mode, rentedNumber, rentedCode]); const toggleOwner = (checked: boolean) => { setValues((cur) => { const next: Values = { ...cur, IS_OWNER: checked ? 'YES' : 'NO' }; @@ -378,6 +424,35 @@ export function EntityForm({ return next; }); setErrors((e) => ({ ...e, [name]: '' })); + if (entity === 'PERSONNEL' && name === 'NATIONALITY_CODE') void fillPersonnelDocument(String(v ?? '')); + // anything that is not a letter has the "other" type, which the old page then locked + if (entity === 'LETTERS' && name === 'MESSAGE_CATEGORY' && String(v) !== 'LETTER') setValues((cur) => ({ ...cur, LETTER_TYPE: 'OTHER_LETTER_TYPE' })); + }; + + // employee: the nationality decides the identity document and the document's nationality (legacy fillNationalityAndPersonnelDoc); + // both boxes are then locked. Omani: first document type, Omani document. Another GCC country: first document type and the + // same country. Anyone else: the third document type, issued by Oman. + const fillPersonnelDocument = async (nat: string) => { + const docs = byName.get('PERSONAL_DOCUMENT_TYPE')?.options ?? []; + const countries = byName.get('LICENSE_NATIONALITY_CODE')?.options ?? []; + const pickCountry = (code: string) => String(countries.find((o) => String(o.CODE).toUpperCase() === code.toUpperCase())?.CODE ?? code); + const apply = (docIndex: number, country: string) => + setValues((cur) => ({ + ...cur, + PERSONAL_DOCUMENT_TYPE: docs[docIndex] ? String(docs[docIndex].CODE) : '', + LICENSE_NATIONALITY_CODE: pickCountry(country), + PASSPORT_NUMBER: '', + PASSPORT_EXPIRY_DATE: '', + })); + if (!nat) return; + if (nat.toUpperCase() === 'OMN') return apply(0, 'OMN'); + try { + const gcc = await rpc('CONFIG', 'is_Gcc_Country', { countryCode: nat }); + if (String(gcc) === '1') apply(0, nat); + else apply(2, 'OMN'); + } catch (e) { + notify.error(e); + } }; // legacy: non-Nafith users confirm the data is correct before saving (role 45 is ticked for them and not shown) @@ -390,6 +465,13 @@ export function EntityForm({ notify.error(new ApiError('MUST_CONFIRM')); return false; } + if (lettersCreate) { + const problem = !letterTexts.length ? 'CREATE_LETTERS_LIST_ERROR_MSG' : !receivers.length ? 'CREATE_LETTERS_ERROR_MSG' : !letterTexts.some((x) => x.ID === '1') ? 'MUST_INSERT_LETTER_DETAILS_AR' : ''; + if (problem) { + notify.error(new ApiError(problem)); + 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'); @@ -420,6 +502,8 @@ export function EntityForm({ // 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 (entity === 'RENTED_TRUCK' && truckInfo) Object.assign(data, truckInfo); + if (lettersCreate) Object.assign(data, lettersPayload(letterTexts, receivers)); if (publicMode) data['g-recaptcha-response'] = captcha.token; return runAction(entity, action, data, id, Object.values(pending), reason, publicMode ? 'external' : 'internal'); }, @@ -488,7 +572,38 @@ export function EntityForm({ .filter((f): f is ResolvedField => !!f && !f.hidden && !formHidden(f.name)) .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)); + // an employee's document type and document nationality follow the nationality: the old page kept them locked + .map((f) => (entity === 'PERSONNEL' && ['PERSONAL_DOCUMENT_TYPE', 'LICENSE_NATIONALITY_CODE'].includes(f.name) ? { ...f, readOnly: true } : f)) + // only a letter has a type to choose; everything else is "other", locked + .map((f) => (lettersCreate && f.name === 'LETTER_TYPE' && !isLetter ? { ...f, readOnly: true } : f)) + .map((f) => (trailerPlateAsSelect(f) ? { ...f, type: 'DROPDOWN', options: byName.get('FLEET_PLATE_CODE')!.options } : f)) + .map((f) => { + // a create form may offer only some of the backend's choices (never when that would leave none) + const only = mode === 'CREATE' ? CREATE_OPTION_ONLY[entity]?.[f.name] : undefined; + const kept = only && f.options?.filter((o) => only.includes(String(o.CODE).trim().toUpperCase())); + return kept?.length ? { ...f, options: kept } : f; + }); + if (lettersCreate && (s.title === 'ADDED_MESSAGES' || s.title === 'LETTER_OPTIONS')) { + return ( + + {lab(s.title)} + {s.title === 'ADDED_MESSAGES' ? ( + + ) : ( + + )} + + ); + } if (!visible.length) return null; if (profile && sectionIndex !== profileTab) return null; const renderField = (f: ResolvedField) => { diff --git a/src/features/forms/LetterLists.tsx b/src/features/forms/LetterLists.tsx new file mode 100644 index 0000000..2097eee --- /dev/null +++ b/src/features/forms/LetterLists.tsx @@ -0,0 +1,272 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { + Autocomplete, Box, Button, Chip, IconButton, MenuItem, Paper, Stack, Table, TableBody, TableCell, TableHead, TableRow, TextField, Typography, +} from '@mui/material'; +import DeleteOutline from '@mui/icons-material/Delete'; +import { ApiError } from '../../api/client'; +import { getOptions, type Option } from '../../api/entity'; +import { useAuth } from '../../auth/AuthContext'; +import { DateField } from '../../components/DateField'; +import { useT, useUi } from '../../i18n'; +import { useNotify } from '../../notify/NotifyProvider'; +import { rangeParts, toRange, useSearchFields, type Filter } from '../search/filters'; + +/** + * The two lists of the old "new message" page: + * - the message texts, one per language (the Arabic one is mandatory), each with its subject and details; + * - the receivers: stakeholder type + role + category, where the category can be an advanced search of that stakeholder type. + * Both are only held here until the message is saved; the form posts them as JSON lists (LETTERS_LIST_ARR / RECEIVERS_LIST_ARR). + */ + +const optLabel = (t: (k: string) => string) => (o: Option) => o.NAME || t(o.CAPTION_CODE ?? String(o.CODE)); + +export interface LetterText { LANGUAGE: string; SUBJECT: string; DETAILS: string; ID: string; languageLabel: string } + +export function LetterTexts({ languages, value, onChange }: { languages: Option[]; value: LetterText[]; onChange: (v: LetterText[]) => void }) { + const t = useT(); + const notify = useNotify(); + const label = optLabel(t); + const [language, setLanguage] = useState(''); + const [subject, setSubject] = useState(''); + const [details, setDetails] = useState(''); + + const add = () => { + if (!language || !subject.trim() || !details.trim()) return notify.error(new ApiError('LETTER_DATA_INSERT_ERROR')); + if (value.some((r) => r.ID.toLowerCase() === language.toLowerCase())) return notify.error(new ApiError('LETTER_PREVIOUSLY_ADDED')); + const lang = languages.find((o) => String(o.CODE) === language); + onChange([...value, { LANGUAGE: language, SUBJECT: subject.trim(), DETAILS: details.trim(), ID: language, languageLabel: lang ? label(lang) : language }]); + setLanguage(''); + setSubject(''); + setDetails(''); + }; + + return ( + + + setLanguage(e.target.value)}> + {languages.map((o) => {label(o)})} + + setSubject(e.target.value)} /> + + setDetails(e.target.value)} multiline minRows={3} /> + + + + + + {t('LANGUAGE')} + {t('SUBJECT')} + {t('DETAILS')} + + + + + {value.length === 0 && {t('NO_INFO')}} + {value.map((r) => ( + + {r.languageLabel} + {r.SUBJECT} + {r.DETAILS} + onChange(value.filter((x) => x.ID !== r.ID))}> + + ))} + +
+
+
+ ); +} + +export interface Receiver { + ENTITY: string; + ROLE: string; + CATEGORY: string; + ADVANCE_SEARCH_OPTIONS?: Record; + ID: string; + entityLabel: string; + roleLabel: string; + categoryLabel: string; + /** the advanced search shown as "caption: value" tags */ + tags?: string[]; +} + +const ALL_STAKEHOLDERS = 'ALL_LETTERS_STAKEHOLDERS'; +const ADVANCED = 'ADVANCE_SEARCH_OPTIONS'; + +/** The advanced-search form of one stakeholder type: its own search fields, as the old page drew them. */ +function AdvancedSearch({ entity, filter, onChange }: { entity: string; filter: Filter; onChange: (f: Filter) => void }) { + const t = useT(); + const ui = useUi(); + const { config } = useAuth(); + const fields = useSearchFields(config, entity).filter((f) => f.advanced && f.id !== 'STATUS_CODE'); + const label = optLabel(t); + const set = (id: string, v: string) => { + const next = { ...filter }; + if (v) next[id] = v; + else delete next[id]; + onChange(next); + }; + const toInput = (v: string) => (v.length === 8 ? `${v.slice(0, 4)}-${v.slice(4, 6)}-${v.slice(6, 8)}` : ''); + const fromInput = (v: string) => v.replace(/-/g, ''); + if (!fields.length) return null; + return ( + + {fields.map((f) => { + const v = filter[f.id] ?? ''; + if (f.type === 'DROPDOWN') { + const options = f.options ?? []; + return ( + String(o.CODE) === v) ?? null} getOptionLabel={label} + isOptionEqualToValue={(a, b) => String(a.CODE) === String(b.CODE)} onChange={(_, o) => set(f.id, o ? String(o.CODE) : '')} + renderInput={(p) => } /> + ); + } + if (f.type === 'DATE') { + const [a, b] = rangeParts(v); + return ( + + set(f.id, toRange(fromInput(iso), b))} /> + set(f.id, toRange(a, fromInput(iso)))} /> + + ); + } + return set(f.id, e.target.value)} slotProps={{ htmlInput: { maxLength: f.maxLength } }} />; + })} + + ); +} + +export function LetterReceivers({ stakeholders, captions, value, onChange }: { stakeholders: Option[]; captions: { stakeholders: string; role: string; category: string }; value: Receiver[]; onChange: (v: Receiver[]) => void }) { + const t = useT(); + const notify = useNotify(); + const { config } = useAuth(); + const label = optLabel(t); + const [entity, setEntity] = useState(''); + const [role, setRole] = useState(''); + const [category, setCategory] = useState(''); + const [filter, setFilter] = useState({}); + + const roles = useQuery({ + queryKey: ['letter-roles', entity], + queryFn: async () => { + const list = await getOptions('getEntityRoles', { ENTITYNAME: entity }); + // more than one role: the receiver can also be "all of them" + return list.length === 1 ? list : [{ CODE: 'ALL', CAPTION_CODE: 'ALL' } as Option, ...list]; + }, + enabled: !!entity, + staleTime: 5 * 60_000, + }); + const categories = useQuery({ + queryKey: ['letter-categories', entity], + queryFn: () => getOptions('getEntityCategory', { ENTITYNAME: entity }), + enabled: !!entity, + staleTime: 5 * 60_000, + }); + // changing the stakeholder type starts the role / category / search over + useEffect(() => { + setRole(''); + setCategory(''); + setFilter({}); + }, [entity]); + useEffect(() => setFilter({}), [category]); + + // the caption of each advanced-search field, for the tags + const searchFields = useSearchFields(config, entity || '_'); + const tagsOf = useMemo( + () => (f: Filter) => + Object.entries(f).map(([k, v]) => { + const sf = searchFields.find((x) => x.id === k); + const shown = sf?.type === 'DROPDOWN' ? (sf.options?.find((o) => String(o.CODE) === v) ? label(sf.options.find((o) => String(o.CODE) === v)!) : v) : v; + return `${sf ? t(sf.caption) : k}: ${shown}`; + }), + [searchFields, t], // eslint-disable-line react-hooks/exhaustive-deps + ); + + const text = (list: Option[] | undefined, code: string) => { + const o = list?.find((x) => String(x.CODE) === code); + return o ? label(o) : code; + }; + + const add = () => { + if (!entity || !role || !category) return notify.error(new ApiError('LETTER_DATA_INSERT_ERROR')); + const advanced = category === ADVANCED; + const used = Object.fromEntries(Object.entries(filter).filter(([, v]) => v)); + if (advanced && !Object.keys(used).length) return notify.error(new ApiError('SELECT_SEARCH_OPTION_ERROR')); + const id = advanced ? `${entity}_${role}_${Object.entries(used).map(([k, v]) => `${k}_${v}`).join('/')}` : `${entity}_${role}_${category}`; + + if (value.some((r) => r.ID.toLowerCase() === id.toLowerCase())) return notify.error(new ApiError('RECEIVER_PREVIOUSLY_ADDED')); + // "all stakeholders" excludes every other receiver; "all roles" excludes the same stakeholder's other ones + if (entity === ALL_STAKEHOLDERS && value.length) return notify.error(new ApiError('RECEIVER_INCLUDED')); + if (value.some((r) => r.ENTITY === ALL_STAKEHOLDERS)) return notify.error(new ApiError('RECEIVER_INCLUDED')); + const sameEntity = value.find((r) => r.ENTITY === entity); + if (role === 'ALL' && value.length && sameEntity) return notify.error(new ApiError('RECEIVER_INCLUDED')); + if (value.some((r) => r.ROLE === 'ALL') && sameEntity) return notify.error(new ApiError('RECEIVER_INCLUDED')); + + onChange([ + ...value, + { + ENTITY: entity, ROLE: role, CATEGORY: category, ID: id, + ...(advanced ? { ADVANCE_SEARCH_OPTIONS: used } : {}), + entityLabel: text(stakeholders, entity), roleLabel: text(roles.data, role), categoryLabel: text(categories.data, category), + ...(advanced ? { tags: tagsOf(used) } : {}), + }, + ]); + setEntity(''); + }; + + return ( + + + setEntity(e.target.value)}> + {stakeholders.map((o) => {label(o)})} + + setRole(e.target.value)} disabled={!entity}> + {(roles.data ?? []).map((o) => {label(o)})} + + setCategory(e.target.value)} disabled={!entity}> + {(categories.data ?? []).map((o) => {label(o)})} + + + {entity && category === ADVANCED && ( + + {t('ACCORDING_TO_ADVANCE_SEARCH_OPTIONS')} + + + )} + + {t('RECEIVERS_LIST')} + + + + + {t('RELATED_ENTITY_ID')} + {t('ROLE')} + {t('CATEGORY')} + + + + + {value.length === 0 && {t('NO_INFO')}} + {value.map((r) => ( + + {r.entityLabel} + {r.roleLabel} + + {r.tags ? {r.tags.map((x) => )} : r.categoryLabel} + + onChange(value.filter((x) => x.ID !== r.ID))}> + + ))} + +
+
+
+ ); +} + +/** What the backend reads: the lists as JSON strings, with only the keys the old page sent. */ +export const lettersPayload = (texts: LetterText[], receivers: Receiver[]) => ({ + LETTERS_LIST_ARR: JSON.stringify(texts.map(({ LANGUAGE, SUBJECT, DETAILS, ID }) => ({ LANGUAGE, SUBJECT, DETAILS, ID }))), + RECEIVERS_LIST_ARR: JSON.stringify(receivers.map(({ ENTITY, ROLE, CATEGORY, ADVANCE_SEARCH_OPTIONS, ID }) => ({ ENTITY, ROLE, CATEGORY, ...(ADVANCE_SEARCH_OPTIONS ? { ADVANCE_SEARCH_OPTIONS } : {}), ID }))), +}); diff --git a/src/features/forms/layouts.ts b/src/features/forms/layouts.ts index 37555db..cf937a5 100644 --- a/src/features/forms/layouts.ts +++ b/src/features/forms/layouts.ts @@ -74,9 +74,20 @@ export const layouts: Record = { export const FLEET_ENTITIES = ['TRUCKS', 'TRAILERS', 'EQUIPMENTS', 'BUSES', 'CARS']; /** Values a new record starts with. A new vehicle's document nationality is Oman (the plate-code rule follows it). */ -export const CREATE_DEFAULTS: Record> = Object.fromEntries( - FLEET_ENTITIES.map((e) => [e, { LICENCE_NATIONALITY: 'OMN' }]), -); +export const CREATE_DEFAULTS: Record> = { + ...Object.fromEntries(FLEET_ENTITIES.map((e) => [e, { LICENCE_NATIONALITY: 'OMN' }])), + // a rented truck's plate is Omani unless the user says otherwise + RENTED_TRUCK: { TRUCK_NATIONALITY: 'OMN' }, + // a new entry permit request: the truck is Omani unless the user says otherwise + FLEET_REQUEST: { FLEET_NATIONALITY_CODE: 'OMN' }, + // a new message starts as a plain notification-type message: the letter type is only chosen for a letter + LETTERS: { LETTER_TYPE: 'OTHER_LETTER_TYPE' }, +}; + +/** Choices a create form offers out of the backend's list: an entry permit request is only for heavy trucks. */ +export const CREATE_OPTION_ONLY: Record> = { + FLEET_REQUEST: { TRUCK_TYPE: ['HEAVY'] }, +}; /** Fields the backend fills in itself: legacy hides them on the create page and shows them once the record exists. */ export const CREATE_HIDDEN: Record = { diff --git a/src/features/subscriptions/SubscriptionWizard.tsx b/src/features/subscriptions/SubscriptionWizard.tsx index f760ae1..c4f8cf6 100644 --- a/src/features/subscriptions/SubscriptionWizard.tsx +++ b/src/features/subscriptions/SubscriptionWizard.tsx @@ -9,6 +9,7 @@ import { import InfoOutlined from '@mui/icons-material/InfoOutlined'; import CalendarMonthOutlined from '@mui/icons-material/CalendarMonthOutlined'; import PaymentsOutlined from '@mui/icons-material/PaymentsOutlined'; +import { API_BASE } from '../../api/client'; import { useAuth } from '../../auth/AuthContext'; import { useNotify } from '../../notify/NotifyProvider'; import { isRtl, useT, useUi } from '../../i18n'; @@ -22,7 +23,6 @@ const ICON = { info: InfoOutlined, duration: CalendarMonthOutlined, price: Payme // packages whose terms differ (the old wizard's "special packages" note) const SPECIAL_NOTE = ['ISD0001', 'ISW0001', 'IRM0001', 'IMA0001', 'IME0001', 'KRY0001', 'SID0001']; const RIYADA = 'RYD0001'; -const CARD_PAYMENT = 3; function Cards({ cards, action, onPick }: { cards: PackageCard[]; action: string; onPick: (c: PackageCard) => void }) { return ( @@ -285,6 +285,12 @@ export function SubscriptionWizard() { nav('/e/FLEET_PENDING_FINANCIAL_TRANSACTIONS/grid'); return; } + // card payment: the old wizard left for the bank's payment page (payment.cfm on the backend, which keeps the session) + if (r.PAYMENT_METHOD === 'CREDIT_CARD' && r.DATA?.BILLING_CODE) { + const params = typeof r.DATA.PARAMS === 'string' ? r.DATA.PARAMS : JSON.stringify(r.DATA.PARAMS ?? {}); + window.location.href = `${API_BASE}/payment.cfm?BILLING_CODE=${encodeURIComponent(r.DATA.BILLING_CODE)}&AMOUNT=${encodeURIComponent(String(r.DATA.AMOUNT ?? ''))}&PARAMS=${encodeURIComponent(params)}`; + return; + } notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved')); nav(sub?.type === 'EMPLOYEES' ? '/e/EMPLOYEES_SUBSCRIPTIONS/grid' : '/e/SUBSCRIPTIONS/grid'); }, @@ -535,14 +541,7 @@ export function SubscriptionWizard() { setMethod(e.target.value)}> {(methods.data ?? []).map((m) => ( - } label={m.NAME} /> - {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} + } label={m.NAME} /> {m.ID === 6 && method === '6' && ( setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} /> )} diff --git a/src/features/view/EntityEvents.tsx b/src/features/view/EntityEvents.tsx index 1af3159..2746215 100644 --- a/src/features/view/EntityEvents.tsx +++ b/src/features/view/EntityEvents.tsx @@ -12,6 +12,7 @@ import { useAuth } from '../../auth/AuthContext'; import { useLabel, useT, useUi } from '../../i18n'; import { sectionFrame } from '../../components/SectionTitle'; import { DateField } from '../../components/DateField'; +import { isBackendDump } from '../../notify/NotifyProvider'; /** * The old record pages ended with a collapsed "Events" card: who did what to the record and when, with a popup that @@ -49,6 +50,32 @@ function parseDetails(html: string): { oldData: Record; newData } } +const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']; +const two = (n: string | number) => String(n).padStart(2, '0'); +const stamp = (y: string, m: string, d: string, time?: string) => `${two(d)}/${two(m)}/${y}${time ? ` ${time}` : ''}`; + +/** + * The log keeps old / new values as the backend wrote them: dates come as 20240430, 20240430111412, "2024-04-30 00:00:00.0", + * {ts '2024-04-30 11:14:12'} or "April, 30 2024 11:14:12". They are shown as dd/mm/yyyy (with the time when there is one). + * Compact digits are only read as a date for a field named *DATE*, so phone and registration numbers stay as they are. + */ +export function formatLogValue(key: string, value: unknown): string { + if (value === null || value === undefined) return ''; + if (typeof value !== 'string') return String(value); + const s = value.trim(); + let m = s.match(/^\{ts '(\d{4})-(\d{2})-(\d{2})(?: (\d{2}:\d{2}:\d{2}))?(?:\.\d+)?'\}$/); + if (m) return stamp(m[1], m[2], m[3], m[4] && m[4] !== '00:00:00' ? m[4] : ''); + m = s.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}:\d{2}:\d{2}))?(?:\.\d+)?(?:Z)?$/); + if (m) return stamp(m[1], m[2], m[3], m[4] && m[4] !== '00:00:00' ? m[4] : ''); + m = s.match(/^([A-Za-z]+),? (\d{1,2}),? (\d{4})(?: (\d{2}:\d{2}:\d{2}))?$/); + if (m && MONTHS.includes(m[1].toLowerCase())) return stamp(m[3], String(MONTHS.indexOf(m[1].toLowerCase()) + 1), m[2], m[4] && m[4] !== '00:00:00' ? m[4] : ''); + m = s.match(/^(\d{4})(\d{2})(\d{2})(?:(\d{2})(\d{2})(\d{2}))?$/); + if (m && /DATE/i.test(key) && +m[2] >= 1 && +m[2] <= 12 && +m[3] >= 1 && +m[3] <= 31) { + return stamp(m[1], m[2], m[3], m[4] && `${m[4]}:${m[5]}:${m[6]}` !== '00:00:00' ? `${m[4]}:${m[5]}:${m[6]}` : ''); + } + return s; +} + export function EntityEvents({ entity, id }: { entity: string; id: string }) { const { config } = useAuth(); const t = useT(); @@ -131,7 +158,7 @@ export function EntityEvents({ entity, id }: { entity: string; id: string }) { {events.isPending && } - {events.error && {t((events.error as Error).message)}} + {events.error && {isBackendDump((events.error as Error).message) ? ui('backendFailed') : t((events.error as Error).message)}} {events.data && ( @@ -153,7 +180,7 @@ export function EntityEvents({ entity, id }: { entity: string; id: string }) { {r[1]}{r[2]} {kiosk && {hasKiosk(r) ? r[3] : ''}} - {rowDate(r)} + {formatLogValue('CREATION_DATE', rowDate(r))} {d && Object.keys(d.newData).length + Object.keys(d.oldData).length > 0 && ( @@ -195,8 +222,8 @@ export function EntityEvents({ entity, id }: { entity: string; id: string }) { {detail && Object.entries(detail.newData).map(([k, v]) => ( {lab(k)} - {detail.oldData[k] === undefined ? '' : String(detail.oldData[k])} - {String(v)} + {detail.oldData[k] === undefined ? '' : formatLogValue(k, detail.oldData[k])} + {formatLogValue(k, v)} ))} diff --git a/src/features/view/EntityView.tsx b/src/features/view/EntityView.tsx index d10b99e..c14b8e7 100644 --- a/src/features/view/EntityView.tsx +++ b/src/features/view/EntityView.tsx @@ -26,6 +26,7 @@ import { SubscriptionDetails } from './SubscriptionDetails'; import { actionNeedsEmail, isDangerous, isSimpleAction } from './actions'; import { FLEET_REQUEST_ORDER, fleetRequestView } from './fleetRequest'; import { PendingPayDialog } from '../gridActions/PendingPayDialog'; +import { isBackendDump } from '../../notify/NotifyProvider'; import { InvoiceSummary } from './InvoiceSummary'; import { EntityEvents } from './EntityEvents'; import { NewPasswordDialog, findNewPassword, isPasswordReset } from '../../components/NewPasswordDialog'; @@ -165,7 +166,8 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { 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) || v.a.ACTION_NAME === 'PRINT_WEIGHING_BRIDGE_DATA')) void downloadReport(file).catch((e) => notify.error(e)); + // (the old page took DATA.FILE for the invoice / print actions whatever its location) + if (file && (/downloadFiles/i.test(file) || ['PRINT_WEIGHING_BRIDGE_DATA', 'GET_INVOICE', 'PRINT'].includes(v.a.ACTION_NAME))) 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 ?? ''); @@ -215,6 +217,16 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { notify.warning('EMAIL_REQUIRED_FOR_ACTION', ui('emailRequiredForAction')); return; } + // registering a stakeholder re-saves its whole form on the backend, which breaks (it answers with an error dump instead of a + // message) when required data such as the manager's name or the phone numbers is missing: say what is missing first + if (a.ACTION_NAME === 'COMPLETE') { + const empty = (v: unknown) => v === undefined || v === null || String(v).trim() === '' || (Array.isArray(v) && !v.length); + const missing = fields.filter((f) => f.required && !f.hidden && !f.readOnly && f.type !== 'ATTACHMENT' && empty(data[f.name])).map((f) => lab(f.caption)); + if (missing.length) { + notify.warning(`${ui('missingRequiredData')} ${missing.join('، ')}`); + return; + } + } // printing only produces a file: no confirmation, like the old page if (a.ACTION_NAME === 'PRINT' || a.ACTION_NAME === 'GET_INVOICE' || a.ACTION_NAME === 'PRINT_WEIGHING_BRIDGE_DATA') { run.mutate({ a }); @@ -355,7 +367,7 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { {tab === 0 && ( - {entity === 'SUBSCRIPTIONS' && } + {entity === 'SUBSCRIPTIONS' && { void qc.invalidateQueries({ queryKey: ['grid', entity] }); void view.refetch(); }} />} {entity !== 'SUBSCRIPTIONS' && layout.sections.map((s) => { if (VIEW_HIDDEN_SECTIONS[entity]?.includes(s.title)) return null; const last = VIEW_LAST_FIELDS[entity] ?? []; @@ -524,7 +536,7 @@ export function EntityView({ entity, id }: { entity: string; id: string }) { {t(String(action?.ACTION_CAPTION_CODE ?? action?.ACTION_NAME ?? ''))} {t('CONFIRM_MSG')} - {run.error && {t((run.error as Error).message)}} + {run.error && {isBackendDump((run.error as Error).message) ? ui('backendFailed') : t((run.error as Error).message)}} diff --git a/src/features/view/SubscriptionDetails.tsx b/src/features/view/SubscriptionDetails.tsx index 35eea21..d05c547 100644 --- a/src/features/view/SubscriptionDetails.tsx +++ b/src/features/view/SubscriptionDetails.tsx @@ -1,12 +1,14 @@ -import { useQuery } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useMutation, useQuery } from '@tanstack/react-query'; import { SectionTitle, sectionFrame } from '../../components/SectionTitle'; import DOMPurify from 'dompurify'; -import { Box, Checkbox, FormControlLabel, Paper, Stack, Typography } from '@mui/material'; +import { Box, Button, Checkbox, FormControlLabel, MenuItem, Paper, Stack, TextField, Typography } from '@mui/material'; import { useAuth } from '../../auth/AuthContext'; +import { useNotify } from '../../notify/NotifyProvider'; import { useLabel, useT, useUi } from '../../i18n'; import { PlateBadge } from '../../components/PlateBadge'; -import { getOptions } from '../../api/entity'; -import { rpc } from '../../api/client'; +import { getOptions, runAction, type EntityAction } from '../../api/entity'; +import { ApiError, rpc } from '../../api/client'; type Data = Record; const s = (v: unknown) => String(v ?? '').trim(); @@ -50,8 +52,9 @@ function Item({ caption, children }: { caption: string; children: React.ReactNod } /** The old subscription page: package line, service data, the vehicle / permit / stakeholder block, stakeholder info and the invoice. */ -export function SubscriptionDetails({ data, label }: { data: Data; label: (field: string, code: unknown) => string }) { +export function SubscriptionDetails({ data, label, id, actions, onChanged }: { data: Data; label: (field: string, code: unknown) => string; id: string; actions?: EntityAction[]; onChanged?: () => void }) { const { user, lang } = useAuth(); + const notify = useNotify(); const lab = useLabel(); const t = useT(); const ui = useUi(); @@ -84,6 +87,41 @@ export function SubscriptionDetails({ data, label }: { data: Data; label: (field return o?.NAME || (o?.CAPTION_CODE ? t(o.CAPTION_CODE) : ''); })(); + // legacy: the Auto permit box is only live for the operations office on a contractual ("CNTR") subscription; ticking it asks for + // the industrial area and the investor, and the "Activate Auto Permit" action saves the choice (an unticked box switches it off) + const canEditAuto = role === 'OPOFF' && s(data.SERVICE_CODE) === 'CNTR' && !!actions?.some((a) => a.ACTION_NAME === 'UPDATE_CONTRACTUAL_SUBSCRIPTION'); + const [autoOn, setAutoOn] = useState(contractual); + const [autoEstate, setAutoEstate] = useState(estateId); + const [autoInvestor, setAutoInvestor] = useState(s(data.INDUSTRIAL_ESTATE_STAKEHOLDER_ID)); + const estates = useQuery({ + queryKey: ['sub-estates', s(data.CODE), s(data.SERVICE_CODE)], + queryFn: () => getOptions('getSubscriptionIndustrialEstates', { package_code: s(data.CODE), service_code: s(data.SERVICE_CODE) }), + enabled: canEditAuto, + staleTime: 5 * 60_000, + }); + const autoInvestors = useQuery({ + queryKey: ['sub-investors', autoEstate], + queryFn: () => getOptions('getInvestorsInLocation', { locationId: autoEstate }), + enabled: canEditAuto && autoOn && !!autoEstate, + staleTime: 5 * 60_000, + }); + const saveAuto = useMutation({ + meta: { loading: 'saving' }, + mutationFn: () => { + if (autoOn && (!autoEstate || !autoInvestor)) throw new ApiError('REQUIRED_FIELD'); + return runAction('SUBSCRIPTIONS', 'UPDATE_CONTRACTUAL_SUBSCRIPTION', { + CONTRACTUAL_SUBSCRIPTION: autoOn ? 'YES' : 'NO', + INDUSTRIAL_ESTATE_ID: autoOn ? autoEstate : '', + INDUSTRIAL_ESTATE_STAKEHOLDER_ID: autoOn ? autoInvestor : '', + }, id, []); + }, + onSuccess: (r) => { + notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved')); + onChanged?.(); + }, + onError: (e) => notify.error(e), + }); + const billing = s(data.BILLING_CODE); const finance = useQuery({ queryKey: ['sub-finance', billing], @@ -146,15 +184,38 @@ export function SubscriptionDetails({ data, label }: { data: Data; label: (field )} - - } - label={lab('CONTRACTUAL_SUBSCRIPTION')} - /> - + {canEditAuto ? ( + + { setAutoOn(e.target.checked); if (e.target.checked && !autoEstate) setAutoEstate(estateId); }} />} + label={lab('CONTRACTUAL_SUBSCRIPTION')} + /> + {autoOn && ( + + { setAutoEstate(e.target.value); setAutoInvestor(''); }}> + {(estates.data ?? []).map((o) => {o.NAME || t(o.CAPTION_CODE ?? String(o.CODE))})} + + setAutoInvestor(e.target.value)}> + {(autoInvestors.data ?? []).map((o) => {o.NAME || t(o.CAPTION_CODE ?? String(o.CODE))})} + + + )} + + + + + ) : ( + + } + label={lab('CONTRACTUAL_SUBSCRIPTION')} + /> + + )} - {contractual && ( + {!canEditAuto && contractual && ( {label('INDUSTRIAL_ESTATE_ID', estateId) || s(data.SUBSCRIPTION_LOCATION_NAME)} {investorName} diff --git a/src/features/view/WeighingDialog.tsx b/src/features/view/WeighingDialog.tsx index 382f4be..6e88a97 100644 --- a/src/features/view/WeighingDialog.tsx +++ b/src/features/view/WeighingDialog.tsx @@ -39,11 +39,13 @@ export function WeighingDialog({ entity, id, open, onClose }: { entity: string; 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][]; + // the bridge's analysis flags an axle that carries more than allowed (AXLE_n_WEIGHT_OVER = 1): the old page printed it in red + const analysis = (d[key === 'ENTRY' ? 'ANALYSEWEIGHINGDATA_IN' : 'ANALYSEWEIGHINGDATA_OUT'] ?? {}) as Reading; + const rows: [string, unknown, boolean][] = [ + [name('total'), d[`TOTAL_WEIGHT_${key}`], false] as [string, unknown, boolean], + [name('speed'), d[`SPEED_${key}`], false] as [string, unknown, boolean], + ...AXLES.map((n) => [`${name('axle')} ${n}`, d[`AXIAL_WEIGHT_AXLE_${n}_${key}`], Number(analysis[`AXLE_${n}_WEIGHT_OVER`]) === 1] as [string, unknown, boolean]), + ].filter(([, v]) => has(v)); return ( {title} @@ -52,10 +54,10 @@ export function WeighingDialog({ entity, id, open, onClose }: { entity: string; ) : (
- {rows.map(([label, v]) => ( + {rows.map(([label, v, over]) => ( - {label} - {String(v)} + {label} + {String(v)} ))} diff --git a/src/i18n/ui.ts b/src/i18n/ui.ts index 8e9c588..d55e260 100644 --- a/src/i18n/ui.ts +++ b/src/i18n/ui.ts @@ -137,6 +137,14 @@ export const UI = { en: 'This user has no email on file. Add one before using this action.', ar: 'لا يوجد بريد إلكتروني مسجل لهذا المستخدم. يرجى إضافته قبل استخدام هذا الإجراء.', }, + missingRequiredData: { + en: 'Required data is missing. Edit the record and fill in:', + ar: 'هناك بيانات مطلوبة ناقصة. عدّل السجل واملأ:', + }, + backendFailed: { + en: 'The system could not complete this action. Check that the record data is complete and try again.', + ar: 'تعذّر على النظام تنفيذ هذا الإجراء. تأكد من اكتمال بيانات السجل ثم حاول مرة أخرى.', + }, total: { en: 'Total', ar: 'الإجمالي' }, newToNafith: { en: 'New to Nafith@Madayn?', ar: 'جديد في نافذ@مدائن؟' }, signUp: { en: 'Sign up', ar: 'إنشاء حساب' }, diff --git a/src/notify/NotifyProvider.tsx b/src/notify/NotifyProvider.tsx index 43c544e..ebca5ec 100644 --- a/src/notify/NotifyProvider.tsx +++ b/src/notify/NotifyProvider.tsx @@ -1,6 +1,6 @@ import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'; import { Alert, Snackbar, type AlertColor } from '@mui/material'; -import { useT } from '../i18n'; +import { useT, useUi } from '../i18n'; interface Note { id: number; @@ -22,9 +22,13 @@ export const useNotify = () => useContext(Ctx); let seq = 0; +/** True for the raw error structure ColdFusion returns when the backend itself fails. */ +export const isBackendDump = (m: string) => /ErrNumber|StackTrace|Resolvedname|^struct\s/i.test(m); + /** Toasts for what the backend says: "saved successfully", validation failures, report ready… */ export function NotifyProvider({ children }: { children: ReactNode }) { const t = useT(); + const ui = useUi(); const [notes, setNotes] = useState([]); const push = useCallback((severity: AlertColor, text: string) => { @@ -47,9 +51,13 @@ export function NotifyProvider({ children }: { children: ReactNode }) { success: (code, fb) => push('success', say(code, fb)), warning: (code, fb) => push('warning', say(code, fb)), info: (code, fb) => push('info', say(code, fb)), - error: (e) => push('error', t(e instanceof Error ? e.message : String(e))), + error: (e) => { + const msg = e instanceof Error ? e.message : String(e); + // a ColdFusion error dump ("struct Detail … ErrNumber … StackTrace …") is never shown to the user + push('error', isBackendDump(msg) ? ui('backendFailed') : t(msg)); + }, }; - }, [push, t]); + }, [push, t, ui]); return (