mams_frontend/src/features/forms/layouts.ts

287 lines
16 KiB
TypeScript

import { rpc } from '../../api/client';
import { getOptions, type Option } from '../../api/entity';
import type { AppConfig } from '../../api/config';
import generatedLayouts from './generated-layouts.json';
export interface Section {
title: string;
fields: string[];
}
/** A dropdown whose options depend on other fields and come from a CONFIG lookup. */
export interface DynamicLookup {
dependsOn: string;
/** a second field the lookup needs (e.g. the stakeholder type next to the stakeholder record) */
alsoOn?: string;
load: (parent: string, also?: string) => Promise<Option[]>;
}
export interface EntityLayout {
sections: Section[];
dynamic?: Record<string, DynamicLookup>;
/** form field -> key in the getView payload, where the backend names them differently */
alias?: Record<string, string>;
/** read-only pages: show this getView key instead of looking a dynamic dropdown up */
viewText?: Record<string, string>;
}
const STAKEHOLDER_NAMES: Record<string, string> = {
'7': 'INVESTORS',
'10': 'OWNERS',
'11': 'COMPANIES',
'12': 'OTHER_STAKEHOLDERS',
};
export const layouts: Record<string, EntityLayout> = {
USERS: {
sections: [
{
title: 'USERS_INFO',
fields: ['LOGIN', 'NAME', 'EMAIL', 'MOBILE', 'AREA_CODE', 'JOB_TITLE', 'LANGUAGE', 'STATUS_CODE', 'LOCATION_IDS', 'LAST_LOGIN_DATE'],
},
],
},
TRUCKS: {
sections: [
// License info leads, with the document nationality first in it: that picks whether FLEET_PLATE_CODE (Omani,
// dropdown) or PLATE_CODE_AR (other nationalities, free text) is the active plate-code field — see EntityForm's plate toggle.
// "Truck Info" and "Vehicle" are merged into one group, as requested.
{ title: 'LICENSEINFO', fields: ['LICENCE_NATIONALITY', 'LICENSE_EXPIRY_FROM', 'LICENSE_EXPIRY_TO', 'OPERATING_CARD_NO', 'CARD_EXPIRY_DATE', 'NOTES'] },
// legacy column order (three columns read row by row): stakeholder type / industrial area / stakeholder name first, then the vehicle data
{ title: 'TRUCKS_INFO', fields: ['RELATED_ENTITY_ID', 'LOCATION_IDS', 'RELATED_ENTITY_RECORD_ID', 'PLATE_NUMBER', 'FLEET_PLATE_CODE', 'PLATE_CODE_AR', 'USE_DESCRIPTION', 'PLATE_TYPE_CODE', 'TRUCK_TYPE', 'MODEL_YEAR', 'VEHICLE_TYPE', 'COLOR_CODE', 'SUBCOLOR', 'EXTREME_CAPACITY', 'ENGINE_CAPACITY', 'ORIGIN_COUNTRY_CODE', 'AXES_NUMBER', 'MANUFACTURING_YEAR', 'EMPTY_WEIGHT', 'ENGINE_NUMBER', 'CHASSES_NUMBER', 'PASSENGER_NUMBER', 'CREATED_BY_NAME', 'UPDATED_BY_NAME', 'LAST_UPDATE_DATE_GRID'] },
// the owner group is the same as the trailer's
{ title: 'OWNERINFO', fields: ['OWNER_NAME', 'NATIONALITY_CODE', 'GOVERNORATE_CODE', 'STATE_CODE', 'CITY_CODE', 'ADDRESS', 'NATIONALITY_LICENCE', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER'] },
{ title: 'INSURANCEINFO', fields: ['INSURANCE_DOCUMENT_NUMBER', 'INSURANCE_TYPE', 'INSURANCE_COMPANY', 'LICENSE_AUTHORITY', 'FIRST_REGISTRATION_DATE'] },
{ title: 'ATTACHMENTS', fields: ['TRUCK_LICENSE_FRONT', 'TRUCK_LICENSE_BACK', 'OWNER_LICENSE_FRONT', 'OWNER_LICENSE_BACK', 'AUTHORIZATION', 'CARD_EXPIRY_FRONT', 'CARD_EXPIRY_BACK'] },
],
alias: { FLEET_PLATE_CODE: 'PLATE_CODE_EN' },
viewText: { RELATED_ENTITY_RECORD_ID: 'OWNER_NAME' },
dynamic: {
STATE_CODE: { dependsOn: 'GOVERNORATE_CODE', load: (g) => getOptions('getLT_STATES', { GOVERNORATE_CODE: g }) },
CITY_CODE: { dependsOn: 'STATE_CODE', load: (s) => getOptions('getLT_CITY', { STATE_CODE: s }) },
RELATED_ENTITY_RECORD_ID: {
dependsOn: 'RELATED_ENTITY_ID',
load: (id) =>
STAKEHOLDER_NAMES[id]
? getOptions('getStakeHoldersList', { STAKEHOLDER_ID: id, STAKEHOLDER_NAME: STAKEHOLDER_NAMES[id] })
: Promise.resolve([]),
},
},
},
};
/** The vehicle modules: they share the plate-code rule and the "vehicle belongs to the stakeholder" owner tick box. */
export const FLEET_ENTITIES = ['TRUCKS', 'TRAILERS', 'EQUIPMENTS', 'BUSES', 'CARS'];
/** Values a new record starts with. A new vehicle's document nationality is Oman (the plate-code rule follows it). */
export const CREATE_DEFAULTS: Record<string, Record<string, string>> = Object.fromEntries(
FLEET_ENTITIES.map((e) => [e, { LICENCE_NATIONALITY: 'OMN' }]),
);
/** Fields the backend fills in itself: legacy hides them on the create page and shows them once the record exists. */
export const CREATE_HIDDEN: Record<string, string[]> = {
TROUBLE_SHOOTING: ['TS_NUMBER', 'GATE_ID', 'CREATION_DATE', 'PERMIT_NUMBER', 'PERMIT_STATUS_CODE'],
VIOLATIONS: ['TOTAL_SAME_REASON'],
// the "Employee info" / "Driver info" groups hold only backend-required extras the legacy create page never showed
PERSONNEL: ['ADDRESS', 'RESIDENCE_TYPE'],
// a new truck has no status yet; the backend sets it
TRUCKS: ['STATUS_CODE'],
// the old create pages hide the operation number: the system assigns it when the plan is saved
SCHEDULING_PLAN: ['OPERATION_NUMBER'],
WAITING_PLAN: ['OPERATION_NUMBER'],
OWNERS: ['PHONE_NUMBER', 'FAX_NUMBER', 'BILLING_ADDRESS'],
// the "Service provider info" group is backend-required extras the legacy create page never showed
OTHER_STAKEHOLDERS: ['CLASSIFICATION', 'SECONDARY_EMAIL', 'BILLING_ADDRESS', 'MANAGER_NAME'],
COMPLAINTS_SUGGESTIONS: ['REPLY'],
// a new ticket: no reply box, and none of the sender details or the support-side attachments (the system fills the
// sender in; the old page showed those two groups only to the Nafith side)
// a new entry permit request is the "stakeholder" shape: the driver and vehicle-plate fields and the driver / truck
// licence attachments belong to the mobile-app shape and the legacy create page hides them
FLEET_REQUEST: [
'OMANI_DRIVER_GRID', 'DRIVER_NAME', 'DRIVER_MOBILE_NUMBER', 'DRIVER_AREA_CODE', 'DRIVER_CN', 'LOCAL_VEHICLE_GRID', 'TRAILER_TYPE',
'PLATE_NUMBER', 'FLEET_PLATE_CODE', 'PLATE_CODE_AR', 'TRAILER_PLATE_NUMBER', 'TRAILER_PLATE_CODE', 'TRAILER_PLATE_CODE_AR',
'DRIVER_ID_FRONT', 'DRIVER_ID_BACK', 'TRUCK_LICENSE_FRONT', 'TRUCK_LICENSE_BACK',
],
// a new user: no status yet, and the industrial area and language are not asked on the create page
USERS: ['STATUS_CODE', 'LOCATION_IDS', 'LANGUAGE'],
COMPANIES: ['RIYADA_CARD_HOLDER'],
TICKETS: ['REPLY', 'TICKET_NUMBER', 'ENTITY_NAME', 'USER_TYPE', 'STAKEHOLDER_NAME', 'MOBILE_NUMBER', 'AREA_CODE', 'LOCATION_IDS', 'OPOFF_ATT_NO_1', 'OPOFF_ATT_NO_2', 'OPOFF_ATT_NO_3'],
};
/** Legacy pages that carry the "I confirm the data is correct" tick box for every user outside Nafith. */
export const CONFIRM_ENTITIES = [
'DEPOSITS', 'BUSES', 'CARS', 'COMPANIES', 'EQUIPMENTS', 'FAMILY_MEMBERS', 'FREEZONE_CLEARING_COMPANIES', 'FREEZONE_DEPOSITORS', 'INVESTORS',
'INVOICES', 'MFZ_PERMITS', 'NOTIFICATION_LOG', 'OTHER_STAKEHOLDERS', 'OWNERS', 'PARKING_YARD', 'PERMITS', 'PERSONNEL', 'RENTED_TRUCK',
'RFID_TAGS', 'TRAILERS', 'TRUCKS', 'VIOLATIONS', 'VISITORS_PERMITS', 'AVAILABLE_ON_PLATFORM', 'AVAILABLE_ON_PLATFORM_SEARCH',
];
/** Groups left out of the edit form (the record keeps its values; nothing in them is asked again). */
export const EDIT_HIDDEN_SECTIONS: Record<string, string[]> = {
COMPANIES: ['COMPANIES_INFO'],
OWNERS: ['OWNERS_INFO'],
// employees: the driver-licence group and the backend-required "Employee info" extras are not shown
PERSONNEL: ['LICENSEINFO', 'PERSONNEL_INFO'],
};
/** Single fields left out of the edit form (and the record page, see VIEW_HIDDEN_FIELDS). */
export const EDIT_HIDDEN_FIELDS: Record<string, string[]> = {
USERS: ['LOCATION_IDS'],
// the Riyada card value is a tick box of its own on the company form (operations office only)
COMPANIES: ['RIYADA_CARD_HOLDER'],
};
/** Fields that are mandatory on the create page although the role metadata does not flag them. */
export const CREATE_REQUIRED: Record<string, string[]> = { TICKETS: ['TICKET_TYPE', 'SUBJECT'] };
/** Whole groups the legacy record page does not show (driver info; investor capacity and investor info). */
export const VIEW_HIDDEN_SECTIONS: Record<string, string[]> = {
OWNERS: ['OWNERS_INFO'],
INVESTORS: ['CAPACITYINFO', 'INVESTORS_INFO'],
OTHER_STAKEHOLDERS: ['OTHER_STAKEHOLDERS_INFO'],
FREEZONE_DEPOSITORS: ['FREEZONE_DEPOSITORS_INFO'],
COMPANIES: ['COMPANIES_INFO'],
PERSONNEL: ['LICENSEINFO', 'PERSONNEL_INFO'],
// the reply box is a popup here; the answers are listed in their own table
TICKETS: ['ADD_REPLY'],
};
/** Fields that only apply to a non-Omani nationality (passport details), and the nationality field that decides it. */
export const NON_OMANI_ONLY: Record<string, { nationality: string; fields: string[]; attachment: string; notRequiredWith?: string }> = {
// legacy: a national number (NN) typed in makes the passport number/expiry optional
PERSONNEL: { nationality: 'NATIONALITY_CODE', fields: ['PASSPORT_NUMBER', 'PASSPORT_EXPIRY_DATE', 'PASSPORT_NOT_OMANI'], attachment: 'PASSPORT_NOT_OMANI', notRequiredWith: 'NN' },
};
/** Sections whose heading is left out of the create form (the fields stay). */
export const HIDDEN_CREATE_TITLES: Record<string, string> = { BLACKLISTS: 'BLACKLISTSINFO' };
/**
* The value a form field takes from the record when the backend names it differently (see `alias`). The backend returns
* language pairs (PLATE_CODE_EN / PLATE_CODE_AR) and the option lists carry the code in the session language, so the
* pair member of the session language is the one that matches an option.
*/
export const aliasSource = (src: string, lang: string) => (lang.toUpperCase() === 'AR' && src.endsWith('_EN') ? `${src.slice(0, -3)}_AR` : src);
export const hasLayout =(entity: string) => entity in layouts;
// ---------------------------------------------------------------------------------------------
// Every other module: the layout is generated from the legacy pages (scripts/gen-layouts.mjs) and
// completed from the backend's own field metadata. Hand-written layouts above win where they exist.
// ---------------------------------------------------------------------------------------------
const generated = generatedLayouts as Record<string, { title: string; fields: string[] }[]>;
const cache = new WeakMap<AppConfig, Map<string, EntityLayout | null>>();
type Row = { ENTITY_NAME: string; FIELD_NAME: string; FIELD_TYPE: string; REQUIRED?: string | number; DDL_VALUES?: Option[] };
/** The backend names some fields differently in the record it returns than in the form's metadata. */
const ENTITY_ALIAS: Record<string, Record<string, string>> = { POS_TRANSACTIONS: { RECEIPT_AMOUNT: 'AMOUNT' } };
/** A group that belongs right after another one (its title, then the title it follows). */
const SECTION_AFTER: Record<string, [string, string]> = { PERMITS: ['TRUCKS_INFO', 'PERMITS_INFO'] };
/** Fields the record page does not show, and fields it puts last in their group. */
export const VIEW_HIDDEN_FIELDS: Record<string, string[]> = {
DEPOSITS: ['RECEIPT_ID'],
// a vehicle's record page does not repeat the owner's identity document in the owner details
...Object.fromEntries(FLEET_ENTITIES.map((e) => [e, ['NATIONALITY_LICENCE', 'PERSONAL_DOCUMENT_TYPE', 'PERSONAL_DOC_NUMBER']])),
USERS: ['LOCATION_IDS'],
};
export const VIEW_LAST_FIELDS: Record<string, string[]> = { DEPOSITS: ['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' };
/** The layout of an entity, or undefined when neither the legacy page nor the backend know any fields. */
export function getLayout(entity: string, config: AppConfig | undefined): EntityLayout | undefined {
if (!config) return undefined;
let perConfig = cache.get(config);
if (!perConfig) cache.set(config, (perConfig = new Map()));
if (perConfig.has(entity)) return perConfig.get(entity) ?? undefined;
const built = build(entity, config);
perConfig.set(entity, built ?? null);
return built;
}
function build(entity: string, config: AppConfig): EntityLayout | undefined {
const rows = (config.ROLE_FIELD_STATUS_AUTHORITY_VIEW as unknown as Row[]).filter((r) => r.ENTITY_NAME === entity);
const known = new Map<string, Row[]>();
for (const r of rows) known.set(r.FIELD_NAME, [...(known.get(r.FIELD_NAME) ?? []), r]);
if (!known.size && !layouts[entity]) return undefined;
const hand = layouts[entity];
let sections: Section[];
if (hand) sections = hand.sections;
else {
// legacy page order first, then any required field the page did not mention
sections = (generated[entity] ?? []).map((s) => ({ title: s.title, fields: s.fields.filter((f) => known.has(f)) })).filter((s) => s.fields.length);
const placed = new Set(sections.flatMap((s) => s.fields));
const extra = [...known.keys()].filter((n) => !placed.has(n) && known.get(n)!.some((r) => r.REQUIRED === 'REQUIRED'));
if (!sections.length) sections = [{ title: `${entity}_INFO`, fields: [...known.keys()] }];
else if (extra.length) sections.push({ title: EXTRA_TITLE[entity] ?? `${entity}_INFO`, fields: extra });
}
// fleet entities (trucks, trailers, equipment, buses, cars): the document nationality sits in License info, the
// first group, and drives which plate-code field shows (see EntityForm's plate toggle)
const names = new Set(sections.flatMap((s) => s.fields));
const options = (n: string) => known.get(n)?.find((r) => r.DDL_VALUES?.length)?.DDL_VALUES ?? [];
// FLEET_PLATE_CODE is the form's name for the field; the backend's own view returns it as PLATE_CODE_EN
const alias: Record<string, string> = { ...(hand?.alias ?? {}), ...(ENTITY_ALIAS[entity] ?? {}) };
const after = SECTION_AFTER[entity];
if (after) {
const from = sections.findIndex((s) => s.title === after[0]);
if (from > 0) {
const [moved] = sections.splice(from, 1);
sections.splice(sections.findIndex((s) => s.title === after[1]) + 1, 0, moved);
}
}
if (names.has('FLEET_PLATE_CODE') && !alias.FLEET_PLATE_CODE) alias.FLEET_PLATE_CODE = 'PLATE_CODE_EN';
const dynamic: Record<string, DynamicLookup> = { ...(hand?.dynamic ?? {}) };
// owner / stakeholder pickers: <X>_RECORD_ID is filled from the type chosen in <X>_ID
for (const n of names) {
if (dynamic[n] || !n.endsWith('_RECORD_ID') || options(n).length) continue;
const twin = n.replace(/_RECORD_ID$/, '_ID');
const kinds = options(twin);
if (!names.has(twin) || !kinds.length) continue;
dynamic[n] = {
dependsOn: twin,
load: (id) => {
const kind = kinds.find((o) => String(o.CODE) === id)?.CAPTION_CODE;
return kind ? getOptions('getStakeHoldersList', { STAKEHOLDER_ID: id, STAKEHOLDER_NAME: kind }) : Promise.resolve([]);
},
};
}
// governorate -> state -> city
if (names.has('GOVERNORATE_CODE') && names.has('STATE_CODE') && !dynamic.STATE_CODE) {
dynamic.STATE_CODE = { dependsOn: 'GOVERNORATE_CODE', load: (g) => getOptions('getLT_STATES', { GOVERNORATE_CODE: g }) };
}
if (names.has('STATE_CODE') && names.has('CITY_CODE') && !dynamic.CITY_CODE) {
dynamic.CITY_CODE = { dependsOn: 'STATE_CODE', load: (s) => getOptions('getLT_CITY', { STATE_CODE: s }) };
}
// pickers the legacy pages filled by hand with their own backend calls
for (const [field, lookup] of Object.entries(ENTITY_LOOKUPS[entity] ?? {})) {
if (names.has(field) && !dynamic[field]) dynamic[field] = lookup;
}
return { ...hand, sections, dynamic, alias };
}
const ENTITY_LOOKUPS: Record<string, Record<string, DynamicLookup>> = {
// investors that hold the chosen industrial area
RENTED_TRUCK: {
INVESTOR_RECORD_ID: { dependsOn: 'LOCATION_IDS', load: (loc) => getOptions('getInvestorsInLocation', { locationId: loc }) },
},
// the user's own trucks that are not already affiliated to the chosen receiver ("<entity id>_<record id>")
AFFILIATION: {
TRUCK_ID: {
dependsOn: 'RECEIVER_RELATED_ENTITY_RECORD_ID',
alsoOn: 'RECEIVER_RELATED_ENTITY_ID',
load: (record, kind) =>
rpc<Option[]>('AFFILIATION', 'getTrucksID', {
DATA: { RELATED_ENTITY_ID: kind ?? '', RELATED_ENTITY_RECORD_ID: record, ID: 0, TRUCK_ID: 0 },
}),
},
},
};