mams_frontend/src/features/gridActions/PendingPayDialog.tsx

172 lines
7.7 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import DOMPurify from 'dompurify';
import {
Alert, Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Radio, RadioGroup, Stack,
TextField, Typography,
} from '@mui/material';
import { useAuth } from '../../auth/AuthContext';
import { ApiError, rpc, type Envelope } from '../../api/client';
import { validateReceipt } from '../../api/packages';
import { useT, useUi } from '../../i18n';
import { useNotify } from '../../notify/NotifyProvider';
const ENTITY = 'FLEET_PENDING_FINANCIAL_TRANSACTIONS';
/** the payment gateway is a separate page of the old site: like the subscription wizard, card payment is not offered here */
const CARD_PAYMENT = 3;
const POS_PAYMENT = 6;
interface Summary {
VEHICLE_COUNT?: number;
HTML_CONTENT?: string;
TOTALPRICE?: number;
SUBSCRIPTIONDETAILSCARD?: string;
PAYMENTMETHODS?: { ID: number; NAME: string }[];
PACKAGE_ID?: number | string;
CODE?: unknown;
}
type Tx = Record<string, unknown>;
/**
* "Pay off debit balance" popup of the overdue charges: the order summary for the charge's package, the payment methods
* the role may use, and — for the Nafith side — the option to include the Nafith service fee.
*/
export function PendingPayDialog({ id, data, onClose, onDone }: { id: string; data: Tx; onClose: () => void; onDone: () => void }) {
const { user } = useAuth();
const t = useT();
const ui = useUi();
const notify = useNotify();
const nafith = user?.role_group === 'NAFITH';
const [withNafith, setWithNafith] = useState(false);
const [method, setMethod] = useState('');
const [receipt, setReceipt] = useState('');
const [error, setError] = useState('');
const summary = useQuery({
queryKey: ['pending-summary', id, withNafith],
queryFn: () =>
rpc<Summary>('CONFIG', 'getPendingFinTansactionsSummaryForNafith', {
package_id: withNafith ? data.NAFITH_PACKAGE_ID : data.STAKEHOLDER_PACKAGE_ID,
type: data.TYPE,
...(withNafith ? { includeNafithFee: true } : {}),
}),
staleTime: 0,
});
const s = summary.data;
const empty = !!s && s.VEHICLE_COUNT === 0;
const methods = s?.PAYMENTMETHODS ?? [];
const total = Number(s?.TOTALPRICE ?? 0);
// the cash-balance method is picked first, as in the old popup
useEffect(() => {
if (!methods.length) return setMethod('');
setMethod((m) => (m && methods.some((x) => String(x.ID) === m) ? m : methods.some((x) => x.ID === 1) ? '1' : ''));
}, [s]); // eslint-disable-line react-hooks/exhaustive-deps
const pay = useMutation({
meta: { loading: 'processing' },
mutationFn: async () => {
const params: Record<string, unknown> = { paymentMethodId: method, amount: total, depts_transcation_ids: id, POS_receipt_id: 0 };
if (method === String(POS_PAYMENT)) {
params.POS_receipt_id = receipt.trim();
const ok = await validateReceipt(receipt.trim(), total);
if (ok !== 'VALID') throw new ApiError(String(ok));
if (nafith) {
Object.assign(params, {
depts_transcation_ids: data.ID,
// legacy: ticking "include the Nafith service" makes the payer's own entity the stakeholder
stakeholder_entity_id: withNafith ? ((user as Record<string, unknown> | null)?.related_entity_id ?? data.STAKEHOLDER_ENTITY_ID) : data.STAKEHOLDER_ENTITY_ID,
stakeholder_entity_Record_id: data.STAKEHOLDER_ENTITY_RECORD_ID,
fleet_entity_id: data.FLEET_ENTITY_ID,
fleet_entity_record_id: data.FLEET_ENTITY_RECORD_ID,
plate_code_ar: data.PLATE_CODE_AR,
plate_code_en: data.PLATE_CODE_EN,
plate_number: data.PLATE_NUMBER,
stakeholder_crn: data.CRN,
permit_id: data.PERMIT_ID,
package_id: s?.PACKAGE_ID,
});
}
}
const r = await rpc<Envelope>(ENTITY, 'PAY', { data: params }, { post: true });
if (String(r.CODE) !== '000') throw new ApiError(String(r.MESSAGE || r.MESSAGECODE || 'ACTION_FAILED'), r.CODE, r.DATA);
return r;
},
onSuccess: (r) => {
notify.success(String(r.MESSAGE ?? 'SUCCESSFUL.OPERATION'), ui('saved'));
onDone();
},
onError: (e) => notify.error(e),
});
const submit = () => {
if (!method) return setError(t('PAYMENT_METHOD_NOT_SELECTED'));
if (method === String(POS_PAYMENT) && !receipt.trim()) return setError(t('PLEASE_ENTER_RECEIPT_NUMBER'));
setError('');
pay.mutate();
};
return (
<Dialog open onClose={() => !pay.isPending && onClose()} maxWidth="md">
<DialogTitle>{t('PAY_OFF_DEBIT_BALANCE')}</DialogTitle>
<DialogContent>
<Typography
sx={{
fontWeight: 700,
mb: 1
}}>{t('ORDER_SUMMARY')}</Typography>
{nafith && (
<FormControlLabel
control={<Checkbox checked={withNafith} onChange={(e) => { setWithNafith(e.target.checked); setMethod(''); }} />}
label={t('INCLUDE_NAFDAP_SERVICE_LBL')}
/>
)}
{summary.isPending && <Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}><CircularProgress size={28} /></Box>}
{summary.error && <Alert severity="error">{t((summary.error as Error).message)}</Alert>}
{s && empty && (
<Box sx={{ textAlign: 'center', py: 3 }} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(s.HTML_CONTENT ?? '') }} />
)}
{s && !empty && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Box sx={{ '& .card': { border: 1, borderColor: 'divider', borderRadius: 1.5, p: 1.5 }, '& h4': { fontSize: 15, m: 0, mb: 1 }, '& h1': { fontSize: 20, m: 0 }, '& p': { m: 0, mb: 0.5 }, '& i': { display: 'none' } }}
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(s.SUBSCRIPTIONDETAILSCARD ?? '') }} />
<Box sx={{ border: 1, borderColor: 'divider', borderRadius: 1.5, p: 1.5 }}>
<Typography
sx={{
fontWeight: 700,
mb: 0.5
}}>{t('PAYMENT_METHOD')}</Typography>
<RadioGroup value={method} onChange={(e) => setMethod(e.target.value)}>
{methods.map((m) => (
<Box key={m.ID}>
<FormControlLabel value={String(m.ID)} disabled={m.ID === CARD_PAYMENT} control={<Radio size="small" />} label={m.NAME} />
{m.ID === CARD_PAYMENT && <Typography
variant="caption"
sx={{
color: "text.secondary",
marginInlineStart: 4,
display: 'block'
}}>{ui('wizCardLater')}</Typography>}
{m.ID === POS_PAYMENT && method === String(POS_PAYMENT) && (
<TextField size="small" label={t('RECEIPT_NUMBER')} value={receipt} onChange={(e) => setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} />
)}
</Box>
))}
</RadioGroup>
</Box>
</Box>
)}
{error && <Alert severity="warning" sx={{ mt: 2 }} onClose={() => setError('')}>{error}</Alert>}
{pay.error && <Alert severity="error" sx={{ mt: 2 }}>{t((pay.error as Error).message)}</Alert>}
</DialogContent>
<DialogActions>
<Stack direction="row" spacing={1}>
<Button onClick={onClose} disabled={pay.isPending}>{t('CLOSE')}</Button>
<Button variant="contained" disabled={pay.isPending || !s || empty} onClick={submit}>{t('PAY')}</Button>
</Stack>
</DialogActions>
</Dialog>
);
}