import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, GlobalStyles, MenuItem, Stack, Tab, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tabs, TextField, Typography, } from '@mui/material'; import AddIcon from '@mui/icons-material/Add'; import AssignmentIcon from '@mui/icons-material/Assignment'; import BadgeIcon from '@mui/icons-material/Badge'; import BlockIcon from '@mui/icons-material/Block'; import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined'; import CheckCircleOutlinedIcon from '@mui/icons-material/CheckCircleOutlined'; import EditIcon from '@mui/icons-material/Edit'; import HistoryIcon from '@mui/icons-material/History'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import PhoneCallbackIcon from '@mui/icons-material/PhoneCallback'; import PhoneInTalkIcon from '@mui/icons-material/PhoneInTalk'; import PhoneDisabledIcon from '@mui/icons-material/PhoneDisabled'; import PrintIcon from '@mui/icons-material/Print'; import RestoreIcon from '@mui/icons-material/Restore'; import RvHookupIcon from '@mui/icons-material/RvHookup'; import SwapHorizIcon from '@mui/icons-material/SwapHoriz'; import UndoIcon from '@mui/icons-material/Undo'; import SearchIcon from '@mui/icons-material/Search'; import SaveIcon from '@mui/icons-material/Save'; import AltRouteIcon from '@mui/icons-material/AltRoute'; import EditNoteIcon from '@mui/icons-material/EditNote'; import LockIcon from '@mui/icons-material/Lock'; import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck'; import ScaleIcon from '@mui/icons-material/Scale'; import { DataGrid } from '@/components/DataGrid'; import { FormCard, FormGrid } from '@/components/FormCard'; // the shared framed section look (see components/SectionPaper): every Paper on the permit screens uses it import { SectionPaper as Paper } from '@/components/SectionPaper'; import { ViewItem } from '@/components/ViewItem'; import { EmptyState } from '@/components/EmptyState'; import { LoadingBanner } from '@/components/LoadingBanner'; import { PageHeader } from '@/components/PageHeader'; import { SectionTitle } from '@/components/SectionTitle'; import { StatusChip } from '@/components/StatusChip'; import { formatDate, formatNumber } from '@/components/meta/format'; import { elementToPdfUrl, type PdfOrientation } from '@/lib/pdf'; import { useFeatureUi } from '@/i18n/useUi'; import { useAuth } from '@/providers/AuthProvider'; import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution, useActivateOrders, useActivation, useAddToQueue, useVoiceCall, useAssignByPn, useClosePermit, useDistribute, useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, useRevokeAllRequested, useSingleTruck, useSubmitOrder, useUpdateOrder, useWeighbridgeManual, } from './api'; import { actionLabel, permitGrid, permitRowActions, permitStatuses, shipmentModeOptions } from './meta/permits'; import strings from './strings'; import { AcceptSlip, InSlip, OutSlip } from './slips'; import type { PermitListItem, TruckDistribution } from './types'; /** Legacy role gates (src/NTP.Application/Grains/Permits/PermitSupport.cs GrainsRoles). */ export const OPERATORS = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'CO']; export const SUPERVISORS = ['SU', 'GPO', 'GNSU', 'GTO', 'CO']; export const WEIGHBRIDGE_ROLES = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'CO', 'GATEIN', 'GATEOUT', 'THRU']; const PHONE_REASONS: { value: string; en: string; ar: string }[] = [ { value: 'لايمكن الاتصال به', en: 'Cannot be reached', ar: 'لايمكن الاتصال به' }, { value: 'رقم الهاتف غير صحيح', en: 'Wrong phone number', ar: 'رقم الهاتف غير صحيح' }, { value: 'الهاتف مغلق', en: 'Phone switched off', ar: 'الهاتف مغلق' }, { value: 'قائمة الانتظار', en: 'Waiting list', ar: 'قائمة الانتظار' }, { value: 'لايرد', en: 'No answer', ar: 'لايرد' }, { value: 'غير موافق', en: 'Does not agree', ar: 'غير موافق' }, { value: 'عدم الحضور بعد التسريب', en: 'Absent after release', ar: 'عدم الحضور بعد التسريب' }, { value: 'عدم الحضور بعد التوزيع', en: 'Absent after distribution', ar: 'عدم الحضور بعد التوزيع' }, { value: 'تجاوز عدد الإستنكافات المسموح بها', en: 'Exceeded the allowed absences', ar: 'تجاوز عدد الإستنكافات المسموح بها' }, ]; const EXPIRY_DAYS = [1, 2, 3, 4, 5, 14, 30]; const FIELD_SX = { width: '100%' } as const; function useRoles() { // Backend-driven (GET /auth/permissions): the role code decides on the server, not here. const { hasRole, can } = useAuth(); return { canCreate: can('grains.permits.create'), canAbsence: can('grains.permits.absence'), canClose: can('grains.permits.close'), canTruckOrder: can('grains.permits.truckOrder'), canTruckStatus: can('grains.permits.truckStatus'), canVoiceCall: can('grains.permits.voiceCall'), isSu: hasRole(['SU']), }; } /** Locale-aware number formatting in the current UI language. */ function useFmt() { const { lang } = useFeatureUi(strings); return (n: unknown) => formatNumber(n, lang); } const digits = (v: string) => v.replace(/[^0-9]/g, ''); const ltr = { htmlInput: { dir: 'ltr' as const } }; /** Small "type a number, press Enter" field used all over the legacy forms. */ function NumberField(props: { label: string; value: string; onChange: (v: string) => void; onEnter?: () => void; autoFocus?: boolean }) { return ( props.onChange(digits(e.target.value))} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); props.onEnter?.(); } }} slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }} /> ); } // ================================================================= reason dialog (cancel / revoke / phone reject) interface ReasonDialogProps { open: boolean; title: string; withExpiry?: boolean; free?: boolean; onClose: () => void; onSubmit: (reason: string, days: number) => void; } function ReasonDialog({ open, title, withExpiry, free, onClose, onSubmit }: ReasonDialogProps) { const { t, lang } = useFeatureUi(strings); const [reason, setReason] = useState(''); const [days, setDays] = useState(1); return ( {title} {free ? ( setReason(e.target.value)} /> ) : ( setReason(e.target.value)}> {PHONE_REASONS.map((r) => {lang === 'ar' ? r.ar : r.en})} )} {withExpiry && ( setDays(Number(e.target.value))}> {EXPIRY_DAYS.map((d) => {d})} )} ); } /** Shared state machine of the row/detail actions of a permit. */ function usePermitActions() { const { t, tr } = useFeatureUi(strings); const navigate = useNavigate(); const confirm = useConfirm(); const accept = usePermitAction('accept'); const revoke = usePermitAction('revoke'); const revokeAccepted = usePermitAction('revoke-accepted'); const convert = usePermitAction('convert-to-resd'); const reactivate = usePermitAction('reactivate'); const cancelOrder = usePermitAction('cancel-order'); const revokePermit = usePermitAction('revoke-permit'); const phoneAccept = usePermitAction('phone-accept'); const phoneReject = usePermitAction('phone-reject'); const [dialog, setDialog] = useState<{ kind: 'cancelOrder' | 'revokePermit' | 'phoneReject'; id: number } | null>(null); async function run(action: string, id: number, status: string | null) { const ask = async (key: Parameters[0], danger = false) => confirm({ message: t(key), danger }); switch (action) { case 'view': navigate(`/grains/permits/${id}`); break; case 'submit': case 'edit': navigate(`/grains/permits/${id}`, { state: { edit: true } }); break; // opens the edit form case 'accept': if (await ask('pm.confirm.accept')) accept.mutate({ id }); break; case 'reject': if (await ask('pm.confirm.revoke', true)) revoke.mutate({ id }); break; case 'revokeAccepted': if (await ask('pm.confirm.revokeAccepted', true)) revokeAccepted.mutate({ id }); break; case 'convertToResd': if (await ask('pm.confirm.convert')) convert.mutate({ id }); break; case 'reactivate': if (await ask('pm.confirm.reactivate')) reactivate.mutate({ id }); break; case 'phoneAccept': if (await ask('pm.confirm.phoneAccept')) phoneAccept.mutate({ id, body: {} }); break; case 'phoneReject': case 'cancelOrder': case 'revokePermit': setDialog({ kind: action, id }); break; case 'print': { // legacy: openWindow(printIn / printOut / acceptPrint .cfm) = a PDF in a new window. Must run synchronously inside the click. const kind = status === 'CLOSE' || status === 'ACTRL' || status === 'CLRPR' ? 'in' : 'accept'; window.open(`/grains/permits/${id}/print/${kind}?pdf=1`, '_blank'); break; } default: break; } } const element = dialog && ( setDialog(null)} onSubmit={(reason, days) => { const { id, kind } = dialog; setDialog(null); if (kind === 'cancelOrder') cancelOrder.mutate({ id, body: { reason } }); else if (kind === 'revokePermit') revokePermit.mutate({ id, body: { reason } }); else phoneReject.mutate({ id, body: { reason, expiryDays: days } }); }} /> ); return { run, element }; } // ================================================================= permit list (GNPermits.cfm) export function PermitsPage() { const { t, lang } = useFeatureUi(strings); const { user } = useAuth(); const { run, element } = usePermitActions(); const companyUser = Number(user?.stkId) === 62; // legacy session.stkid = 62 const showRevoked = String(user?.userId ?? '').toUpperCase() === 'GTOM1'; // legacy: only this login sees "ملغي" const meta = useMemo(() => { const h = { onAction: (a: string, r: PermitListItem) => void run(a, r.id, r.shipmentStatusCode) }; return { ...permitGrid(h, { companyUser, showRevoked }), rowActions: permitRowActions(h) }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [companyUser, showRevoked]); const { canCreate, canVoiceCall } = useRoles(); const add = useAddToQueue(); const voiceCall = useVoiceCall(); const confirm = useConfirm(); const [open, setOpen] = useState(false); const [tn, setTn] = useState(''); const [tt, setTt] = useState('BULK'); async function save() { if (!tn.trim() || !(await confirm({ message: t('pm.queue.confirm') }))) return; add.mutate({ tn: tn.trim(), tt, checkStatuses: false }, { onSuccess: (r) => { if (r.success) { setOpen(false); setTn(''); } } }); } return ( <> {canVoiceCall && ( )} {canCreate && } )} /> {element} setOpen(false)} fullWidth maxWidth="xs"> {t('pm.queue.add')} void save()} /> setTt(e.target.value)}> {shipmentModeOptions.map((o) => {typeof o.label === 'string' ? o.label : o.label[lang]})} ); } // ================================================================= permit details + order form (createGnOrder.cfm, viewPermitDetails.cfm) interface OrderValues { tn: string; trn: string; nnpn: string; name: string; dln: string; dled: string; opType: string } const emptyOrder: OrderValues = { tn: '', trn: '', nnpn: '', name: '', dln: '', dled: '', opType: 'IMPT' }; export function PermitDetailPage() { const fmt = useFmt(); const { t, tr, lang } = useFeatureUi(strings); const { id: idParam } = useParams(); const id = Number(idParam); const detail = usePermitDetail(id); const { run, element } = usePermitActions(); const submit = useSubmitOrder(); const update = useUpdateOrder(); const confirm = useConfirm(); const toast = useToast(); const [v, setV] = useState(emptyOrder); // The edit form is a dialog opened by the header button or by the row action (router state { edit: true }). const location = useLocation(); const [editing, setEditing] = useState(() => !!(location.state as { edit?: boolean } | null)?.edit); // Looked-up data of the trailer / driver typed in the form. undefined = unchanged (the permit's own data), null = not found. // 'pending' = the id was changed but not validated yet (validated when Enter is pressed). const [trailerLook, setTrailerLook] = useState> | null | undefined | 'pending'>(undefined); const [driverLook, setDriverLook] = useState> | null | undefined | 'pending'>(undefined); // A company turn (permit created from the company share) has no truck yet: the truck number is typed and validated like the trailer. const [truckLook, setTruckLook] = useState> | undefined | 'pending'>(undefined); const d = detail.data; const openEdit = () => { if (!d) return; setV({ tn: d.truck?.tn ?? '', trn: d.trailer?.tn ?? '', nnpn: d.driver?.nnpn ?? '', name: d.driver?.name ?? '', dln: d.driver?.dln ?? '', dled: d.driver?.dled ?? '', opType: d.operationTypeCode ?? 'IMPT', }); setTrailerLook(undefined); setDriverLook(undefined); setTruckLook(undefined); setEditing(true); }; // opened straight from the list: fill the form once the permit has loaded const [filled, setFilled] = useState(false); if (d && editing && !filled) { setFilled(true); openEdit(); } const trnTyped = v.trn.trim(); const nnpnTyped = v.nnpn.trim(); const ownTrn = d?.trailer?.tn ?? ''; const ownNnpn = d?.driver?.nnpn ?? ''; const ownTn = d?.truck?.tn ?? ''; if (detail.isLoading) return ; if (!d) return ; const canSubmit = d.actions.includes('submit'); const canEdit = d.actions.includes('edit'); const editable = canSubmit || canEdit; const set = (k: keyof OrderValues) => (e: { target: { value: string } }) => setV((p) => ({ ...p, [k]: e.target.value })); // what the form shows read-only for the typed trailer / driver const trailerShown = trailerLook === 'pending' ? null : trailerLook === undefined ? d.trailer : trailerLook; const driverShown = driverLook === 'pending' ? null : driverLook === undefined ? d.driver : driverLook; // Changing the trailer number / driver id clears the related data; Enter validates it and fills the data in. const changeTrailer = (e: { target: { value: string } }) => { const x = e.target.value; setV((p) => ({ ...p, trn: x })); setTrailerLook(x.trim() === ownTrn ? undefined : 'pending'); }; const changeDriver = (e: { target: { value: string } }) => { const x = e.target.value; setV((p) => ({ ...p, nnpn: x })); setDriverLook(x.trim() === ownNnpn ? undefined : 'pending'); }; async function checkTrailer() { if (!trnTyped || trailerLook !== 'pending') return; try { setTrailerLook((await fetchTrailer(trnTyped)) ?? null); } catch (e) { setTrailerLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } } async function checkDriver() { if (!nnpnTyped || driverLook !== 'pending') return; try { setDriverLook((await fetchDriver(nnpnTyped)) ?? null); } catch (e) { setDriverLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } } const changeTruck = (e: { target: { value: string } }) => { const x = e.target.value; setV((p) => ({ ...p, tn: x })); setTruckLook(x.trim() ? 'pending' : undefined); }; async function checkTruck() { if (!v.tn.trim() || truckLook !== 'pending') return; try { setTruckLook((await fetchTruck(v.tn.trim())) ?? null); } catch (e) { setTruckLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } } const onEnter = (run: () => Promise) => (e: { key: string; preventDefault: () => void }) => { if (e.key === 'Enter') { e.preventDefault(); void run(); } }; const fdate = (x: string | null | undefined) => (x ? formatDate(x, lang) || x : ''); const truckOk = !!ownTn || (!!v.tn.trim() && !!truckLook && truckLook !== 'pending'); const complete = !!(truckOk && trnTyped && nnpnTyped && trailerShown && driverShown?.name && driverShown.dln && (canEdit && !canSubmit ? true : v.opType)); async function save() { if (!complete || !driverShown || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; // the truck never changes here; the driver data is the looked-up (or the permit's own) data of the typed id const body = { tn: (ownTn || v.tn).trim(), trn: trnTyped, nnpn: nnpnTyped, dln: (driverShown.dln ?? '').trim(), dled: driverShown.dled || null, name: (driverShown.name ?? '').trim(), }; const done = { onSuccess: () => setEditing(false) }; if (canSubmit) submit.mutate({ id, body: { ...body, opType: v.opType } }, done); else update.mutate({ id, body }, done); } const others = d.actions.filter((a) => !['view', 'submit', 'edit'].includes(a)); const fd = (x: string | null | undefined) => (x ? formatDate(x, lang) || x : null); const when = (x: string | null) => { if (!x) return ''; const dt = new Date(x); const p2 = (n: number) => String(n).padStart(2, '0'); return Number.isNaN(dt.getTime()) ? x : `${dt.getFullYear()}/${p2(dt.getMonth() + 1)}/${p2(dt.getDate())} ${p2(dt.getHours())}:${p2(dt.getMinutes())}`; }; const cols = { display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))', lg: 'repeat(4, minmax(0, 1fr))' } } as const; // header buttons (top end side like the other record pages): the edit / submit toggle first, then the other actions const headerActions = ( <> {editable && ( )} {others.map((a) => ( ))} ); return ( <> } actions={headerActions} backTo="/grains/permits" /> {d.pn} {d.queueNo} {d.shift} {d.cargoType} {d.truck?.tn} {d.truck?.chasesNumber} {d.truck?.axials} {fd(d.truck?.regDate)} {d.trailer?.tn} {d.trailer?.chasesNumber} {d.operationType} {d.trailer?.axials} {fd(d.trailer?.regDate)} {d.driver?.nnpn} {d.driver?.name} {d.driver?.dln} {fd(d.driver?.dled)} setEditing(false)} fullWidth maxWidth="sm"> {t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')} {/* the truck is fixed; only the trailer number and the driver id can change, the rest follows from them */} {ownTn ? ( ) : ( )} {canSubmit && !d.operationTypeCode ? ( {lang === 'ar' ? 'محمل' : 'Loaded'} {lang === 'ar' ? 'فارغ' : 'Empty'} ) : ( )} {t('pm.events.type')} {t('pm.events.by')} {t('pm.events.status')} {t('pm.events.date')} {t('pm.events.weight')} {t('pm.events.remarks')} {d.events.map((e, i) => ( {e.eventCaption ?? e.eventType} {e.doneBy} {e.currentStatus} {when(e.eventDate)} {e.weight === null ? '' : fmt(e.weight)} {e.remarks} ))} {d.events.length === 0 && {tr({ en: 'No movements', ar: 'لا توجد حركات' })}}
{element} ); } /** Header buttons of the permit page: icon per action; the destructive ones are red. */ const ACTION_ICONS: Record = { print: , accept: , reject: , revokeAccepted: , convertToResd: , phoneAccept: , phoneReject: , cancelOrder: , revokePermit: , reactivate: , }; const DANGER_ACTIONS = new Set(['reject', 'revokeAccepted', 'phoneReject', 'cancelOrder', 'revokePermit']); function Info({ label, children, ltr: isLtr }: { label: string; children?: ReactNode; ltr?: boolean }) { return ( {children ? (isLtr ? {children} : children) : null} ); } // ================================================================= destinations (assginggdest / ManualInput / activateOrders) function AssignByPn() { const { t, lang } = useFeatureUi(strings); const groups = useLocationGroups(); const assign = useAssignByPn(); const confirm = useConfirm(); const [pn, setPn] = useState(''); const [dest, setDest] = useState(''); const [mode, setMode] = useState(''); const cargo = [{ id: 38, ar: 'قمح سائب', en: 'Wheat bulk' }, { id: 39, ar: 'شعير سائب', en: 'Barley bulk' }, { id: 40, ar: 'قمح مشول', en: 'Wheat packed' }, { id: 41, ar: 'شعير مشول', en: 'Barley packed' }]; const locations = [...(groups.data?.packed ?? []), ...(groups.data?.bulk ?? []), ...(groups.data?.bulkGallab ?? [])]; async function save() { if (!pn || !dest || !mode || !(await confirm({ message: t('pm.dest.confirm') }))) return; assign.mutate({ pn, destId: Number(dest), shipmentMode: Number(mode) }); } return ( } disabled={!pn || !dest || !mode} onClick={() => void save()}>{t('common.save')}} > setMode(e.target.value)}> {cargo.map((c) => {lang === 'ar' ? c.ar : c.en})} setDest(e.target.value)}> {locations.map((l) => {l.name})} ); } /** Label beside its field (legacy manual-input screen). */ function MiRow({ label, children }: { label: string; children: ReactNode }) { return ( {label} {children} ); } function ManualInput() { const { t } = useFeatureUi(strings); const dates = useOrderDates(); const manual = useManualInput(); const confirm = useConfirm(); const toast = useToast(); const [pn, setPn] = useState(''); const [date, setDate] = useState(''); const [orders, setOrders] = useState<{ orderId: number; name: string | null }[]>([]); const [orderId, setOrderId] = useState(''); const [ltw, setLtw] = useState(''); const [lgw, setLgw] = useState(''); async function loadOrders(d: string) { setDate(d); setOrderId(''); if (!pn || !d) return; try { const rows = await fetchAllowedDestinations(pn, d); setOrders(rows.filter((r) => r.orderId > 0)); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } } async function loadAlt() { if (!pn || !date) return; try { setOrders((await fetchOrdersForPermit(pn, date)).map((o) => ({ orderId: o.id, name: o.destName }))); } catch { /* shown by the client */ } } const valid = pn && date && orderId && ltw && lgw; async function save() { if (!valid || !(await confirm({ message: t('pm.manual.confirm') }))) return; manual.mutate({ pn, orderId: Number(orderId), orderDate: date, ltw: Number(ltw), lgw: Number(lgw) }); } return ( )} > void loadOrders(e.target.value)}> {(dates.data ?? []).map((d) => {d.split('-').reverse().join('/')})} setOrderId(e.target.value)} helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}> {orders.map((o) => {o.name})} ); } function Activation() { const fmt = useFmt(); const { t } = useFeatureUi(strings); const q = useActivation(); const activate = useActivateOrders(); const confirm = useConfirm(); const [checked, setChecked] = useState | null>(null); if (q.isLoading) return ; const rows = q.data ?? []; const sel = checked ?? new Set(rows.filter((r) => r.statusCode === 'ACTIVE').map((r) => `${r.locId}-${r.ctId}`)); const toggle = (k: string) => { const n = new Set(sel); if (n.has(k)) n.delete(k); else n.add(k); setChecked(n); }; async function save() { if (await confirm({ message: t('pm.activate.confirm') })) activate.mutate([...sel], { onSuccess: () => setChecked(null) }); } return ( } onClick={() => void save()}>{t('common.save')}} > {t('pm.activate.loc')}{t('pm.activate.cargo')} {t('pm.activate.total')}{t('pm.activate.used')} {rows.map((r) => { const k = `${r.locId}-${r.ctId}`; return ( toggle(k)} /> {r.loc}{r.ct} {fmt(r.total)}{fmt(r.used)} ); })}
); } // Three separate screens (each with its own menu entry and permission key), previously tabs of one page. export function DestinationsPage() { const { t } = useFeatureUi(strings); return ( <> ); } export function ManualInputPage() { const { t } = useFeatureUi(strings); return ( <> ); } export function ActivationPage() { const { t } = useFeatureUi(strings); return ( <> ); } // ================================================================= separate screens moved out of the tabs /** طلبية التموين (orders menu): distributed permits per destination type. */ export function SupplyOrderPage() { const { t } = useFeatureUi(strings); const pivot = useDistributionPivot(); return ( <> {t('pm.dist.company')}{t('pm.dist.silos')} {t('pm.dist.direct')}{t('pm.dist.packed')}{(pivot.data ?? []).map((r) => ( {r.company}{r.silos} {r.direct}{r.packed} ))}
); } /** اغلاق إرسالية (permits menu): close a permit manually. */ export function ClosePermitPage() { const { t } = useFeatureUi(strings); const closeP = useClosePermit(); const confirm = useConfirm(); const [pn, setPn] = useState(''); return ( <> } disabled={!pn} onClick={async () => { if (await confirm({ message: t('pm.wb.closeConfirm'), danger: true })) closeP.mutate(pn); }}>{t('pm.wb.close')} )} > ); } /** استعلام عن سيارة (permits menu). */ export function TruckInquiryPage() { const { t } = useFeatureUi(strings); return ( <> ); } // ================================================================= distribution function DistributeTab() { const fmt = useFmt(); const { t, lang } = useFeatureUi(strings); const distribute = useDistribute(); const confirm = useConfirm(); // confirm texts are the legacy ones (GNPermits.cfm), one per category const cats = [ { v: 'PCKD', en: 'Packed', ar: 'مشول', q: 'هل أنت متأكد من توزيع طلبية المشول لهذا اليوم؟' }, { v: 'BULK_AHALE', en: 'Bulk - individuals', ar: 'سائب - أفراد', q: 'هل أنت متأكد من توزيع طلبية سائب افراد لهذا اليوم؟' }, { v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات', q: 'هل أنت متأكد من توزيع طلبية سائب شركات لهذا اليوم؟' }, { v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد', q: 'هل أنت متأكد من توزيع طلبية قلاب أفراد لهذا اليوم؟' }, { v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات', q: 'هل أنت متأكد من توزيع طلبية قلاب شركات لهذا اليوم؟' }, ]; const [cat, setCat] = useState(''); // nothing preselected: a distribution run cannot be undone const summary = useDistributionSummary(); async function go() { const c = cats.find((x) => x.v === cat); if (!c) return; if (await confirm({ message: lang === 'ar' ? c.q : `Distribute today's ${c.en} order?` })) distribute.mutate(cat); } return ( setCat(e.target.value)}> {cats.map((c) => {lang === 'ar' ? c.ar : c.en})} {t('pm.dist.summary')} {t('pm.dist.company')}{t('pm.dist.count')}{(summary.data ?? []).map((r) => {r.comp}{fmt(r.cnt)})}
); } function ProcessTab() { const { t } = useFeatureUi(strings); const open = useProcessOpen(); const single = useSingleTruck(); const withDest = useProcessOpenWithDestination(); const revokeAll = useRevokeAllRequested(); const { isSu } = useRoles(); const confirm = useConfirm(); const toast = useToast(); const dates = useOrderDates(); const [tn, setTn] = useState(''); const [pn, setPn] = useState(''); const [orderId, setOrderId] = useState(''); const [date, setDate] = useState(''); const [reserved, setReserved] = useState(false); const [orders, setOrders] = useState<{ orderId: number; name: string | null }[]>([]); const [limit, setLimit] = useState(''); // legacy: the destination list is bound to the permit number and the order date (getAllowedDestinationsByDate) useEffect(() => { setOrderId(''); if (!pn || !date) { setOrders([]); return; } let live = true; fetchAllowedDestinations(pn, date) .then((rows) => { if (live) setOrders(rows.filter((r) => r.orderId > 0)); }) .catch((e) => { if (live) { setOrders([]); toast.error(e instanceof Error ? e.message : t('error.generic')); } }); return () => { live = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [pn, date]); return ( {t('pm.proc.byTruck')} {t('pm.proc.withDest')} setDate(e.target.value)}> {(dates.data ?? []).map((d) => {d.split('-').reverse().join('/')})} setOrderId(e.target.value)} helperText={orders.length === 0 && pn && date ? t('pm.manual.noOrders') : undefined}> {orders.map((o) => {o.name})} setReserved(e.target.checked)} /> {t('pm.proc.reserved')} {isSu && ( {t('pm.proc.revokeAll')} )} ); } function SearchTruckTab() { const { t } = useFeatureUi(strings); const toast = useToast(); const [tn, setTn] = useState(''); const [r, setR] = useState(null); async function go() { if (!tn) return; try { setR(await searchTruckDistribution(tn)); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } } return ( } disabled={!tn} onClick={() => void go()}>{t('common.search')}} > void go()} /> {r && ( {r.status} {r.companyLocations} {r.order} {`${r.trucksTotalQuantity} / ${r.tenderTotalQuantity}`} {r.errorMsg && {r.errorMsg}} )} ); } export function DistributionPage() { const { t } = useFeatureUi(strings); const [tab, setTab] = useState<'distribute' | 'process'>('distribute'); const { canTruckOrder } = useRoles(); return ( <> setTab(v)} variant="scrollable" sx={{ mb: 2 }}> {canTruckOrder && } {tab === 'distribute' && } {tab === 'process' && canTruckOrder && } ); } // ================================================================= weighbridges function ManualTab() { const { t } = useFeatureUi(strings); const save = useWeighbridgeManual(); const toast = useToast(); const { user } = useAuth(); const [tn, setTn] = useState(''); const loc = user?.locationId ? String(user.locationId) : ''; const [locInput, setLocInput] = useState(''); const [wi, setWi] = useState(''); const [wo, setWo] = useState(''); const [found, setFound] = useState<{ destination: string | null; message: string | null } | null>(null); const location = loc || locInput; async function find() { if (!tn) return; try { const r = await searchDestination(tn); setFound({ destination: r.destination, message: r.message }); } catch (e) { setFound(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } } const row = { display: 'grid', gridTemplateColumns: { xs: '1fr', sm: '140px minmax(0, 280px)' }, alignItems: 'center', gap: 1 } as const; return ( {t('pm.wb.truckNo')} { setTn(v); setFound(null); }} onEnter={() => void find()} /> {t('pm.wb.dest')} {found ? (found.destination ?? '-') : ''} {found?.message && {found.message}} } disabled={!tn || !location || !wi || !wo} onClick={() => save.mutate({ tn, locationId: Number(location), weightIn: Number(wi), weightOut: Number(wo) })}>{t('common.save')} )} > {!loc && ( {t('pm.wb.location')} )} {t('pm.wb.first')} {t('pm.wb.second')} ); } export function WeighbridgePage() { const { t } = useFeatureUi(strings); return ( <> ); } // ================================================================= print pages (acceptPrint / printIn / printOut) const printStyles = ( ); /** * Print sheet. With `?pdf=1` (opened by the Print action in a new tab) it renders the sheet to an A5 PDF (portrait for the * acceptance slip, landscape for the in/out slips, like legacy cfdocument) and replaces this tab with the PDF. * Without it the sheet is shown with a Print button (browser print dialog). */ function PrintShell({ title, children, loading, error, orientation, bare, width = 640 }: { title: string; children: ReactNode; loading: boolean; error: boolean; orientation: PdfOrientation; bare?: boolean; width?: number; }) { const { t } = useFeatureUi(strings); const [sp] = useSearchParams(); const wantsPdf = sp.get('pdf') === '1'; const sheet = useRef(null); const [pdfFailed, setPdfFailed] = useState(false); const [pdfUrl, setPdfUrl] = useState(null); useEffect(() => { if (!wantsPdf || loading || error || pdfFailed || pdfUrl || !sheet.current) return; let cancelled = false; // short timer (not requestAnimationFrame, which does not run in a background tab) so the sheet is laid out first const id = window.setTimeout(() => { elementToPdfUrl(sheet.current!, orientation).then( (url) => { if (cancelled) return; setPdfUrl(url); // full-screen frame below: works even where top-level blob navigation is blocked window.location.replace(url); // normal browsers: this tab becomes the PDF itself }, () => { if (!cancelled) setPdfFailed(true); }, ); }, 80); return () => { cancelled = true; window.clearTimeout(id); }; }, [wantsPdf, loading, error, pdfFailed, pdfUrl, orientation]); if (loading) return ; if (error) return {t('pm.print.failed')}; return ( <> {printStyles} {pdfUrl && ( )} {wantsPdf && !pdfFailed && !pdfUrl && {t('pm.print.generating')}} {pdfFailed && {t('pm.print.pdfFailed')}} {bare ? ( // data-pdf-literal: designed black on white, captured exactly as laid out (no theme neutralising) {children} ) : ( {title} {children} )} ); } export function PrintAcceptPage() { const { t } = useFeatureUi(strings); const id = Number(useParams().id); const q = usePrintAccept(id); const d = q.data; return ( {d && } ); } export function PrintInPage() { const { t } = useFeatureUi(strings); const id = Number(useParams().id); const q = usePrintIn(id); const d = q.data; return ( {d && } ); } export function PrintOutPage() { const { t } = useFeatureUi(strings); const id = Number(useParams().id); const q = usePrintOut(id); const d = q.data; return ( {d && } ); }