import { useState } from 'react'; import { useMutation, useQuery } from '@tanstack/react-query'; import { SectionTitle, sectionFrame } from '../../components/SectionTitle'; import DOMPurify from 'dompurify'; 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, runAction, type EntityAction } from '../../api/entity'; import { ApiError, rpc } from '../../api/client'; type Data = Record; const s = (v: unknown) => String(v ?? '').trim(); const FINANCE_ROLES = ['OPOFF', 'SHIFT_SUPERVISOR', 'LOP_CC']; const SHOW_FINANCE = (role: string) => FINANCE_ROLES.includes(role); function Group({ title, code, children }: { title: string; code?: string; children: React.ReactNode }) { return ( {title} {children} ); } function Item({ caption, children }: { caption: string; children: React.ReactNode }) { const empty = children === undefined || children === null || children === ''; return ( {caption} {empty ? — : children} ); } /** The old subscription page: package line, service data, the vehicle / permit / stakeholder block, stakeholder info and the invoice. */ 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(); const L = lang === 'AR' ? 'AR' : 'EN'; const rtl = L === 'AR'; const role = String(user?.role_code ?? ''); const unowned = s(data.DRIVER_DOCUMENT_NATIONALITY) !== ''; const category = s(data.TARGETED_CATEGORY); const nonOmani = s(data.FLEET_NATIONALITY) !== 'OMN'; const plateCode = (prefix: string) => s(data[`${prefix}PLATE_CODE_${nonOmani ? 'AR' : L}`]) || s(data[`${prefix}PLATE_CODE_AR`]); const plate = (prefix: string) => { const n = s(data[`${prefix}PLATE_NUMBER`]); return n ? : ''; }; const title = `${s(data.CODE)} - ${s(data[`DESCRIPTION_${L}`])} / ${s(data.SERVICE_GROUP_CODE)} - ${s(data[`SERVICE_GROUP_NAME_${L}`])}`; const estateId = s(data.PERIODIC_SUBSCRIPTION_LOCATION_ID); const contractual = Number(data.CONTRACTUAL_SUBSCRIPTION) === 1; const investors = useQuery({ queryKey: ['sub-investors', estateId], queryFn: () => getOptions('getInvestorsInLocation', { locationId: estateId }), enabled: contractual && !!estateId, staleTime: 5 * 60_000, }); const investorName = (() => { const id = s(data.INDUSTRIAL_ESTATE_STAKEHOLDER_ID); const o = (investors.data ?? []).find((x) => String(x.CODE) === id); 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], queryFn: async () => { const r = await rpc<{ DATA?: { FINANCIAL_TRANSACTION_INFO?: string } }>('SUBSCRIPTIONS', 'FINANCIAL_TRANSACTION_INFO', { billing_code: billing }); return r.DATA?.FINANCIAL_TRANSACTION_INFO ?? ''; }, enabled: SHOW_FINANCE(role) && !!billing, staleTime: 60_000, }); const mobile = s(data.DRIVER_MOBILE_NUMBER); return ( {s(data[`SERVICE_DESCRIPTION_${L}`])} {s(data.ACTIVATION_DATE_GRID)} {s(data[`DURATION_${L}`])} {s(data.EXPIRY_DATE_GRID)} {/* the old page always listed the estate for a fleet's own subscription: the periodic one, else the package's */} {!unowned && ( {(estateId && label('INDUSTRIAL_ESTATE_ID', estateId)) || s(data.SUBSCRIPTION_LOCATION_NAME) || label('INDUSTRIAL_ESTATE_ID', data.PACKAGE_LOCATION_ID)} )} {unowned ? ( <> {label('FLEET_NATIONALITY', data.FLEET_NATIONALITY)} {label('TRAILER_TYPE', data.TRAILER_TYPE)} {plate('')} {label('CARGO_TYPE', data.CARGO_TYPE)} {plate('TRAILER_')} {label('OPERATION_TYPE', data.OPERATION_TYPE)} {label('DRIVER_DOCUMENT_NATIONALITY', data.DRIVER_DOCUMENT_NATIONALITY)} {s(data.DRIVER_NAME)} {label('DRIVER_DOCUMENT_TYPE', data.DRIVER_DOCUMENT_TYPE)} {label('DRIVER_NATIONALITY', data.DRIVER_NATIONALITY)} {s(data.DRIVER_DOCUMENT_NUMBER)} {mobile && {[label('DRIVER_MOBILE_AREA_CODE', data.DRIVER_MOBILE_AREA_CODE), mobile].filter(Boolean).join(' ')}} ) : category === 'PERMITS' ? ( {s(data.PERMIT_NUMBER)} ) : category === 'STAKEHOLDERS' ? ( {s(data.STAKEHOLDER_CRN)} ) : ( {plate('')} )} {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')} /> )} {!canEditAuto && contractual && ( {label('INDUSTRIAL_ESTATE_ID', estateId) || s(data.SUBSCRIPTION_LOCATION_NAME)} {investorName} )} {finance.data && ( {ui('financialInfo')} )} ); }