369 lines
19 KiB
TypeScript
369 lines
19 KiB
TypeScript
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<HTMLElement | null>(null);
|
|
|
|
const run = async (path: string, params: Record<string, string>, 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 (
|
|
<>
|
|
<PageHeader
|
|
title={tr(strings['trips.title'])}
|
|
actions={reports.length > 0 && (
|
|
<>
|
|
<Button variant="outlined" startIcon={<SummarizeIcon />} onClick={(e) => setMenu(e.currentTarget)}>{t('trips.reports')}</Button>
|
|
<Menu anchorEl={menu} open={!!menu} onClose={() => setMenu(null)}>
|
|
{reports.map((r) => <MenuItem key={r.key} onClick={r.go}>{r.label}</MenuItem>)}
|
|
</Menu>
|
|
</>
|
|
)}
|
|
/>
|
|
<DataGrid meta={meta} />
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ one trip
|
|
function Num({ v }: { v: number | null | undefined }) {
|
|
const { lang } = useFeatureUi(strings);
|
|
return v === null || v === undefined ? null : <bdi dir="ltr">{formatNumber(v, lang)}</bdi>;
|
|
}
|
|
|
|
function Section({ title, icon, children }: { title: string; icon: ElementType; children: ReactNode }) {
|
|
return (
|
|
<SectionPaper sx={{ p: 2 }}>
|
|
<SectionTitle icon={icon} title={title} />
|
|
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', md: 'repeat(4, 1fr)' } }}>{children}</Box>
|
|
</SectionPaper>
|
|
);
|
|
}
|
|
|
|
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 <LoadingBanner variant="first" />;
|
|
if (q.isError || !q.data) return <Alert severity="error">{q.error?.message ?? t('trips.loadFailed')}</Alert>;
|
|
return <TripView trip={q.data} />;
|
|
}
|
|
|
|
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<TripVoucher | null>(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) => (
|
|
<Button key={a} variant={a === 'print' ? 'outlined' : 'contained'} startIcon={a === 'print' ? <PrintIcon /> : undefined}
|
|
color={a.endsWith('Reverse') ? 'warning' : 'primary'} disabled={action.isPending || printer.isPending} onClick={() => void run(a)}>
|
|
{t(`trips.act.${a}` as 'trips.act.exchange')}
|
|
</Button>
|
|
))}
|
|
</>
|
|
);
|
|
|
|
return (
|
|
<Stack spacing={2}>
|
|
<PageHeader
|
|
title={`${t('trips.pn')}: ${trip.pn ?? ''}`}
|
|
backTo={ROOT}
|
|
status={<StatusChip value={trip.statusCode} statuses={statuses} size="medium" />}
|
|
actions={buttons}
|
|
/>
|
|
|
|
<Section icon={AssignmentIcon} title={t('trips.sec.basic')}>
|
|
<ViewItem label={t('trips.pn')}><bdi dir="ltr">{trip.pn}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.dispatchDate')}><bdi dir="ltr">{trip.dispatchDate}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.tn')}><bdi dir="ltr">{trip.tn}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.trn')}><bdi dir="ltr">{trip.trn}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.client')}>{trip.clientName}</ViewItem>
|
|
<ViewItem label={t('trips.nnpn')}><bdi dir="ltr">{trip.nnpn}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.driver')}>{trip.driverName}</ViewItem>
|
|
<ViewItem label={t('trips.status')}>{tr(statuses.find((s) => s.value === trip.statusCode)?.label) || trip.statusCode}</ViewItem>
|
|
<ViewItem label={t('trips.card')}><bdi dir="ltr">{trip.cardNumber}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.currentBalance')}><Num v={trip.currentBalance} /></ViewItem>
|
|
{trip.dieselCharge < 2 && <ViewItem label={t('trips.newBalance')}><Num v={trip.newBalance} /></ViewItem>}
|
|
{trip.wageClaimId && (
|
|
<ViewItem label={t('trips.wageClaim')}>
|
|
<Link component={RouterLink} to={`/refinery/wage-claims/${trip.wageClaimId}`}>{trip.wageClaimNo ?? trip.wageClaimId}</Link>
|
|
</ViewItem>
|
|
)}
|
|
{dischargeSection && <ViewItem label={t('trips.tripNetWage')}><Num v={trip.tripNetWage} /></ViewItem>}
|
|
{dischargeSection && <ViewItem label={t('trips.remaining')}><Num v={trip.remainingBalance} /></ViewItem>}
|
|
{dischargeSection && (
|
|
<ViewItem label={t('trips.netWage')}>
|
|
<Num v={trip.netWage} /> <Typography component="span" variant="caption" color="error">{t('trips.canEdit')}</Typography>
|
|
</ViewItem>
|
|
)}
|
|
</Section>
|
|
|
|
{loaded && (
|
|
<Section icon={FileUploadIcon} title={t('trips.sec.loading')}>
|
|
<ViewItem label={t('trips.loadingNo')}><bdi dir="ltr">{trip.loadingNo}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.loadingFrom')}><bdi dir="ltr">{trip.actualLoadingDate}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.grossWeight')}><Num v={trip.grossWeight} /></ViewItem>
|
|
<ViewItem label={t('trips.emptyWeight')}><Num v={trip.emptyWeight} /></ViewItem>
|
|
<ViewItem label={t('trips.netLoading')}><Num v={trip.netLoadingWeight} /></ViewItem>
|
|
</Section>
|
|
)}
|
|
|
|
{dischargeSection && (
|
|
<Section icon={FileDownloadIcon} title={t('trips.sec.discharge')}>
|
|
<ViewItem label={t('trips.dischargeNo')}><bdi dir="ltr">{trip.dischargeAuthNo}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.dischargeDate')}><bdi dir="ltr">{trip.dischargeEntryDate}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.actualGross')}><Num v={trip.actualGrossWeight} /></ViewItem>
|
|
<ViewItem label={t('trips.actualEmpty')}><Num v={trip.actualEmptyWeight} /></ViewItem>
|
|
<ViewItem label={t('trips.netDischarge')}><Num v={trip.netDischargeWeight} /></ViewItem>
|
|
<ViewItem label={t('trips.liters')}><Num v={trip.litersWeight} /></ViewItem>
|
|
<ViewItem label={t('trips.waterAmount')}><Num v={trip.waterAmount} /></ViewItem>
|
|
<ViewItem label={t('trips.difference')}><Num v={trip.weightDifference} /></ViewItem>
|
|
<ViewItem label={t('trips.sediment')}><Num v={trip.sedimentAmount} /></ViewItem>
|
|
</Section>
|
|
)}
|
|
|
|
{loaded && (
|
|
<Section icon={PaymentsIcon} title={t('trips.sec.payment')}>
|
|
{w?.epayment === 1 && (
|
|
<>
|
|
<ViewItem label={t('trips.walletNumber')}><bdi dir="ltr">{w.walletNumber}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.ownerNnpn')}><bdi dir="ltr">{w.ownerNnpn}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.ownerName')}>{w.ownerName}</ViewItem>
|
|
</>
|
|
)}
|
|
{w?.epayment === 0 && (
|
|
<>
|
|
<Typography color="error" sx={{ gridColumn: '1 / -1' }}>{t('trips.payByBank')}</Typography>
|
|
<ViewItem label={t('trips.ownerName')}>{w.ownerName}</ViewItem>
|
|
<ViewItem label={t('trips.bank')}>{w.bankName}</ViewItem>
|
|
<ViewItem label={t('trips.iban')}><bdi dir="ltr">{w.iban}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.bankAccount')}><bdi dir="ltr">{w.bankAccount}</bdi></ViewItem>
|
|
</>
|
|
)}
|
|
{(!w || w.epayment === null) && <Typography color="error" sx={{ gridColumn: '1 / -1' }}>{t('trips.noPaymentMethod')}</Typography>}
|
|
<ViewItem label={t('trips.receivedBy')}>{trip.receivedByName}</ViewItem>
|
|
<ViewItem label={t('trips.receivedDate')}><bdi dir="ltr">{trip.receivedDate}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.paymentedDate')}><bdi dir="ltr">{trip.paymentedDate}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.voucher')}><bdi dir="ltr">{trip.voucherSerialNumber}</bdi></ViewItem>
|
|
<ViewItem label={t('trips.remarks')}>{trip.remarks}</ViewItem>
|
|
</Section>
|
|
)}
|
|
|
|
{dischargeSection && (
|
|
<Section icon={AccountBalanceWalletIcon} title={t('trips.sec.driverWallet')}>
|
|
{w?.driverWalletNumber
|
|
? <ViewItem label={t('trips.driverWallet')}><bdi dir="ltr">{w.driverWalletNumber}</bdi></ViewItem>
|
|
: <Typography color="error" sx={{ gridColumn: '1 / -1' }}>{t('trips.driverNoWallet')}</Typography>}
|
|
</Section>
|
|
)}
|
|
|
|
<TripLog tripId={trip.id} />
|
|
<VoucherDialog voucher={voucher} onClose={() => setVoucher(null)} />
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ history
|
|
function TripLog({ tripId }: { tripId: number }) {
|
|
const { t } = useFeatureUi(strings);
|
|
const [page, setPage] = useState(1);
|
|
const [open, setOpen] = useState(false);
|
|
const [shown, setShown] = useState<TripLogRow | null>(null);
|
|
const q = useTripLog(tripId, page, open);
|
|
return (
|
|
<SectionPaper sx={{ p: 2 }}>
|
|
<Box role="button" tabIndex={0} aria-expanded={open} onClick={() => 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 } }}>
|
|
<SectionTitle icon={HistoryIcon} title={t('trips.sec.history')} />
|
|
</Box>
|
|
{open && (
|
|
<>
|
|
{q.isLoading && <LoadingBanner variant="first" />}
|
|
{q.data && q.data.items.length === 0 && <Typography color="text.secondary" sx={{ p: 1 }}>{t('trips.log.none')}</Typography>}
|
|
{q.data && q.data.items.length > 0 && (
|
|
<>
|
|
<Table size="small">
|
|
<TableHead>
|
|
<TableRow>
|
|
<TableCell>{t('trips.log.method')}</TableCell>
|
|
<TableCell>{t('trips.log.date')}</TableCell>
|
|
<TableCell>{t('trips.log.user')}</TableCell>
|
|
<TableCell />
|
|
</TableRow>
|
|
</TableHead>
|
|
<TableBody>
|
|
{q.data.items.map((r) => (
|
|
<TableRow key={r.id}>
|
|
<TableCell>{methodCaptions[r.methodName ?? ''] ?? r.methodName}</TableCell>
|
|
<TableCell><bdi dir="ltr">{r.logDate}</bdi></TableCell>
|
|
<TableCell>{r.login}</TableCell>
|
|
<TableCell>
|
|
{r.methodName !== 'CREATE' && (r.oldData || r.newData) && (
|
|
<Button size="small" startIcon={<VisibilityOutlined />} onClick={() => setShown(r)}>{t('trips.log.old')} / {t('trips.log.new')}</Button>
|
|
)}
|
|
</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
<TablePagination component="div" count={q.data.totalCount} page={page - 1} rowsPerPage={10} rowsPerPageOptions={[10]}
|
|
onPageChange={(_, p) => setPage(p + 1)} />
|
|
</>
|
|
)}
|
|
</>
|
|
)}
|
|
<LogDialog row={shown} onClose={() => setShown(null)} />
|
|
</SectionPaper>
|
|
);
|
|
}
|
|
|
|
function parse(json: string | null): Record<string, unknown> {
|
|
try { return json ? (JSON.parse(json) as Record<string, unknown>) : {}; } 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 (
|
|
<Dialog open={!!row} onClose={onClose} maxWidth="sm" fullWidth>
|
|
<DialogTitle>{methodCaptions[row?.methodName ?? ''] ?? row?.methodName}</DialogTitle>
|
|
<DialogContent>
|
|
<Table size="small">
|
|
<TableHead>
|
|
<TableRow>
|
|
<TableCell>{t('trips.log.property')}</TableCell>
|
|
<TableCell>{t('trips.log.old')}</TableCell>
|
|
<TableCell>{t('trips.log.new')}</TableCell>
|
|
</TableRow>
|
|
</TableHead>
|
|
<TableBody>
|
|
{keys.map((k) => (
|
|
<TableRow key={k}>
|
|
<TableCell>{propertyCaptions[k] ?? k}</TableCell>
|
|
<TableCell>{String(oldD[k] ?? '')}</TableCell>
|
|
<TableCell>{String(newD[k] ?? '')}</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
</DialogContent>
|
|
<DialogActions><Button onClick={onClose}>{t('common.close')}</Button></DialogActions>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ cash voucher (legacy print: A5 pdf)
|
|
function VoucherDialog({ voucher, onClose }: { voucher: TripVoucher | null; onClose: () => void }) {
|
|
const { t } = useFeatureUi(strings);
|
|
return (
|
|
<Dialog open={!!voucher} onClose={onClose} maxWidth="sm" fullWidth>
|
|
{/* print only the voucher, not the page behind the dialog */}
|
|
<GlobalStyles styles={{ '@media print': { 'body *': { visibility: 'hidden' }, '#trip-voucher, #trip-voucher *': { visibility: 'visible' }, '#trip-voucher': { position: 'absolute', top: 0, left: 0, right: 0 } } }} />
|
|
<DialogContent>
|
|
{voucher && (
|
|
<Box id="trip-voucher" dir="rtl" sx={{ p: 2, '@media print': { p: 0 } }}>
|
|
{/* the printed voucher always carries the Arabic logo (white background, fixed size) */}
|
|
<Box sx={{ textAlign: 'left', mb: 1, bgcolor: '#fff', lineHeight: 0 }}>
|
|
<img src="/brand/nafith-ar.gif" alt="نافذ" width={139} height={30} style={{ display: 'inline-block' }} />
|
|
</Box>
|
|
<Typography align="center" sx={{ fontSize: 18, fontWeight: 700, mb: 3 }}>{t('trips.voucher.title')}</Typography>
|
|
<Stack direction="row" sx={{ justifyContent: 'space-between', mb: 3 }}>
|
|
<span>{t('trips.voucher.date')} : <bdi dir="ltr">{voucher.date}</bdi></span>
|
|
<b>{t('trips.voucher.no')} : <bdi dir="ltr">{voucher.serial}</bdi></b>
|
|
</Stack>
|
|
<Typography sx={{ mb: 1 }}>{t('trips.voucher.body1')} <bdi dir="ltr">{voucher.amount}</bdi> {t('trips.voucher.dinar')}</Typography>
|
|
<Typography sx={{ mb: 4 }}>{t('trips.voucher.body2')} <bdi dir="ltr">{voucher.dischargeAuthNo}</bdi></Typography>
|
|
<Typography sx={{ mb: 6 }}>{t('trips.voucher.receiver')}: {voucher.ownerName}</Typography>
|
|
<Typography>{t('trips.voucher.accountant')}</Typography>
|
|
</Box>
|
|
)}
|
|
</DialogContent>
|
|
<DialogActions sx={{ '@media print': { display: 'none' } }}>
|
|
<Button startIcon={<PrintIcon />} variant="contained" onClick={() => window.print()}>{t('trips.voucher.print')}</Button>
|
|
<Button onClick={onClose}>{t('common.close')}</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
);
|
|
}
|