feat(migrations): add national_code_verified flag to users and normalize bank_account representation

- Added a new column `national_code_verified` to the `users` table.
- Normalized the `bank_account` field in the `representations` table from a single object to an array of IBANs with a default `verified` status of false.

feat(ApiIrService): implement identity verification client for api.ir

- Created `ApiIrService` to handle identity verification via api.ir.
- Implemented methods for matching national code with mobile and IBAN with national code and birth date.
- Added error handling and logging for external API requests.
This commit is contained in:
hamed
2026-06-25 19:38:47 +03:30
parent 9b608aaeac
commit c2c6ae4d02
515 changed files with 194899 additions and 55 deletions
+2
View File
@@ -32,6 +32,7 @@ import SettingsPage from './pages/SettingsPage';
import FinancialReportPage from './pages/FinancialReportPage';
import RepresentationSettlementPage from './pages/RepresentationSettlementPage';
import RepresentationFinancePage from './pages/RepresentationFinancePage';
import RepresentationProfilePage from './pages/RepresentationProfilePage';
import DoctorProfilePage from './pages/DoctorProfilePage';
import MyPatientsPage from './pages/MyPatientsPage';
import NewSessionPage from './pages/NewSessionPage';
@@ -172,6 +173,7 @@ export default function App() {
{/* فقط ادمین — کلینیک از طریق دعوتنامه در صفحه کلینیک خود دکتر اضافه می‌کند */}
<Route path="representation-settlement" element={<RoleRoute roles={['representation']}><RepresentationSettlementPage /></RoleRoute>} />
<Route path="representation-finance" element={<RoleRoute roles={['representation']}><RepresentationFinancePage /></RoleRoute>} />
<Route path="representation-profile" element={<RoleRoute roles={['representation']}><RepresentationProfilePage /></RoleRoute>} />
<Route path="doctors" element={<RoleRoute roles={['admin', 'representation']}><DoctorsPage /></RoleRoute>} />
<Route path="doctors/new" element={<RoleRoute roles={['admin', 'representation']}><DoctorFormPage /></RoleRoute>} />
<Route path="doctors/:uuid" element={<RoleRoute roles={['admin', 'doctor', 'clinic', 'representation']}><DoctorDetailPage /></RoleRoute>} />
@@ -389,6 +389,12 @@ function buildSections(
{ to: "/admin/representation-settlement", icon: BanknotesIcon, label: "تسویه حساب" },
],
},
{
label: "حساب",
items: [
{ to: "/admin/representation-profile", icon: UserCircleIcon, label: "پروفایل" },
],
},
];
}
@@ -0,0 +1,180 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { CheckBadgeIcon, TrashIcon, PlusIcon } from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
interface IbanItem {
id: string;
iban: string;
bank_name: string | null;
owner_name: string | null;
verified: boolean;
}
interface RepProfile {
full_name: string;
mobile_number: string | null;
national_code: string | null;
national_code_verified: boolean;
bank_account: IbanItem[] | null;
}
// پاسخ تک‌منبعی ممکن است double-nested باشد
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const unwrap = (d: any): RepProfile | undefined => d?.data?.data ?? d?.data;
export default function RepresentationProfilePage() {
const qc = useQueryClient();
const [nationalCode, setNationalCode] = useState('');
const [iban, setIban] = useState('');
const [birthDate, setBirthDate] = useState('');
const meQ = useQuery({
queryKey: ['representation-me'],
queryFn: () => api.get<ApiResponse<RepProfile>>('/api/v1/representation/me'),
staleTime: 30_000,
});
const profile = unwrap(meQ.data);
const verified = profile?.national_code_verified ?? false;
const ibans = profile?.bank_account ?? [];
const verifyMut = useMutation({
mutationFn: (code: string) =>
api.post<ApiResponse<RepProfile>>('/api/v1/representation/verify-national-code', { national_code: code }),
onSuccess: () => {
toast.success('کد ملی با موفقیت تأیید شد');
setNationalCode('');
qc.invalidateQueries({ queryKey: ['representation-me'] });
},
onError: (e: Error) => toast.error(e.message),
});
const addIbanMut = useMutation({
mutationFn: (v: string) =>
api.post<ApiResponse<RepProfile>>('/api/v1/representation/iban', { iban: v }),
onSuccess: () => {
toast.success('شماره شبا تأیید و اضافه شد');
setIban('');
qc.invalidateQueries({ queryKey: ['representation-me'] });
},
onError: (e: Error) => toast.error(e.message),
});
const removeIbanMut = useMutation({
mutationFn: (id: string) =>
api.delete<ApiResponse<RepProfile>>(`/api/v1/representation/iban/${id}`),
onSuccess: () => {
toast.success('شماره شبا حذف شد');
qc.invalidateQueries({ queryKey: ['representation-me'] });
},
onError: (e: Error) => toast.error(e.message),
});
const submitNationalCode = () => {
const code = nationalCode.replace(/\D/g, '');
if (code.length !== 10) { toast.error('کد ملی باید ۱۰ رقم باشد'); return; }
verifyMut.mutate(code);
};
const submitIban = () => {
if (!iban.trim()) { toast.error('شماره شبا را وارد کنید'); return; }
addIbanMut.mutate(iban.trim());
};
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="card card-pad">
<div className="card-title-row" style={{ marginBottom: 12 }}>
<h3 style={{ fontSize: 16 }}>تأیید هویت</h3>
{verified && (
<span className="badge green" style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<CheckBadgeIcon style={{ width: 15, height: 15 }} /> کد ملی تأیید شده
</span>
)}
</div>
{verified ? (
<div className="muted" style={{ fontSize: 13.5 }}>
کد ملی: <span dir="ltr" style={{ fontWeight: 600 }}>{profile?.national_code}</span>
</div>
) : (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<input
type="text" inputMode="numeric" dir="ltr" maxLength={10} value={nationalCode}
placeholder="کد ملی ۱۰ رقمی"
onChange={(e) => setNationalCode(e.target.value.replace(/\D/g, ''))}
style={{ width: 220, 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', textAlign: 'center' }}
/>
<button className="btn primary" onClick={submitNationalCode} disabled={verifyMut.isPending}>
{verifyMut.isPending ? 'در حال تأیید...' : 'تأیید کد ملی'}
</button>
<span className="muted" style={{ fontSize: 12 }}>با استعلام شاهکار بررسی میشود</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>
<span className="muted" style={{ fontSize: 12 }}>{ibans.length} از ۲</span>
</div>
<div style={{ overflowX: 'auto' }}>
<table className="tbl" style={{ width: '100%' }}>
<thead><tr><th>شماره شبا</th><th>بانک</th><th>صاحب حساب</th><th>وضعیت</th><th></th></tr></thead>
<tbody>
{ibans.length === 0 && (
<tr><td colSpan={5} className="muted" style={{ textAlign: 'center', padding: 16 }}>هنوز شبایی ثبت نشده است</td></tr>
)}
{ibans.map((b) => (
<tr key={b.id}>
<td dir="ltr" style={{ textAlign: 'left', fontFamily: 'monospace' }}>{b.iban}</td>
<td>{b.bank_name ?? '—'}</td>
<td>{b.owner_name ?? '—'}</td>
<td><span className={`badge ${b.verified ? 'green' : 'gray'}`}>{b.verified ? 'تأیید شده' : 'تأیید نشده'}</span></td>
<td style={{ textAlign: 'center' }}>
<button className="btn icon danger" title="حذف" onClick={() => removeIbanMut.mutate(b.id)} disabled={removeIbanMut.isPending}>
<TrashIcon style={{ width: 16, height: 16 }} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{!verified && (
<div className="muted" style={{ fontSize: 12.5, marginTop: 12 }}>
برای افزودن شبا ابتدا باید کد ملی خود را تأیید کنید.
</div>
)}
{verified && ibans.length < 2 && (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 14 }}>
<input
type="text" dir="ltr" value={iban} placeholder="IR000000000000000000000000"
onChange={(e) => setIban(e.target.value)}
style={{ width: 320, height: 38, padding: '0 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', fontSize: 13, boxSizing: 'border-box', fontFamily: 'monospace' }}
/>
<button className="btn primary" onClick={submitIban} disabled={addIbanMut.isPending} style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<PlusIcon style={{ width: 16, height: 16 }} />
{addIbanMut.isPending ? 'در حال بررسی...' : 'افزودن شبا'}
</button>
<span className="muted" style={{ fontSize: 12 }}>مالکیت با استعلام بررسی میشود</span>
</div>
)}
</div>
</div>
);
}
@@ -22,9 +22,13 @@ 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 balanceQ = useQuery({
queryKey: ['wallet-balance'],
@@ -34,6 +38,14 @@ export default function RepresentationSettlementPage() {
// 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'),
@@ -51,8 +63,8 @@ export default function RepresentationSettlementPage() {
const settlements: SettlementRow[] = (listQ.data?.data as any)?.data ?? listQ.data?.data ?? [];
const createMut = useMutation({
mutationFn: (amountRials: number) =>
api.post<ApiResponse<SettlementRow>>('/api/v1/settlement', { amount_rials: amountRials }),
mutationFn: (payload: { amount_rials: number; iban_id: string }) =>
api.post<ApiResponse<SettlementRow>>('/api/v1/settlement', payload),
onSuccess: () => {
toast.success('درخواست تسویه ثبت شد');
setAmount('');
@@ -67,7 +79,8 @@ export default function RepresentationSettlementPage() {
const n = Number(amount);
if (!n || n <= 0) { toast.error('مبلغ نامعتبر است'); return; }
if (n > balance) { toast.error('مبلغ بیشتر از موجودی قابل برداشت است'); return; }
createMut.mutate(n);
if (!ibanId) { toast.error('انتخاب شماره شبا الزامی است'); return; }
createMut.mutate({ amount_rials: n, iban_id: ibanId });
};
const cards = [
@@ -98,17 +111,34 @@ export default function RepresentationSettlementPage() {
<div className="card-title-row" style={{ marginBottom: 12 }}>
<h3 style={{ fontSize: 16 }}>ثبت درخواست جدید</h3>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<input
type="number" min={0} dir="ltr" value={amount} placeholder="مبلغ به ریال"
onChange={(e) => setAmount(e.target.value)}
style={{ width: 240, 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' }}
/>
<button className="btn primary" onClick={submit} disabled={createMut.isPending}>
{createMut.isPending ? 'در حال ثبت...' : 'ثبت درخواست'}
</button>
<span className="muted" style={{ fontSize: 12 }}>حداکثر: {formatRial(balance)}</span>
</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="number" min={0} dir="ltr" value={amount} placeholder="مبلغ به ریال"
onChange={(e) => setAmount(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' }}
/>
<select
value={ibanId} onChange={(e) => setIbanId(e.target.value)} dir="ltr"
style={{ width: 320, height: 38, padding: '0 10px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', fontSize: 12.5, boxSizing: 'border-box' }}
>
<option value="">انتخاب شماره شبا...</option>
{ibans.map((b) => (
<option key={b.id} value={b.id}>{b.iban}{b.bank_name ? `${b.bank_name}` : ''}</option>
))}
</select>
<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)' }}>
+32 -10
View File
@@ -78,7 +78,7 @@ export default function SettlementDetailPage() {
onError: (e: Error) => toast.error(e.message),
});
// آپلود رسید → سپس ثبت پرداخت نهایی (paid). مبلغ قبلاً هنگام درخواست از کیف‌پول کسر شده.
// آپلود رسید (بدون نهایی‌سازی). نهایی‌سازی با دکمه‌ی جداگانه‌ی «تکمیل» انجام می‌شود.
const handleReceiptUpload = async (file: File) => {
setPaying(true);
try {
@@ -94,15 +94,26 @@ export default function SettlementDetailPage() {
const json = await res.json();
const url = json?.data?.url;
if (!url) throw new Error('آپلود رسید ناموفق بود');
await api.post<ApiResponse<null>>(`/api/v1/settlement/${uuid}/paid`, { receipt: url });
toast.success('پرداخت ثبت شد');
// رسید را در همان رکورد ذخیره می‌کنیم تا دکمه‌ی «تکمیل» فعال شود (وضعیت همچنان approved).
await api.post<ApiResponse<null>>(`/api/v1/settlement/${uuid}/receipt`, { receipt: url });
toast.success('رسید آپلود شد');
qc.invalidateQueries({ queryKey: ['settlement-detail', uuid] });
qc.invalidateQueries({ queryKey: ['settlements'] });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) { toast.error(e?.message ?? 'خطا در ثبت پرداخت'); }
} catch (e: any) { toast.error(e?.message ?? 'خطا در آپلود رسید'); }
finally { setPaying(false); }
};
// تکمیل: نهایی‌سازی پرداخت (وضعیت → paid). مبلغ قبلاً هنگام درخواست از کیف‌پول کسر شده.
const completeMut = useMutation({
mutationFn: () => api.post<ApiResponse<null>>(`/api/v1/settlement/${uuid}/paid`, { receipt: s?.receipt }),
onSuccess: () => {
toast.success('تسویه تکمیل شد');
qc.invalidateQueries({ queryKey: ['settlement-detail', uuid] });
qc.invalidateQueries({ queryKey: ['settlements'] });
},
onError: (e: Error) => toast.error(e.message),
});
if (isLoading) {
return (
<div className="fade-in">
@@ -186,16 +197,27 @@ export default function SettlementDetailPage() {
)}
{s.status === 'approved' && (
<div style={{ marginTop: 14 }}>
<div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
<input ref={receiptInputRef} type="file" accept="image/*" style={{ display: 'none' }}
onChange={e => e.target.files?.[0] && handleReceiptUpload(e.target.files[0])} />
<button className="btn primary sm" disabled={paying}
<button className="btn ghost sm" disabled={paying}
onClick={() => receiptInputRef.current?.click()}>
<ArrowUpTrayIcon style={{ width: 15, height: 15 }} />
{paying ? 'در حال ثبت...' : 'آپلود رسید و ثبت پرداخت'}
{paying ? 'در حال آپلود...' : (s.receipt ? 'تغییر رسید' : 'آپلود رسید')}
</button>
<p className="muted" style={{ fontSize: 12, marginTop: 8 }}>
با آپلود رسید، وضعیت به «پرداخت شده» تغییر میکند. مبلغ هنگام ثبت درخواست از کیفپول کسر شده است.
{/* دکمه‌ی تکمیل فقط بعد از آپلود رسید فعال می‌شود */}
<button className="btn primary sm" disabled={!s.receipt || completeMut.isPending}
onClick={() => completeMut.mutate()}
title={!s.receipt ? 'ابتدا رسید را آپلود کنید' : undefined}>
<CheckIcon style={{ width: 15, height: 15 }} />
{completeMut.isPending ? 'در حال تکمیل...' : 'تکمیل'}
</button>
<p className="muted" style={{ fontSize: 12, width: '100%' }}>
{s.receipt
? 'با زدن «تکمیل»، وضعیت به «پرداخت شده» تغییر می‌کند. مبلغ هنگام ثبت درخواست از کیف‌پول کسر شده است.'
: 'ابتدا رسید پرداخت را آپلود کنید، سپس دکمه‌ی «تکمیل» فعال می‌شود.'}
</p>
</div>
)}