feat: add mobile-based patient lookup for appointment booking
- Implemented a new endpoint `/api/v1/my/appointment/patient-lookup` to search for patients by mobile number before booking an appointment. - Updated the `NewAppointmentModal` component to utilize the new patient lookup feature, allowing for direct booking if the patient is found with a national code. - Enhanced the appointment booking form to handle mobile input normalization and display relevant fields based on the search results. - Added tests for the new patient lookup functionality, ensuring proper behavior for found and not found cases, as well as validation for mobile input. - Updated sidebar tests to reflect changes in the sidebar component structure and functionality.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/utils';
|
||||
|
||||
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 { useAuthStore } from '../stores/authStore';
|
||||
import { NewAppointmentModal } from './AppointmentsPage';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
const post = api.post as ReturnType<typeof vi.fn>;
|
||||
|
||||
const slot = { start: 1_800_000_000, end: 1_800_001_800, start_time: '15:00', end_time: '15:30', doctor_uuid: 'doc1', doctor_name: 'دکتر تست' };
|
||||
|
||||
beforeEach(() => {
|
||||
get.mockReset();
|
||||
post.mockReset();
|
||||
useAuthStore.setState({ primaryRole: 'doctor' } as any);
|
||||
post.mockResolvedValue({ success: true, data: { uuid: 'new1' } });
|
||||
});
|
||||
|
||||
describe('NewAppointmentModal — جستجوی موبایلمحور', () => {
|
||||
it('submit stays disabled until a mobile search is done', () => {
|
||||
renderWithProviders(<NewAppointmentModal slot={slot} onClose={() => {}} onSuccess={() => {}} />);
|
||||
fireEvent.change(screen.getByPlaceholderText('مثال: 09123456789'), { target: { value: '09121234567' } });
|
||||
// بدون جستجو، ثبت نوبت غیرفعال است
|
||||
expect(screen.getByRole('button', { name: 'ثبت نوبت' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('converts Persian digits to English and searches by the normalized mobile', async () => {
|
||||
get.mockResolvedValue({ success: true, data: { found: false } });
|
||||
renderWithProviders(<NewAppointmentModal slot={slot} onClose={() => {}} onSuccess={() => {}} />);
|
||||
|
||||
const input = screen.getByPlaceholderText('مثال: 09123456789') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '۰۹۱۲۳۴۵۶۷۸۹' } });
|
||||
expect(input.value).toBe('09123456789');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'جستجو' }));
|
||||
await waitFor(() => expect(get).toHaveBeenCalledWith('/api/v1/my/appointment/patient-lookup?mobile=09123456789'));
|
||||
});
|
||||
|
||||
it('found patient with national code books directly without extra fields', async () => {
|
||||
get.mockResolvedValue({ success: true, data: { found: true, name: 'علی محمدی', mobile: '09121234567', national_code: '0012345678' } });
|
||||
renderWithProviders(<NewAppointmentModal slot={slot} onClose={() => {}} onSuccess={() => {}} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('مثال: 09123456789'), { target: { value: '09121234567' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'جستجو' }));
|
||||
|
||||
await screen.findByText('بیمار یافت شد');
|
||||
expect(screen.getByText('علی محمدی')).toBeInTheDocument();
|
||||
// فیلد کد ملی برای بیمارِ یافتشده نمایش داده نمیشود
|
||||
expect(screen.queryByPlaceholderText('کد ملی ۱۰ رقمی')).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ثبت نوبت' }));
|
||||
await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/my/appointment', expect.objectContaining({
|
||||
doctor_uuid: 'doc1',
|
||||
patient_mobile: '09121234567',
|
||||
patient_name: 'علی محمدی',
|
||||
patient_national_code: '0012345678',
|
||||
})));
|
||||
});
|
||||
|
||||
it('unknown mobile reveals national code + name fields and books the new patient', async () => {
|
||||
get.mockResolvedValue({ success: true, data: { found: false } });
|
||||
renderWithProviders(<NewAppointmentModal slot={slot} onClose={() => {}} onSuccess={() => {}} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('مثال: 09123456789'), { target: { value: '09990001122' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'جستجو' }));
|
||||
|
||||
const nc = await screen.findByPlaceholderText('کد ملی ۱۰ رقمی');
|
||||
fireEvent.change(screen.getByPlaceholderText('مثال: علی محمدی'), { target: { value: 'مریم خلیلی' } });
|
||||
fireEvent.change(nc, { target: { value: '1234567891' } });
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ثبت نوبت' }));
|
||||
await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/my/appointment', expect.objectContaining({
|
||||
patient_mobile: '09990001122',
|
||||
patient_name: 'مریم خلیلی',
|
||||
patient_national_code: '1234567891',
|
||||
})));
|
||||
});
|
||||
});
|
||||
@@ -94,16 +94,39 @@ function DateNavigator({ date, onChange }: { date: string; onChange: (d: string)
|
||||
|
||||
interface BookingSlot { start: number; end: number; start_time: string; end_time: string; doctor_uuid: string; doctor_name: string; }
|
||||
|
||||
function NewAppointmentModal({
|
||||
interface PatientLookup { found: boolean; name?: string | null; mobile?: string; national_code?: string | null }
|
||||
|
||||
export function NewAppointmentModal({
|
||||
slot, onClose, onSuccess,
|
||||
}: { slot: BookingSlot; onClose: () => void; onSuccess: () => void }) {
|
||||
const [mobile, setMobile] = useState('');
|
||||
const [lookup, setLookup] = useState<PatientLookup | null>(null);
|
||||
const [patientName, setPatientName] = useState('');
|
||||
const [nationalCode, setNationalCode] = useState('');
|
||||
|
||||
const role = useAuthStore(s => s.primaryRole);
|
||||
const createEndpoint = role === 'admin' ? '/api/v1/admin/appointment' : '/api/v1/my/appointment';
|
||||
|
||||
const isValid = mobile.length >= 10 && patientName.trim().length >= 2;
|
||||
const mobileValid = /^09\d{9}$/.test(mobile);
|
||||
// یک بیمارِ یافتشده که کد ملی دارد، بدون فرم اضافی قابل استفاده است.
|
||||
const foundWithNationalCode = !!lookup?.found && !!lookup.national_code;
|
||||
const needsDetails = lookup !== null && !foundWithNationalCode; // یافتنشده، یا یافتشده بدون کد ملی
|
||||
|
||||
const effectiveName = foundWithNationalCode ? (lookup?.name ?? '') : patientName.trim();
|
||||
const effectiveNationalCode = foundWithNationalCode ? (lookup?.national_code ?? '') : nationalCode;
|
||||
const detailsValid = effectiveName.length >= 2 && effectiveNationalCode.length === 10;
|
||||
const isValid = mobileValid && (foundWithNationalCode || (needsDetails && detailsValid));
|
||||
|
||||
const search = useMutation({
|
||||
mutationFn: () => api.get(`/api/v1/my/appointment/patient-lookup?mobile=${encodeURIComponent(mobile)}`),
|
||||
onSuccess: (res: any) => {
|
||||
const data: PatientLookup = res?.data ?? { found: false };
|
||||
setLookup(data);
|
||||
setPatientName(data.found ? (data.name ?? '') : '');
|
||||
setNationalCode(data.found ? (data.national_code ?? '') : '');
|
||||
},
|
||||
onError: (e: any) => toast.error(e?.response?.data?.errors?.[0]?.message ?? e?.message ?? 'خطا در جستجو'),
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => api.post(createEndpoint, {
|
||||
@@ -111,7 +134,8 @@ function NewAppointmentModal({
|
||||
slot_start: slot.start,
|
||||
slot_end: slot.end,
|
||||
patient_mobile: mobile,
|
||||
patient_name: patientName.trim(),
|
||||
patient_name: effectiveName,
|
||||
patient_national_code: effectiveNationalCode,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
toast.success('نوبت با موفقیت ثبت شد');
|
||||
@@ -133,6 +157,18 @@ function NewAppointmentModal({
|
||||
display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6,
|
||||
};
|
||||
|
||||
// تغییر موبایل نتیجهی جستجوی قبلی را باطل میکند تا کاربر دوباره جستجو کند.
|
||||
function onMobileChange(v: string) {
|
||||
// ارقام فارسی/عربی → انگلیسی، فقط رقم، حداکثر ۱۱ رقم (کیبورد فارسی هم پذیرفته میشود).
|
||||
const normalized = v
|
||||
.replace(/[۰-۹]/g, d => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(d)))
|
||||
.replace(/[٠-٩]/g, d => String('٠١٢٣٤٥٦٧٨٩'.indexOf(d)))
|
||||
.replace(/\D/g, '')
|
||||
.slice(0, 11);
|
||||
setMobile(normalized);
|
||||
if (lookup !== null) { setLookup(null); setPatientName(''); setNationalCode(''); }
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 500,
|
||||
@@ -148,27 +184,69 @@ function NewAppointmentModal({
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={labelSx}>نام و نام خانوادگی بیمار *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={patientName}
|
||||
onChange={e => setPatientName(e.target.value)}
|
||||
placeholder="مثال: علی محمدی"
|
||||
style={inputSx}
|
||||
autoFocus
|
||||
/>
|
||||
<label style={labelSx}>شماره موبایل بیمار *</label>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input
|
||||
type="tel"
|
||||
inputMode="numeric"
|
||||
maxLength={11}
|
||||
value={mobile}
|
||||
onChange={e => onMobileChange(e.target.value)}
|
||||
placeholder="مثال: 09123456789"
|
||||
style={{ ...inputSx, direction: 'ltr' }}
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
className="btn sm"
|
||||
onClick={() => search.mutate()}
|
||||
disabled={!mobileValid || search.isPending}
|
||||
style={{ whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{search.isPending ? '...' : 'جستجو'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={labelSx}>شماره موبایل بیمار *</label>
|
||||
<input
|
||||
type="tel"
|
||||
value={mobile}
|
||||
onChange={e => setMobile(e.target.value)}
|
||||
placeholder="مثال: 09123456789"
|
||||
style={{ ...inputSx, direction: 'ltr' }}
|
||||
/>
|
||||
</div>
|
||||
{foundWithNationalCode && (
|
||||
<div style={{
|
||||
marginBottom: 16, padding: '10px 12px', borderRadius: 'var(--r-sm)',
|
||||
background: 'var(--success-bg)', border: '1px solid var(--success)', fontSize: 13,
|
||||
}}>
|
||||
<div style={{ fontWeight: 700, color: 'var(--success)', marginBottom: 2 }}>بیمار یافت شد</div>
|
||||
<div style={{ color: 'var(--text)' }}>{lookup?.name}</div>
|
||||
<div style={{ color: 'var(--text-2)', direction: 'ltr', textAlign: 'right' }}>کد ملی: {lookup?.national_code}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{needsDetails && (
|
||||
<>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 10 }}>
|
||||
{lookup?.found ? 'برای این بیمار کد ملی ثبت نشده — لطفاً تکمیل کنید:' : 'کاربری با این شماره یافت نشد — بیمار جدید:'}
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={labelSx}>نام و نام خانوادگی بیمار *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={patientName}
|
||||
onChange={e => setPatientName(e.target.value)}
|
||||
placeholder="مثال: علی محمدی"
|
||||
style={inputSx}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={labelSx}>کد ملی بیمار *</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
maxLength={10}
|
||||
value={nationalCode}
|
||||
onChange={e => setNationalCode(e.target.value.replace(/\D/g, '').slice(0, 10))}
|
||||
placeholder="کد ملی ۱۰ رقمی"
|
||||
style={{ ...inputSx, direction: 'ltr' }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
|
||||
<button className="btn sm" onClick={onClose}>انصراف</button>
|
||||
|
||||
Reference in New Issue
Block a user