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; /** * "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('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 = { 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 | 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(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 ( !pay.isPending && onClose()} maxWidth="md"> {t('PAY_OFF_DEBIT_BALANCE')} {t('ORDER_SUMMARY')} {nafith && ( { setWithNafith(e.target.checked); setMethod(''); }} />} label={t('INCLUDE_NAFDAP_SERVICE_LBL')} /> )} {summary.isPending && } {summary.error && {t((summary.error as Error).message)}} {s && empty && ( )} {s && !empty && ( {t('PAYMENT_METHOD')} setMethod(e.target.value)}> {methods.map((m) => ( } label={m.NAME} /> {m.ID === CARD_PAYMENT && {ui('wizCardLater')}} {m.ID === POS_PAYMENT && method === String(POS_PAYMENT) && ( setReceipt(e.target.value)} slotProps={{ htmlInput: { maxLength: 12 } }} sx={{ marginInlineStart: 4, mb: 1 }} /> )} ))} )} {error && setError('')}>{error}} {pay.error && {t((pay.error as Error).message)}} ); }