diff --git a/assets/admin/components/PatientTagsCell.tsx b/assets/admin/components/PatientTagsCell.tsx new file mode 100644 index 00000000..872c2b0f --- /dev/null +++ b/assets/admin/components/PatientTagsCell.tsx @@ -0,0 +1,105 @@ +import { useState } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { PlusIcon, XMarkIcon } from '@heroicons/react/24/outline'; +import { toast } from 'sonner'; +import { api } from '../lib/api'; +import type { ApiResponse } from '../lib/api'; +import { formatNumber } from '../lib/utils'; +import type { PatientRecord } from '../types'; + +interface TenantTag { uuid: string; name: string; color: string; active: boolean } + +/** + * The برچسب‌ها cell for a patient row: shows the record's tag dots and, on click, + * opens a popover to assign/remove tenant tags inline. Assignment PATCHes the + * record's full `tags` array (the backend replaces the set) and refreshes the list. + */ +export default function PatientTagsCell({ record }: { record: PatientRecord }) { + const qc = useQueryClient(); + const [open, setOpen] = useState(false); + const current = record.tags ?? []; + const currentUuids = current.map((t) => t.uuid); + + const { data: tagsData, isLoading } = useQuery>({ + queryKey: ['tenant-tags'], + queryFn: () => api.get('/api/v1/tenant-tags'), + enabled: open, + }); + const allTags = tagsData?.data ?? []; + + const mutate = useMutation({ + mutationFn: (uuids: string[]) => api.patch(`/api/v1/patient/${record.uuid}`, { tags: uuids }), + onSuccess: () => qc.invalidateQueries({ queryKey: ['patients'] }), + onError: (e: any) => toast.error(e?.message || 'خطا در به‌روزرسانی برچسب‌ها'), + }); + + const toggle = (uuid: string) => { + const next = currentUuids.includes(uuid) ? currentUuids.filter((u) => u !== uuid) : [...currentUuids, uuid]; + mutate.mutate(next); + }; + + return ( + + {current.length === 0 ? ( + + ) : ( + + )} + + {open && ( + <> +
setOpen(false)} /> +
+
+ برچسب‌ها + +
+ {isLoading ? ( +
در حال بارگذاری…
+ ) : allTags.length === 0 ? ( +
برچسبی تعریف نشده است.
+ ) : ( +
+ {allTags.map((tag) => { + const assigned = currentUuids.includes(tag.uuid); + return ( + + ); + })} +
+ )} +
+ + )} + + ); +} diff --git a/assets/admin/components/PatientsFilterModal.tsx b/assets/admin/components/PatientsFilterModal.tsx new file mode 100644 index 00000000..4e7de44f --- /dev/null +++ b/assets/admin/components/PatientsFilterModal.tsx @@ -0,0 +1,152 @@ +import { useEffect, useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { api } from '../lib/api'; +import type { ApiResponse } from '../lib/api'; +import Modal from './ui/Modal'; +import PersianDateInput from './ui/PersianDateInput'; + +export interface PatientFilters { + gender?: string; // male | female + insurance_id?: string; + admitted_from?: string; // gregorian Y-m-d + admitted_to?: string; + service_status?: string; // pending | completed + has_debt?: boolean; + tags?: string[]; // tenant-tag uuids +} + +interface TenantTag { uuid: string; name: string; color: string } +interface PricingInsurance { insurance_id: number; insurance_name: string; type: string } + +const EMPTY: PatientFilters = {}; + +function Segmented({ value, onChange, options }: { value: string | undefined; onChange: (v: string) => void; options: { label: string; value: string }[] }) { + return ( +
+ {options.map((o) => { + const active = (value ?? '') === o.value; + return ( + + ); + })} +
+ ); +} + +/** فیلترها — advanced patient-list filter modal, ported from tauri FilesFilterModal. */ +export default function PatientsFilterModal({ open, onClose, value, onApply }: { + open: boolean; onClose: () => void; value: PatientFilters; onApply: (f: PatientFilters) => void; +}) { + const [f, setF] = useState(value); + useEffect(() => { if (open) setF(value); }, [open, value]); + + const { data: tagsData } = useQuery>({ + queryKey: ['tenant-tags'], queryFn: () => api.get('/api/v1/tenant-tags'), enabled: open, + }); + const tags = tagsData?.data ?? []; + + const { data: pricingData } = useQuery>({ + queryKey: ['insurance-pricing'], queryFn: () => api.get('/api/v1/insurance-pricing'), enabled: open, + }); + const insurances = (pricingData?.data?.insurances ?? []).filter((i) => i.type === 'basic'); + + const set = (k: K, v: PatientFilters[K]) => setF((p) => ({ ...p, [k]: v })); + const toggleTag = (uuid: string) => { + const cur = f.tags ?? []; + set('tags', cur.includes(uuid) ? cur.filter((u) => u !== uuid) : [...cur, uuid]); + }; + + const label: React.CSSProperties = { fontSize: 13, fontWeight: 700, color: 'var(--text-2)', marginBottom: 8, display: 'block' }; + const selectedTags = f.tags ?? []; + + return ( + + + + + }> +
+
+ +
+
set('admitted_from', v)} placeholder="از تاریخ" />
+ تا +
set('admitted_to', v)} placeholder="تا تاریخ" />
+
+
+ +
+ + +
+ +
+ + set('service_status', v || undefined)} + options={[{ label: 'همه', value: '' }, { label: 'تکمیل نشده', value: 'pending' }, { label: 'تکمیل شده', value: 'completed' }]} + /> +
+ +
+ + +
+ +
+ + set('gender', v || undefined)} + options={[{ label: 'هر دو', value: '' }, { label: 'آقا', value: 'male' }, { label: 'خانم', value: 'female' }]} + /> +
+ +
+ + {tags.length === 0 ? ( + برچسبی تعریف نشده است. + ) : ( +
+ {tags.map((t) => { + const on = selectedTags.includes(t.uuid); + return ( + + ); + })} +
+ )} +
+
+
+ ); +} diff --git a/assets/admin/pages/PatientsListPage.test.tsx b/assets/admin/pages/PatientsListPage.test.tsx index 898dcf50..ca947786 100644 --- a/assets/admin/pages/PatientsListPage.test.tsx +++ b/assets/admin/pages/PatientsListPage.test.tsx @@ -1,7 +1,8 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { screen, fireEvent } from '@testing-library/react'; +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 {}, @@ -11,16 +12,21 @@ import { api } from '../lib/api'; import PatientsListPage from './PatientsListPage'; const get = api.get as ReturnType; +const patch = api.patch as ReturnType; + +const PATIENTS = [ + { 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: [] }, +]; 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 }, + patch.mockReset(); + patch.mockResolvedValue({ success: true, data: {} }); + get.mockImplementation((url: string) => { + if (url.includes('/tenant-tags')) return Promise.resolve({ success: true, data: [{ uuid: 'tag1', name: 'خوش‌حساب', color: '#0a0', active: true }] }); + if (url.includes('/insurance-pricing')) return Promise.resolve({ success: true, data: { insurances: [{ insurance_id: 1, insurance_name: 'تأمین اجتماعی', type: 'basic' }] } }); + return Promise.resolve({ success: true, data: PATIENTS, meta: { totalRecords: 2 } }); }); }); @@ -30,8 +36,8 @@ describe('PatientsListPage (پرونده‌ها)', () => { 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(); + // record with no tags shows the inline "add" trigger + expect(screen.getByText('اضافه کردن')).toBeInTheDocument(); }); it('switches to the card view', async () => { @@ -41,4 +47,25 @@ describe('PatientsListPage (پرونده‌ها)', () => { expect(screen.getByText('دنیا خلیلی')).toBeInTheDocument(); expect(screen.getAllByText('مشاهده').length).toBeGreaterThan(0); }); + + it('assigns a tag inline through the برچسب‌ها popover', async () => { + renderWithProviders(, { route: '/admin/patients' }); + await screen.findByText('علی بدیعی زاده'); + + fireEvent.click(screen.getByText('اضافه کردن')); // open popover for the untagged record (r2) + fireEvent.click(await screen.findByText('خوش‌حساب')); // toggle the tenant tag + + await waitFor(() => expect(patch).toHaveBeenCalledWith('/api/v1/patient/r2', { tags: ['tag1'] })); + }); + + it('applies an advanced filter and re-queries with the param', async () => { + renderWithProviders(, { route: '/admin/patients' }); + await screen.findByText('دنیا خلیلی'); + + fireEvent.click(screen.getByLabelText('فیلترها')); + fireEvent.click(await screen.findByLabelText('فقط پرونده‌های دارای بدهی')); + fireEvent.click(screen.getByRole('button', { name: 'اعمال تغییرات' })); + + await waitFor(() => expect(get.mock.calls.some(([u]) => String(u).includes('has_debt=1'))).toBe(true)); + }); }); diff --git a/assets/admin/pages/PatientsListPage.tsx b/assets/admin/pages/PatientsListPage.tsx index 6c8bef25..2c6ed934 100644 --- a/assets/admin/pages/PatientsListPage.tsx +++ b/assets/admin/pages/PatientsListPage.tsx @@ -8,25 +8,27 @@ import { import { api } from '../lib/api'; import type { ApiResponse } from '../lib/api'; import type { PatientRecord } from '../types'; -import { formatNumber } from '../lib/utils'; +import { formatNumber, toDate } from '../lib/utils'; import Pagination from '../components/ui/Pagination'; +import PatientTagsCell from '../components/PatientTagsCell'; +import PatientsFilterModal, { type PatientFilters } from '../components/PatientsFilterModal'; const LIMIT = 20; const EMPTY: PatientRecord[] = []; -function TagDots({ tags }: { tags?: PatientRecord['tags'] }) { - if (!tags || tags.length === 0) return null; - return ( - - {tags.slice(0, 3).map((t, i) => ( - - ))} - {tags.length > 3 && +{formatNumber(tags.length - 3)}} - - ); +/** unix start-of-day for `from`, end-of-day for `to`, from a gregorian Y-m-d. */ +function dayBound(value: string | undefined, end: boolean): number | undefined { + if (!value) return undefined; + const d = toDate(value); + if (!d) return undefined; + const secs = Math.floor(d.setHours(0, 0, 0, 0) / 1000); + return end ? secs + 86399 : secs; +} + +/** Number of filters currently applied (for the button badge). */ +function countFilters(f: PatientFilters): number { + return [f.gender, f.insurance_id, f.admitted_from, f.admitted_to, f.service_status, f.has_debt || undefined, f.tags?.length ? '1' : undefined] + .filter(Boolean).length; } /** پرونده‌ها — patient records list (table + card views) matching the Figma design. */ @@ -35,12 +37,28 @@ export default function PatientsListPage() { const [page, setPage] = useState(1); const [search, setSearch] = useState(''); const [view, setView] = useState<'table' | 'card'>('table'); + const [filterOpen, setFilterOpen] = useState(false); + const [filters, setFilters] = useState({}); + + const qs = new URLSearchParams({ page: String(page), limit: String(LIMIT) }); + if (search) qs.set('search', search); + if (filters.gender) qs.set('gender', filters.gender); + if (filters.insurance_id) qs.set('insurance_id', filters.insurance_id); + if (filters.service_status) qs.set('service_status', filters.service_status); + if (filters.has_debt) qs.set('has_debt', '1'); + if (filters.tags?.length) qs.set('tags', filters.tags.join(',')); + const af = dayBound(filters.admitted_from, false); + const at = dayBound(filters.admitted_to, true); + if (af) qs.set('admitted_from', String(af)); + if (at) qs.set('admitted_to', String(at)); const { data, isLoading } = useQuery & { meta?: { totalRecords: number } }>({ - queryKey: ['patients', page, search], - queryFn: () => api.get(`/api/v1/patients?page=${page}&limit=${LIMIT}&search=${encodeURIComponent(search)}`), + queryKey: ['patients', qs.toString()], + queryFn: () => api.get(`/api/v1/patients?${qs.toString()}`), }); + const activeFilters = countFilters(filters); + const records = data?.data ?? EMPTY; const total = data?.meta?.totalRecords ?? 0; @@ -70,8 +88,11 @@ export default function PatientsListPage() {
-