import { useState, type ElementType, type ReactNode } from 'react'; import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom'; import { Alert, Box, Button, Dialog, GlobalStyles, DialogActions, DialogContent, DialogTitle, Link, Menu, MenuItem, Stack, Table, TableBody, TableCell, TableHead, TableRow, TablePagination, Typography, } from '@mui/material'; import SummarizeIcon from '@mui/icons-material/Summarize'; import PrintIcon from '@mui/icons-material/Print'; import AccountBalanceWalletIcon from '@mui/icons-material/AccountBalanceWallet'; import AssignmentIcon from '@mui/icons-material/Assignment'; import FileDownloadIcon from '@mui/icons-material/FileDownload'; import FileUploadIcon from '@mui/icons-material/FileUpload'; import HistoryIcon from '@mui/icons-material/History'; import PaymentsIcon from '@mui/icons-material/Payments'; import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined'; import { DataGrid } from '@/components/DataGrid'; import { LoadingBanner } from '@/components/LoadingBanner'; import { PageHeader } from '@/components/PageHeader'; import { SectionPaper } from '@/components/SectionPaper'; import { SectionTitle } from '@/components/SectionTitle'; import { StatusChip } from '@/components/StatusChip'; import { ViewItem } from '@/components/ViewItem'; import { formatNumber } from '@/components/meta/format'; import { useFeatureUi } from '@/i18n/useUi'; import { useAuth } from '@/providers/AuthProvider'; import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { downloadFile } from '../../grains-orders/api'; import { actionKeys, actionPaths, BASE, usePrintVoucher, useTrip, useTripAction, useTripLog } from './api'; import { statuses, tripsGrid } from './meta'; import strings, { methodCaptions, propertyCaptions } from './strings'; import type { TripDetail, TripLogRow, TripVoucher } from './types'; const ROOT = '/refinery/trips'; const MONEY_ACTIONS = new Set(['firstAdvance', 'secondAdvance', 'firstAdvanceReverse', 'secondAdvanceReverse', 'exchange', 'payment', 'cashPayment', 'confirmExchange']); // ------------------------------------------------------------------ list export function TripsPage() { const { t, tr } = useFeatureUi(strings); const { can } = useAuth(); const navigate = useNavigate(); const toast = useToast(); const [menu, setMenu] = useState(null); const run = async (path: string, params: Record, name: string) => { setMenu(null); try { await downloadFile(`${BASE}/reports/${path}`, params, name); toast.success(t('trips.report.done')); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } }; // the report uses the filters of the list (they are in the URL query string) const current = () => Object.fromEntries([...new URLSearchParams(window.location.search)].filter(([k]) => !['page', 'size', 'f'].includes(k))); const reports: { key: string; label: string; show: boolean; go: () => void }[] = [ { key: 'trips', label: t('trips.report.trips'), show: can('refinery.trips.report'), go: () => void run('trips', current(), 'refinery-trips.xlsx') }, { key: 'operator', label: t('trips.report.operator'), show: can('refinery.trips.operatorReport'), go: () => void run('operator', current(), 'refinery-trips-operator.xlsx') }, { key: 'exchange', label: t('trips.report.exchange'), show: can('refinery.trips.exchangeReport'), go: () => void run('exchange', current(), 'refinery-trips-exchange.xlsx') }, { key: 'diesel', label: t('trips.report.diesel'), show: can('refinery.trips.dieselReport'), go: () => void run('diesel', current(), 'refinery-diesel.xlsx') }, { key: 'cards', label: t('trips.report.cards'), show: can('refinery.trips.cardsReport'), go: () => void run('cards', { tn: current().tn ?? '' }, 'refinery-cards.xlsx') }, { key: 'bank', label: t('trips.report.bank'), show: can('refinery.trips.bankReport'), go: () => { const account = window.prompt(t('trips.report.bankAsk'), current().bankAccount ?? ''); if (account) void run('bank', { bankAccount: account, statusCode: current().statusCode ?? '' }, 'refinery-bank.xlsx'); }, }, ].filter((r) => r.show); const meta = tripsGrid((r) => navigate(`${ROOT}/${r.id}`)); return ( <> 0 && ( <> setMenu(null)}> {reports.map((r) => {r.label})} )} /> ); } // ------------------------------------------------------------------ one trip function Num({ v }: { v: number | null | undefined }) { const { lang } = useFeatureUi(strings); return v === null || v === undefined ? null : {formatNumber(v, lang)}; } function Section({ title, icon, children }: { title: string; icon: ElementType; children: ReactNode }) { return ( {children} ); } export function TripPage() { const { id } = useParams(); const tripId = Number(id); const q = useTrip(Number.isFinite(tripId) ? tripId : null); const { t } = useFeatureUi(strings); if (q.isLoading) return ; if (q.isError || !q.data) return {q.error?.message ?? t('trips.loadFailed')}; return ; } function TripView({ trip }: { trip: TripDetail }) { const { t, tr } = useFeatureUi(strings); const { can } = useAuth(); const confirm = useConfirm(); const action = useTripAction(trip.id); const printer = usePrintVoucher(trip.id); const [voucher, setVoucher] = useState(null); const w = trip.wallet; const late = ['DISCHARGED', 'PENDING_EXCHANGE', 'READY_TO_PAY', 'EXCHANGED', 'COMPLETE'].includes(trip.statusCode ?? ''); const loaded = late || ['LOADED', 'DISCHARGING_FILL', 'ARRIVE_LOCATION', 'DISCHARGING'].includes(trip.statusCode ?? ''); const dischargeSection = late; const available = trip.actions.filter((a) => can(actionKeys[a])); const run = async (a: string) => { if (a === 'print') { printer.mutate(undefined, { onSuccess: setVoucher }); return; } const message = MONEY_ACTIONS.has(a) ? t('trips.act.confirmMoney') : t('trips.act.confirm'); if (await confirm({ title: t(`trips.act.${a}` as 'trips.act.exchange'), message })) action.mutate(a); }; const buttons = ( <> {available.filter((a) => a in actionPaths || a === 'print').map((a) => ( ))} ); return ( } actions={buttons} />
{trip.pn} {trip.dispatchDate} {trip.tn} {trip.trn} {trip.clientName} {trip.nnpn} {trip.driverName} {tr(statuses.find((s) => s.value === trip.statusCode)?.label) || trip.statusCode} {trip.cardNumber} {trip.dieselCharge < 2 && } {trip.wageClaimId && ( {trip.wageClaimNo ?? trip.wageClaimId} )} {dischargeSection && } {dischargeSection && } {dischargeSection && ( {t('trips.canEdit')} )}
{loaded && (
{trip.loadingNo} {trip.actualLoadingDate}
)} {dischargeSection && (
{trip.dischargeAuthNo} {trip.dischargeEntryDate}
)} {loaded && (
{w?.epayment === 1 && ( <> {w.walletNumber} {w.ownerNnpn} {w.ownerName} )} {w?.epayment === 0 && ( <> {t('trips.payByBank')} {w.ownerName} {w.bankName} {w.iban} {w.bankAccount} )} {(!w || w.epayment === null) && {t('trips.noPaymentMethod')}} {trip.receivedByName} {trip.receivedDate} {trip.paymentedDate} {trip.voucherSerialNumber} {trip.remarks}
)} {dischargeSection && (
{w?.driverWalletNumber ? {w.driverWalletNumber} : {t('trips.driverNoWallet')}}
)} setVoucher(null)} />
); } // ------------------------------------------------------------------ history function TripLog({ tripId }: { tripId: number }) { const { t } = useFeatureUi(strings); const [page, setPage] = useState(1); const [open, setOpen] = useState(false); const [shown, setShown] = useState(null); const q = useTripLog(tripId, page, open); return ( setOpen((o) => !o)} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen((o) => !o); } }} sx={{ cursor: 'pointer', '& h2': { mb: open ? 1.5 : 0 } }}> {open && ( <> {q.isLoading && } {q.data && q.data.items.length === 0 && {t('trips.log.none')}} {q.data && q.data.items.length > 0 && ( <> {t('trips.log.method')} {t('trips.log.date')} {t('trips.log.user')} {q.data.items.map((r) => ( {methodCaptions[r.methodName ?? ''] ?? r.methodName} {r.logDate} {r.login} {r.methodName !== 'CREATE' && (r.oldData || r.newData) && ( )} ))}
setPage(p + 1)} /> )} )} setShown(null)} />
); } function parse(json: string | null): Record { try { return json ? (JSON.parse(json) as Record) : {}; } catch { return {}; } } function LogDialog({ row, onClose }: { row: TripLogRow | null; onClose: () => void }) { const { t } = useFeatureUi(strings); const oldD = parse(row?.oldData ?? null); const newD = parse(row?.newData ?? null); const keys = [...new Set([...Object.keys(oldD), ...Object.keys(newD)])]; return ( {methodCaptions[row?.methodName ?? ''] ?? row?.methodName} {t('trips.log.property')} {t('trips.log.old')} {t('trips.log.new')} {keys.map((k) => ( {propertyCaptions[k] ?? k} {String(oldD[k] ?? '')} {String(newD[k] ?? '')} ))}
); } // ------------------------------------------------------------------ cash voucher (legacy print: A5 pdf) function VoucherDialog({ voucher, onClose }: { voucher: TripVoucher | null; onClose: () => void }) { const { t } = useFeatureUi(strings); return ( {/* print only the voucher, not the page behind the dialog */} {voucher && ( {/* the printed voucher always carries the Arabic logo (white background, fixed size) */} نافذ {t('trips.voucher.title')} {t('trips.voucher.date')} : {voucher.date} {t('trips.voucher.no')} : {voucher.serial} {t('trips.voucher.body1')} {voucher.amount} {t('trips.voucher.dinar')} {t('trips.voucher.body2')} {voucher.dischargeAuthNo} {t('trips.voucher.receiver')}: {voucher.ownerName} {t('trips.voucher.accountant')} )} ); }