feat: add optional inventory package association to service items and implement audit logging

- Added `inventory_package_uuid` and `inventory_package_title` fields to the `ServiceItem` interface.
- Updated API documentation to reflect new fields in service item responses.
- Implemented methods in `ClinicServiceController` to handle inventory package associations.
- Created `ServiceItemAuditLog` entity and repository for tracking changes to service items.
- Added functionality to log changes to service items, including inventory package associations.
- Implemented tests for attaching/detaching inventory packages and auditing changes.
- Created database migrations for new fields and audit log table.
This commit is contained in:
hamed
2026-07-18 12:26:15 +03:30
parent 42d9ad26c5
commit c4a661b542
14 changed files with 885 additions and 24 deletions
@@ -8,6 +8,7 @@ import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { ServiceItem, ClinicStaff } from '../types';
import type { InventoryPackage } from '../hooks/useInventory';
import { rialToToman, tomanToRial } from '../lib/utils';
import { numericField } from '../lib/forms';
import Modal from './ui/Modal';
@@ -20,10 +21,15 @@ const itemSchema = z.object({
staff_uuids: z.array(z.string()).optional(),
duration_minutes: z.coerce.number().min(0).optional(),
bookable: z.boolean().optional(),
/** پکیج کالای مصرفی؛ رشته‌ی خالی یعنی بدون پکیج. */
inventory_package_uuid: z.string().optional(),
});
type ItemForm = z.infer<typeof itemSchema>;
const EMPTY_FORM: ItemForm = { name: '', price_rials: 0, staff_uuids: [], duration_minutes: undefined, bookable: false };
const EMPTY_FORM: ItemForm = {
name: '', price_rials: 0, staff_uuids: [], duration_minutes: undefined,
bookable: false, inventory_package_uuid: '',
};
interface Props {
/** `'create'` برای سرویس جدید، شیء سرویس برای ویرایش، `null` یعنی بسته. */
@@ -52,6 +58,13 @@ export default function ServiceItemFormModal({ item, sectionUuid, onClose, onMan
});
const allStaff = staffData?.data ?? [];
const { data: packagesData } = useQuery<ApiResponse<InventoryPackage[]>>({
queryKey: ['inventory-packages'],
queryFn: () => api.get('/api/v1/inventory-packages'),
enabled: item !== null,
});
const packages = packagesData?.data ?? [];
const form = useForm<ItemForm>({ resolver: zodResolver(itemSchema), defaultValues: EMPTY_FORM });
useEffect(() => {
@@ -63,6 +76,7 @@ export default function ServiceItemFormModal({ item, sectionUuid, onClose, onMan
staff_uuids: (editing.staff_members ?? (editing.staff ? [editing.staff] : [])).map((s) => s.uuid),
duration_minutes: editing.duration_minutes ?? undefined,
bookable: editing.bookable ?? false,
inventory_package_uuid: editing.inventory_package_uuid ?? '',
}
: EMPTY_FORM);
}, [item]);
@@ -73,21 +87,24 @@ export default function ServiceItemFormModal({ item, sectionUuid, onClose, onMan
if (editing) qc.invalidateQueries({ queryKey: ['service-item', editing.uuid] });
};
// رشته‌ی خالی در payload یعنی «بدون پکیج»؛ بک‌اند null می‌خواهد.
const toPayload = (body: ItemForm) => ({
...body,
price_rials: tomanToRial(body.price_rials),
inventory_package_uuid: body.inventory_package_uuid || null,
});
const createItem = useMutation({
mutationFn: (body: ItemForm) => api.post('/api/v1/service-item', {
...body,
...toPayload(body),
section_uuid: sectionUuid,
price_rials: tomanToRial(body.price_rials),
}),
onSuccess: () => { invalidate(); onClose(); toast.success('سرویس ایجاد شد'); },
onError: (e: Error) => toast.error(e.message),
});
const editItem = useMutation({
mutationFn: (body: ItemForm) => api.patch(`/api/v1/service-item/${editing!.uuid}`, {
...body,
price_rials: tomanToRial(body.price_rials),
}),
mutationFn: (body: ItemForm) => api.patch(`/api/v1/service-item/${editing!.uuid}`, toPayload(body)),
onSuccess: () => { invalidate(); onClose(); toast.success('سرویس ویرایش شد'); },
onError: (e: Error) => toast.error(e.message),
});
@@ -204,6 +221,19 @@ export default function ServiceItemFormModal({ item, sectionUuid, onClose, onMan
<span style={{ fontSize: 13 }}>نمایش در نوبتدهی</span>
</label>
</div>
<div>
<label className="field-label">پکیج کالای مصرفی</label>
<SearchableSelect
options={packages.map((p) => ({ value: p.uuid, label: p.title }))}
value={form.watch('inventory_package_uuid') || null}
onChange={(v) => form.setValue('inventory_package_uuid', v == null ? '' : String(v))}
placeholder="بدون پکیج (اختیاری)"
noOptionsMessage="پکیجی تعریف نشده است"
isClearable
height={42}
/>
</div>
</div>
{/* بیمه — تنظیمات فقط در «پوشش بیمه» مدیریت می‌شود تا داده‌ی تکراری ساخته نشود. */}
@@ -38,6 +38,10 @@ const mockApi = (item: unknown = ITEM, notFound = false) => {
effective_plan: { name: 'professional', level: 2, max_secretaries: 10, features: { services: true } },
} });
if (url.includes('/payment/config')) return Promise.resolve({ success: true, data: { test_mode: true, gateways: [] } });
if (url.includes('/audit-logs')) return Promise.resolve({ success: true, data: [
{ uuid: 'l1', field: 'price_rials', operation: 'update', old_value: '7000000', new_value: '8500000', actor_name: 'دکتر تست', created_at: 1_800_000_000 },
{ uuid: 'l2', field: 'name', operation: 'create', old_value: null, new_value: 'سرم ۵۰۰cc', actor_name: 'دکتر تست', created_at: 1_700_000_000 },
] });
if (url.includes('/service-item/')) {
return notFound ? Promise.reject(new Error('یافت نشد')) : Promise.resolve({ success: true, data: item });
}
@@ -51,6 +55,12 @@ const mockApi = (item: unknown = ITEM, notFound = false) => {
if (url.includes('/tenant-insurances')) return Promise.resolve({ data: { data: [
{ uuid: 'ins1', insurance_name: 'بیمه ایران', insurance_kind: 'basic', coverage_percent: 70 },
] } });
if (url.includes('/inventory-packages')) return Promise.resolve({ success: true, data: [
{
uuid: 'pkg1', title: 'پکیج سرم', total: 1_200_000, available: true,
items: [{ itemUuid: 'i1', name: 'سرم رینگر', unit: 'عدد', price: 600_000, amount: 2 }],
},
] });
return Promise.resolve({ success: true, data: [] });
});
};
@@ -125,6 +135,35 @@ describe('ServiceDetailPage (جزئیات سرویس)', () => {
expect(screen.queryByText('این خدمت شامل بیمه می‌شود')).not.toBeInTheDocument();
});
it('تب کالاهای مرتبط، اقلام پکیج متصل را نشان می‌دهد', async () => {
mockApi({ ...ITEM, inventory_package_uuid: 'pkg1', inventory_package_title: 'پکیج سرم' });
render();
fireEvent.click(await screen.findByText('کالاهای مرتبط'));
expect(await screen.findByText('پکیج سرم')).toBeInTheDocument();
expect(screen.getByText('سرم رینگر')).toBeInTheDocument();
expect(screen.getByText('۲ عدد')).toBeInTheDocument();
});
it('سرویس بدون پکیج، حالت خالی با لینک انبار می‌دهد', async () => {
render();
fireEvent.click(await screen.findByText('کالاهای مرتبط'));
expect(await screen.findByText('پکیج کالایی به این سرویس متصل نیست')).toBeInTheDocument();
expect(screen.getByText('مدیریت انبار')).toBeInTheDocument();
});
it('تب لاگ تغییرات، مقدار قبل و بعد را خوانا نشان می‌دهد', async () => {
render();
fireEvent.click(await screen.findByText('لاگ تغییرات'));
expect(await screen.findByText('قیمت پایه')).toBeInTheDocument();
expect(screen.getByText('۷۰۰٬۰۰۰ تومان')).toBeInTheDocument();
expect(screen.getByText('۸۵۰٬۰۰۰ تومان')).toBeInTheDocument();
expect(screen.getByText('ایجاد')).toBeInTheDocument();
expect(screen.getAllByText(/توسط دکتر تست/).length).toBeGreaterThan(0);
});
it('سرویس غیرفعال نشان «غیرفعال» و دکمه فعال‌کردن دارد', async () => {
mockApi({ ...ITEM, active: false });
render();
+160 -1
View File
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
BanknotesIcon, ShieldCheckIcon, ClockIcon, UsersIcon, PencilIcon,
@@ -9,6 +9,7 @@ import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { ServiceItem } from '../types';
import type { InventoryPackage } from '../hooks/useInventory';
import { formatRial, formatNumber, formatYear, formatDateTime } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import FeatureGate from '../components/ui/FeatureGate';
@@ -49,9 +50,42 @@ const TABS = [
{ id: 'info', label: 'اطلاعات سرویس' },
{ id: 'tariffs', label: 'تعرفه‌ها' },
{ id: 'insurance', label: 'بیمه‌ها' },
{ id: 'goods', label: 'کالاهای مرتبط' },
{ id: 'history', label: 'لاگ تغییرات' },
] as const;
type TabId = typeof TABS[number]['id'];
interface AuditLog {
uuid: string;
field: string;
operation: 'create' | 'update';
old_value: string | null;
new_value: string | null;
actor_name: string | null;
created_at: number;
}
/** برچسب فارسی فیلدهای لاگ — باید با ServiceItemAuditService::TRACKED هم‌تراز بماند. */
const FIELD_LABELS: Record<string, string> = {
name: 'نام سرویس',
price_rials: 'قیمت پایه',
active: 'وضعیت',
duration_minutes: 'زمان متوسط',
bookable: 'نمایش در نوبت‌دهی',
insurance_covered: 'پوشش بیمه',
inventory_package: 'پکیج کالا',
};
/** مقدار خام لاگ را برای نمایش قابل‌فهم می‌کند (بولین، مبلغ، خالی). */
function auditValue(field: string, raw: string | null): string {
if (raw === null || raw === '') return '—';
if (['active', 'bookable', 'insurance_covered'].includes(field)) return raw === '1' ? 'بله' : 'خیر';
if (field === 'price_rials') return formatRial(Number(raw));
if (field === 'duration_minutes') return `${formatNumber(Number(raw))} دقیقه`;
if (field === 'inventory_package') return 'پکیج متصل';
return raw;
}
const KIND = {
basic: { label: 'پایه', cls: 'blue' },
supplementary: { label: 'تکمیلی', cls: 'violet' },
@@ -252,6 +286,129 @@ function ContractCoverageRow({ contract, itemUuid }: { contract: TenantInsurance
);
}
function GoodsTab({ item, onEdit }: { item: ServiceItem; onEdit: () => void }) {
const { data, isLoading } = useQuery<ApiResponse<InventoryPackage[]>>({
queryKey: ['inventory-packages'],
queryFn: () => api.get('/api/v1/inventory-packages'),
});
const linked = (data?.data ?? []).find((p) => p.uuid === item.inventory_package_uuid);
return (
<div className="card card-pad">
<div className="card-title-row">
<div>
<b style={{ fontSize: 14 }}>کالاهای مرتبط</b>
<div className="muted" style={{ fontSize: 12 }}>
پکیج کالای مصرفی این خدمت؛ در «انبار» ساخته و در فرم سرویس انتخاب میشود.
</div>
</div>
<button className="btn primary sm" onClick={onEdit}>انتخاب پکیج</button>
</div>
{isLoading ? (
<div className="muted" style={{ fontSize: 13, padding: '12px 0' }}>در حال بارگذاری...</div>
) : !item.inventory_package_uuid ? (
<div className="empty" style={{ padding: '28px 0' }}>
<CubeIcon style={{ width: 30, height: 30 }} />
<p className="muted">پکیج کالایی به این سرویس متصل نیست</p>
<Link className="btn sm" to="/admin/inventory">مدیریت انبار</Link>
</div>
) : !linked ? (
<div className="muted" style={{ fontSize: 13, padding: '12px 0' }}>
{item.inventory_package_title ?? 'پکیج متصل'} جزئیات در دسترس نیست
</div>
) : (
<div style={{ marginTop: 12 }}>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
padding: '10px 12px', borderRadius: 'var(--r-sm)', background: 'var(--primary-soft)', marginBottom: 10,
}}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
<CubeIcon style={{ width: 15, color: 'var(--primary)' }} />
<b>{linked.title}</b>
{!linked.available && <span className="badge gray" style={{ fontSize: 10 }}>موجودی ناکافی</span>}
</span>
<b style={{ fontSize: 13.5, color: 'var(--primary)' }}>{formatRial(linked.total)}</b>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{linked.items.map((line) => (
<div key={line.itemUuid} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
padding: '9px 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)',
}}>
<span style={{ fontSize: 13 }}>{line.name}</span>
<span style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'inline-flex', gap: 10 }}>
<span>{formatNumber(line.amount)} {line.unit}</span>
<span>{formatRial(line.price * line.amount)}</span>
</span>
</div>
))}
</div>
</div>
)}
</div>
);
}
function HistoryTab({ item }: { item: ServiceItem }) {
const { data, isLoading } = useQuery<ApiResponse<AuditLog[]>>({
queryKey: ['service-item-audit', item.uuid],
queryFn: () => api.get(`/api/v1/service-item/${item.uuid}/audit-logs`),
});
const logs = data?.data ?? [];
return (
<div className="card card-pad">
<div className="card-title-row">
<div>
<b style={{ fontSize: 14 }}>لاگ تغییرات</b>
<div className="muted" style={{ fontSize: 12 }}>
چه کسی، چه فیلدی را، کِی و از چه مقداری به چه مقداری تغییر داد.
</div>
</div>
</div>
{isLoading ? (
<div className="muted" style={{ fontSize: 13, padding: '12px 0' }}>در حال بارگذاری...</div>
) : logs.length === 0 ? (
<div className="empty" style={{ padding: '28px 0' }}>
<ClockIcon style={{ width: 30, height: 30 }} />
<p className="muted">تغییری ثبت نشده است</p>
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
{logs.map((log) => (
<div key={log.uuid} style={{
padding: '10px 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)',
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 6 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
<b>{FIELD_LABELS[log.field] ?? log.field}</b>
{log.operation === 'create' && <span className="badge green" style={{ fontSize: 10 }}>ایجاد</span>}
</span>
<span style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{formatDateTime(log.created_at)}</span>
</div>
{log.operation === 'update' && (
<div style={{ fontSize: 12.5, color: 'var(--text-2)', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<span style={{ color: 'var(--text-3)', textDecoration: 'line-through' }}>{auditValue(log.field, log.old_value)}</span>
<span style={{ color: 'var(--text-3)' }}></span>
<span style={{ fontWeight: 600 }}>{auditValue(log.field, log.new_value)}</span>
</div>
)}
{log.actor_name && (
<div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 4 }}>توسط {log.actor_name}</div>
)}
</div>
))}
</div>
)}
</div>
);
}
function ServiceDetailPageInner() {
const { uuid } = useParams<{ uuid: string }>();
const navigate = useNavigate();
@@ -339,6 +496,8 @@ function ServiceDetailPageInner() {
{tab === 'info' && <InfoTab item={item} />}
{tab === 'tariffs' && <TariffsTab item={item} onManage={() => setTariffOpen(true)} />}
{tab === 'insurance' && <InsuranceTab item={item} onManage={() => setInsuranceOpen(true)} />}
{tab === 'goods' && <GoodsTab item={item} onEdit={() => setEditOpen(true)} />}
{tab === 'history' && <HistoryTab item={item} />}
<ServiceItemFormModal
item={editOpen ? item : null}
+3
View File
@@ -516,6 +516,9 @@ export interface ServiceItem {
price_rials: number;
section_uuid?: string;
section_name?: string;
/** پکیج کالای مصرفی متصل به این خدمت (اختیاری) */
inventory_package_uuid?: string | null;
inventory_package_title?: string | null;
created_at?: number;
updated_at?: number;
/** primary staff (first member) — kept for backward compatibility */