feat: port tauri create-service payment flow to admin session settlement

Port the tauri /files/create-service page (payment mode) to the admin SPA
and back it with real multi-part session settlement:

Backend:
- New SessionPayment entity (session_payments table): partial payments
  per session with method (wallet/pos/cash/card), amount, paid_at, actor
- PatientSession: settlement discount (percent/fixed), discount_rials,
  paid_at, payments relation; remaining debt derived from
  final - discount - paid total
- POST /api/v1/session/{uuid}/payments: register a partial payment;
  wallet method debits the patient wallet; zero remaining marks paid
- PATCH /api/v1/session/{uuid}: accepts discount_type/discount_value
  (null removes) and paid_at, backward compatible
- New error codes: ERR_SESSION_PAYMENT_INVALID/_EXCEEDS,
  ERR_SESSION_DISCOUNT_INVALID
- Migration + 14 functional tests (partial/full/wallet/exceed/discount)

Frontend (admin):
- SessionPaymentPage: two-step stepper (پرداخت ← جزییات) ported from
  tauri AddService payment mode — service cost, settlement discount
  input, Jalali payment date, wallet balance, 4-method payment accordion,
  paid-list box, details summary
- SessionStepper + stepper/payment icons ported verbatim from tauri SVGs
- «تکمیل پرداخت» on SessionServiceCard now navigates to the payment page
  (replaces the small settle modal on PatientDetailPage)
- Routes for patients/ and my-patients/ variants; vitest coverage
- docs/api/patient.md updated

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-16 13:32:06 +03:30
co-authored by Claude Opus 4.8
parent 73ae4baa66
commit 27d088c6dd
18 changed files with 1425 additions and 55 deletions
+10 -8
View File
@@ -199,16 +199,18 @@ describe('PatientDetailPage (پرونده تب‌دار)', () => {
await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/patient/r1/wallet/charge', { amount_rials: 500000, payment_method: 'cash' }));
});
it('settles a session from the wallet via the payment-method chooser', async () => {
const patch = api.patch as ReturnType<typeof vi.fn>;
patch.mockResolvedValue({ success: true, data: {} });
renderDetail();
it('navigates to the session payment page when «تکمیل پرداخت» is clicked', async () => {
renderWithProviders(
<Routes>
<Route path="/admin/patients/:uuid" element={<PatientDetailPage />} />
<Route path="/admin/patients/:recordUuid/session/:sessionUuid/pay" element={<div>صفحه تکمیل پرداخت</div>} />
</Routes>,
{ route: '/admin/patients/r1' },
);
await loaded();
// تب سرویس‌ها پیش‌فرض است؛ کارت پرداخت‌نشده → «تکمیل پرداخت»
// تب سرویس‌ها پیش‌فرض است؛ کارت پرداخت‌نشده → «تکمیل پرداخت» → صفحه‌ی استپر پرداخت
fireEvent.click(await screen.findByText('تکمیل پرداخت'));
expect(await screen.findByText('روش پرداخت مراجعه')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'کیف پول بیمار' }));
await waitFor(() => expect(patch).toHaveBeenCalledWith('/api/v1/session/s1', { payment_method: 'wallet' }));
expect(await screen.findByText('صفحه تکمیل پرداخت')).toBeInTheDocument();
});
it('renders the notes tab with a compose box and empty state', async () => {
+22 -43
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useSearchParams, Link } from 'react-router-dom';
import { useParams, useSearchParams, Link, useNavigate } from 'react-router-dom';
import {
ChevronRightIcon, PencilIcon, ClipboardDocumentCheckIcon, DocumentTextIcon,
CalendarDaysIcon, CreditCardIcon, BanknotesIcon, ChatBubbleLeftRightIcon,
@@ -13,7 +13,7 @@ import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import { useAuthStore } from '../stores/authStore';
import { formatDate, formatRial, formatTime, formatNumber } from '../lib/utils';
import { formatDate, formatDateTime, formatRial, formatTime, formatNumber } from '../lib/utils';
import DataTable, { type Column } from '../components/ui/DataTable';
import type { WalletTxn } from '../hooks/usePatientWallet';
import type { WalletModalSubmit } from '../components/WalletTransactionModal';
@@ -78,8 +78,8 @@ export default function PatientDetailPage() {
const record = data?.data;
const qc = useQueryClient();
const nav = useNavigate();
const [invoiceUuid, setInvoiceUuid] = useState<string | null>(null);
const [settleTarget, setSettleTarget] = useState<string | null>(null);
// ── فرم «اطلاعات پرونده» (اینلاین، معادل tauri FileInfoSection) ──────────────
// استان/شهر (Location) و بیمهٔ پایه (insurance-pricing) برای گزینه‌های فرم.
@@ -143,19 +143,6 @@ export default function PatientDetailPage() {
.filter((a: any) => (a.starts_at ?? 0) >= nowSec && !String(a.status).startsWith('cancelled'))
.sort((a: any, b: any) => a.starts_at - b.starts_at)[0]?.starts_at ?? null;
const settle = useMutation({
mutationFn: ({ sessionUuid, method }: { sessionUuid: string; method: string }) =>
api.patch(`/api/v1/session/${sessionUuid}`, { payment_method: method }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['patient-sessions', uuid] });
// پرداخت از کیف پول موجودی را کم می‌کند → دفتر کیف پول را هم تازه کن.
qc.invalidateQueries({ queryKey: ['patient-wallet', uuid] });
toast.success('پرداخت ثبت شد');
setSettleTarget(null);
},
onError: (e: any) => toast.error(e?.message || 'خطا در ثبت پرداخت'),
});
return (
<div className="fade-in">
{/* breadcrumb + patient banner (tauri BreadcrumbHeader + FileServicesHeader) */}
@@ -230,7 +217,7 @@ export default function PatientDetailPage() {
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', columnGap: 6, rowGap: 10, alignItems: 'stretch' }}>
{sessions.map((s) => (
<SessionServiceCard key={s.uuid} session={s} settling={settle.isPending} onSettle={(u) => setSettleTarget(u)} onViewInvoice={(iv) => setInvoiceUuid(iv)} />
<SessionServiceCard key={s.uuid} session={s} onSettle={(u) => nav(`/admin/patients/${uuid}/session/${u}/pay`)} onViewInvoice={(iv) => setInvoiceUuid(iv)} />
))}
</div>
)}
@@ -254,28 +241,6 @@ export default function PatientDetailPage() {
)}
<InvoiceSummaryModal invoiceUuid={invoiceUuid} onClose={() => setInvoiceUuid(null)} />
{/* انتخاب روش پرداختِ مراجعه (نقدی / کارت / کیف پول) */}
<Modal open={settleTarget !== null} title="روش پرداخت مراجعه" onClose={() => setSettleTarget(null)}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<p style={{ fontSize: 13, color: 'var(--text-3)', margin: 0 }}>روش تسویهٔ این مراجعه را انتخاب کنید:</p>
{[
{ method: 'cash', label: 'نقدی' },
{ method: 'card', label: 'کارت به کارت' },
{ method: 'wallet', label: 'کیف پول بیمار' },
].map((m) => (
<button
key={m.method}
className="btn"
style={{ justifyContent: 'flex-start' }}
disabled={settle.isPending}
onClick={() => settleTarget && settle.mutate({ sessionUuid: settleTarget, method: m.method })}
>
{m.label}
</button>
))}
</div>
</Modal>
</div>
);
}
@@ -663,6 +628,20 @@ function CallCenterTab({ uuid }: { uuid: string }) {
const [summary, setSummary] = useState('');
const [outcome, setOutcome] = useState<'success' | 'missed'>('success');
// Keep تاریخ/ساعت تماس live while the user hasn't manually edited them, so a
// long-open tab doesn't submit a stale time without a page refresh.
const dateTouched = useRef(false);
const timeTouched = useRef(false);
useEffect(() => {
const sync = () => {
if (!dateTouched.current) setDate(nowDate());
if (!timeTouched.current) setTime(nowTime());
};
const id = window.setInterval(sync, 30_000);
window.addEventListener('focus', sync);
return () => { window.clearInterval(id); window.removeEventListener('focus', sync); };
}, []);
const { data, isLoading } = useQuery<ApiResponse<Call[]>>({
queryKey: ['patient-calls', uuid],
queryFn: () => api.get(`/api/v1/patient/${uuid}/calls`),
@@ -679,7 +658,7 @@ function CallCenterTab({ uuid }: { uuid: string }) {
const calledAt = iso ? Math.floor(new Date(iso).getTime() / 1000) : Math.floor(Date.now() / 1000);
return api.post(`/api/v1/patient/${uuid}/call`, { subject, summary, outcome, called_at: calledAt, personnel: userName });
},
onSuccess: () => { invalidate(); setDate(nowDate()); setTime(nowTime()); setSubject(''); setSummary(''); setOutcome('success'); toast.success('تماس ثبت شد'); },
onSuccess: () => { invalidate(); dateTouched.current = false; timeTouched.current = false; setDate(nowDate()); setTime(nowTime()); setSubject(''); setSummary(''); setOutcome('success'); toast.success('تماس ثبت شد'); },
onError: (e: any) => toast.error(e.message),
});
const del = useMutation({
@@ -703,9 +682,9 @@ function CallCenterTab({ uuid }: { uuid: string }) {
<div style={{ width: 320, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 18 }}>
<div style={{ fontSize: 14, fontWeight: 700, textAlign: 'center', marginBottom: 16 }}>ثبت تماس جدید</div>
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>تاریخ تماس</label>
<div style={{ margin: '6px 0 12px' }}><PersianDateInput value={date} onChange={setDate} /></div>
<div style={{ margin: '6px 0 12px' }}><PersianDateInput value={date} onChange={(v) => { dateTouched.current = true; setDate(v); }} /></div>
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>ساعت تماس</label>
<div className="field" style={{ margin: '6px 0 12px' }}><input type="time" value={time} onChange={(e) => setTime(e.target.value)} dir="ltr" /></div>
<div className="field" style={{ margin: '6px 0 12px' }}><input type="time" value={time} onChange={(e) => { timeTouched.current = true; setTime(e.target.value); }} dir="ltr" /></div>
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>موضوع تماس</label>
<div className="field" style={{ margin: '6px 0 12px' }}><input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="موضوع تماس" /></div>
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>خلاصه تماس</label>
@@ -746,7 +725,7 @@ function CallCenterTab({ uuid }: { uuid: string }) {
{c.summary && <div style={{ fontSize: 12.5, color: 'var(--text-2)', marginTop: 4 }}>{c.summary}</div>}
</div>
<div style={{ textAlign: 'end', minWidth: 120 }}>
<div style={{ fontSize: 12, color: 'var(--text-3)' }}>{formatDate(c.called_at)}</div>
<div style={{ fontSize: 12, color: 'var(--text-3)' }}>{formatDateTime(c.called_at)}</div>
{c.personnel && <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>{c.personnel}</div>}
<button className="btn sm ghost" aria-label="حذف" style={{ color: 'var(--danger)', marginTop: 4 }} onClick={() => del.mutate(c.uuid)}><TrashIcon style={{ width: 14 }} /></button>
</div>
@@ -0,0 +1,147 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, waitFor } from '@testing-library/react';
import { Routes, Route } from 'react-router-dom';
import { renderWithProviders } from '../test/utils';
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
ApiError: class extends Error {},
}));
import { api } from '../lib/api';
import { formatRial } from '../lib/utils';
import SessionPaymentPage from './SessionPaymentPage';
const get = api.get as ReturnType<typeof vi.fn>;
const post = api.post as ReturnType<typeof vi.fn>;
const patch = api.patch as ReturnType<typeof vi.fn>;
const session = (over: object = {}) => ({
uuid: 's1',
services: [{ service_name: 'کاشت مو' }],
doctor_name: 'دکتر فتحی',
visit_price_rials: 0,
final_price_rials: 2_500_000,
is_paid: false,
patient_debt_rials: 2_300_000,
discount_rials: 200_000,
paid_total_rials: 0,
payments: [] as object[],
created_at: 1_700_000_000,
...over,
});
function mockGets(sessions: object[]) {
get.mockImplementation((url: string) => {
if (url === '/api/v1/patient/r1') {
return Promise.resolve({ success: true, data: { uuid: 'r1', user_name: 'ساغر صابری', profile: {} } });
}
if (url === '/api/v1/patient/r1/sessions') return Promise.resolve({ success: true, data: sessions });
if (url === '/api/v1/patient/r1/wallet') {
return Promise.resolve({ success: true, data: { balance_rials: 300_000, recent_transactions: [] } });
}
return Promise.resolve({ success: true, data: [] });
});
}
function renderPage() {
return renderWithProviders(
<Routes>
<Route path="/admin/patients/:recordUuid/session/:sessionUuid/pay" element={<SessionPaymentPage />} />
</Routes>,
{ route: '/admin/patients/r1/session/s1/pay' },
);
}
beforeEach(() => {
get.mockReset();
post.mockReset();
patch.mockReset();
});
describe('SessionPaymentPage (تکمیل پرداخت مراجعه)', () => {
it('renders payment step with real cost, wallet balance and remaining debt', async () => {
mockGets([session()]);
renderPage();
expect(await screen.findByText('هزینه سرویس:')).toBeInTheDocument();
expect(screen.getAllByText(formatRial(2_500_000)).length).toBeGreaterThan(0);
// استپر دو گام حالت payment
expect(screen.getByText('پرداخت')).toBeInTheDocument();
expect(screen.getByText('جزییات')).toBeInTheDocument();
// موجودی کیف پول
expect(screen.getByText('موجودی کیف پول:')).toBeInTheDocument();
// چهار روش پرداخت tauri
expect(screen.getByText('پرداخت از طریق کیف پول')).toBeInTheDocument();
expect(screen.getByText('پرداخت از طریق کارت خوان')).toBeInTheDocument();
expect(screen.getByText('پرداخت نقدی')).toBeInTheDocument();
expect(screen.getByText('کارت به کارت')).toBeInTheDocument();
// breadcrumb با نام بیمار
expect(screen.getByText('ساغر صابری')).toBeInTheDocument();
});
it('submits a partial payment via the accordion (POST /session/{uuid}/payments)', async () => {
mockGets([session()]);
post.mockResolvedValue({ success: true, data: session({ paid_total_rials: 500_000 }) });
renderPage();
fireEvent.click(await screen.findByText('پرداخت نقدی'));
fireEvent.change(screen.getByPlaceholderText('مبلغ (تومان)'), { target: { value: '500000' } });
fireEvent.click(screen.getByText('ثبت پرداخت'));
await waitFor(() => expect(post).toHaveBeenCalledTimes(1));
const [url, body] = post.mock.calls[0];
expect(url).toBe('/api/v1/session/s1/payments');
expect(body).toMatchObject({ method: 'cash', amount_rials: 500000 });
expect(typeof (body as any).paid_at).toBe('number');
});
it('applies and removes settlement discount (PATCH /session/{uuid})', async () => {
mockGets([session()]);
patch.mockResolvedValue({ success: true, data: session() });
renderPage();
await screen.findByText('هزینه سرویس:');
// حذف تخفیف → discount_type: null
fireEvent.click(screen.getByText('حذف تخفیف'));
await waitFor(() => expect(patch).toHaveBeenCalledWith('/api/v1/session/s1', { discount_type: null }));
});
it('shows registered payments and moves to details step', async () => {
mockGets([session({
payments: [
{ uuid: 'p1', method: 'cash', amount_rials: 1_000_000, paid_at: 1_700_000_000 },
{ uuid: 'p2', method: 'wallet', amount_rials: 300_000, paid_at: 1_700_000_000 },
],
paid_total_rials: 1_300_000,
patient_debt_rials: 1_000_000,
})]);
renderPage();
// «پرداخت نقدی» هم عنوان آکاردئون است هم برچسب پرداخت ثبت‌شده
expect((await screen.findAllByText('پرداخت نقدی')).length).toBeGreaterThanOrEqual(2);
expect(screen.getByText('پرداخت از کیف پول')).toBeInTheDocument();
// گام جزییات
fireEvent.click(screen.getByText('ثبت و ادامه'));
expect(screen.getByText('صدور فاکتور')).toBeInTheDocument();
expect(screen.getByText('کاشت مو')).toBeInTheDocument();
expect(screen.getByText('دکتر فتحی')).toBeInTheDocument();
expect(screen.getByText('مبلغ باقی مانده:')).toBeInTheDocument();
});
it('renders empty payments state (پرداختی ثبت نشده است)', async () => {
mockGets([session({ payments: [], discount_rials: 0 })]);
renderPage();
expect(await screen.findByText('پرداختی ثبت نشده است')).toBeInTheDocument();
});
it('shows not-found message when session uuid does not exist', async () => {
mockGets([session({ uuid: 'other' })]);
renderPage();
expect(await screen.findByText('مراجعه یافت نشد')).toBeInTheDocument();
});
});
+355
View File
@@ -0,0 +1,355 @@
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ChevronDownIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import { formatRial } from '../lib/utils';
import type { SessionCardData } from '../components/SessionServiceCard';
import SessionStepper from '../components/SessionStepper';
import SearchableSelect from '../components/ui/SearchableSelect';
import PersianDateInput from '../components/ui/PersianDateInput';
import {
ArrowLeftPH, ArrowLeftD, CloseModalD, Step2PaymentCard,
FilesServiceBalanceWallet, TrashRed,
} from '../components/icons/FilesServiceIcons';
/** روش‌های پرداخت — همان چهار گزینه‌ی آکاردئون tauri Step2Payment. */
const METHODS: { key: string; label: string }[] = [
{ key: 'wallet', label: 'پرداخت از طریق کیف پول' },
{ key: 'pos', label: 'پرداخت از طریق کارت خوان' },
{ key: 'cash', label: 'پرداخت نقدی' },
{ key: 'card', label: 'کارت به کارت' },
];
const METHOD_LABELS: Record<string, string> = {
wallet: 'پرداخت از کیف پول', pos: 'پرداخت کارتخوان', cash: 'پرداخت نقدی', card: 'کارت به کارت',
};
const todayISO = () => new Date().toISOString().slice(0, 10);
/** YYYY-MM-DD → unix (ظهر همان روز تا با هر timezone یک روز بماند) */
const isoToUnix = (iso: string) => Math.floor(new Date(`${iso}T12:00:00`).getTime() / 1000);
/**
* تکمیل پرداخت مراجعه — پورت صفحه‌ی tauri /files/create-service در حالت payment:
* استپر دوگامی «پرداخت ← جزییات» با تخفیف تسویه، پرداخت چندتکه و تاریخ پرداخت.
*/
export default function SessionPaymentPage() {
const { recordUuid = '', sessionUuid = '' } = useParams();
const nav = useNavigate();
const qc = useQueryClient();
const steps = ['پرداخت', 'جزییات'];
const [activeStep, setActiveStep] = useState(0);
const [discountType, setDiscountType] = useState('');
const [discountValue, setDiscountValue] = useState('');
const [paymentDate, setPaymentDate] = useState(todayISO());
const [expanded, setExpanded] = useState<string | null>(null);
const [amount, setAmount] = useState('');
const recordQ = useQuery<ApiResponse<PatientRecord>>({
queryKey: ['patient-detail', recordUuid],
queryFn: () => api.get(`/api/v1/patient/${recordUuid}`),
enabled: !!recordUuid,
});
const record = recordQ.data?.data as PatientRecord | undefined;
const patientName = record?.user_name || record?.profile?.full_name || '—';
const sessionsQ = useQuery<ApiResponse<SessionCardData[]>>({
queryKey: ['patient-sessions', recordUuid],
queryFn: () => api.get(`/api/v1/patient/${recordUuid}/sessions`),
enabled: !!recordUuid,
});
const session = (sessionsQ.data?.data ?? []).find((s) => s.uuid === sessionUuid);
const walletQ = useQuery<ApiResponse<{ balance_rials: number }>>({
queryKey: ['patient-wallet', recordUuid],
queryFn: () => api.get(`/api/v1/patient/${recordUuid}/wallet`),
enabled: !!recordUuid,
});
const walletBalance = (walletQ.data?.data as any)?.balance_rials ?? 0;
const invalidate = () => {
qc.invalidateQueries({ queryKey: ['patient-sessions', recordUuid] });
qc.invalidateQueries({ queryKey: ['patient-wallet', recordUuid] });
};
const discountMut = useMutation({
mutationFn: (body: object) => api.patch(`/api/v1/session/${sessionUuid}`, body),
onSuccess: () => { invalidate(); toast.success('تخفیف به‌روزرسانی شد'); },
onError: (e: Error) => toast.error(e.message),
});
const payMut = useMutation({
mutationFn: (body: object) => api.post(`/api/v1/session/${sessionUuid}/payments`, body),
onSuccess: () => { invalidate(); setAmount(''); toast.success('پرداخت ثبت شد'); },
onError: (e: Error) => toast.error(e.message),
});
const applyDiscount = () => {
if (!discountType || !discountValue) return;
discountMut.mutate({ discount_type: discountType, discount_value: Number(discountValue) });
};
const removeDiscount = () => {
setDiscountType(''); setDiscountValue('');
discountMut.mutate({ discount_type: null });
};
const submitPayment = (method: string) => {
if (!amount) return;
payMut.mutate({ method, amount_rials: Number(amount), paid_at: isoToUnix(paymentDate) });
};
const finalPrice = session?.final_price_rials ?? 0;
const discountRials = session?.discount_rials ?? 0;
const debt = session?.patient_debt_rials ?? 0;
const payments = session?.payments ?? [];
const serviceNames = (session?.services ?? []).map((s) => s.service_name || s.name).filter(Boolean) as string[];
if ((session?.visit_price_rials ?? 0) > 0) serviceNames.unshift('ویزیت');
const finish = () => nav(`/admin/patients/${recordUuid}?tab=services`);
if (sessionsQ.isLoading) {
return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>در حال بارگذاری...</div>;
}
if (!session) {
return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>مراجعه یافت نشد</div>;
}
const fieldLabel: React.CSSProperties = { fontSize: 14, color: '#6B7280', marginBottom: 8, display: 'block' };
const primaryBtn: React.CSSProperties = { background: '#5559CE', color: '#fff', border: 'none', borderRadius: 4, height: 46, fontSize: 14, fontWeight: 500, cursor: 'pointer' };
const ghostBtn: React.CSSProperties = { background: 'transparent', color: '#5559CE', border: '1px solid #5559CE', borderRadius: 4, height: 46, fontSize: 14, fontWeight: 500, cursor: 'pointer' };
return (
<div className="fade-in" style={{ width: '100%' }}>
{/* breadcrumb — tauri AddService header */}
<div style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 30 }}>
<div className="dark:text-[#A1A1A1]" style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#6B7280', fontSize: 12, padding: '0 16px' }}>
<div
onClick={() => nav(-1)}
className="bg-white dark:bg-[#222433]"
style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 8px', borderRadius: 12, cursor: 'pointer' }}
>
<ArrowLeftPH style={{ width: 18, height: 18, rotate: '180deg' }} />
<span>بازگشت</span>
</div>
<ArrowLeftD />
<span>پرونده</span>
<ArrowLeftD />
<span className="dark:text-[#D7D8ED]" style={{ color: '#111827' }}>{patientName}</span>
</div>
</div>
{/* card — tauri width 748 centered */}
<div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
<div className="bg-white dark:bg-[#222433]" style={{ width: 748, maxWidth: '100%', padding: 24 }}>
<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8 }}>
<button
type="button"
aria-label="بستن"
onClick={() => nav(-1)}
style={{ minWidth: 40, height: 40, marginBottom: 8, borderRadius: '50%', border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
>
<CloseModalD />
</button>
</div>
<SessionStepper activeStep={activeStep} steps={steps} />
{activeStep === 0 ? (
<>
{/* هزینه سرویس */}
<div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '12px 0 16px' }}>
<Step2PaymentCard />
<span style={{ fontSize: 14, color: '#F97316', fontWeight: 700 }}>هزینه سرویس:</span>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 700, color: '#525252' }}>{formatRial(finalPrice)}</span>
</div>
{/* تخفیف — port of tauri DiscountInput (نوع + مقدار + ثبت) */}
<span style={fieldLabel}>تخفیف:</span>
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
<div className="bg-white dark:bg-[#222433] dark:border-[#35343D]" style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', border: '1px solid #e0e0e0', borderRadius: 8, marginBottom: 16 }}>
<div style={{ minWidth: 150, borderLeft: '1px solid #e0e0e0', padding: '0 4px' }}>
<SearchableSelect
options={[{ value: 'percent', label: 'درصدی' }, { value: 'fixed', label: 'مبلغ ثابت' }]}
value={discountType}
onChange={(v) => setDiscountType(v ? String(v) : '')}
placeholder="مبلغ تخفیف"
/>
</div>
<input
type="number"
min={0}
dir="ltr"
placeholder="مقدار تخفیف را وارد نمایید"
value={discountValue}
onChange={(e) => setDiscountValue(e.target.value)}
style={{ flex: 1, minWidth: 0, height: 40, padding: '0 12px', fontSize: 13, border: 'none', outline: 'none', background: 'transparent', color: 'inherit' }}
/>
<button
type="button"
onClick={applyDiscount}
disabled={discountMut.isPending || !discountType || !discountValue}
style={{ height: 40, minWidth: 72, border: 'none', borderRadius: '0 4px 4px 0', background: '#E8EBFF', color: '#3B3F9F', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
ثبت
</button>
</div>
<div
onClick={removeDiscount}
style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0, cursor: 'pointer', marginBottom: 16, minWidth: 120, justifyContent: 'center' }}
>
<TrashRed color="#EF4444" size={18} />
<span className="dark:text-[#A1A1A1]" style={{ fontSize: 13, color: '#6B7280' }}>حذف تخفیف</span>
</div>
</div>
<p style={{ fontSize: 13, marginBottom: 16 }}>
<span className="dark:text-[#D7D8ED]" style={{ color: '#2f2f2f' }}>مبلغ تخفیف:</span>{' '}
<span style={{ color: '#D32F2F' }}>{formatRial(discountRials)}</span>
</p>
{/* تاریخ پرداخت */}
<span className="dark:text-[#A1A1A1]" style={{ ...fieldLabel, color: '#3b3b3b' }}>تاریخ پرداخت</span>
<PersianDateInput value={paymentDate} onChange={setPaymentDate} />
{/* روش‌های پرداخت */}
<span className="dark:text-[#A1A1A1]" style={{ ...fieldLabel, color: '#3b3b3b', marginTop: 24 }}>انتخاب روش های پرداخت:</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ display: 'flex', gap: 4 }}>
<FilesServiceBalanceWallet />
<span style={{ fontSize: 14, color: '#F97316', marginBottom: 8, fontWeight: 600 }}>موجودی کیف پول:</span>
</div>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 600, color: '#525252', marginBottom: 4 }}>{formatRial(walletBalance)}</span>
</div>
{/* آکاردئون چهار روش — باز شدن هر روش: مبلغ + ثبت پرداخت */}
<div style={{ marginTop: 8 }}>
{METHODS.map((m) => {
const open = expanded === m.key;
return (
<div key={m.key} className="dark:border-[#35343D]" style={{ borderBottom: '1px solid #e0e0e0' }}>
<button
type="button"
aria-expanded={open}
onClick={() => { setExpanded(open ? null : m.key); setAmount(''); }}
style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '14px 4px', background: 'transparent', border: 'none', cursor: 'pointer' }}
>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 600, color: '#111827' }}>{m.label}</span>
<ChevronDownIcon style={{ width: 16, color: '#6B7280', transform: open ? 'rotate(180deg)' : undefined, transition: 'transform .15s' }} />
</button>
{open && (
<div style={{ display: 'flex', gap: 8, padding: '0 4px 14px' }}>
<input
type="number"
min={1}
dir="ltr"
className="input"
placeholder="مبلغ (تومان)"
value={amount}
onChange={(e) => setAmount(e.target.value)}
style={{ flex: 1, height: 40 }}
/>
<button
type="button"
onClick={() => submitPayment(m.key)}
disabled={payMut.isPending || !amount}
style={{ ...primaryBtn, height: 40, padding: '0 20px', borderRadius: 8 }}
>
ثبت پرداخت
</button>
</div>
)}
</div>
);
})}
</div>
{/* پرداخت شده‌ها — باکس خط‌چین tauri */}
<div className="dark:border-[#404040] dark:bg-[#222433]" style={{ border: '1px dashed #C7C9F4', borderRadius: 8, padding: 16, marginTop: 16, background: '#fff' }}>
<span className="dark:text-[#6A6AD9]" style={{ fontSize: 16, fontWeight: 500, color: '#636bd4', display: 'block', marginBottom: 16 }}>پرداخت شده ها:</span>
{payments.length === 0 ? (
<span className="dark:text-[#A1A1A1]" style={{ fontSize: 13, color: '#6B7280' }}>پرداختی ثبت نشده است</span>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{payments.map((p) => (
<div key={p.uuid} className="dark:border-[#404040]" style={{ display: 'flex', alignItems: 'center', gap: 32, padding: '4px 0', borderBottom: '1px solid #e0e0e0' }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span className="dark:bg-[#6A6AD9]" style={{ width: 8, height: 8, borderRadius: '50%', background: '#636bd4' }} />
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, color: '#111827' }}>{METHOD_LABELS[p.method] ?? p.method}</span>
</span>
<span className="dark:text-[#D7D8ED]" style={{ flex: 1, textAlign: 'left', fontSize: 14, color: '#111827' }}>مبلغ : {formatRial(p.amount_rials)}</span>
</div>
))}
</div>
)}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#111827' }}>مبلغ باقیمانده :</span>
<span className="dark:text-[#FF5252]" style={{ fontSize: 14, fontWeight: 600, color: '#d32f2f' }}>{formatRial(debt)}</span>
</div>
</div>
{/* ACTIONS */}
<div style={{ display: 'flex', gap: 8, marginTop: 16, width: '100%', justifyContent: 'flex-end' }}>
<div style={{ width: '50%', display: 'flex', gap: 4 }}>
<button type="button" style={{ ...ghostBtn, flex: 1 }} onClick={() => nav(-1)}>انصراف</button>
<button type="button" style={{ ...primaryBtn, flex: 1 }} onClick={() => setActiveStep(1)}>ثبت و ادامه</button>
</div>
</div>
</>
) : (
<>
{/* گام جزییات — پورت tauri Step3Final با دیتای واقعی */}
<div dir="rtl" className="dark:border-[#404040] dark:bg-[#222433]" style={{ padding: 16, border: '1px dashed #A7A7E0' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 32, marginBottom: 16 }}>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#2f2f2f' }}>
{serviceNames.length ? serviceNames.join(' - ') : 'ویزیت'}
</span>
<span className="dark:bg-[#404040]" style={{ width: 1, height: 38, background: '#E0E0E0' }} />
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#525252' }}>{session.doctor_name || '—'}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 72, marginBottom: 16 }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#525252' }}>هزینه سرویس:</span>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#525252' }}>{formatRial(finalPrice)}</span>
</span>
<span className="dark:bg-[#404040]" style={{ width: 1, height: 38, background: '#E0E0E0' }} />
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#525252' }}>تخفیف:</span>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 500, color: '#525252' }}>{formatRial(discountRials)}</span>
</span>
</div>
<span className="dark:text-[#6A6AD9]" style={{ fontSize: 13, fontWeight: 600, color: '#5559CE', display: 'block', marginBottom: 12 }}>پرداخت شده ها:</span>
{payments.length === 0 ? (
<span className="dark:text-[#A1A1A1]" style={{ fontSize: 13, color: '#6B7280' }}>پرداختی ثبت نشده است</span>
) : payments.map((p) => (
<div key={p.uuid} className="dark:border-[#404040]" style={{ display: 'flex', alignItems: 'center', gap: 56, padding: '8px 0', borderBottom: '1px solid #EEE' }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span className="dark:bg-[#6A6AD9]" style={{ width: 6, height: 6, borderRadius: '50%', background: '#5559CE', flexShrink: 0 }} />
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 600, color: '#525252' }}>{METHOD_LABELS[p.method] ?? p.method}</span>
</span>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 600, color: '#111827' }}>مبلغ: {formatRial(p.amount_rials)}</span>
</div>
))}
<div style={{ display: 'flex', width: '100%', justifyContent: 'flex-end', alignItems: 'center' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16 }}>
<span className="dark:text-[#D7D8ED]" style={{ fontSize: 14, fontWeight: 600, color: '#525252' }}>مبلغ باقی مانده:</span>
<span className="dark:text-[#FF5252]" style={{ fontSize: 14, fontWeight: 600, color: '#d32f2f' }}>{formatRial(debt)}</span>
</div>
</div>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16, width: '100%', maxWidth: 320, margin: '16px auto 0' }}>
<button type="button" style={{ ...ghostBtn, flex: 1 }} onClick={() => setActiveStep(0)}>انصراف</button>
<button type="button" style={{ ...primaryBtn, flex: 1 }} onClick={finish}>صدور فاکتور</button>
</div>
</>
)}
</div>
</div>
</div>
);
}