Users typing on a Persian keyboard produced two distinct failures. Fields with type="number" silently returned an empty string — the browser rejects Persian digits, so the value was lost and saved as empty or zero. Text fields passed the Persian characters straight through to the database, where a mobile stored as ۰۹۱۲… never matches 09… again. The secretary form hit the second case with no validation at all. Frontend: - Adds digitsOnly() and the national-code schemas to lib/utils, plus lib/forms with numericField()/latinDigitsField() wrappers for React Hook Form fields. - Converts every type="number" input to type="text" inputMode="numeric" with digit normalization; none remain. Fields that legitimately carry non-digits (sheba, landline) only get the digits translated, keeping IR and separators. - Points the patient national-code and mobile schemas at the shared normalizing schemas, which accept Persian input instead of rejecting it. - Drops two duplicate local digit converters in favour of the shared helper. Backend: - Adds NumericFieldNormalizerSubscriber, translating digits in whitelisted numeric keys of JSON request bodies under /api/v1/ before controllers run, so nobat724_front and clinic-pro-tauri are covered too. Translation only — no characters are stripped, non-string values and other keys are untouched. Three component tests asserted on role="spinbutton" and numeric input values; both are properties of type="number", so they were updated to match the new text inputs. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
180 lines
8.3 KiB
TypeScript
180 lines
8.3 KiB
TypeScript
import React, { useMemo, useState } from 'react';
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { toast } from 'sonner';
|
|
import { api } from '../lib/api';
|
|
import type { ApiResponse } from '../lib/api';
|
|
import { formatRial, formatDate, tomanToRial } from '../lib/utils';
|
|
import Pagination from '../components/ui/Pagination';
|
|
import SearchableSelect from '../components/ui/SearchableSelect';
|
|
import { digitsOnly } from '../lib/utils';
|
|
|
|
interface WalletBalance { balance_rials: number }
|
|
interface RepSummary { income: { settlable_rials: number; settled_rials: number; pending_rials: number } }
|
|
interface SettlementRow {
|
|
uuid: string;
|
|
amount_rials: number;
|
|
status: 'pending' | 'approved' | 'rejected' | 'paid';
|
|
admin_note: string | null;
|
|
created_at: number;
|
|
}
|
|
|
|
const STATUS_LABEL: Record<string, string> = {
|
|
pending: 'در انتظار بررسی', approved: 'تأیید شده', rejected: 'رد شده', paid: 'پرداخت شده',
|
|
};
|
|
const STATUS_CLASS: Record<string, string> = {
|
|
pending: 'gray', approved: 'green', rejected: 'red', paid: 'green',
|
|
};
|
|
|
|
interface IbanItem { id: string; iban: string; bank_name: string | null; verified: boolean }
|
|
interface RepMe { bank_account: IbanItem[] | null }
|
|
|
|
export default function RepresentationSettlementPage() {
|
|
const qc = useQueryClient();
|
|
const [amount, setAmount] = useState('');
|
|
const [ibanId, setIbanId] = useState('');
|
|
const [page, setPage] = useState(1);
|
|
const limit = 20;
|
|
|
|
const balanceQ = useQuery({
|
|
queryKey: ['wallet-balance'],
|
|
queryFn: () => api.get<ApiResponse<WalletBalance>>('/api/v1/wallet/balance'),
|
|
staleTime: 30_000,
|
|
});
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const balance: number = ((balanceQ.data?.data as any)?.data ?? balanceQ.data?.data)?.balance_rials ?? 0;
|
|
|
|
const meQ = useQuery({
|
|
queryKey: ['representation-me'],
|
|
queryFn: () => api.get<ApiResponse<RepMe>>('/api/v1/representation/me'),
|
|
staleTime: 30_000,
|
|
});
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const ibans: IbanItem[] = (((meQ.data?.data as any)?.data ?? meQ.data?.data)?.bank_account ?? []).filter((b: IbanItem) => b.verified);
|
|
|
|
const summaryQ = useQuery({
|
|
queryKey: ['representation-summary'],
|
|
queryFn: () => api.get<ApiResponse<RepSummary>>('/api/v1/representation/dashboard/summary'),
|
|
staleTime: 60_000,
|
|
});
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const income = useMemo<any>(() => ((summaryQ.data?.data as any)?.data ?? summaryQ.data?.data)?.income, [summaryQ.data]);
|
|
|
|
const listQ = useQuery({
|
|
queryKey: ['settlements-mine', page],
|
|
queryFn: () => api.get<ApiResponse<SettlementRow[]>>(`/api/v1/settlement?page=${page}&limit=${limit}`),
|
|
staleTime: 30_000,
|
|
});
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const settlements: SettlementRow[] = (listQ.data?.data as any)?.data ?? listQ.data?.data ?? [];
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const settlementsTotal: number = (listQ.data?.data as any)?.meta?.totalRecords ?? settlements.length;
|
|
|
|
const createMut = useMutation({
|
|
mutationFn: (payload: { amount_rials: number; iban_id: string }) =>
|
|
api.post<ApiResponse<SettlementRow>>('/api/v1/settlement', payload),
|
|
onSuccess: () => {
|
|
toast.success('درخواست تسویه ثبت شد');
|
|
setAmount('');
|
|
qc.invalidateQueries({ queryKey: ['settlements-mine'] });
|
|
qc.invalidateQueries({ queryKey: ['wallet-balance'] });
|
|
qc.invalidateQueries({ queryKey: ['representation-summary'] });
|
|
},
|
|
onError: (e: Error) => toast.error(e.message),
|
|
});
|
|
|
|
const submit = () => {
|
|
const n = Number(amount); // تومان
|
|
if (!n || n <= 0) { toast.error('مبلغ نامعتبر است'); return; }
|
|
const rial = tomanToRial(n);
|
|
if (rial > balance) { toast.error('مبلغ بیشتر از موجودی قابل برداشت است'); return; }
|
|
if (!ibanId) { toast.error('انتخاب شماره شبا الزامی است'); return; }
|
|
createMut.mutate({ amount_rials: rial, iban_id: ibanId });
|
|
};
|
|
|
|
const cards = [
|
|
{ label: 'موجودی قابل برداشت', value: formatRial(balance), color: 'var(--primary)' },
|
|
{ label: 'مجموع تسویهشده', value: formatRial(income?.settled_rials ?? 0), color: 'var(--success)' },
|
|
{ label: 'در انتظار تسویه', value: formatRial(income?.pending_rials ?? 0), color: 'var(--warning)' },
|
|
];
|
|
|
|
return (
|
|
<div className="fade-in">
|
|
<div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
|
|
<div>
|
|
<h1 className="section-title">تسویه حساب</h1>
|
|
<div className="muted" style={{ fontSize: 13, marginTop: 2 }}>درخواست برداشت از کیفپول نماینده</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="stat-grid">
|
|
{cards.map(c => (
|
|
<div key={c.label} className="stat" style={{ background: 'var(--surface-3)' }}>
|
|
<div className="lbl">{c.label}</div>
|
|
<div className="val" style={{ color: c.color, fontSize: 15 }}>{c.value}</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
<div className="card card-pad" style={{ marginTop: 'var(--gap)' }}>
|
|
<div className="card-title-row" style={{ marginBottom: 12 }}>
|
|
<h3 style={{ fontSize: 16 }}>ثبت درخواست جدید</h3>
|
|
</div>
|
|
{ibans.length === 0 ? (
|
|
<div className="muted" style={{ fontSize: 13 }}>
|
|
برای ثبت درخواست تسویه، ابتدا در{' '}
|
|
<a href="/admin/representation-profile" style={{ color: 'var(--primary)', fontWeight: 600 }}>پروفایل</a>{' '}
|
|
یک شماره شبای تأییدشده اضافه کنید.
|
|
</div>
|
|
) : (
|
|
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
|
|
<input
|
|
type="text" inputMode="numeric" dir="ltr" value={amount} placeholder="مبلغ به تومان"
|
|
onChange={(e) => setAmount(digitsOnly(e.target.value))}
|
|
style={{ width: 200, height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', fontSize: 13.5, boxSizing: 'border-box' }}
|
|
/>
|
|
<div style={{ width: 320 }}>
|
|
<SearchableSelect
|
|
options={ibans.map((b) => ({ value: String(b.id), label: `${b.iban}${b.bank_name ? ` — ${b.bank_name}` : ''}` }))}
|
|
value={ibanId || null}
|
|
onChange={(v) => setIbanId(v ? String(v) : '')}
|
|
placeholder="انتخاب شماره شبا..."
|
|
isClearable
|
|
height={38}
|
|
/>
|
|
</div>
|
|
<button className="btn primary" onClick={submit} disabled={createMut.isPending}>
|
|
{createMut.isPending ? 'در حال ثبت...' : 'ثبت درخواست'}
|
|
</button>
|
|
<span className="muted" style={{ fontSize: 12 }}>حداکثر: {formatRial(balance)}</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="card card-pad" style={{ marginTop: 'var(--gap)' }}>
|
|
<div className="card-title-row" style={{ marginBottom: 12 }}>
|
|
<h3 style={{ fontSize: 16 }}>درخواستهای قبلی</h3>
|
|
</div>
|
|
<div style={{ overflowX: 'auto' }}>
|
|
<div className="table-wrap"><table className="tbl" style={{ width: '100%' }}>
|
|
<thead><tr><th>مبلغ</th><th>وضعیت</th><th>توضیح مدیر</th><th>تاریخ</th></tr></thead>
|
|
<tbody>
|
|
{settlements.length === 0 && (
|
|
<tr><td colSpan={4} className="muted" style={{ textAlign: 'center', padding: 16 }}>درخواستی ثبت نشده است</td></tr>
|
|
)}
|
|
{settlements.map(s => (
|
|
<tr key={s.uuid}>
|
|
<td>{formatRial(s.amount_rials)}</td>
|
|
<td><span className={`badge ${STATUS_CLASS[s.status] ?? 'gray'}`}>{STATUS_LABEL[s.status] ?? s.status}</span></td>
|
|
<td>{s.admin_note ?? '—'}</td>
|
|
<td>{formatDate(s.created_at)}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table></div>
|
|
</div>
|
|
<Pagination page={page} total={settlementsTotal} limit={limit} onPageChange={setPage} />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|