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>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user