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:
@@ -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