1136 lines
56 KiB
TypeScript
1136 lines
56 KiB
TypeScript
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 (
|
|
<TextField
|
|
size="small" sx={FIELD_SX} label={props.label} value={props.value} autoFocus={props.autoFocus}
|
|
onChange={(e) => 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 (
|
|
<Dialog open={open} onClose={onClose} fullWidth maxWidth="xs">
|
|
<DialogTitle>{title}</DialogTitle>
|
|
<DialogContent>
|
|
<Stack spacing={2} sx={{ pt: 1 }}>
|
|
{free ? (
|
|
<TextField size="small" sx={FIELD_SX} autoFocus multiline minRows={2} label={t('pm.reason')} value={reason} onChange={(e) => setReason(e.target.value)} />
|
|
) : (
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.reason')} value={reason} onChange={(e) => setReason(e.target.value)}>
|
|
{PHONE_REASONS.map((r) => <MenuItem key={r.value} value={r.value}>{lang === 'ar' ? r.ar : r.en}</MenuItem>)}
|
|
</TextField>
|
|
)}
|
|
{withExpiry && (
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.delayDays')} value={days} onChange={(e) => setDays(Number(e.target.value))}>
|
|
{EXPIRY_DAYS.map((d) => <MenuItem key={d} value={d}>{d}</MenuItem>)}
|
|
</TextField>
|
|
)}
|
|
</Stack>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button onClick={onClose}>{t('common.cancel')}</Button>
|
|
<Button variant="contained" disabled={!reason.trim()} onClick={() => { onSubmit(reason.trim(), days); setReason(''); }}>{t('common.save')}</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
/** 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<typeof t>[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 && (
|
|
<ReasonDialog
|
|
open
|
|
free={dialog.kind !== 'phoneReject'}
|
|
withExpiry={dialog.kind === 'phoneReject'}
|
|
title={tr(actionLabel(dialog.kind))}
|
|
onClose={() => 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 (
|
|
<>
|
|
<PageHeader
|
|
title={t('pm.list.title')} subtitle={t('pm.list.subtitle')}
|
|
actions={(
|
|
<>
|
|
{canVoiceCall && (
|
|
<Button
|
|
variant="outlined" startIcon={<PhoneInTalkIcon />} disabled={voiceCall.isPending}
|
|
onClick={async () => { if (await confirm({ message: t('pm.voice.confirm') })) voiceCall.mutate(); }}
|
|
>
|
|
{t('pm.voice.call')}
|
|
</Button>
|
|
)}
|
|
{canCreate && <Button variant="contained" startIcon={<AddIcon />} onClick={() => setOpen(true)}>{t('pm.queue.add')}</Button>}
|
|
</>
|
|
)}
|
|
/>
|
|
<DataGrid meta={meta} />
|
|
{element}
|
|
<Dialog open={open} onClose={() => setOpen(false)} fullWidth maxWidth="xs">
|
|
<DialogTitle>{t('pm.queue.add')}</DialogTitle>
|
|
<DialogContent>
|
|
<Stack spacing={2} sx={{ pt: 1 }}>
|
|
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void save()} />
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.queue.cargo')} value={tt} onChange={(e) => setTt(e.target.value)}>
|
|
{shipmentModeOptions.map((o) => <MenuItem key={String(o.value)} value={String(o.value)}>{typeof o.label === 'string' ? o.label : o.label[lang]}</MenuItem>)}
|
|
</TextField>
|
|
</Stack>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button onClick={() => setOpen(false)}>{t('common.cancel')}</Button>
|
|
<Button variant="contained" disabled={!tn.trim()} onClick={() => void save()}>{t('common.save')}</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ================================================================= 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<OrderValues>(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<Awaited<ReturnType<typeof fetchTrailer>> | null | undefined | 'pending'>(undefined);
|
|
const [driverLook, setDriverLook] = useState<Awaited<ReturnType<typeof fetchDriver>> | 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<Awaited<ReturnType<typeof fetchTruck>> | 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 <LoadingBanner />;
|
|
if (!d) return <EmptyState title={t('pm.notFound')} />;
|
|
|
|
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<void>) => (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 && (
|
|
<Button variant="contained" startIcon={<EditIcon />} onClick={openEdit}>
|
|
{tr(actionLabel(canSubmit ? 'submit' : 'edit'))}
|
|
</Button>
|
|
)}
|
|
{others.map((a) => (
|
|
<Button key={a} variant="outlined" color={DANGER_ACTIONS.has(a) ? 'error' : 'primary'} startIcon={ACTION_ICONS[a]} onClick={() => void run(a, id, d.statusCode)}>
|
|
{tr(actionLabel(a))}
|
|
</Button>
|
|
))}
|
|
</>
|
|
);
|
|
|
|
return (
|
|
<>
|
|
<PageHeader
|
|
title={t('pm.detail.title', { pn: d.pn ?? '' })}
|
|
subtitle={d.companyName ?? undefined}
|
|
status={<StatusChip value={d.statusCode} statuses={permitStatuses} size="medium" />}
|
|
actions={headerActions}
|
|
backTo="/grains/permits"
|
|
/>
|
|
<Stack spacing={2}>
|
|
<Paper sx={{ p: 2 }}>
|
|
<SectionTitle icon={AssignmentIcon} title={t('pm.detail.sectionPermit')} />
|
|
<Box sx={cols}>
|
|
<Info label={t('pm.detail.pn')} ltr>{d.pn}</Info>
|
|
<Info label={t('pm.detail.queueNo')} ltr>{d.queueNo}</Info>
|
|
<Info label={t('pm.detail.shift')}>{d.shift}</Info>
|
|
<Info label={t('pm.detail.cargo')}>{d.cargoType}</Info>
|
|
</Box>
|
|
</Paper>
|
|
|
|
<Paper sx={{ p: 2 }}>
|
|
<SectionTitle icon={LocalShippingIcon} title={t('pm.detail.sectionTruck')} />
|
|
<Box sx={cols}>
|
|
<Info label={t('pm.detail.truckNo')} ltr>{d.truck?.tn}</Info>
|
|
<Info label={t('pm.detail.chassis')} ltr>{d.truck?.chasesNumber}</Info>
|
|
<Info label={t('pm.detail.axles')}>{d.truck?.axials}</Info>
|
|
<Info label={t('pm.detail.licenseDate')} ltr>{fd(d.truck?.regDate)}</Info>
|
|
</Box>
|
|
</Paper>
|
|
|
|
<Paper sx={{ p: 2 }}>
|
|
<SectionTitle icon={RvHookupIcon} title={t('pm.detail.sectionTrailer')} />
|
|
<Box sx={cols}>
|
|
<Info label={t('pm.detail.trailerNo')} ltr>{d.trailer?.tn}</Info>
|
|
<Info label={t('pm.detail.chassis')} ltr>{d.trailer?.chasesNumber}</Info>
|
|
<Info label={t('pm.detail.operation')}>{d.operationType}</Info>
|
|
<Info label={t('pm.detail.axles')}>{d.trailer?.axials}</Info>
|
|
<Info label={t('pm.detail.licenseDate')} ltr>{fd(d.trailer?.regDate)}</Info>
|
|
</Box>
|
|
</Paper>
|
|
|
|
<Paper sx={{ p: 2 }}>
|
|
<SectionTitle icon={BadgeIcon} title={t('pm.detail.sectionDriver')} />
|
|
<Box sx={cols}>
|
|
<Info label={t('pm.detail.nnpn')} ltr>{d.driver?.nnpn}</Info>
|
|
<Info label={t('pm.detail.driverName')}>{d.driver?.name}</Info>
|
|
<Info label={t('pm.detail.licenseNo')} ltr>{d.driver?.dln}</Info>
|
|
<Info label={t('pm.detail.licenseExpiry')} ltr>{fd(d.driver?.dled)}</Info>
|
|
</Box>
|
|
</Paper>
|
|
|
|
<Dialog open={editable && editing} onClose={() => setEditing(false)} fullWidth maxWidth="sm">
|
|
<DialogTitle>{t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')}</DialogTitle>
|
|
<DialogContent>
|
|
<Box sx={{ display: 'grid', gap: 2, pt: 1, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))' } }}>
|
|
{/* the truck is fixed; only the trailer number and the driver id can change, the rest follows from them */}
|
|
{ownTn ? (
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.order.tn')} value={ownTn} disabled slotProps={ltr} />
|
|
) : (
|
|
<TextField size="small" sx={FIELD_SX} autoFocus label={t('pm.order.tn')} value={v.tn} onChange={changeTruck} onKeyDown={onEnter(checkTruck)} slotProps={ltr}
|
|
error={!!v.tn.trim() && truckLook === null} helperText={truckLook === 'pending' ? t('pm.order.pressEnter') : truckLook === null ? t('pm.order.notRegistered') : undefined} />
|
|
)}
|
|
{canSubmit && !d.operationTypeCode ? (
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.order.opType')} value={v.opType} onChange={set('opType')}>
|
|
<MenuItem value="IMPT">{lang === 'ar' ? 'محمل' : 'Loaded'}</MenuItem>
|
|
<MenuItem value="EXPT">{lang === 'ar' ? 'فارغ' : 'Empty'}</MenuItem>
|
|
</TextField>
|
|
) : (
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.order.opType')} value={d.operationType ?? ''} disabled />
|
|
)}
|
|
|
|
<TextField size="small" sx={FIELD_SX} autoFocus label={t('pm.order.trn')} value={v.trn} onChange={changeTrailer} onKeyDown={onEnter(checkTrailer)} slotProps={ltr}
|
|
error={!!trnTyped && trailerLook === null} helperText={trailerLook === 'pending' ? t('pm.order.pressEnter') : trailerLook === null ? t('pm.order.notRegistered') : undefined} />
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.detail.chassis')} value={trailerShown?.chasesNumber ?? ''} disabled slotProps={ltr} />
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.detail.axles')} value={trailerShown?.axials ?? ''} disabled />
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.detail.licenseDate')} value={fdate(trailerShown?.regDate)} disabled slotProps={ltr} />
|
|
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.order.nnpn')} value={v.nnpn} onChange={changeDriver} onKeyDown={onEnter(checkDriver)} slotProps={ltr}
|
|
error={!!nnpnTyped && driverLook === null} helperText={driverLook === 'pending' ? t('pm.order.pressEnter') : driverLook === null ? t('pm.order.driverMissing') : undefined} />
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.order.name')} value={driverShown?.name ?? ''} disabled />
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.order.dln')} value={driverShown?.dln ?? ''} disabled slotProps={ltr} />
|
|
<TextField size="small" sx={FIELD_SX} label={t('pm.order.dled')} value={fdate(driverShown?.dled)} disabled slotProps={ltr} />
|
|
</Box>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button color="inherit" onClick={() => setEditing(false)}>{t('common.cancel')}</Button>
|
|
<Button variant="contained" disabled={!complete} onClick={() => void save()}>{t(canSubmit ? 'pm.order.submit' : 'pm.order.update')}</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
|
|
<Paper sx={{ p: 2 }}>
|
|
<SectionTitle icon={HistoryIcon} title={t('pm.events.title')} />
|
|
<TableContainer>
|
|
<Table size="small">
|
|
<TableHead>
|
|
<TableRow>
|
|
<TableCell>{t('pm.events.type')}</TableCell>
|
|
<TableCell sx={{ display: { xs: 'none', sm: 'table-cell' } }}>{t('pm.events.by')}</TableCell>
|
|
<TableCell>{t('pm.events.status')}</TableCell>
|
|
<TableCell>{t('pm.events.date')}</TableCell>
|
|
<TableCell align="right">{t('pm.events.weight')}</TableCell>
|
|
<TableCell sx={{ display: { xs: 'none', md: 'table-cell' } }}>{t('pm.events.remarks')}</TableCell>
|
|
</TableRow>
|
|
</TableHead>
|
|
<TableBody>
|
|
{d.events.map((e, i) => (
|
|
<TableRow key={i}>
|
|
<TableCell>{e.eventCaption ?? e.eventType}</TableCell>
|
|
<TableCell sx={{ display: { xs: 'none', sm: 'table-cell' } }}>{e.doneBy}</TableCell>
|
|
<TableCell>{e.currentStatus}</TableCell>
|
|
<TableCell sx={{ whiteSpace: 'nowrap' }} dir="ltr">{when(e.eventDate)}</TableCell>
|
|
<TableCell align="right" dir="ltr">{e.weight === null ? '' : fmt(e.weight)}</TableCell>
|
|
<TableCell sx={{ display: { xs: 'none', md: 'table-cell' } }}>{e.remarks}</TableCell>
|
|
</TableRow>
|
|
))}
|
|
{d.events.length === 0 && <TableRow><TableCell colSpan={6}>{tr({ en: 'No movements', ar: 'لا توجد حركات' })}</TableCell></TableRow>}
|
|
</TableBody>
|
|
</Table>
|
|
</TableContainer>
|
|
</Paper>
|
|
</Stack>
|
|
{element}
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** Header buttons of the permit page: icon per action; the destructive ones are red. */
|
|
const ACTION_ICONS: Record<string, ReactNode> = {
|
|
print: <PrintIcon />, accept: <CheckCircleOutlinedIcon />, reject: <BlockIcon />, revokeAccepted: <UndoIcon />, convertToResd: <SwapHorizIcon />,
|
|
phoneAccept: <PhoneCallbackIcon />, phoneReject: <PhoneDisabledIcon />, cancelOrder: <CancelOutlinedIcon />, revokePermit: <CancelOutlinedIcon />,
|
|
reactivate: <RestoreIcon />,
|
|
};
|
|
const DANGER_ACTIONS = new Set(['reject', 'revokeAccepted', 'phoneReject', 'cancelOrder', 'revokePermit']);
|
|
|
|
function Info({ label, children, ltr: isLtr }: { label: string; children?: ReactNode; ltr?: boolean }) {
|
|
return (
|
|
<ViewItem label={label}>
|
|
{children ? (isLtr ? <bdi dir="ltr">{children}</bdi> : children) : null}
|
|
</ViewItem>
|
|
);
|
|
}
|
|
|
|
// ================================================================= 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 (
|
|
<FormCard
|
|
icon={AltRouteIcon} title={t('pm.form.permitData')}
|
|
actions={<Button variant="contained" startIcon={<SaveIcon />} disabled={!pn || !dest || !mode} onClick={() => void save()}>{t('common.save')}</Button>}
|
|
>
|
|
<FormGrid>
|
|
<NumberField autoFocus label={t('pm.order.pn')} value={pn} onChange={setPn} />
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.dest.cargo')} value={mode} onChange={(e) => setMode(e.target.value)}>
|
|
{cargo.map((c) => <MenuItem key={c.id} value={String(c.id)}>{lang === 'ar' ? c.ar : c.en}</MenuItem>)}
|
|
</TextField>
|
|
<Box sx={{ gridColumn: { md: '1 / -1' } }}>
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.dest.destination')} value={dest} onChange={(e) => setDest(e.target.value)}>
|
|
{locations.map((l) => <MenuItem key={l.id} value={String(l.id)}>{l.name}</MenuItem>)}
|
|
</TextField>
|
|
</Box>
|
|
</FormGrid>
|
|
</FormCard>
|
|
);
|
|
}
|
|
|
|
/** Label beside its field (legacy manual-input screen). */
|
|
function MiRow({ label, children }: { label: string; children: ReactNode }) {
|
|
return (
|
|
<Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', sm: '110px minmax(0, 1fr)' }, alignItems: 'center', gap: 1 }}>
|
|
<Typography sx={{ fontSize: 14 }}>{label}</Typography>
|
|
<Box>{children}</Box>
|
|
</Box>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<FormCard
|
|
icon={EditNoteIcon} title={t('pm.form.manualData')} maxWidth={860}
|
|
actions={(
|
|
<>
|
|
<Button variant="contained" startIcon={<SaveIcon />} disabled={!valid} onClick={() => void save()}>{t('common.save')}</Button>
|
|
<Button onClick={() => void loadAlt()} disabled={!pn || !date}>{t('pm.manual.altList')}</Button>
|
|
</>
|
|
)}
|
|
>
|
|
<Box sx={{ display: 'grid', gap: 1.75, columnGap: 4, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
|
|
<MiRow label={t('pm.manual.orderDate')}>
|
|
<TextField select size="small" sx={FIELD_SX} value={date} onChange={(e) => void loadOrders(e.target.value)}>
|
|
{(dates.data ?? []).map((d) => <MenuItem key={d} value={d}>{d.split('-').reverse().join('/')}</MenuItem>)}
|
|
</TextField>
|
|
</MiRow>
|
|
<Box />
|
|
<MiRow label={t('pm.order.pn')}><NumberField label="" value={pn} onChange={setPn} /></MiRow>
|
|
<MiRow label={t('pm.manual.order')}>
|
|
<TextField select size="small" sx={FIELD_SX} value={orderId} onChange={(e) => setOrderId(e.target.value)}
|
|
helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}>
|
|
{orders.map((o) => <MenuItem key={o.orderId} value={String(o.orderId)}>{o.name}</MenuItem>)}
|
|
</TextField>
|
|
</MiRow>
|
|
<MiRow label={t('pm.manual.ltw')}><NumberField label="" value={ltw} onChange={setLtw} /></MiRow>
|
|
<MiRow label={t('pm.manual.lgw')}><NumberField label="" value={lgw} onChange={setLgw} /></MiRow>
|
|
</Box>
|
|
</FormCard>
|
|
);
|
|
}
|
|
|
|
function Activation() {
|
|
const fmt = useFmt();
|
|
const { t } = useFeatureUi(strings);
|
|
const q = useActivation();
|
|
const activate = useActivateOrders();
|
|
const confirm = useConfirm();
|
|
const [checked, setChecked] = useState<Set<string> | null>(null);
|
|
if (q.isLoading) return <LoadingBanner />;
|
|
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 (
|
|
<FormCard
|
|
icon={PlaylistAddCheckIcon} title={t('pm.activation.title')} maxWidth={920}
|
|
actions={<Button variant="contained" startIcon={<SaveIcon />} onClick={() => void save()}>{t('common.save')}</Button>}
|
|
>
|
|
<TableContainer sx={{ border: 1, borderColor: 'divider', borderRadius: 1.5 }}>
|
|
<Table size="small">
|
|
<TableHead sx={{ bgcolor: 'action.hover' }}>
|
|
<TableRow><TableCell /><TableCell>{t('pm.activate.loc')}</TableCell><TableCell>{t('pm.activate.cargo')}</TableCell>
|
|
<TableCell align="center">{t('pm.activate.total')}</TableCell><TableCell align="center">{t('pm.activate.used')}</TableCell></TableRow>
|
|
</TableHead>
|
|
<TableBody>
|
|
{rows.map((r) => {
|
|
const k = `${r.locId}-${r.ctId}`;
|
|
return (
|
|
<TableRow key={k} hover>
|
|
<TableCell padding="checkbox"><Checkbox checked={sel.has(k)} disabled={r.total === 0} onChange={() => toggle(k)} /></TableCell>
|
|
<TableCell>{r.loc}</TableCell><TableCell>{r.ct}</TableCell>
|
|
<TableCell align="center" dir="ltr">{fmt(r.total)}</TableCell><TableCell align="center" dir="ltr">{fmt(r.used)}</TableCell>
|
|
</TableRow>
|
|
);
|
|
})}
|
|
</TableBody>
|
|
</Table>
|
|
</TableContainer>
|
|
</FormCard>
|
|
);
|
|
}
|
|
|
|
// 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 (
|
|
<>
|
|
<PageHeader title={t('pm.dest.title')} subtitle={t('pm.dest.subtitle')} />
|
|
<AssignByPn />
|
|
</>
|
|
);
|
|
}
|
|
|
|
export function ManualInputPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
return (
|
|
<>
|
|
<PageHeader title={t('pm.manual.title')} subtitle={t('pm.manual.subtitle')} />
|
|
<ManualInput />
|
|
</>
|
|
);
|
|
}
|
|
|
|
export function ActivationPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
return (
|
|
<>
|
|
<PageHeader title={t('pm.activation.title')} subtitle={t('pm.activation.subtitle')} />
|
|
<Activation />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ================================================================= 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 (
|
|
<>
|
|
<PageHeader title={t('pm.supply.title')} subtitle={t('pm.supply.subtitle')} />
|
|
<Paper variant="outlined" sx={{ p: 2 }}>
|
|
<Table size="small">
|
|
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="center">{t('pm.dist.silos')}</TableCell>
|
|
<TableCell align="center">{t('pm.dist.direct')}</TableCell><TableCell align="center">{t('pm.dist.packed')}</TableCell></TableRow></TableHead>
|
|
<TableBody>{(pivot.data ?? []).map((r) => (
|
|
<TableRow key={r.companyCode ?? 0}><TableCell>{r.company}</TableCell><TableCell align="center" dir="ltr">{r.silos}</TableCell>
|
|
<TableCell align="center" dir="ltr">{r.direct}</TableCell><TableCell align="center" dir="ltr">{r.packed}</TableCell></TableRow>
|
|
))}</TableBody>
|
|
</Table>
|
|
</Paper>
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** اغلاق إرسالية (permits menu): close a permit manually. */
|
|
export function ClosePermitPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
const closeP = useClosePermit();
|
|
const confirm = useConfirm();
|
|
const [pn, setPn] = useState('');
|
|
return (
|
|
<>
|
|
<PageHeader title={t('pm.close.title')} subtitle={t('pm.close.subtitle')} />
|
|
<FormCard
|
|
icon={LockIcon} title={t('pm.form.permitData')} maxWidth={520}
|
|
actions={(
|
|
<Button variant="contained" color="error" startIcon={<LockIcon />} disabled={!pn}
|
|
onClick={async () => { if (await confirm({ message: t('pm.wb.closeConfirm'), danger: true })) closeP.mutate(pn); }}>{t('pm.wb.close')}</Button>
|
|
)}
|
|
>
|
|
<NumberField autoFocus label={t('pm.order.pn')} value={pn} onChange={setPn} />
|
|
</FormCard>
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** استعلام عن سيارة (permits menu). */
|
|
export function TruckInquiryPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
return (
|
|
<>
|
|
<PageHeader title={t('pm.dist.tabSearch')} subtitle={t('pm.inquiry.subtitle')} />
|
|
<SearchTruckTab />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ================================================================= 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 (
|
|
<Stack spacing={3}>
|
|
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ maxWidth: 560 }}>
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.dist.category')} value={cat} onChange={(e) => setCat(e.target.value)}>
|
|
{cats.map((c) => <MenuItem key={c.v} value={c.v}>{lang === 'ar' ? c.ar : c.en}</MenuItem>)}
|
|
</TextField>
|
|
<Button variant="contained" disabled={!cat || distribute.isPending} onClick={() => void go()} sx={{ whiteSpace: 'nowrap' }}>{t('pm.dist.run')}</Button>
|
|
</Stack>
|
|
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: '1fr' }}>
|
|
<Paper sx={{ p: 2 }}>
|
|
<Typography variant="subtitle1" sx={{ mb: 1 }}>{t('pm.dist.summary')}</Typography>
|
|
<Table size="small">
|
|
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="center">{t('pm.dist.count')}</TableCell></TableRow></TableHead>
|
|
<TableBody>{(summary.data ?? []).map((r) => <TableRow key={r.companyCode ?? 0}><TableCell>{r.comp}</TableCell><TableCell align="center" dir="ltr">{fmt(r.cnt)}</TableCell></TableRow>)}</TableBody>
|
|
</Table>
|
|
</Paper>
|
|
</Box>
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<Stack spacing={3} sx={{ maxWidth: 520 }}>
|
|
<Paper sx={{ p: 2 }}>
|
|
<Stack spacing={2}>
|
|
<Typography variant="subtitle1">{t('pm.proc.byTruck')}</Typography>
|
|
<NumberField label={t('pm.order.tn')} value={tn} onChange={setTn} />
|
|
<Stack direction="row" spacing={1}>
|
|
<Button variant="contained" disabled={!tn} onClick={async () => { if (await confirm({ message: t('pm.proc.confirm') })) open.mutate({ tn, cargoType: null, saveScrn: true }); }}>{t('pm.proc.autoOrder')}</Button>
|
|
<Button disabled={!tn} onClick={async () => { if (await confirm({ message: t('pm.proc.confirm') })) single.mutate(tn); }}>{t('pm.proc.single')}</Button>
|
|
</Stack>
|
|
</Stack>
|
|
</Paper>
|
|
<Paper sx={{ p: 2 }}>
|
|
<Stack spacing={2}>
|
|
<Typography variant="subtitle1">{t('pm.proc.withDest')}</Typography>
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.manual.orderDate')} value={date} onChange={(e) => setDate(e.target.value)}>
|
|
{(dates.data ?? []).map((d) => <MenuItem key={d} value={d}>{d.split('-').reverse().join('/')}</MenuItem>)}
|
|
</TextField>
|
|
<NumberField label={t('pm.order.pn')} value={pn} onChange={setPn} />
|
|
<TextField select size="small" sx={FIELD_SX} label={t('pm.manual.order')} value={orderId} onChange={(e) => setOrderId(e.target.value)}
|
|
helperText={orders.length === 0 && pn && date ? t('pm.manual.noOrders') : undefined}>
|
|
{orders.map((o) => <MenuItem key={o.orderId} value={String(o.orderId)}>{o.name}</MenuItem>)}
|
|
</TextField>
|
|
<Stack direction="row" sx={{ alignItems: 'center' }}>
|
|
<Checkbox size="small" checked={reserved} onChange={(e) => setReserved(e.target.checked)} />
|
|
<Typography variant="body2">{t('pm.proc.reserved')}</Typography>
|
|
</Stack>
|
|
<Box><Button variant="contained" disabled={!pn || !orderId || !date || withDest.isPending}
|
|
onClick={async () => { if (await confirm({ message: t('pm.proc.confirm') })) withDest.mutate({ pn, locations: Number(orderId), orderDate: date, reservedQueue: reserved }); }}>{t('common.save')}</Button></Box>
|
|
</Stack>
|
|
</Paper>
|
|
{isSu && (
|
|
<Paper sx={{ p: 2 }}>
|
|
<Stack spacing={2}>
|
|
<Typography variant="subtitle1">{t('pm.proc.revokeAll')}</Typography>
|
|
<NumberField label={t('pm.proc.limit')} value={limit} onChange={setLimit} />
|
|
<Box><Button color="error" variant="outlined" disabled={!limit}
|
|
onClick={async () => { if (await confirm({ message: t('pm.proc.revokeAllConfirm'), danger: true })) revokeAll.mutate(Number(limit)); }}>{t('pm.proc.revokeAllRun')}</Button></Box>
|
|
</Stack>
|
|
</Paper>
|
|
)}
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
function SearchTruckTab() {
|
|
const { t } = useFeatureUi(strings);
|
|
const toast = useToast();
|
|
const [tn, setTn] = useState('');
|
|
const [r, setR] = useState<TruckDistribution | null>(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 (
|
|
<Stack spacing={2}>
|
|
<FormCard
|
|
icon={SearchIcon} title={t('pm.form.truckData')} maxWidth={620}
|
|
actions={<Button variant="contained" startIcon={<SearchIcon />} disabled={!tn} onClick={() => void go()}>{t('common.search')}</Button>}
|
|
>
|
|
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void go()} />
|
|
</FormCard>
|
|
{r && (
|
|
<FormCard icon={LocalShippingIcon} title={t('pm.form.result')} maxWidth={620}>
|
|
<Stack spacing={1}>
|
|
<Info label={t('pm.search.status')}>{r.status}</Info>
|
|
<Info label={t('pm.search.locations')}>{r.companyLocations}</Info>
|
|
<Info label={t('pm.search.orders')}>{r.order}</Info>
|
|
<Info label={t('pm.search.quantities')} ltr>{`${r.trucksTotalQuantity} / ${r.tenderTotalQuantity}`}</Info>
|
|
{r.errorMsg && <Alert severity="warning">{r.errorMsg}</Alert>}
|
|
</Stack>
|
|
</FormCard>
|
|
)}
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
export function DistributionPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
const [tab, setTab] = useState<'distribute' | 'process'>('distribute');
|
|
const { canTruckOrder } = useRoles();
|
|
return (
|
|
<>
|
|
<PageHeader
|
|
title={t('pm.dist.title')} subtitle={t('pm.dist.subtitle')}
|
|
/>
|
|
<Tabs value={tab} onChange={(_, v: typeof tab) => setTab(v)} variant="scrollable" sx={{ mb: 2 }}>
|
|
<Tab value="distribute" label={t('pm.dist.tabDistribute')} />
|
|
{canTruckOrder && <Tab value="process" label={t('pm.dist.tabProcess')} />}
|
|
</Tabs>
|
|
{tab === 'distribute' && <DistributeTab />}
|
|
{tab === 'process' && canTruckOrder && <ProcessTab />}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ================================================================= 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 (
|
|
<Stack spacing={2}>
|
|
<FormCard icon={SearchIcon} title={t('pm.form.truckData')} maxWidth={760}>
|
|
<Stack spacing={1.5}>
|
|
<Stack direction="row" spacing={2} sx={{ alignItems: 'center', flexWrap: 'wrap' }} useFlexGap>
|
|
<Box sx={{ ...row, flex: 1, minWidth: 260 }}>
|
|
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.truckNo')}</Typography>
|
|
<NumberField autoFocus label="" value={tn} onChange={(v) => { setTn(v); setFound(null); }} onEnter={() => void find()} />
|
|
</Box>
|
|
<Button variant="outlined" startIcon={<SearchIcon />} onClick={() => void find()} disabled={!tn}>{t('pm.wb.search')}</Button>
|
|
</Stack>
|
|
<Box sx={row}>
|
|
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.dest')}</Typography>
|
|
<Typography sx={{ color: 'primary.main', fontWeight: 700 }}>
|
|
{found ? (found.destination ?? '-') : ''}
|
|
{found?.message && <Typography component="span" variant="caption" sx={{ color: 'text.secondary', fontWeight: 400, marginInlineStart: 1 }}>{found.message}</Typography>}
|
|
</Typography>
|
|
</Box>
|
|
</Stack>
|
|
</FormCard>
|
|
|
|
<FormCard
|
|
icon={ScaleIcon} title={t('pm.wb.card')} maxWidth={760}
|
|
actions={(
|
|
<Button variant="contained" startIcon={<SaveIcon />} disabled={!tn || !location || !wi || !wo}
|
|
onClick={() => save.mutate({ tn, locationId: Number(location), weightIn: Number(wi), weightOut: Number(wo) })}>{t('common.save')}</Button>
|
|
)}
|
|
>
|
|
<Stack spacing={1.5}>
|
|
{!loc && (
|
|
<Box sx={row}>
|
|
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.location')}</Typography>
|
|
<NumberField label="" value={locInput} onChange={setLocInput} />
|
|
</Box>
|
|
)}
|
|
<Box sx={row}>
|
|
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.first')}</Typography>
|
|
<NumberField label="" value={wi} onChange={setWi} />
|
|
</Box>
|
|
<Box sx={row}>
|
|
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.second')}</Typography>
|
|
<NumberField label="" value={wo} onChange={setWo} />
|
|
</Box>
|
|
</Stack>
|
|
</FormCard>
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
export function WeighbridgePage() {
|
|
const { t } = useFeatureUi(strings);
|
|
return (
|
|
<>
|
|
<PageHeader title={t('pm.wb.title')} subtitle={t('pm.wb.subtitle')} />
|
|
<ManualTab />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ================================================================= print pages (acceptPrint / printIn / printOut)
|
|
const printStyles = (
|
|
<GlobalStyles styles={{
|
|
'@media print': {
|
|
'header, nav, aside, .MuiAppBar-root, .MuiDrawer-root, .no-print': { display: 'none !important' },
|
|
main: { margin: '0 !important', padding: '0 !important' },
|
|
body: { background: '#fff !important' },
|
|
},
|
|
}} />
|
|
);
|
|
|
|
/**
|
|
* 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<HTMLDivElement>(null);
|
|
const [pdfFailed, setPdfFailed] = useState(false);
|
|
const [pdfUrl, setPdfUrl] = useState<string | null>(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 <LoadingBanner />;
|
|
if (error) return <Alert severity="warning">{t('pm.print.failed')}</Alert>;
|
|
return (
|
|
<>
|
|
{printStyles}
|
|
{pdfUrl && (
|
|
<Box component="iframe" src={pdfUrl} title={title} sx={{ position: 'fixed', inset: 0, width: '100%', height: '100%', border: 0, zIndex: 2000, bgcolor: '#fff' }} />
|
|
)}
|
|
{wantsPdf && !pdfFailed && !pdfUrl && <Alert severity="info" className="no-print" sx={{ mb: 2 }}>{t('pm.print.generating')}</Alert>}
|
|
{pdfFailed && <Alert severity="warning" className="no-print" sx={{ mb: 2 }}>{t('pm.print.pdfFailed')}</Alert>}
|
|
<Stack direction="row" spacing={1} className="no-print" sx={{ mb: 2 }}>
|
|
<Button variant="contained" startIcon={<PrintIcon />} onClick={() => window.print()}>{t('pm.print.print')}</Button>
|
|
</Stack>
|
|
{bare ? (
|
|
// data-pdf-literal: designed black on white, captured exactly as laid out (no theme neutralising)
|
|
<Box ref={sheet} data-pdf-literal sx={{ maxWidth: width, mx: 'auto', bgcolor: '#fff', color: '#000' }}>{children}</Box>
|
|
) : (
|
|
<Paper ref={sheet} sx={{ p: 3, maxWidth: 780, mx: 'auto' }}>
|
|
<Typography variant="h5" sx={{ textAlign: 'center', mb: 2 }}>{title}</Typography>
|
|
{children}
|
|
</Paper>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
export function PrintAcceptPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
const id = Number(useParams().id);
|
|
const q = usePrintAccept(id);
|
|
const d = q.data;
|
|
return (
|
|
<PrintShell title={t('pm.print.acceptTitle')} orientation="portrait" bare loading={q.isLoading} error={q.isError || !d}>
|
|
{d && <AcceptSlip d={d} />}
|
|
</PrintShell>
|
|
);
|
|
}
|
|
|
|
export function PrintInPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
const id = Number(useParams().id);
|
|
const q = usePrintIn(id);
|
|
const d = q.data;
|
|
return (
|
|
<PrintShell title={t('pm.print.inTitle')} orientation="landscape" bare width={900} loading={q.isLoading} error={q.isError || !d}>
|
|
{d && <InSlip d={d} />}
|
|
</PrintShell>
|
|
);
|
|
}
|
|
|
|
export function PrintOutPage() {
|
|
const { t } = useFeatureUi(strings);
|
|
const id = Number(useParams().id);
|
|
const q = usePrintOut(id);
|
|
const d = q.data;
|
|
return (
|
|
<PrintShell title={t('pm.print.outTitle')} orientation="landscape" bare width={900} loading={q.isLoading} error={q.isError || !d}>
|
|
{d && <OutSlip d={d} />}
|
|
</PrintShell>
|
|
);
|
|
}
|
|
|