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:
hamed
2026-07-15 18:27:29 +03:30
parent f378bf58e6
commit 5d5089244b
8 changed files with 1416 additions and 467 deletions
File diff suppressed because it is too large Load Diff
+64 -49
View File
@@ -1,63 +1,78 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { renderWithProviders } from '../../test/utils';
import { fireEvent, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../../test/utils";
vi.mock('../../hooks/useSubscription', () => ({
useSubscription: () => ({ hasFeature: () => true }),
vi.mock("../../hooks/useSubscription", () => ({
useSubscription: () => ({ hasFeature: () => true }),
}));
import Sidebar from './Sidebar';
import { useAuthStore } from '../../stores/authStore';
import { useAuthStore } from "../../stores/authStore";
import Sidebar from "./Sidebar";
describe('Sidebar — expandable نوبت‌ها menu', () => {
beforeEach(() => {
useAuthStore.setState({
primaryRole: 'admin', dbUuid: 'c1', userName: 'ادمین',
availableContexts: [], context: null,
} as any);
});
describe("Sidebar — expandable نوبت‌ها menu", () => {
beforeEach(() => {
useAuthStore.setState({
primaryRole: "admin",
dbUuid: "c1",
userName: "ادمین",
availableContexts: [],
context: null,
} as any);
});
it('renders نوبت‌ها as a collapsible parent and reveals sub-items on click', () => {
renderWithProviders(<Sidebar />, { route: '/admin/dashboard' });
it("renders نوبت‌ها as a collapsible parent and reveals sub-items on click", () => {
renderWithProviders(<Sidebar />, { route: "/admin/dashboard" });
// منوی والد به شکل دکمه
const parent = screen.getByRole('button', { name: /نوبت‌ها/ });
expect(parent).toBeInTheDocument();
// منوی والد به شکل دکمه
const parent = screen.getByRole("button", { name: /نوبت‌ها/ });
expect(parent).toBeInTheDocument();
// در ابتدا (مسیر داشبورد) بسته است → زیرمنوها نیستند
expect(screen.queryByText('نوبت های تایید شده')).toBeNull();
// در ابتدا (مسیر داشبورد) بسته است → زیرمنوها نیستند
expect(screen.queryByText("نوبت ها")).toBeNull();
fireEvent.click(parent);
fireEvent.click(parent);
// پس از باز شدن، دو زیرمنو دیده می‌شوند
expect(screen.getByText('نوبت های تایید شده')).toBeInTheDocument();
expect(screen.getByText('افزودن نوبت')).toBeInTheDocument();
});
// پس از باز شدن، دو زیرمنو دیده می‌شوند
expect(screen.getByText("نوبت ها")).toBeInTheDocument();
expect(screen.getByText("افزودن نوبت")).toBeInTheDocument();
});
it('auto-expands when a child route is active', () => {
renderWithProviders(<Sidebar />, { route: '/admin/appointments/new' });
// چون «افزودن نوبت» فعال است، منو باید خودکار باز باشد
expect(screen.getByText('افزودن نوبت')).toBeInTheDocument();
expect(screen.getByText('نوبت های تایید شده')).toBeInTheDocument();
});
it("auto-expands when a child route is active", () => {
renderWithProviders(<Sidebar />, { route: "/admin/appointments/new" });
// چون «افزودن نوبت» فعال است، منو باید خودکار باز باشد
expect(screen.getByText("افزودن نوبت")).toBeInTheDocument();
expect(screen.getByText("نوبت ها")).toBeInTheDocument();
});
});
describe('Sidebar — خدمات در منوی اصلی (نه تنظیمات)', () => {
it('shows خدمات in the clinic main menu linking to /admin/clinic-services', () => {
useAuthStore.setState({
primaryRole: 'clinic', dbUuid: 'c1', userName: 'کلینیک',
availableContexts: [], context: null,
} as any);
renderWithProviders(<Sidebar />, { route: '/admin/dashboard' });
expect(screen.getByText('سرویس ها').closest('a')).toHaveAttribute('href', '/admin/clinic-services');
});
describe("Sidebar — خدمات در منوی اصلی (نه تنظیمات)", () => {
it("shows خدمات in the clinic main menu linking to /admin/clinic-services", () => {
useAuthStore.setState({
primaryRole: "clinic",
dbUuid: "c1",
userName: "کلینیک",
availableContexts: [],
context: null,
} as any);
renderWithProviders(<Sidebar />, { route: "/admin/dashboard" });
expect(screen.getByText("سرویس ها").closest("a")).toHaveAttribute(
"href",
"/admin/clinic-services",
);
});
it('shows خدمات in the doctor main menu linking to /admin/clinic-services', () => {
useAuthStore.setState({
primaryRole: 'doctor', dbUuid: null, userName: 'پزشک',
availableContexts: [], context: null,
} as any);
renderWithProviders(<Sidebar />, { route: '/admin/dashboard' });
expect(screen.getByText('سرویس ها').closest('a')).toHaveAttribute('href', '/admin/clinic-services');
});
it("shows خدمات in the doctor main menu linking to /admin/clinic-services", () => {
useAuthStore.setState({
primaryRole: "doctor",
dbUuid: null,
userName: "پزشک",
availableContexts: [],
context: null,
} as any);
renderWithProviders(<Sidebar />, { route: "/admin/dashboard" });
expect(screen.getByText("سرویس ها").closest("a")).toHaveAttribute(
"href",
"/admin/clinic-services",
);
});
});
+57 -14
View File
@@ -22,12 +22,12 @@ import {
StarIcon,
TagIcon,
UserCircleIcon,
WrenchScrewdriverIcon,
UserGroupIcon,
UsersIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { useState } from "react";
import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { useSubscription } from "../../hooks/useSubscription";
import { useAuthStore } from "../../stores/authStore";
import { useUiStore } from "../../stores/uiStore";
@@ -45,7 +45,7 @@ type Section = { label: string; items: SectionItem[] };
/** زیرمنوهای مشترکِ «نوبت‌ها» (نوبت‌های تأییدشده + افزودن نوبت). */
const APPOINTMENTS_CHILDREN: SubItem[] = [
{ to: "/admin/appointments", label: "نوبت های تایید شده", icon: CalendarDaysIcon },
{ to: "/admin/appointments", label: "نوبت ها", icon: CalendarDaysIcon },
{ to: "/admin/appointments/new", label: "افزودن نوبت", icon: PlusIcon },
];
@@ -61,8 +61,17 @@ function buildSections(
{
label: "عمومی",
items: [
{ to: "/admin/dashboard", icon: ChartBarIcon, label: "داشبورد" },
{ to: "/admin/appointments", icon: CalendarDaysIcon, label: "نوبت‌های من", children: APPOINTMENTS_CHILDREN },
{
to: "/admin/dashboard",
icon: ChartBarIcon,
label: "داشبورد",
},
{
to: "/admin/appointments",
icon: CalendarDaysIcon,
label: "نوبت‌های من",
children: APPOINTMENTS_CHILDREN,
},
],
},
];
@@ -84,7 +93,11 @@ function buildSections(
label: "کاربران",
},
{ to: "/admin/doctors", icon: HeartIcon, label: "پزشکان" },
{ to: "/admin/doctor-claims", icon: HeartIcon, label: "تصاحب پروفایل" },
{
to: "/admin/doctor-claims",
icon: HeartIcon,
label: "تصاحب پروفایل",
},
{
to: "/admin/clinics",
icon: BuildingOffice2Icon,
@@ -399,27 +412,47 @@ function buildSections(
{
label: "عمومی",
items: [
{ to: "/admin/dashboard", icon: ChartBarIcon, label: "داشبورد" },
{
to: "/admin/dashboard",
icon: ChartBarIcon,
label: "داشبورد",
},
],
},
{
label: "مدیریت",
items: [
{ to: "/admin/doctors", icon: HeartIcon, label: "پزشکان" },
{ to: "/admin/clinics", icon: BuildingOffice2Icon, label: "کلینیک‌ها" },
{
to: "/admin/clinics",
icon: BuildingOffice2Icon,
label: "کلینیک‌ها",
},
],
},
{
label: "مالی",
items: [
{ to: "/admin/representation-finance", icon: CreditCardIcon, label: "گزارش مالی" },
{ to: "/admin/representation-settlement", icon: BanknotesIcon, label: "تسویه حساب" },
{
to: "/admin/representation-finance",
icon: CreditCardIcon,
label: "گزارش مالی",
},
{
to: "/admin/representation-settlement",
icon: BanknotesIcon,
label: "تسویه حساب",
},
],
},
{
label: "حساب",
items: [
{ to: "/admin/representation-profile", icon: UserCircleIcon, label: "پروفایل" },
{
to: "/admin/representation-profile",
icon: UserCircleIcon,
label: "پروفایل",
},
],
},
];
@@ -581,8 +614,14 @@ function NavItem({
export default function Sidebar({ mobileOpen: _m, onMobileClose: _c }: Props) {
const sidebarOpen = useUiStore((s) => s.sidebarOpen);
const { logout, primaryRole, userName, availableContexts, dbUuid, context } =
useAuthStore();
const {
logout,
primaryRole,
userName,
availableContexts,
dbUuid,
context,
} = useAuthStore();
const { hasFeature } = useSubscription();
const navigate = useNavigate();
@@ -594,7 +633,11 @@ export default function Sidebar({ mobileOpen: _m, onMobileClose: _c }: Props) {
{/* Brand */}
<div className="sidebar-brand">
<div className="brand-logo">
<img src="/logo.svg" alt="Clinic Pro" className="brand-img" />
<img
src="/logo.svg"
alt="Clinic Pro"
className="brand-img"
/>
</div>
<div className="brand-text">
<b>ClinicPro</b>
@@ -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',
})));
});
});
+100 -22
View File
@@ -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>
+40
View File
@@ -434,6 +434,46 @@ Create a new appointment for a patient. Used by doctor/clinic/secretary to book
---
## GET `/api/v1/my/appointment/patient-lookup`
جستجوی بیمار با شماره موبایل، پیش از ثبت نوبت. فرم ثبت نوبت اول با موبایل جستجو می‌کند؛ اگر بیمار یافت شد و کد ملی دارد، مستقیم استفاده می‌شود، وگرنه کد ملی و نام از کاربر گرفته می‌شود.
**Auth:** `IS_AUTHENTICATED_FULLY` — Roles: `ROLE_DOCTOR`, `ROLE_CLINIC`, `ROLE_SECRETARY`, `ROLE_ADMIN`
> برخلاف `GET /api/v1/patient/search-user`، این endpoint به فیچر `patient_records` اشتراک وابسته نیست و `ROLE_ADMIN` را هم می‌پذیرد، چون ثبت نوبت باید مستقل از اشتراک کار کند.
### Query Parameters
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `mobile` | string | ✅ | شماره موبایل ایران (`^09\d{9}$`)؛ ارقام فارسی به انگلیسی تبدیل می‌شوند |
### Response `200` — یافت شد
```json
{
"success": true,
"data": {
"found": true,
"name": "علی محمدی",
"mobile": "09123456789",
"national_code": "0012345678"
}
}
```
> `national_code` ممکن است `null` باشد (بیمار قدیمی بدون کد ملی) — در این حالت فرم کد ملی را می‌گیرد.
### Response `200` — یافت نشد
```json
{ "success": true, "data": { "found": false } }
```
### Error Responses
| Code | HTTP | Description |
|------|------|-------------|
| `FORBIDDEN` | 403 | Role not allowed |
| `VALIDATION` | 422 | Invalid `mobile` (`field: mobile`) |
---
## GET /api/v1/my/appointments
Role-aware paginated list of appointments. Returns only what the authenticated user is authorized to see.
@@ -40,6 +40,7 @@ class MyAppointmentsController extends BaseController
private readonly \App\ClinicService\Repository\ServiceItemRepository $itemRepo,
private readonly \App\Staff\Repository\ClinicStaffRepository $staffRepo,
private readonly PatientResolver $patientResolver,
private readonly \App\Auth\Repository\UserRepository $userRepo,
) {}
#[Route('/api/v1/my/appointment', methods: ['POST'])]
@@ -144,6 +145,39 @@ class MyAppointmentsController extends BaseController
], 201);
}
/**
* Booking-scoped patient lookup by mobile. Lets the booking form search an
* existing patient before asking for national code / name. Unlike
* /patient/search-user this is not gated by the patient_records feature and
* allows ROLE_ADMIN, because booking must work regardless of subscription.
*/
#[Route('/api/v1/my/appointment/patient-lookup', methods: ['GET'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function patientLookup(Request $request, #[CurrentUser] User $user): JsonResponse
{
$allowed = ['ROLE_DOCTOR', 'ROLE_CLINIC', 'ROLE_SECRETARY', 'ROLE_ADMIN'];
if (!array_intersect($allowed, $user->getRoles())) {
return $this->error(ErrorCodes::FORBIDDEN, 'دسترسی ندارید', 403);
}
$mobile = InputValidator::toEnglishDigits(trim((string) $request->query->get('mobile', '')));
if (!InputValidator::isValidIranMobile($mobile)) {
return $this->error(ErrorCodes::VALIDATION, 'شماره موبایل نامعتبر است', 422, 'mobile');
}
$patient = $this->userRepo->findByMobile($mobile);
if ($patient === null) {
return $this->success(['found' => false]);
}
return $this->success([
'found' => true,
'name' => $patient->getRealName(),
'mobile' => $patient->getMobileNumber(),
'national_code' => $patient->getNationalCode(),
]);
}
#[Route('/api/v1/my/appointments', methods: ['GET'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function myAppointments(Request $request, #[CurrentUser] User $user): JsonResponse
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Tests\Appointment;
use App\Auth\Entity\User;
use App\Tests\ApiTestCase;
/**
* GET /api/v1/my/appointment/patient-lookup — mobile-first patient search used
* by the booking form before asking for national code / name.
*/
class PatientLookupTest extends ApiTestCase
{
private function booker(): User
{
return $this->createUser(['ROLE_DOCTOR']);
}
private function mobile(): string
{
return '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT);
}
private function nationalCode(): string
{
return '00' . str_pad((string) random_int(0, 99_999_999), 8, '0', STR_PAD_LEFT);
}
public function testFoundWithNationalCode(): void
{
$mobile = $this->mobile();
$nc = $this->nationalCode();
$patient = $this->createUser(['ROLE_USER'], $mobile);
$patient->setRealName('علی محمدی');
$patient->setNationalCode($nc);
$this->em->flush();
$res = $this->authJson('GET', '/api/v1/my/appointment/patient-lookup?mobile=' . $mobile, $this->booker());
self::assertSame(200, $this->responseCode());
self::assertTrue($res['data']['found']);
self::assertSame('علی محمدی', $res['data']['name']);
self::assertSame($nc, $res['data']['national_code']);
}
public function testFoundWithoutNationalCode(): void
{
$mobile = $this->mobile();
$patient = $this->createUser(['ROLE_USER'], $mobile);
$patient->setRealName('بدون کدملی');
$this->em->flush();
$res = $this->authJson('GET', '/api/v1/my/appointment/patient-lookup?mobile=' . $mobile, $this->booker());
self::assertSame(200, $this->responseCode());
self::assertTrue($res['data']['found']);
self::assertNull($res['data']['national_code']);
}
public function testNotFound(): void
{
$res = $this->authJson('GET', '/api/v1/my/appointment/patient-lookup?mobile=' . $this->mobile(), $this->booker());
self::assertSame(200, $this->responseCode());
self::assertFalse($res['data']['found']);
}
public function testInvalidMobileIs422(): void
{
$this->authJson('GET', '/api/v1/my/appointment/patient-lookup?mobile=123', $this->booker());
self::assertSame(422, $this->responseCode());
}
public function testPlainUserIsForbidden(): void
{
$this->authJson('GET', '/api/v1/my/appointment/patient-lookup?mobile=' . $this->mobile(), $this->createUser(['ROLE_USER']));
self::assertSame(403, $this->responseCode());
}
}