feat(patients): phase A — records list + create/edit form (Figma)

Rebuild the patient records (پرونده‌ها) area, phase A of the Figma redesign:

- BE: add a clinic-scoped `record_number` and a TenantTag `tags` M2M to
  PatientRecord (migration + EAGER-hydrated collection). POST /patient and
  PATCH /patient/{uuid} now accept `record_number` and tenant-scoped `tags`
  (foreign tag → 422); demographic fields (gender, date_of_birth,
  referral_source, description) continue to live on UserProfile via PATCH.
- FE: new PatientsListPage (table + card views, search, pagination, tags
  column, "تشکیل پرونده") at /admin/patients, and PatientRecordFormPage
  (create/edit) that POSTs the record then PATCHes the demographics. Point
  the sidebar "پرونده" entry to the new list.

Phases B–E (tabbed patient file, service stepper, invoice, payments/wallet,
call-center) follow. Backend covered by PHPUnit, FE by Vitest.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-13 14:54:38 +03:30
co-authored by Claude Opus 4.8
parent c46800610f
commit 15c6f5dce7
13 changed files with 671 additions and 4 deletions
+5
View File
@@ -53,6 +53,8 @@ import SettingsMenuPage from './pages/SettingsMenuPage';
import AccountSettingsPage from './pages/AccountSettingsPage';
import TagsSettingsPage from './pages/TagsSettingsPage';
import AppointmentSettingsPage from './pages/AppointmentSettingsPage';
import PatientsListPage from './pages/PatientsListPage';
import PatientRecordFormPage from './pages/PatientRecordFormPage';
import PaymentSuccessPage from './pages/PaymentSuccessPage';
import PwaInstallBanner from './components/ui/PwaInstallBanner';
@@ -190,6 +192,9 @@ export default function App() {
{/* دکتر / منشی / کلینیک */}
<Route path="my-patients" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><MyPatientsPage /></RoleRoute>} />
<Route path="patients" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><PatientsListPage /></RoleRoute>} />
<Route path="patients/new" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><PatientRecordFormPage /></RoleRoute>} />
<Route path="patients/:uuid/edit" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><PatientRecordFormPage /></RoleRoute>} />
<Route path="my-patients/:recordUuid/session/new" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><NewSessionPage /></RoleRoute>} />
<Route path="insurance-pricing" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><InsurancePricingPage /></RoleRoute>} />
<Route path="claims" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClaimsPage /></RoleRoute>} />
+3 -3
View File
@@ -199,7 +199,7 @@ function buildSections(
label: "نوبت‌ها",
},
{
to: "/admin/my-patients",
to: "/admin/patients",
icon: FolderOpenIcon,
label: "پرونده بیماران",
feature: "patient_records",
@@ -280,7 +280,7 @@ function buildSections(
label: "نوبت‌های من",
},
{
to: "/admin/my-patients",
to: "/admin/patients",
icon: FolderOpenIcon,
label: "پرونده بیماران",
feature: "patient_records",
@@ -351,7 +351,7 @@ function buildSections(
label: "نوبت‌ها",
},
{
to: "/admin/my-patients",
to: "/admin/patients",
icon: FolderOpenIcon,
label: "پرونده بیماران",
feature: "patient_records",
@@ -0,0 +1,53 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, waitFor } from '@testing-library/react';
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 PatientRecordFormPage from './PatientRecordFormPage';
const post = api.post as ReturnType<typeof vi.fn>;
const patch = api.patch as ReturnType<typeof vi.fn>;
beforeEach(() => {
post.mockReset(); patch.mockReset();
post.mockResolvedValue({ success: true, data: { uuid: 'new-1' } });
patch.mockResolvedValue({ success: true, data: {} });
});
describe('PatientRecordFormPage (تشکیل پرونده)', () => {
it('creates a record then patches the demographic fields', async () => {
renderWithProviders(<PatientRecordFormPage />, { route: '/admin/patients/new' });
fireEvent.change(screen.getByPlaceholderText('نام و نام خانوادگی را وارد نمایید'), { target: { value: 'بیمار نمونه' } });
fireEvent.change(screen.getByPlaceholderText('شماره پرونده'), { target: { value: 'P-1001' } });
fireEvent.change(screen.getAllByRole('combobox')[0], { target: { value: 'female' } }); // gender
fireEvent.change(screen.getByPlaceholderText('کد ملی را وارد نمایید'), { target: { value: '1234567890' } });
fireEvent.change(screen.getByPlaceholderText('شماره تماس را وارد نمایید'), { target: { value: '09120000000' } });
fireEvent.click(screen.getByRole('button', { name: 'ثبت اطلاعات' }));
await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/patient', expect.objectContaining({
name: 'بیمار نمونه', mobile: '09120000000', national_code: '1234567890', record_number: 'P-1001',
})));
await waitFor(() => expect(patch).toHaveBeenCalledWith('/api/v1/patient/new-1', expect.objectContaining({ gender: 'female' })));
});
it('blocks submit and shows a validation error for a bad national code', async () => {
renderWithProviders(<PatientRecordFormPage />, { route: '/admin/patients/new' });
fireEvent.change(screen.getByPlaceholderText('نام و نام خانوادگی را وارد نمایید'), { target: { value: 'ب' } });
fireEvent.change(screen.getByPlaceholderText('شماره پرونده'), { target: { value: 'P-1' } });
fireEvent.change(screen.getAllByRole('combobox')[0], { target: { value: 'male' } });
fireEvent.change(screen.getByPlaceholderText('کد ملی را وارد نمایید'), { target: { value: '12' } });
fireEvent.change(screen.getByPlaceholderText('شماره تماس را وارد نمایید'), { target: { value: '09120000000' } });
fireEvent.click(screen.getByRole('button', { name: 'ثبت اطلاعات' }));
expect(await screen.findByText('کد ملی باید ۱۰ رقم باشد')).toBeInTheDocument();
expect(post).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,154 @@
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ChevronRightIcon } 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 PersianDateInput from '../components/ui/PersianDateInput';
const REFERRAL_OPTIONS = ['اینستاگرام', 'معرفی دوستان و آشنایان', 'جستجوی اینترنتی', 'تابلو مطب', 'سایر'];
const schema = z.object({
name: z.string().min(1, 'نام و نام خانوادگی الزامی است'),
record_number: z.string().min(1, 'شماره پرونده الزامی است'),
gender: z.enum(['male', 'female'], { errorMap: () => ({ message: 'جنسیت را انتخاب کنید' }) }),
national_code: z.string().regex(/^\d{10}$/, 'کد ملی باید ۱۰ رقم باشد'),
mobile: z.string().regex(/^09\d{9}$/, 'شماره تماس نامعتبر است'),
birth_date: z.string().optional(),
referral_source: z.string().optional(),
description: z.string().optional(),
});
type Form = z.infer<typeof schema>;
const toEpoch = (iso?: string) => (iso ? Math.floor(new Date(iso).getTime() / 1000) : null);
const fromEpoch = (ts?: number | null) => (ts ? new Date(ts * 1000).toISOString().slice(0, 10) : '');
/** تشکیل/ویرایش پرونده — patient record create & edit form (Figma "تشکیل پرونده"). */
export default function PatientRecordFormPage() {
const { uuid } = useParams<{ uuid: string }>();
const isEdit = !!uuid;
const navigate = useNavigate();
const qc = useQueryClient();
const form = useForm<Form>({
resolver: zodResolver(schema),
defaultValues: { name: '', record_number: '', gender: undefined as any, national_code: '', mobile: '', birth_date: '', referral_source: '', description: '' },
});
const { data: recordData } = useQuery<ApiResponse<PatientRecord>>({
queryKey: ['patient', uuid],
queryFn: () => api.get(`/api/v1/patient/${uuid}`),
enabled: isEdit,
});
useEffect(() => {
const r = recordData?.data;
if (!r) return;
const p: any = r.profile ?? {};
form.reset({
name: r.user_name ?? '',
record_number: r.record_number ?? '',
gender: (p.gender as 'male' | 'female') ?? undefined,
national_code: r.user_national_code ?? '',
mobile: r.user_mobile ?? '',
birth_date: fromEpoch(p.date_of_birth),
referral_source: p.referral_source ?? '',
description: p.description ?? '',
});
}, [recordData]); // eslint-disable-line react-hooks/exhaustive-deps
const save = useMutation({
mutationFn: async (d: Form) => {
const profilePayload = {
gender: d.gender,
date_of_birth: toEpoch(d.birth_date),
referral_source: d.referral_source || null,
description: d.description || null,
};
if (isEdit) {
return api.patch(`/api/v1/patient/${uuid}`, {
name: d.name, national_code: d.national_code, mobile: d.mobile, record_number: d.record_number, ...profilePayload,
});
}
// create: POST creates the record + identity, then PATCH applies the profile demographics
const created = await api.post<ApiResponse<PatientRecord>>('/api/v1/patient', {
name: d.name, mobile: d.mobile, national_code: d.national_code, record_number: d.record_number,
});
const newUuid = (created as any)?.data?.uuid;
if (newUuid) await api.patch(`/api/v1/patient/${newUuid}`, profilePayload);
return created;
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['patients'] });
toast.success(isEdit ? 'پرونده ویرایش شد' : 'پرونده تشکیل شد');
navigate('/admin/patients');
},
onError: (e: any) => toast.error(e.message),
});
const Field = ({ label, required, error, children }: { label: string; required?: boolean; error?: string; children: React.ReactNode }) => (
<div>
<label className="field-label">{label} {required && <span style={{ color: 'var(--danger)' }}>*</span>}</label>
{children}
{error && <span className="field-error">{error}</span>}
</div>
);
return (
<div className="fade-in" style={{ maxWidth: 1000, margin: '0 auto' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
<Link to="/admin/patients" className="btn sm ghost" style={{ color: 'var(--text-2)' }}><ChevronRightIcon style={{ width: 16 }} /> بازگشت</Link>
<div style={{ fontSize: 14, color: 'var(--text-3)' }}>پرونده <b style={{ color: 'var(--text)' }}>{isEdit ? 'ویرایش پرونده' : 'تشکیل پرونده'}</b></div>
</div>
<form onSubmit={form.handleSubmit((d) => save.mutate(d))}
style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 24 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 18 }}>
<Field label="نام و نام خانوادگی مراجعه کننده" required error={form.formState.errors.name?.message}>
<div className="field"><input {...form.register('name')} placeholder="نام و نام خانوادگی را وارد نمایید" /></div>
</Field>
<Field label="شماره پرونده" required error={form.formState.errors.record_number?.message}>
<div className="field"><input {...form.register('record_number')} placeholder="شماره پرونده" /></div>
</Field>
<Field label="جنسیت" required error={form.formState.errors.gender?.message}>
<div className="field"><select {...form.register('gender')} style={{ width: '100%', border: 'none', background: 'transparent', fontFamily: 'inherit' }}>
<option value="">انتخاب...</option>
<option value="female">زن</option>
<option value="male">مرد</option>
</select></div>
</Field>
<Field label="کد ملی" required error={form.formState.errors.national_code?.message}>
<div className="field"><input {...form.register('national_code')} inputMode="numeric" placeholder="کد ملی را وارد نمایید" /></div>
</Field>
<Field label="شماره تماس" required error={form.formState.errors.mobile?.message}>
<div className="field"><input {...form.register('mobile')} inputMode="numeric" placeholder="شماره تماس را وارد نمایید" /></div>
</Field>
<Field label="تاریخ تولد">
<PersianDateInput value={form.watch('birth_date') ?? ''} onChange={(v) => form.setValue('birth_date', v)} />
</Field>
<Field label="نحوه آشنایی">
<div className="field"><select {...form.register('referral_source')} style={{ width: '100%', border: 'none', background: 'transparent', fontFamily: 'inherit' }}>
<option value="">انتخاب کنید...</option>
{REFERRAL_OPTIONS.map((o) => <option key={o} value={o}>{o}</option>)}
</select></div>
</Field>
</div>
<div style={{ marginTop: 18 }}>
<Field label="توضیحات">
<div className="field" style={{ height: 'auto' }}><textarea {...form.register('description')} rows={4} placeholder="توضیحات" style={{ width: '100%', border: 'none', background: 'transparent', fontFamily: 'inherit', resize: 'vertical' }} /></div>
</Field>
</div>
<button type="submit" className="btn primary" style={{ marginTop: 22, height: 44, padding: '0 24px' }} disabled={save.isPending}>
{save.isPending ? 'در حال ذخیره...' : 'ثبت اطلاعات'}
</button>
</form>
</div>
);
}
@@ -0,0 +1,44 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent } 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 PatientsListPage from './PatientsListPage';
const get = api.get as ReturnType<typeof vi.fn>;
beforeEach(() => {
get.mockReset();
get.mockResolvedValue({
success: true,
data: [
{ uuid: 'r1', user_name: 'دنیا خلیلی', user_mobile: '09165401233', user_national_code: '1744023654', record_number: '123456789', tags: [{ uuid: 't1', name: 'فوری', color: '#F00' }] },
{ uuid: 'r2', user_name: 'علی بدیعی زاده', user_mobile: '09165401233', user_national_code: null, record_number: '123456789', tags: [] },
],
meta: { totalRecords: 2 },
});
});
describe('PatientsListPage (پرونده‌ها)', () => {
it('renders the records table with the create button', async () => {
renderWithProviders(<PatientsListPage />, { route: '/admin/patients' });
expect(await screen.findByText('دنیا خلیلی')).toBeInTheDocument();
expect(screen.getByText('علی بدیعی زاده')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /تشکیل پرونده/ })).toBeInTheDocument();
// record with no tags shows the "add" link
expect(screen.getByText('+ اضافه کردن')).toBeInTheDocument();
});
it('switches to the card view', async () => {
renderWithProviders(<PatientsListPage />, { route: '/admin/patients' });
await screen.findByText('دنیا خلیلی');
fireEvent.click(screen.getByLabelText('نمایش کارتی'));
expect(screen.getByText('دنیا خلیلی')).toBeInTheDocument();
expect(screen.getAllByText('مشاهده').length).toBeGreaterThan(0);
});
});
+154
View File
@@ -0,0 +1,154 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import {
PlusIcon, PencilIcon, EyeIcon, MagnifyingGlassIcon, AdjustmentsHorizontalIcon,
Squares2X2Icon, TableCellsIcon, ExclamationCircleIcon, IdentificationIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { PatientRecord } from '../types';
import { formatNumber } from '../lib/utils';
import Pagination from '../components/ui/Pagination';
const LIMIT = 20;
const EMPTY: PatientRecord[] = [];
function TagDots({ tags }: { tags?: PatientRecord['tags'] }) {
if (!tags || tags.length === 0) return null;
return (
<span style={{ display: 'inline-flex', alignItems: 'center' }}>
{tags.slice(0, 3).map((t, i) => (
<span key={t.uuid} title={t.name} style={{
width: 16, height: 16, borderRadius: '50%', background: t.color,
border: '2px solid var(--surface)', marginInlineStart: i === 0 ? 0 : -6,
}} />
))}
{tags.length > 3 && <span style={{ fontSize: 11, color: 'var(--text-3)', marginInlineStart: 4 }}>+{formatNumber(tags.length - 3)}</span>}
</span>
);
}
/** پرونده‌ها — patient records list (table + card views) matching the Figma design. */
export default function PatientsListPage() {
const navigate = useNavigate();
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [view, setView] = useState<'table' | 'card'>('table');
const { data, isLoading } = useQuery<ApiResponse<PatientRecord[]> & { meta?: { totalRecords: number } }>({
queryKey: ['patients', page, search],
queryFn: () => api.get(`/api/v1/patients?page=${page}&limit=${LIMIT}&search=${encodeURIComponent(search)}`),
});
const records = data?.data ?? EMPTY;
const total = data?.meta?.totalRecords ?? 0;
const editHref = (r: PatientRecord) => `/admin/patients/${r.uuid}/edit`;
// detail page arrives in phase B; view currently opens the edit form
const viewHref = editHref;
return (
<div className="fade-in" style={{ maxWidth: 1160, margin: '0 auto' }}>
{/* Header */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 20 }}>
<h1 className="section-title">پروندهها</h1>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
<div style={{ position: 'relative' }}>
<MagnifyingGlassIcon style={{ width: 16, position: 'absolute', insetInlineStart: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', pointerEvents: 'none' }} />
<input
className="cp-input" placeholder="کد ملی، شماره پرونده یا نام مراجعه کننده را وارد کنید..."
value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }}
style={{ width: 320, maxWidth: '60vw', height: 40, paddingInlineStart: 34 }}
/>
</div>
{/* view toggle */}
<div style={{ display: 'flex', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', overflow: 'hidden' }}>
<button aria-label="نمایش کارتی" onClick={() => setView('card')} style={{ padding: '8px 10px', border: 'none', cursor: 'pointer', background: view === 'card' ? 'var(--primary-soft)' : 'var(--surface)', color: view === 'card' ? 'var(--primary)' : 'var(--text-3)' }}>
<Squares2X2Icon style={{ width: 18 }} />
</button>
<button aria-label="نمایش جدولی" onClick={() => setView('table')} style={{ padding: '8px 10px', border: 'none', cursor: 'pointer', background: view === 'table' ? 'var(--primary-soft)' : 'var(--surface)', color: view === 'table' ? 'var(--primary)' : 'var(--text-3)' }}>
<TableCellsIcon style={{ width: 18 }} />
</button>
</div>
<button className="btn" aria-label="فیلترها" style={{ height: 40, width: 44, padding: 0, display: 'grid', placeItems: 'center' }}>
<AdjustmentsHorizontalIcon style={{ width: 18 }} />
</button>
<button className="btn primary" style={{ height: 40 }} onClick={() => navigate('/admin/patients/new')}>
<PlusIcon style={{ width: 16 }} /> تشکیل پرونده
</button>
</div>
</div>
{isLoading ? (
<div style={{ padding: 24, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
) : records.length === 0 ? (
<div className="card" style={{ padding: '60px 0', textAlign: 'center', color: 'var(--text-3)' }}>
<IdentificationIcon style={{ width: 52, margin: '0 auto 14px', display: 'block', opacity: 0.3 }} />
<div style={{ fontSize: 14, color: 'var(--text-2)' }}>پروندهای یافت نشد.</div>
</div>
) : view === 'table' ? (
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 760 }}>
<thead>
<tr style={{ background: 'var(--surface-2)', color: 'var(--text-2)', fontSize: 13 }}>
{['ردیف', 'مراجعه کننده', 'برچسب ها', 'شماره پرونده', 'شماره تماس', 'کد ملی', 'عملیات'].map((h) => (
<th key={h} style={{ padding: '12px 14px', textAlign: 'center', fontWeight: 600, whiteSpace: 'nowrap' }}>{h}</th>
))}
</tr>
</thead>
<tbody>
{records.map((r, i) => (
<tr key={r.uuid} style={{ borderTop: '1px solid var(--border)', fontSize: 13.5, textAlign: 'center' }}>
<td style={{ padding: '12px 14px', color: 'var(--text-3)' }}>{formatNumber((page - 1) * LIMIT + i + 1)}</td>
<td style={{ padding: '12px 14px' }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 600 }}>
{r.user_name || '—'}
{!r.user_national_code && <ExclamationCircleIcon style={{ width: 16, color: 'var(--danger)' }} />}
</span>
</td>
<td style={{ padding: '12px 14px' }}>
{r.tags && r.tags.length > 0 ? <TagDots tags={r.tags} /> : <Link to={editHref(r)} style={{ color: 'var(--primary)', fontSize: 12.5, textDecoration: 'none' }}>+ اضافه کردن</Link>}
</td>
<td style={{ padding: '12px 14px' }}>{r.record_number || '—'}</td>
<td style={{ padding: '12px 14px', direction: 'ltr' }}>{r.user_mobile || '—'}</td>
<td style={{ padding: '12px 14px', direction: 'ltr' }}>{r.user_national_code || '—'}</td>
<td style={{ padding: '12px 14px' }}>
<span style={{ display: 'inline-flex', gap: 8, justifyContent: 'center' }}>
<Link to={viewHref(r)} aria-label="مشاهده" style={{ color: 'var(--primary)' }}><EyeIcon style={{ width: 18 }} /></Link>
<Link to={editHref(r)} aria-label="ویرایش" style={{ color: 'var(--accent)' }}><PencilIcon style={{ width: 18 }} /></Link>
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
{records.map((r) => (
<div key={r.uuid} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
<span style={{ fontWeight: 700, fontSize: 15 }}>{r.user_name || '—'}</span>
<TagDots tags={r.tags} />
</div>
<div style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'flex', flexDirection: 'column', gap: 4 }}>
<span>شماره پرونده: {r.record_number || '—'}</span>
<span style={{ direction: 'ltr', textAlign: 'right' }}>تماس: {r.user_mobile || '—'}</span>
<span style={{ direction: 'ltr', textAlign: 'right' }}>کد ملی: {r.user_national_code || '—'}</span>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 12, borderTop: '1px solid var(--border)', paddingTop: 10 }}>
<Link to={viewHref(r)} className="btn sm ghost" style={{ flex: 1, justifyContent: 'center', color: 'var(--primary)' }}><EyeIcon style={{ width: 15 }} /> مشاهده</Link>
<Link to={editHref(r)} className="btn sm ghost" style={{ flex: 1, justifyContent: 'center', color: 'var(--accent)' }}><PencilIcon style={{ width: 15 }} /> ویرایش</Link>
</div>
</div>
))}
</div>
)}
<div style={{ marginTop: 20, display: 'flex', justifyContent: 'center' }}>
<Pagination page={page} total={total} limit={LIMIT} onPageChange={setPage} />
</div>
</div>
);
}
+4
View File
@@ -521,6 +521,10 @@ export interface PatientRecord {
user_name?: string | null;
user_mobile?: string | null;
user_national_code?: string | null;
/** clinic case-file number */
record_number?: string | null;
/** record labels (TenantTag) */
tags?: { uuid: string; name: string; color: string }[];
created_at: number;
profile?: PatientProfile | null;
}
+5 -1
View File
@@ -79,11 +79,15 @@ Creates a patient record for a user under the current entity. If the record alre
"user_uuid": "string (اختیاری)",
"mobile": "09xxxxxxxxx (اختیاری — برای جستجو یا ساخت بیمار جدید)",
"name": "string (الزامی فقط هنگام ساخت بیمار جدید)",
"national_code": "string (اختیاری، ۱۰ رقم)"
"national_code": "string (اختیاری، ۱۰ رقم)",
"record_number": "string (اختیاری) — شماره پرونده، مخصوص رکورد",
"tags": ["uuid برچسب‌های TenantTag (اختیاری) — باید متعلق به همین tenant باشند"]
}
```
- اگر `user_uuid` و `mobile` هر دو خالی باشند → خطا.
- `record_number` و `tags` روی خودِ رکورد ذخیره می‌شوند (نه پروفایل کاربر). سایر مشخصات دموگرافیک (`gender`, `date_of_birth`, `referral_source`, `description`, بیمه‌ها) روی `UserProfile` هستند و از طریق `PATCH /patient/{uuid}` ست می‌شوند. پاسخ همیشه `record_number` و `tags: [{uuid,name,color}]` را برمی‌گرداند.
- برچسب متعلق به tenant دیگر → `422 ERR_VALIDATION_001` (`field: tags`).
- `national_code` فقط وقتی روی کاربر ست می‌شود که کاربر کد ملی نداشته باشد.
- موبایل تکراری duplicate نمی‌سازد؛ همان کاربر استفاده می‌شود.
- **یکتایی کد ملی:** اگر `national_code` ارسالی قبلاً به پروفایل کاربر دیگری تعلق داشته باشد → `409` با کد `ERR_PROFILE_001` (`field: national_code`). پیام خطا شامل شماره موبایلِ ماسک‌شده‌ی صاحب کد است (مثلاً «این کد ملی قبلاً با شماره 0912****56 ثبت شده است»). یک کد ملی = یک بیمار در کل سیستم (هم‌راستا با قید یکتای `profiles.national_code`).
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260713110856 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE patient_record_tags (patient_record_id INT NOT NULL, tenant_tag_id INT NOT NULL, INDEX IDX_BA083ABDEB76A733 (patient_record_id), INDEX IDX_BA083ABD9B790748 (tenant_tag_id), PRIMARY KEY (patient_record_id, tenant_tag_id)) DEFAULT CHARACTER SET utf8mb4');
$this->addSql('ALTER TABLE patient_record_tags ADD CONSTRAINT FK_BA083ABDEB76A733 FOREIGN KEY (patient_record_id) REFERENCES patient_records (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE patient_record_tags ADD CONSTRAINT FK_BA083ABD9B790748 FOREIGN KEY (tenant_tag_id) REFERENCES tenant_tags (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE patient_records ADD record_number VARCHAR(40) DEFAULT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE patient_record_tags DROP FOREIGN KEY FK_BA083ABDEB76A733');
$this->addSql('ALTER TABLE patient_record_tags DROP FOREIGN KEY FK_BA083ABD9B790748');
$this->addSql('DROP TABLE patient_record_tags');
$this->addSql('ALTER TABLE patient_records DROP record_number');
}
}
@@ -49,9 +49,33 @@ class PatientController extends BaseController
private readonly InvoiceRepository $invoiceRepo,
private readonly \App\Appointment\Repository\AppointmentRepository $appointmentRepo,
private readonly \App\ClinicInvitation\Repository\ClinicDoctorInvitationRepository $invitationRepo,
private readonly \App\Tag\Repository\TenantTagRepository $tenantTagRepo,
private readonly LoggerInterface $logger,
) {}
/**
* Assign record labels from the payload (`tags` = array of TenantTag uuids),
* scoped to the caller's entity. Returns a 422 response on a foreign tag,
* otherwise null. Does nothing when `tags` is absent.
*/
private function applyRecordTags(PatientRecord $record, array $data, string $entityType, int $entityId): ?JsonResponse
{
if (!array_key_exists('tags', $data)) {
return null;
}
$uuids = is_array($data['tags']) ? $data['tags'] : [];
$tags = [];
foreach (array_values(array_unique(array_filter($uuids))) as $uuid) {
$tag = $this->tenantTagRepo->findByUuid((string) $uuid);
if ($tag === null || $tag->getEntityType() !== $entityType || $tag->getEntityId() !== $entityId) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'برچسب انتخاب‌شده متعلق به شما نیست', 422, 'tags');
}
$tags[] = $tag;
}
$record->setTags($tags);
return null;
}
private function buildPatientProfile(User $patient): array
{
$p = $this->profileRepo->findByUser($patient);
@@ -196,6 +220,15 @@ class PatientController extends BaseController
}
$record = new PatientRecord($entityType, $entityId, $patient, $user->hasRole('ROLE_DOCTOR') ? 'doctor' : 'clinic', $entityId);
if (($rn = trim((string) ($data['record_number'] ?? ''))) !== '') {
$record->setRecordNumber($rn);
}
$tagError = $this->applyRecordTags($record, $data, $entityType, $entityId);
if ($tagError !== null) {
return $tagError;
}
$this->recordRepo->save($record);
return $this->success($record->toArray(), 201);
@@ -335,6 +368,16 @@ class PatientController extends BaseController
}
$this->profileRepo->save($profile);
if (array_key_exists('record_number', $data)) {
$rn = trim((string) ($data['record_number'] ?? ''));
$record->setRecordNumber($rn === '' ? null : $rn);
}
$tagError = $this->applyRecordTags($record, $data, $entityType, $entityId);
if ($tagError !== null) {
return $tagError;
}
$this->recordRepo->save($record);
$out = $record->toArray();
$out['profile'] = $this->buildPatientProfile($patient);
+44
View File
@@ -4,6 +4,7 @@ namespace App\Patient\Entity;
use App\Auth\Entity\User;
use App\Patient\Repository\PatientRecordRepository;
use App\Tag\Entity\TenantTag;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@@ -41,6 +42,20 @@ class PatientRecord
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
// Clinic-scoped case-file number. Patient identity/demographics (gender,
// date_of_birth, referral_source, description, insurance, …) live on the
// patient's UserProfile and are set via PATCH /patient/{uuid}.
#[ORM\Column(name: 'record_number', type: 'string', length: 40, nullable: true)]
private ?string $recordNumber = null;
/**
* @var Collection<int, TenantTag> record labels. EAGER so the typed
* collection is always hydrated (see ServiceItem for the same pitfall).
*/
#[ORM\ManyToMany(targetEntity: TenantTag::class, fetch: 'EAGER')]
#[ORM\JoinTable(name: 'patient_record_tags')]
private Collection $tags;
#[ORM\OneToMany(targetEntity: PatientSession::class, mappedBy: 'record', cascade: ['remove'])]
private Collection $sessions;
@@ -54,6 +69,7 @@ class PatientRecord
$this->createdById = $createdById;
$this->createdAt = time();
$this->sessions = new ArrayCollection();
$this->tags = new ArrayCollection();
}
public function getId(): ?int { return $this->id; }
@@ -65,6 +81,29 @@ class PatientRecord
public function getCreatedById(): int { return $this->createdById; }
public function getCreatedAt(): int { return $this->createdAt; }
public function getRecordNumber(): ?string { return $this->recordNumber; }
public function setRecordNumber(?string $v): self { $this->recordNumber = $v; return $this; }
/** @return Collection<int, TenantTag> */
public function getTags(): Collection
{
// Doctrine hydrates without the constructor; guard the typed property.
return $this->tags ??= new ArrayCollection();
}
/** @param TenantTag[] $tags */
public function setTags(array $tags): self
{
$collection = $this->getTags();
$collection->clear();
foreach ($tags as $t) {
if (!$collection->contains($t)) {
$collection->add($t);
}
}
return $this;
}
public function toArray(): array
{
return [
@@ -75,6 +114,11 @@ class PatientRecord
'user_name' => $this->user->getRealName(),
'user_mobile' => $this->user->getMobileNumber(),
'user_national_code' => $this->user->getNationalCode(),
'record_number' => $this->recordNumber,
'tags' => array_map(
fn(TenantTag $t) => $t->toArray(),
array_values($this->getTags()->toArray())
),
'created_by_type' => $this->createdByType,
'created_at' => $this->createdAt,
];
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Tests\Patient;
use App\Doctor\Entity\Doctor;
use App\Patient\Entity\PatientRecord;
use App\Patient\Repository\PatientRecordRepository;
use App\Tag\Entity\TenantTag;
use App\Tests\ApiTestCase;
/**
* PatientRecord carries clinic-scoped case-file fields (record_number, gender,
* birth_date, referral_source, description) and a set of TenantTag labels.
*/
class PatientRecordFieldsTest extends ApiTestCase
{
public function testFieldsAndTagsRoundTrip(): void
{
$owner = $this->createUser(['ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر');
$this->em->persist($doctor);
$this->em->flush();
$t1 = new TenantTag('doctor', $doctor->getId(), 'فوری', '#FF0000');
$t2 = new TenantTag('doctor', $doctor->getId(), 'پیگیری', '#00AA00');
$this->em->persist($t1);
$this->em->persist($t2);
$this->em->flush();
$patient = $this->createUser(['ROLE_USER']); // random unique mobile — db_test is never reset
$patient->setRealName('بیمار نمونه');
$this->em->flush();
$record = new PatientRecord('doctor', $doctor->getId(), $patient, 'doctor', $doctor->getId());
$record->setRecordNumber('P-1001')
->setTags([$t1, $t2]);
$this->em->persist($record);
$this->em->flush();
$uuid = $record->getUuid();
$this->em->clear();
/** @var PatientRecordRepository $repo */
$repo = static::getContainer()->get(PatientRecordRepository::class);
$reloaded = $repo->findByUuid($uuid);
self::assertNotNull($reloaded);
self::assertCount(2, $reloaded->getTags());
$arr = $reloaded->toArray();
self::assertSame('P-1001', $arr['record_number']);
self::assertCount(2, $arr['tags']);
self::assertSame('فوری', $arr['tags'][0]['name']);
}
}
@@ -0,0 +1,72 @@
<?php
namespace App\Tests\Patient;
use App\Doctor\Entity\Doctor;
use App\Tag\Entity\TenantTag;
use App\Tests\ApiTestCase;
/**
* POST/PATCH /patient accept `record_number` and tenant-scoped `tags` (uuids).
*/
class PatientRecordTagsApiTest extends ApiTestCase
{
private function doctor(): array
{
$owner = $this->createUser(['ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر');
$this->em->persist($doctor);
$this->em->flush();
return [$owner, $doctor];
}
private function tag(int $doctorId, string $name): TenantTag
{
$t = new TenantTag('doctor', $doctorId, $name, '#FF0000');
$this->em->persist($t);
$this->em->flush();
return $t;
}
public function testCreateAndUpdateWithRecordNumberAndTags(): void
{
[$owner, $doctor] = $this->doctor();
$t1 = $this->tag($doctor->getId(), 'فوری');
$t2 = $this->tag($doctor->getId(), 'پیگیری');
$mobile = '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT);
$created = $this->authJson('POST', '/api/v1/patient', $owner, [
'mobile' => $mobile,
'name' => 'بیمار نمونه',
'record_number' => 'P-1001',
'tags' => [$t1->getUuid(), $t2->getUuid()],
]);
self::assertSame(201, $this->responseCode());
self::assertSame('P-1001', $created['data']['record_number']);
self::assertCount(2, $created['data']['tags']);
$uuid = $created['data']['uuid'];
// update: keep one tag, change record number
$updated = $this->authJson('PATCH', '/api/v1/patient/' . $uuid, $owner, [
'record_number' => 'P-2002',
'tags' => [$t1->getUuid()],
]);
self::assertSame(200, $this->responseCode());
self::assertSame('P-2002', $updated['data']['record_number']);
self::assertCount(1, $updated['data']['tags']);
}
public function testRejectsForeignTag(): void
{
[$owner, $doctor] = $this->doctor();
$mobile = '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT);
$created = $this->authJson('POST', '/api/v1/patient', $owner, ['mobile' => $mobile, 'name' => 'ب']);
$uuid = $created['data']['uuid'];
[, $doctorB] = $this->doctor();
$foreign = $this->tag($doctorB->getId(), 'خارجی');
$this->authJson('PATCH', '/api/v1/patient/' . $uuid, $owner, ['tags' => [$foreign->getUuid()]]);
self::assertSame(422, $this->responseCode());
}
}