diff --git a/src/components/cases/convert-to-collections-dialog.tsx b/src/components/cases/convert-to-collections-dialog.tsx index 5744a15..a992b8a 100644 --- a/src/components/cases/convert-to-collections-dialog.tsx +++ b/src/components/cases/convert-to-collections-dialog.tsx @@ -35,17 +35,26 @@ const STATUS_OPTIONS = [ { value: "closed", label: "Closed" }, ]; +function extractDefendantSurname(title: string): string | null { + if (!title) return null; + const m = title.match(/\sv\.?s?\.?\s+([A-Za-z'’\-]+)/i); + if (!m) return null; + return m[1].trim().toLowerCase(); +} + export function ConvertToCollectionsDialog({ open, onOpenChange, caseId, clientId, + caseTitle, onCreated, }: { open: boolean; onOpenChange: (v: boolean) => void; caseId: string; clientId: string; + caseTitle?: string; onCreated?: () => void; }) { const { user } = useAuth(); @@ -80,13 +89,27 @@ export function ConvertToCollectionsDialog({ .select("homeowner_id") .eq("case_id", caseId), ]); - setHomeowners(hos ?? []); - setExistingIds( - new Set((cols ?? []).map((c) => c.homeowner_id).filter((id): id is string => !!id)), + const hoList = hos ?? []; + setHomeowners(hoList); + const existing = new Set( + (cols ?? []).map((c) => c.homeowner_id).filter((id): id is string => !!id), ); + setExistingIds(existing); + + // Pre-select homeowner if there's exactly one surname match from the case title + const surname = extractDefendantSurname(caseTitle ?? ""); + if (surname) { + const matches = hoList.filter( + (h) => + (h.last_name || "").toLowerCase() === surname && !existing.has(h.id), + ); + if (matches.length === 1) { + setSelected(new Set([matches[0].id])); + } + } setLoading(false); })(); - }, [open, caseId, clientId]); + }, [open, caseId, clientId, caseTitle]); const available = useMemo( () => homeowners.filter((h) => !existingIds.has(h.id)),