feat(insurance): redesign insurance management page to match Figma
Rebuild the /admin/insurance-pricing contracts UI to the Figma "مدیریت بیمه" design and inject the coverage/franchise/ceiling fields the design omitted. Backend: - Add contract-level `kind` column to TenantInsurance (basic|supplementary), defaulting to the catalog type; migration Version20260715093358. - POST/PATCH /billing/tenant-insurances now accept effective_from, effective_to, kind; PATCH also toggles is_active without clobbering the user-set effective_to (unlike DELETE/deactivate). - List returns the latest version of every insurance (active + inactive) via TenantInsuranceRepository::findLatestByTenant, for the فعال/غیرفعال toggle. Frontend: - New InsuranceModal (ui/Modal + SearchableSelect + PersianDateInput) with the seven fields; submit "ثبت بیمه". - TenantInsuranceContracts rebuilt: header + search box, desktop table (ردیف/نام/کد/نوع/وضعیت/عملیات) and mobile cards, status toggle -> PATCH. - utils: isoToUnix/unixToIso helpers for contract dates. Tests: TenantInsuranceContractApiTest (create/edit/toggle/list, 5 cases), InsuranceModal + TenantInsuranceContracts vitest suites, docs/api updated. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { screen, fireEvent } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/utils';
|
||||
import InsuranceModal, {
|
||||
buildInsurancePayload, contractToForm, EMPTY_FORM, type Contract, type InsuranceOption,
|
||||
} from './InsuranceModal';
|
||||
|
||||
const mkContract = (over: Partial<Contract> = {}): Contract => ({
|
||||
uuid: 'c-1', insurance_id: 3, insurance_name: 'بیمه ایران', insurance_kind: 'basic',
|
||||
version: 1, is_active: true, coverage_percent: 70, franchise_rials: 500_000,
|
||||
annual_ceiling_rials: 20_000_000, kind: 'basic', effective_from: 1_700_000_000,
|
||||
effective_to: null, ...over,
|
||||
});
|
||||
|
||||
const options: InsuranceOption[] = [
|
||||
{ insurance_id: 3, insurance_name: 'بیمه ایران', type: 'basic' },
|
||||
{ insurance_id: 5, insurance_name: 'بیمه آسیا', type: 'supplementary' },
|
||||
];
|
||||
|
||||
describe('buildInsurancePayload', () => {
|
||||
it('converts toman → rials, percent, and Y-m-d → unix', () => {
|
||||
const payload = buildInsurancePayload({
|
||||
...EMPTY_FORM, insuranceId: '3', kind: 'supplementary',
|
||||
coverage: '80', franchise: '50000', ceiling: '2000000',
|
||||
effectiveFrom: '2024-01-01', effectiveTo: '2025-01-01',
|
||||
});
|
||||
expect(payload.insurance_id).toBe(3);
|
||||
expect(payload.kind).toBe('supplementary');
|
||||
expect(payload.coverage_percent).toBe(80);
|
||||
expect(payload.franchise_rials).toBe(500_000); // 50000 toman × 10
|
||||
expect(payload.annual_ceiling_rials).toBe(20_000_000);
|
||||
expect(typeof payload.effective_from).toBe('number');
|
||||
expect(payload.effective_to).toBeGreaterThan(payload.effective_from!);
|
||||
});
|
||||
|
||||
it('empty ceiling → null (بینهایت), empty dates → null', () => {
|
||||
const payload = buildInsurancePayload({ ...EMPTY_FORM, insuranceId: '3', coverage: '50' });
|
||||
expect(payload.annual_ceiling_rials).toBeNull();
|
||||
expect(payload.effective_from).toBeNull();
|
||||
expect(payload.effective_to).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('contractToForm', () => {
|
||||
it('maps rials → toman and uses contract kind', () => {
|
||||
const form = contractToForm(mkContract({ franchise_rials: 300_000, kind: 'supplementary' }));
|
||||
expect(form.franchise).toBe('30000');
|
||||
expect(form.kind).toBe('supplementary');
|
||||
expect(form.coverage).toBe('70');
|
||||
});
|
||||
});
|
||||
|
||||
describe('InsuranceModal', () => {
|
||||
it('renders all seven fields in add mode', () => {
|
||||
renderWithProviders(
|
||||
<InsuranceModal open editContract={null} options={options} onClose={() => {}} onSubmit={() => {}} />,
|
||||
);
|
||||
expect(screen.getByText('افزودن بیمه')).toBeInTheDocument();
|
||||
expect(screen.getByText('نام بیمه')).toBeInTheDocument();
|
||||
expect(screen.getByText('نوع بیمه')).toBeInTheDocument();
|
||||
expect(screen.getByText('تاریخ شروع قرارداد')).toBeInTheDocument();
|
||||
expect(screen.getByText('تاریخ پایان قرارداد')).toBeInTheDocument();
|
||||
expect(screen.getByText('درصد پوشش')).toBeInTheDocument();
|
||||
expect(screen.getByText('فرانشیز (تومان)')).toBeInTheDocument();
|
||||
expect(screen.getByText('سقف تعهد (تومان)')).toBeInTheDocument();
|
||||
expect(screen.getByText('ثبت بیمه')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('submits the built payload for an edited contract', () => {
|
||||
const onSubmit = vi.fn();
|
||||
renderWithProviders(
|
||||
<InsuranceModal open editContract={mkContract()} options={options} onClose={() => {}} onSubmit={onSubmit} />,
|
||||
);
|
||||
fireEvent.click(screen.getByText('ثبت بیمه'));
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
insurance_id: 3, coverage_percent: 70, franchise_rials: 500_000, kind: 'basic',
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import Modal from './ui/Modal';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
import PersianDateInput from './ui/PersianDateInput';
|
||||
import { isoToUnix, rialToToman, tomanToRial, unixToIso } from '../lib/utils';
|
||||
|
||||
export interface InsuranceOption {
|
||||
insurance_id: number;
|
||||
insurance_name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface Contract {
|
||||
uuid: string;
|
||||
insurance_id: number;
|
||||
insurance_name: string | null;
|
||||
insurance_kind: string | null;
|
||||
version: number;
|
||||
is_active: boolean;
|
||||
coverage_percent: number;
|
||||
franchise_rials: number;
|
||||
annual_ceiling_rials: number | null;
|
||||
kind: string | null;
|
||||
effective_from: number;
|
||||
effective_to: number | null;
|
||||
}
|
||||
|
||||
export interface InsuranceFormValues {
|
||||
insuranceId: string;
|
||||
kind: string;
|
||||
effectiveFrom: string; // Y-m-d
|
||||
effectiveTo: string; // Y-m-d
|
||||
coverage: string;
|
||||
franchise: string; // toman
|
||||
ceiling: string; // toman
|
||||
}
|
||||
|
||||
export const KIND_LABEL: Record<string, string> = {
|
||||
basic: 'پایه',
|
||||
supplementary: 'تکمیلی',
|
||||
};
|
||||
|
||||
export const EMPTY_FORM: InsuranceFormValues = {
|
||||
insuranceId: '', kind: 'basic', effectiveFrom: '', effectiveTo: '',
|
||||
coverage: '', franchise: '', ceiling: '',
|
||||
};
|
||||
|
||||
/** Map a contract to editable form values (rials → toman, unix → Y-m-d). */
|
||||
export function contractToForm(c: Contract): InsuranceFormValues {
|
||||
return {
|
||||
insuranceId: String(c.insurance_id),
|
||||
kind: c.kind ?? c.insurance_kind ?? 'basic',
|
||||
effectiveFrom: unixToIso(c.effective_from),
|
||||
effectiveTo: unixToIso(c.effective_to),
|
||||
coverage: String(c.coverage_percent ?? ''),
|
||||
franchise: c.franchise_rials != null ? String(rialToToman(c.franchise_rials)) : '',
|
||||
ceiling: c.annual_ceiling_rials != null ? String(rialToToman(c.annual_ceiling_rials)) : '',
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the API payload from form values (toman → rials, Y-m-d → unix). */
|
||||
export function buildInsurancePayload(v: InsuranceFormValues) {
|
||||
return {
|
||||
insurance_id: Number(v.insuranceId),
|
||||
kind: v.kind || null,
|
||||
coverage_percent: Number(v.coverage) || 0,
|
||||
franchise_rials: tomanToRial(Number(v.franchise) || 0),
|
||||
annual_ceiling_rials: v.ceiling === '' ? null : tomanToRial(Number(v.ceiling)),
|
||||
effective_from: isoToUnix(v.effectiveFrom),
|
||||
effective_to: isoToUnix(v.effectiveTo),
|
||||
};
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
editContract: Contract | null;
|
||||
/** Insurance catalog options; in edit mode all are shown, in add mode only the available ones. */
|
||||
options: InsuranceOption[];
|
||||
onClose: () => void;
|
||||
onSubmit: (payload: ReturnType<typeof buildInsurancePayload>) => void;
|
||||
isPending?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add/edit insurance contract modal (افزودن/ویرایش بیمه). Presentational: owns form
|
||||
* state, emits the built payload via onSubmit. Fields mirror the Figma "افزودن بیمه"
|
||||
* modal plus the injected coverage/franchise/ceiling controls.
|
||||
*/
|
||||
export default function InsuranceModal({ open, editContract, options, onClose, onSubmit, isPending }: Props) {
|
||||
const [form, setForm] = useState<InsuranceFormValues>(EMPTY_FORM);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setForm(editContract ? contractToForm(editContract) : EMPTY_FORM);
|
||||
}, [open, editContract]);
|
||||
|
||||
const set = (patch: Partial<InsuranceFormValues>) => setForm((f) => ({ ...f, ...patch }));
|
||||
const isEdit = editContract !== null;
|
||||
|
||||
const submit = () => {
|
||||
if (!form.insuranceId) return;
|
||||
onSubmit(buildInsurancePayload(form));
|
||||
};
|
||||
|
||||
const field = { display: 'flex', flexDirection: 'column' as const, gap: 6 };
|
||||
const label = { fontSize: 12, fontWeight: 600, color: 'var(--text-2)' };
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={isEdit ? 'ویرایش بیمه' : 'افزودن بیمه'}
|
||||
size="md"
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<>
|
||||
<button type="button" className="btn ghost" onClick={onClose}>لغو</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn primary"
|
||||
disabled={!form.insuranceId || isPending}
|
||||
onClick={submit}
|
||||
>
|
||||
{isPending ? '...' : 'ثبت بیمه'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
<div style={field}>
|
||||
<label style={label}>نام بیمه</label>
|
||||
<SearchableSelect
|
||||
options={options.map((i) => ({ value: String(i.insurance_id), label: i.insurance_name }))}
|
||||
value={form.insuranceId}
|
||||
onChange={(v) => set({ insuranceId: v ? String(v) : '' })}
|
||||
isDisabled={isEdit}
|
||||
placeholder="انتخاب کنید..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={field}>
|
||||
<label style={label}>نوع بیمه</label>
|
||||
<select className="input" value={form.kind} onChange={(e) => set({ kind: e.target.value })}>
|
||||
<option value="basic">پایه</option>
|
||||
<option value="supplementary">تکمیلی</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<div style={field}>
|
||||
<label style={label}>تاریخ شروع قرارداد</label>
|
||||
<PersianDateInput value={form.effectiveFrom} onChange={(v) => set({ effectiveFrom: v })} placeholder="انتخاب" />
|
||||
</div>
|
||||
<div style={field}>
|
||||
<label style={label}>تاریخ پایان قرارداد</label>
|
||||
<PersianDateInput value={form.effectiveTo} onChange={(v) => set({ effectiveTo: v })} placeholder="انتخاب" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
|
||||
<div style={field}>
|
||||
<label style={label}>درصد پوشش</label>
|
||||
<input type="number" min={0} max={100} dir="ltr" className="input" value={form.coverage} onChange={(e) => set({ coverage: e.target.value })} />
|
||||
</div>
|
||||
<div style={field}>
|
||||
<label style={label}>فرانشیز (تومان)</label>
|
||||
<input type="number" min={0} dir="ltr" className="input" value={form.franchise} onChange={(e) => set({ franchise: e.target.value })} />
|
||||
</div>
|
||||
<div style={field}>
|
||||
<label style={label}>سقف تعهد (تومان)</label>
|
||||
<input type="number" min={0} dir="ltr" className="input" placeholder="بینهایت" value={form.ceiling} onChange={(e) => set({ ceiling: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
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 {},
|
||||
}));
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
import { api } from '../lib/api';
|
||||
import TenantInsuranceContracts, { filterInsurances } from './TenantInsuranceContracts';
|
||||
import type { Contract } from './InsuranceModal';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
const patch = api.patch as ReturnType<typeof vi.fn>;
|
||||
|
||||
const mk = (over: Partial<Contract>): Contract => ({
|
||||
uuid: 'u', insurance_id: 3, insurance_name: 'بیمه ایران', insurance_kind: 'basic',
|
||||
version: 1, is_active: true, coverage_percent: 70, franchise_rials: 0,
|
||||
annual_ceiling_rials: null, kind: 'basic', effective_from: 0, effective_to: null, ...over,
|
||||
});
|
||||
|
||||
describe('filterInsurances', () => {
|
||||
const list = [
|
||||
mk({ uuid: 'a', insurance_id: 3, insurance_name: 'بیمه ایران' }),
|
||||
mk({ uuid: 'b', insurance_id: 5, insurance_name: 'بیمه آسیا' }),
|
||||
];
|
||||
it('filters by name', () => {
|
||||
expect(filterInsurances(list, 'آسیا')).toHaveLength(1);
|
||||
expect(filterInsurances(list, 'آسیا')[0].uuid).toBe('b');
|
||||
});
|
||||
it('filters by code (insurance_id)', () => {
|
||||
expect(filterInsurances(list, '5')).toHaveLength(1);
|
||||
});
|
||||
it('empty query returns all', () => {
|
||||
expect(filterInsurances(list, ' ')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TenantInsuranceContracts', () => {
|
||||
beforeEach(() => {
|
||||
get.mockReset();
|
||||
patch.mockReset();
|
||||
patch.mockResolvedValue({ success: true, data: { data: {} } });
|
||||
get.mockImplementation((path: string) => {
|
||||
if (path.includes('tenant-insurances')) {
|
||||
return Promise.resolve({ success: true, data: { data: [
|
||||
mk({ uuid: 'u1', insurance_id: 3, insurance_name: 'بیمه ایران', is_active: true }),
|
||||
mk({ uuid: 'u2', insurance_id: 5, insurance_name: 'بیمه آسیا', is_active: false }),
|
||||
] } });
|
||||
}
|
||||
return Promise.resolve({ success: true, data: { insurances: [] } });
|
||||
});
|
||||
});
|
||||
|
||||
// Desktop table and mobile cards both render in jsdom (CSS `hidden`/`md:` is inert),
|
||||
// so each row's text appears twice — assertions use *AllBy* accordingly.
|
||||
it('lists active and inactive contracts', async () => {
|
||||
renderWithProviders(<TenantInsuranceContracts />);
|
||||
expect((await screen.findAllByText('بیمه ایران')).length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('بیمه آسیا').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('search box filters rows by name', async () => {
|
||||
renderWithProviders(<TenantInsuranceContracts />);
|
||||
await screen.findAllByText('بیمه ایران');
|
||||
fireEvent.change(screen.getByPlaceholderText('جستجو در بیمه ها...'), { target: { value: 'آسیا' } });
|
||||
expect(screen.queryByText('بیمه ایران')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByText('بیمه آسیا').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('status toggle PATCHes is_active', async () => {
|
||||
renderWithProviders(<TenantInsuranceContracts />);
|
||||
await screen.findAllByText('بیمه ایران');
|
||||
// The active row's toggle offers to deactivate it.
|
||||
const toggles = screen.getAllByLabelText('غیرفعال کردن');
|
||||
fireEvent.click(toggles[0]);
|
||||
await waitFor(() =>
|
||||
expect(patch).toHaveBeenCalledWith('/api/v1/billing/tenant-insurances/u1', { is_active: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,211 +1,202 @@
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState, type ReactNode } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { TrashIcon, PlusIcon, PencilIcon } from '@heroicons/react/24/outline';
|
||||
import { PlusIcon, PencilIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import { formatRial, rialToToman, tomanToRial } from '../lib/utils';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
import { formatRial } from '../lib/utils';
|
||||
import InsuranceModal, { Contract, InsuranceOption, KIND_LABEL, buildInsurancePayload } from './InsuranceModal';
|
||||
|
||||
interface Contract {
|
||||
uuid: string;
|
||||
insurance_id: number;
|
||||
insurance_name: string | null;
|
||||
insurance_kind: string | null;
|
||||
version: number;
|
||||
coverage_percent: number;
|
||||
franchise_rials: number;
|
||||
annual_ceiling_rials: number | null;
|
||||
/** Case-insensitive filter over insurance name (and code) — the "جستجو در بیمه ها..." box. */
|
||||
export function filterInsurances(list: Contract[], query: string): Contract[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return list;
|
||||
return list.filter((c) =>
|
||||
(c.insurance_name ?? '').toLowerCase().includes(q) ||
|
||||
String(c.insurance_id).includes(q),
|
||||
);
|
||||
}
|
||||
|
||||
interface InsuranceOption {
|
||||
insurance_id: number;
|
||||
insurance_name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
const KIND_LABEL: Record<string, string> = {
|
||||
basic: 'پایه',
|
||||
supplementary: 'تکمیلی',
|
||||
};
|
||||
|
||||
export default function TenantInsuranceContracts() {
|
||||
const qc = useQueryClient();
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [editUuid, setEditUuid] = useState<string | null>(null);
|
||||
const [insuranceId, setInsuranceId] = useState('');
|
||||
const [coverage, setCoverage] = useState('');
|
||||
const [franchise, setFranchise] = useState('');
|
||||
const [ceiling, setCeiling] = useState('');
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editContract, setEditContract] = useState<Contract | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const contractsQuery = useQuery<{ data: Contract[] }>({
|
||||
const contractsQuery = useQuery({
|
||||
queryKey: ['tenant-insurances'],
|
||||
queryFn: () => api.get('/api/v1/billing/tenant-insurances'),
|
||||
});
|
||||
|
||||
const pricingQuery = useQuery<{ data: { insurances: InsuranceOption[] } }>({
|
||||
const pricingQuery = useQuery({
|
||||
queryKey: ['insurance-pricing'],
|
||||
queryFn: () => api.get('/api/v1/insurance-pricing'),
|
||||
});
|
||||
|
||||
const contracts = (contractsQuery.data as any)?.data?.data ?? [];
|
||||
const contracts: Contract[] = (contractsQuery.data as any)?.data?.data ?? [];
|
||||
const allInsurances: InsuranceOption[] = (pricingQuery.data as any)?.data?.insurances ?? [];
|
||||
const activeIds = new Set(contracts.map((c: Contract) => c.insurance_id));
|
||||
const activeIds = new Set(contracts.map((c) => c.insurance_id));
|
||||
const available = allInsurances.filter((i) => !activeIds.has(i.insurance_id));
|
||||
|
||||
const resetForm = () => {
|
||||
setInsuranceId('');
|
||||
setCoverage('');
|
||||
setFranchise('');
|
||||
setCeiling('');
|
||||
setAddOpen(false);
|
||||
setEditUuid(null);
|
||||
};
|
||||
const rows = useMemo(() => filterInsurances(contracts, search), [contracts, search]);
|
||||
|
||||
const openEdit = (c: Contract) => {
|
||||
setEditUuid(c.uuid);
|
||||
setAddOpen(false);
|
||||
setInsuranceId(String(c.insurance_id));
|
||||
setCoverage(String(c.coverage_percent ?? ''));
|
||||
setFranchise(c.franchise_rials != null ? String(rialToToman(c.franchise_rials)) : '');
|
||||
setCeiling(c.annual_ceiling_rials != null ? String(rialToToman(c.annual_ceiling_rials)) : '');
|
||||
};
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ['tenant-insurances'] });
|
||||
|
||||
const editMut = useMutation({
|
||||
mutationFn: () =>
|
||||
api.patch(`/api/v1/billing/tenant-insurances/${editUuid}`, {
|
||||
coverage_percent: Number(coverage) || 0,
|
||||
franchise_rials: tomanToRial(Number(franchise) || 0),
|
||||
annual_ceiling_rials: ceiling === '' ? null : tomanToRial(Number(ceiling)),
|
||||
}),
|
||||
const saveMut = useMutation({
|
||||
mutationFn: (payload: ReturnType<typeof buildInsurancePayload>) =>
|
||||
editContract
|
||||
? api.patch(`/api/v1/billing/tenant-insurances/${editContract.uuid}`, payload)
|
||||
: api.post('/api/v1/billing/tenant-insurances', payload),
|
||||
onSuccess: () => {
|
||||
toast.success('قرارداد بیمه ویرایش شد');
|
||||
resetForm();
|
||||
qc.invalidateQueries({ queryKey: ['tenant-insurances'] });
|
||||
toast.success(editContract ? 'قرارداد بیمه ویرایش شد' : 'قرارداد بیمه فعال شد');
|
||||
closeModal();
|
||||
invalidate();
|
||||
},
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const addMut = useMutation({
|
||||
mutationFn: () =>
|
||||
api.post('/api/v1/billing/tenant-insurances', {
|
||||
insurance_id: Number(insuranceId),
|
||||
coverage_percent: Number(coverage) || 0,
|
||||
franchise_rials: tomanToRial(Number(franchise) || 0),
|
||||
annual_ceiling_rials: ceiling === '' ? null : tomanToRial(Number(ceiling)),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
toast.success('قرارداد بیمه فعال شد');
|
||||
resetForm();
|
||||
qc.invalidateQueries({ queryKey: ['tenant-insurances'] });
|
||||
},
|
||||
const toggleMut = useMutation({
|
||||
mutationFn: (c: Contract) =>
|
||||
api.patch(`/api/v1/billing/tenant-insurances/${c.uuid}`, { is_active: !c.is_active }),
|
||||
onSuccess: () => invalidate(),
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const delMut = useMutation({
|
||||
mutationFn: (uuid: string) => api.delete(`/api/v1/billing/tenant-insurances/${uuid}`),
|
||||
onSuccess: () => {
|
||||
toast.success('قرارداد غیرفعال شد');
|
||||
qc.invalidateQueries({ queryKey: ['tenant-insurances'] });
|
||||
},
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
const openAdd = () => { setEditContract(null); setModalOpen(true); };
|
||||
const openEdit = (c: Contract) => { setEditContract(c); setModalOpen(true); };
|
||||
const closeModal = () => { setModalOpen(false); setEditContract(null); };
|
||||
|
||||
return (
|
||||
<div className="card" style={{ padding: 20, marginBottom: 16 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
|
||||
<div>
|
||||
<h2 style={{ fontSize: 14, fontWeight: 700, margin: 0 }}>قراردادهای بیمه</h2>
|
||||
<p style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 4, lineHeight: 1.7 }}>
|
||||
بیمههایی که با آنها قرارداد دارید. درصد پوشش، فرانشیز و سقف تعهد هر بیمه را تعیین کنید.
|
||||
</p>
|
||||
</div>
|
||||
{!addOpen && available.length > 0 && (
|
||||
<button className="btn primary sm" onClick={() => setAddOpen(true)}>
|
||||
<PlusIcon style={{ width: 14 }} /> افزودن بیمه
|
||||
</button>
|
||||
)}
|
||||
<div className="card" style={{ padding: 20 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
|
||||
<h2 style={{ fontSize: 15, fontWeight: 700, margin: 0 }}>مدیریت بیمه</h2>
|
||||
<button className="btn primary sm" onClick={openAdd}>
|
||||
<PlusIcon style={{ width: 15 }} /> افزودن بیمه
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{(addOpen || editUuid) && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'flex-end', padding: 14, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--surface)', marginBottom: 14 }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<label style={{ fontSize: 11.5, fontWeight: 600 }}>بیمه</label>
|
||||
<div style={{ minWidth: 200 }}>
|
||||
<SearchableSelect
|
||||
options={(editUuid ? allInsurances : available).map((i) => ({ value: String(i.insurance_id), label: `${i.insurance_name} (${KIND_LABEL[i.type] ?? i.type})` }))}
|
||||
value={insuranceId}
|
||||
onChange={(v) => setInsuranceId(v ? String(v) : '')}
|
||||
isDisabled={!!editUuid}
|
||||
placeholder="انتخاب..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<label style={{ fontSize: 11.5, fontWeight: 600 }}>درصد پوشش</label>
|
||||
<input type="number" min={0} max={100} dir="ltr" className="input" style={{ width: 100 }} value={coverage} onChange={(e) => setCoverage(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<label style={{ fontSize: 11.5, fontWeight: 600 }}>فرانشیز (تومان)</label>
|
||||
<input type="number" min={0} dir="ltr" className="input" style={{ width: 130 }} value={franchise} onChange={(e) => setFranchise(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<label style={{ fontSize: 11.5, fontWeight: 600 }}>سقف تعهد (تومان)</label>
|
||||
<input type="number" min={0} dir="ltr" className="input" style={{ width: 130 }} placeholder="بینهایت" value={ceiling} onChange={(e) => setCeiling(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button
|
||||
className="btn primary sm"
|
||||
disabled={!insuranceId || addMut.isPending || editMut.isPending}
|
||||
onClick={() => (editUuid ? editMut.mutate() : addMut.mutate())}
|
||||
>
|
||||
{addMut.isPending || editMut.isPending ? '...' : 'ذخیره'}
|
||||
</button>
|
||||
<button className="btn ghost sm" onClick={resetForm}>لغو</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ position: 'relative', marginBottom: 16 }}>
|
||||
<MagnifyingGlassIcon style={{ width: 16, position: 'absolute', insetInlineStart: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }} />
|
||||
<input
|
||||
className="input"
|
||||
style={{ paddingInlineStart: 36 }}
|
||||
placeholder="جستجو در بیمه ها..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{contractsQuery.isLoading ? (
|
||||
<div className="muted" style={{ fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : contracts.length === 0 ? (
|
||||
<div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: '12px 0' }}>
|
||||
هنوز با هیچ بیمهای قرارداد فعال ندارید.
|
||||
) : rows.length === 0 ? (
|
||||
<div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: '16px 0', textAlign: 'center' }}>
|
||||
{search ? 'بیمهای یافت نشد.' : 'هنوز با هیچ بیمهای قرارداد ندارید.'}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
|
||||
{(['basic', 'supplementary'] as const).map((kind) => {
|
||||
const group = contracts.filter((c: Contract) => c.insurance_kind === kind);
|
||||
if (group.length === 0) return null;
|
||||
return (
|
||||
<div key={kind}>
|
||||
<div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 8 }}>
|
||||
بیمه {KIND_LABEL[kind]}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{group.map((c: Contract) => (
|
||||
<div key={c.uuid} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 10, border: '1px solid var(--border)' }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 13.5 }}>{c.insurance_name ?? `#${c.insurance_id}`}</div>
|
||||
<div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 2 }}>
|
||||
پوشش {c.coverage_percent}٪
|
||||
{c.franchise_rials > 0 && ` · فرانشیز ${formatRial(c.franchise_rials)}`}
|
||||
{c.annual_ceiling_rials != null && ` · سقف ${formatRial(c.annual_ceiling_rials)}`}
|
||||
</div>
|
||||
<>
|
||||
{/* Desktop table */}
|
||||
<div className="hidden md:block" style={{ overflowX: 'auto' }}>
|
||||
<table className="data-table" style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'start', color: 'var(--text-3)', fontSize: 12 }}>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'start' }}>ردیف</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'start' }}>نام بیمه</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'start' }}>کد</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'start' }}>نوع بیمه</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'start' }}>وضعیت</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'start' }}>عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((c, i) => (
|
||||
<tr key={c.uuid} style={{ borderTop: '1px solid var(--border)', fontSize: 13 }}>
|
||||
<td style={{ padding: '12px' }}>{i + 1}</td>
|
||||
<td style={{ padding: '12px', fontWeight: 600 }}>
|
||||
{c.insurance_name ?? `#${c.insurance_id}`}
|
||||
<div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 400, marginTop: 2 }}>
|
||||
پوشش {c.coverage_percent}٪
|
||||
{c.franchise_rials > 0 && ` · فرانشیز ${formatRial(c.franchise_rials)}`}
|
||||
{c.annual_ceiling_rials != null && ` · سقف ${formatRial(c.annual_ceiling_rials)}`}
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: '12px', color: 'var(--text-2)' }} dir="ltr">{c.insurance_id}</td>
|
||||
<td style={{ padding: '12px' }}>{KIND_LABEL[c.insurance_kind ?? ''] ?? c.insurance_kind ?? '—'}</td>
|
||||
<td style={{ padding: '12px' }}>
|
||||
<StatusToggle contract={c} onToggle={() => toggleMut.mutate(c)} disabled={toggleMut.isPending} />
|
||||
</td>
|
||||
<td style={{ padding: '12px' }}>
|
||||
<button className="mini-btn" title="ویرایش" onClick={() => openEdit(c)}>
|
||||
<PencilIcon style={{ width: 15 }} />
|
||||
</button>
|
||||
<button className="mini-btn danger" title="غیرفعالسازی" disabled={delMut.isPending} onClick={() => delMut.mutate(c.uuid)}>
|
||||
<TrashIcon style={{ width: 15 }} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Mobile cards */}
|
||||
<div className="md:hidden" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{rows.map((c) => (
|
||||
<div key={c.uuid} style={{ border: '1px solid var(--border)', borderRadius: 12, padding: 14 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
|
||||
<div style={{ fontWeight: 700, fontSize: 14 }}>{c.insurance_name ?? `#${c.insurance_id}`}</div>
|
||||
<button className="mini-btn" title="ویرایش" onClick={() => openEdit(c)}>
|
||||
<PencilIcon style={{ width: 15 }} />
|
||||
</button>
|
||||
</div>
|
||||
<Row label="کد" value={<span dir="ltr">{c.insurance_id}</span>} />
|
||||
<Row label="نوع بیمه" value={KIND_LABEL[c.insurance_kind ?? ''] ?? c.insurance_kind ?? '—'} />
|
||||
<Row label="وضعیت" value={<StatusToggle contract={c} onToggle={() => toggleMut.mutate(c)} disabled={toggleMut.isPending} />} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<InsuranceModal
|
||||
open={modalOpen}
|
||||
editContract={editContract}
|
||||
options={editContract ? allInsurances : available}
|
||||
onClose={closeModal}
|
||||
onSubmit={(payload) => saveMut.mutate(payload)}
|
||||
isPending={saveMut.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, value }: { label: string; value: ReactNode }) {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', fontSize: 12.5, borderTop: '1px solid var(--border-2)' }}>
|
||||
<span style={{ color: 'var(--text-3)' }}>{label}:</span>
|
||||
<span>{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusToggle({ contract, onToggle, disabled }: { contract: Contract; onToggle: () => void; disabled?: boolean }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={contract.is_active}
|
||||
aria-label={contract.is_active ? 'غیرفعال کردن' : 'فعال کردن'}
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: disabled ? 'default' : 'pointer', padding: 0 }}
|
||||
>
|
||||
<span style={{
|
||||
width: 36, height: 20, borderRadius: 999, position: 'relative', transition: 'background .2s',
|
||||
background: contract.is_active ? 'var(--primary)' : 'var(--border)',
|
||||
}}>
|
||||
<span style={{
|
||||
position: 'absolute', top: 2, width: 16, height: 16, borderRadius: 999, background: '#fff', transition: 'inset-inline .2s',
|
||||
insetInlineStart: contract.is_active ? 18 : 2,
|
||||
}} />
|
||||
</span>
|
||||
<span style={{ fontSize: 12, color: contract.is_active ? 'var(--success)' : 'var(--text-3)' }}>
|
||||
{contract.is_active ? 'فعال' : 'غیرفعال'}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -46,6 +46,17 @@ export function toGregorianDate(d: Date): string {
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
// API stores contract dates as Unix seconds; the date input speaks Y-m-d strings.
|
||||
export function isoToUnix(iso: string): number | null {
|
||||
const d = toDate(iso);
|
||||
return d && !isNaN(d.getTime()) ? Math.floor(d.getTime() / 1000) : null;
|
||||
}
|
||||
|
||||
export function unixToIso(ts: number | null | undefined): string {
|
||||
if (ts == null) return '';
|
||||
return toGregorianDate(new Date(ts * 1000));
|
||||
}
|
||||
|
||||
export function maskMobile(mobile: string): string {
|
||||
if (mobile.length < 7) return mobile;
|
||||
return mobile.slice(0, 4) + '***' + mobile.slice(-3);
|
||||
|
||||
+10
-2
@@ -353,7 +353,7 @@ entity جاری از `#[CurrentUser]` resolve میشود: نقش `ROLE_DOCTOR
|
||||
قرارداد یک پزشک/کلینیک با یک بیمه: درصد پوشش، فرانشیز، سقف تعهد سالانه، نسخهبندی و وضعیت فعال. مبنای محاسبهی سهم در سیستم صورتحساب (`docs/architecture/insurance-billing-system.md`). tenant از `#[CurrentUser]` (`ROLE_DOCTOR`→doctor، `ROLE_CLINIC`→clinic). جدول `tenant_insurances`.
|
||||
|
||||
### GET `/api/v1/billing/tenant-insurances`
|
||||
لیست قراردادهای فعال tenant جاری.
|
||||
لیست قراردادهای tenant جاری — **آخرین نسخهٔ هر بیمه، فعال یا غیرفعال** (برای toggle فعال/غیرفعال در UI مدیریت بیمه). `insurance_kind` = `kind` قرارداد در صورت تعیین، وگرنه نوع بیمه از کاتالوگ.
|
||||
|
||||
**Permission:** `AUTH` (doctor/clinic)
|
||||
|
||||
@@ -372,6 +372,7 @@ entity جاری از `#[CurrentUser]` resolve میشود: نقش `ROLE_DOCTOR
|
||||
"coverage_percent": 70,
|
||||
"franchise_rials": 0,
|
||||
"annual_ceiling_rials": null,
|
||||
"kind": "basic",
|
||||
"effective_from": 1718900000,
|
||||
"effective_to": null
|
||||
}
|
||||
@@ -390,12 +391,19 @@ entity جاری از `#[CurrentUser]` resolve میشود: نقش `ROLE_DOCTOR
|
||||
| `coverage_percent` | float | درصد پوشش (۰–۱۰۰) |
|
||||
| `franchise_rials` | int | فرانشیز ثابت سهم بیمار |
|
||||
| `annual_ceiling_rials` | int \| null | سقف تعهد (null = بینهایت) |
|
||||
| `kind` | string \| null | نوع بیمه قرارداد (`basic`/`supplementary`); خالی → پیشفرض نوع کاتالوگ |
|
||||
| `effective_from` | int \| null | تاریخ شروع قرارداد (Unix)؛ null → اکنون |
|
||||
| `effective_to` | int \| null | تاریخ پایان قرارداد (Unix)؛ null → نامحدود |
|
||||
|
||||
پاسخ `201`: `{ success, data: { …contract } }`.
|
||||
خطاها: `404 ERR_NOT_FOUND_001` بیمه یافت نشد · `422 ERR_VALIDATION_001` insurance_id الزامی · `403 ERR_FORBIDDEN_001` پروفایل یافت نشد.
|
||||
|
||||
### PATCH `/api/v1/billing/tenant-insurances/{uuid}`
|
||||
ویرایش `coverage_percent` / `franchise_rials` / `annual_ceiling_rials`. فقط قرارداد متعلق به tenant جاری.
|
||||
ویرایش فیلدهای قرارداد (همه اختیاری، فقط کلیدهای موجود اعمال میشوند). فقط قرارداد متعلق به tenant جاری.
|
||||
|
||||
**Body:** `coverage_percent` · `franchise_rials` · `annual_ceiling_rials` · `kind` · `effective_from` · `effective_to` · `is_active`.
|
||||
|
||||
- `is_active` (bool): toggle فعال/غیرفعال. برخلاف `DELETE`، مقدار `effective_to`ِ تعیینشدهٔ کاربر را دستنخورده نگه میدارد (برای reactivate).
|
||||
|
||||
### DELETE `/api/v1/billing/tenant-insurances/{uuid}`
|
||||
غیرفعالسازی نرم (soft) — `is_active=false` و `effective_to=now`. داده حذف نمیشود.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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 Version20260715093358 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('ALTER TABLE tenant_insurances ADD kind VARCHAR(20) DEFAULT NULL');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// this down() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('ALTER TABLE tenant_insurances DROP kind');
|
||||
}
|
||||
}
|
||||
@@ -312,7 +312,7 @@ class InsuranceController extends BaseController
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$contracts = $this->tenantInsuranceRepo->findActiveByTenant($entityType, $entityId);
|
||||
$contracts = $this->tenantInsuranceRepo->findLatestByTenant($entityType, $entityId);
|
||||
|
||||
$byId = [];
|
||||
foreach ($this->insuranceRepo->findActive(null) as $ins) {
|
||||
@@ -322,7 +322,8 @@ class InsuranceController extends BaseController
|
||||
$data = array_map(function (TenantInsurance $c) use ($byId) {
|
||||
$row = $c->toArray();
|
||||
$row['insurance_name'] = $byId[$c->getInsuranceId()]['name'] ?? null;
|
||||
$row['insurance_kind'] = $byId[$c->getInsuranceId()]['type'] ?? null;
|
||||
// Contract-level kind wins over the catalog type when the tenant categorised it.
|
||||
$row['insurance_kind'] = $c->getKind() ?? ($byId[$c->getInsuranceId()]['type'] ?? null);
|
||||
return $row;
|
||||
}, $contracts);
|
||||
|
||||
@@ -352,6 +353,9 @@ class InsuranceController extends BaseController
|
||||
(int) ($data['franchise_rials'] ?? 0),
|
||||
isset($data['annual_ceiling_rials']) && $data['annual_ceiling_rials'] !== null
|
||||
? (int) $data['annual_ceiling_rials'] : null,
|
||||
isset($data['effective_from']) && $data['effective_from'] !== null ? (int) $data['effective_from'] : null,
|
||||
isset($data['effective_to']) && $data['effective_to'] !== null ? (int) $data['effective_to'] : null,
|
||||
isset($data['kind']) && $data['kind'] !== '' ? (string) $data['kind'] : null,
|
||||
);
|
||||
|
||||
return $this->success(['data' => $contract->toArray()], 201);
|
||||
@@ -377,6 +381,20 @@ class InsuranceController extends BaseController
|
||||
if (array_key_exists('annual_ceiling_rials', $data)) {
|
||||
$contract->setAnnualCeilingRials($data['annual_ceiling_rials'] !== null ? (int) $data['annual_ceiling_rials'] : null);
|
||||
}
|
||||
if (array_key_exists('kind', $data)) {
|
||||
$contract->setKind($data['kind'] !== '' && $data['kind'] !== null ? (string) $data['kind'] : null);
|
||||
}
|
||||
if (array_key_exists('effective_from', $data) && $data['effective_from'] !== null) {
|
||||
$contract->setEffectiveFrom((int) $data['effective_from']);
|
||||
}
|
||||
if (array_key_exists('effective_to', $data)) {
|
||||
$contract->setEffectiveTo($data['effective_to'] !== null ? (int) $data['effective_to'] : null);
|
||||
}
|
||||
// Status toggle (فعال/غیرفعال) is set here directly so it does not clobber the
|
||||
// user-chosen effective_to the way the DELETE/deactivate path does.
|
||||
if (array_key_exists('is_active', $data)) {
|
||||
$contract->setActive((bool) $data['is_active']);
|
||||
}
|
||||
|
||||
$this->tenantInsuranceRepo->save($contract);
|
||||
|
||||
|
||||
@@ -47,6 +47,10 @@ class TenantInsurance
|
||||
#[ORM\Column(name: 'annual_ceiling_rials', type: 'integer', nullable: true)]
|
||||
private ?int $annualCeilingRials = null;
|
||||
|
||||
/** Contract-level insurance kind ('basic'|'supplementary'); overrides the catalog type when set. */
|
||||
#[ORM\Column(name: 'kind', type: 'string', length: 20, nullable: true)]
|
||||
private ?string $kind = null;
|
||||
|
||||
#[ORM\Column(name: 'effective_from', type: 'integer')]
|
||||
private int $effectiveFrom;
|
||||
|
||||
@@ -81,6 +85,7 @@ class TenantInsurance
|
||||
public function getCoveragePercent(): float { return (float) $this->coveragePercent; }
|
||||
public function getFranchiseRials(): int { return $this->franchiseRials; }
|
||||
public function getAnnualCeilingRials(): ?int { return $this->annualCeilingRials; }
|
||||
public function getKind(): ?string { return $this->kind; }
|
||||
public function getEffectiveFrom(): int { return $this->effectiveFrom; }
|
||||
public function getEffectiveTo(): ?int { return $this->effectiveTo; }
|
||||
|
||||
@@ -88,6 +93,8 @@ class TenantInsurance
|
||||
public function setCoveragePercent(float $v): self { $this->coveragePercent = (string) $v; $this->updatedAt = time(); return $this; }
|
||||
public function setFranchiseRials(int $v): self { $this->franchiseRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setAnnualCeilingRials(?int $v): self { $this->annualCeilingRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setKind(?string $v): self { $this->kind = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setEffectiveFrom(int $v): self { $this->effectiveFrom = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setEffectiveTo(?int $v): self { $this->effectiveTo = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
@@ -102,6 +109,7 @@ class TenantInsurance
|
||||
'coverage_percent' => (float) $this->coveragePercent,
|
||||
'franchise_rials' => $this->franchiseRials,
|
||||
'annual_ceiling_rials' => $this->annualCeilingRials,
|
||||
'kind' => $this->kind,
|
||||
'effective_from' => $this->effectiveFrom,
|
||||
'effective_to' => $this->effectiveTo,
|
||||
];
|
||||
|
||||
@@ -27,6 +27,33 @@ class TenantInsuranceRepository extends ServiceEntityRepository
|
||||
->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* Latest version of every insurance the tenant has a contract with, active or not.
|
||||
* The management UI shows one row per insurance with a فعال/غیرفعال toggle, so both
|
||||
* states must be returned; older versions are collapsed to the newest.
|
||||
*
|
||||
* @return TenantInsurance[]
|
||||
*/
|
||||
public function findLatestByTenant(string $entityType, int $entityId): array
|
||||
{
|
||||
$rows = $this->createQueryBuilder('t')
|
||||
->where('t.entityType = :type')
|
||||
->andWhere('t.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->orderBy('t.insuranceId', 'ASC')
|
||||
->addOrderBy('t.version', 'DESC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$latest = [];
|
||||
foreach ($rows as $row) {
|
||||
$latest[$row->getInsuranceId()] ??= $row;
|
||||
}
|
||||
|
||||
return array_values($latest);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?TenantInsurance
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
|
||||
@@ -31,8 +31,12 @@ class TenantInsuranceService
|
||||
float $coveragePercent,
|
||||
int $franchiseRials = 0,
|
||||
?int $annualCeilingRials = null,
|
||||
?int $effectiveFrom = null,
|
||||
?int $effectiveTo = null,
|
||||
?string $kind = null,
|
||||
): TenantInsurance {
|
||||
if ($this->insuranceRepo->find($insuranceId) === null) {
|
||||
$insurance = $this->insuranceRepo->find($insuranceId);
|
||||
if ($insurance === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'بیمه یافت نشد', 404);
|
||||
}
|
||||
|
||||
@@ -45,8 +49,15 @@ class TenantInsuranceService
|
||||
$contract->setCoveragePercent($coveragePercent)
|
||||
->setFranchiseRials($franchiseRials)
|
||||
->setAnnualCeilingRials($annualCeilingRials)
|
||||
// kind defaults to the catalog type; caller may override to categorise the contract.
|
||||
->setKind($kind ?? $insurance->getType()->value)
|
||||
->setEffectiveTo($effectiveTo)
|
||||
->setActive(true);
|
||||
|
||||
if ($effectiveFrom !== null) {
|
||||
$contract->setEffectiveFrom($effectiveFrom);
|
||||
}
|
||||
|
||||
$this->repo->save($contract);
|
||||
|
||||
return $contract;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Insurance;
|
||||
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Insurance\Entity\Insurance;
|
||||
use App\Insurance\Enum\InsuranceType;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* Covers the tenant insurance contract management flow used by the redesigned
|
||||
* /admin/insurance-pricing page: create with contract dates + kind, edit those
|
||||
* fields, toggle فعال/غیرفعال, and list returning inactive contracts too.
|
||||
*/
|
||||
class TenantInsuranceContractApiTest extends ApiTestCase
|
||||
{
|
||||
/** @return array{0: \App\Auth\Entity\User, 1: Insurance} */
|
||||
private function makeDoctorAndInsurance(InsuranceType $type = InsuranceType::Basic): array
|
||||
{
|
||||
$owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$doctor = new Doctor($owner, 'دکتر تست بیمه');
|
||||
$this->em->persist($doctor);
|
||||
|
||||
$insurance = new Insurance('بیمه ایران ' . random_int(1000, 9999), $type);
|
||||
$this->em->persist($insurance);
|
||||
$this->em->flush();
|
||||
|
||||
return [$owner, $insurance];
|
||||
}
|
||||
|
||||
public function testCreateContractPersistsDatesAndKind(): void
|
||||
{
|
||||
[$owner, $insurance] = $this->makeDoctorAndInsurance(InsuranceType::Basic);
|
||||
|
||||
$body = $this->authJson('POST', '/api/v1/billing/tenant-insurances', $owner, [
|
||||
'insurance_id' => $insurance->getId(),
|
||||
'coverage_percent' => 70,
|
||||
'franchise_rials' => 500_000,
|
||||
'annual_ceiling_rials' => 20_000_000,
|
||||
'effective_from' => 1_700_000_000,
|
||||
'effective_to' => 1_800_000_000,
|
||||
'kind' => 'supplementary',
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $this->responseCode());
|
||||
$row = $body['data']['data'];
|
||||
$this->assertEquals(70.0, $row['coverage_percent']);
|
||||
$this->assertSame(500_000, $row['franchise_rials']);
|
||||
$this->assertSame(20_000_000, $row['annual_ceiling_rials']);
|
||||
$this->assertSame(1_700_000_000, $row['effective_from']);
|
||||
$this->assertSame(1_800_000_000, $row['effective_to']);
|
||||
$this->assertSame('supplementary', $row['kind']);
|
||||
$this->assertTrue($row['is_active']);
|
||||
}
|
||||
|
||||
public function testKindDefaultsToCatalogTypeWhenOmitted(): void
|
||||
{
|
||||
[$owner, $insurance] = $this->makeDoctorAndInsurance(InsuranceType::Basic);
|
||||
|
||||
$body = $this->authJson('POST', '/api/v1/billing/tenant-insurances', $owner, [
|
||||
'insurance_id' => $insurance->getId(),
|
||||
'coverage_percent' => 50,
|
||||
]);
|
||||
|
||||
$this->assertSame(201, $this->responseCode());
|
||||
$this->assertSame('basic', $body['data']['data']['kind']);
|
||||
}
|
||||
|
||||
public function testEditUpdatesDatesKindAndAmounts(): void
|
||||
{
|
||||
[$owner, $insurance] = $this->makeDoctorAndInsurance();
|
||||
$created = $this->authJson('POST', '/api/v1/billing/tenant-insurances', $owner, [
|
||||
'insurance_id' => $insurance->getId(),
|
||||
'coverage_percent' => 40,
|
||||
]);
|
||||
$uuid = $created['data']['data']['uuid'];
|
||||
|
||||
$body = $this->authJson('PATCH', "/api/v1/billing/tenant-insurances/$uuid", $owner, [
|
||||
'coverage_percent' => 90,
|
||||
'franchise_rials' => 123_000,
|
||||
'annual_ceiling_rials' => null,
|
||||
'effective_to' => 1_900_000_000,
|
||||
'kind' => 'supplementary',
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$this->assertEquals(90.0, $body['data']['data']['coverage_percent']);
|
||||
$this->assertSame(123_000, $body['data']['data']['franchise_rials']);
|
||||
$this->assertNull($body['data']['data']['annual_ceiling_rials']);
|
||||
$this->assertSame(1_900_000_000, $body['data']['data']['effective_to']);
|
||||
$this->assertSame('supplementary', $body['data']['data']['kind']);
|
||||
}
|
||||
|
||||
public function testToggleIsActiveDoesNotClobberEffectiveTo(): void
|
||||
{
|
||||
[$owner, $insurance] = $this->makeDoctorAndInsurance();
|
||||
$created = $this->authJson('POST', '/api/v1/billing/tenant-insurances', $owner, [
|
||||
'insurance_id' => $insurance->getId(),
|
||||
'coverage_percent' => 60,
|
||||
'effective_to' => 1_850_000_000,
|
||||
]);
|
||||
$uuid = $created['data']['data']['uuid'];
|
||||
|
||||
$off = $this->authJson('PATCH', "/api/v1/billing/tenant-insurances/$uuid", $owner, ['is_active' => false]);
|
||||
$this->assertFalse($off['data']['data']['is_active']);
|
||||
// Deactivating via the toggle must keep the user-set effective_to intact.
|
||||
$this->assertSame(1_850_000_000, $off['data']['data']['effective_to']);
|
||||
|
||||
$on = $this->authJson('PATCH', "/api/v1/billing/tenant-insurances/$uuid", $owner, ['is_active' => true]);
|
||||
$this->assertTrue($on['data']['data']['is_active']);
|
||||
}
|
||||
|
||||
public function testListReturnsInactiveContracts(): void
|
||||
{
|
||||
[$owner, $insurance] = $this->makeDoctorAndInsurance();
|
||||
$created = $this->authJson('POST', '/api/v1/billing/tenant-insurances', $owner, [
|
||||
'insurance_id' => $insurance->getId(),
|
||||
'coverage_percent' => 30,
|
||||
]);
|
||||
$uuid = $created['data']['data']['uuid'];
|
||||
$this->authJson('PATCH', "/api/v1/billing/tenant-insurances/$uuid", $owner, ['is_active' => false]);
|
||||
|
||||
$body = $this->authJson('GET', '/api/v1/billing/tenant-insurances', $owner);
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
|
||||
$rows = $body['data']['data'] ?? $body['data'];
|
||||
$found = array_filter($rows, fn ($r) => $r['uuid'] === $uuid);
|
||||
$this->assertCount(1, $found, 'inactive contract must still appear in the list');
|
||||
$this->assertFalse(array_values($found)[0]['is_active']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user