Added close/reopen & apply homeowner
X-Lovable-Edit-ID: edt-5c6ff09e-dce3-45a4-a70c-04c5b98ed794 Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
@@ -59,7 +59,11 @@ import {
|
||||
FilePlus,
|
||||
Phone,
|
||||
Tag,
|
||||
Lock,
|
||||
Unlock,
|
||||
UserPlus,
|
||||
} from "lucide-react";
|
||||
import { SearchableSelect } from "@/components/ui/searchable-select";
|
||||
import { toast } from "sonner";
|
||||
import { spawnNextCollectionWorkflowTask } from "@/lib/workflow-chain";
|
||||
import { ApplyCollectionWorkflowDialog } from "@/components/collections/apply-collection-workflow-dialog";
|
||||
@@ -105,6 +109,8 @@ function CollectionDetailRoute() {
|
||||
const [escalating, setEscalating] = useState(false);
|
||||
const [addTaskOpen, setAddTaskOpen] = useState(false);
|
||||
const [applyWfOpen, setApplyWfOpen] = useState(false);
|
||||
const [applyHoOpen, setApplyHoOpen] = useState(false);
|
||||
const [closingBusy, setClosingBusy] = useState(false);
|
||||
const [reload, setReload] = useState(0);
|
||||
|
||||
|
||||
@@ -266,6 +272,39 @@ function CollectionDetailRoute() {
|
||||
else refreshTasks();
|
||||
};
|
||||
|
||||
const closeCollection = async () => {
|
||||
if (!collection) return;
|
||||
if (!confirm("Close this collection? Open tasks will be hidden but data is preserved. You can reopen anytime.")) return;
|
||||
setClosingBusy(true);
|
||||
const { error } = await supabase
|
||||
.from("collections")
|
||||
.update({ status: "closed", closed_at: new Date().toISOString().slice(0, 10) })
|
||||
.eq("id", collection.id);
|
||||
setClosingBusy(false);
|
||||
if (error) {
|
||||
toast.error("Could not close", { description: error.message });
|
||||
return;
|
||||
}
|
||||
toast.success("Collection closed");
|
||||
setReload((r) => r + 1);
|
||||
};
|
||||
|
||||
const reopenCollection = async () => {
|
||||
if (!collection) return;
|
||||
setClosingBusy(true);
|
||||
const { error } = await supabase
|
||||
.from("collections")
|
||||
.update({ status: "late_notice", closed_at: null })
|
||||
.eq("id", collection.id);
|
||||
setClosingBusy(false);
|
||||
if (error) {
|
||||
toast.error("Could not reopen", { description: error.message });
|
||||
return;
|
||||
}
|
||||
toast.success("Collection reopened");
|
||||
setReload((r) => r + 1);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<ProtectedLayout>
|
||||
@@ -302,20 +341,42 @@ function CollectionDetailRoute() {
|
||||
return (
|
||||
<ProtectedLayout>
|
||||
<PageContainer>
|
||||
<div className="flex items-center justify-between gap-2 mb-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate({ to: "/collections" })}
|
||||
className="-ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" /> All collections
|
||||
</Button>
|
||||
{collection.case?.client?.id && (
|
||||
<Button size="sm" onClick={() => navigate({ to: "/invoices/new/$clientId", params: { clientId: collection.case.client.id }, search: { caseId: collection.case.id } })}>
|
||||
<FilePlus className="h-4 w-4 mr-1.5" /> Generate invoice
|
||||
<div className="flex items-center justify-between gap-2 mb-3 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate({ to: "/collections" })}
|
||||
className="-ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" /> All collections
|
||||
</Button>
|
||||
)}
|
||||
{collection.status === "closed" && (
|
||||
<Badge variant="outline" className="border-emerald-600 text-emerald-700">
|
||||
Closed{collection.closed_at ? ` · ${formatDate(collection.closed_at)}` : ""}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button size="sm" variant="outline" onClick={() => setApplyHoOpen(true)}>
|
||||
<UserPlus className="h-4 w-4 mr-1.5" />
|
||||
{collection.homeowner ? "Change homeowner" : "Apply homeowner"}
|
||||
</Button>
|
||||
{collection.status === "closed" ? (
|
||||
<Button size="sm" variant="outline" onClick={reopenCollection} disabled={closingBusy}>
|
||||
<Unlock className="h-4 w-4 mr-1.5" /> Reopen
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="sm" variant="outline" onClick={closeCollection} disabled={closingBusy}>
|
||||
<Lock className="h-4 w-4 mr-1.5" /> Close collection
|
||||
</Button>
|
||||
)}
|
||||
{collection.case?.client?.id && (
|
||||
<Button size="sm" onClick={() => navigate({ to: "/invoices/new/$clientId", params: { clientId: collection.case.client.id }, search: { caseId: collection.case.id } })}>
|
||||
<FilePlus className="h-4 w-4 mr-1.5" /> Generate invoice
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs: Workflow (collections-specific) + same case tabs */}
|
||||
@@ -539,6 +600,13 @@ function CollectionDetailRoute() {
|
||||
caseId={collection.case?.id ?? null}
|
||||
onApplied={refreshTasks}
|
||||
/>
|
||||
|
||||
<ApplyHomeownerDialog
|
||||
open={applyHoOpen}
|
||||
onOpenChange={setApplyHoOpen}
|
||||
collection={collection}
|
||||
onSaved={() => setReload((r) => r + 1)}
|
||||
/>
|
||||
</PageContainer>
|
||||
</ProtectedLayout>
|
||||
);
|
||||
@@ -659,3 +727,209 @@ function AddTaskDialog({
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function ApplyHomeownerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
collection,
|
||||
onSaved,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
collection: any;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const [contacts, setContacts] = useState<any[]>([]);
|
||||
const [homeowners, setHomeowners] = useState<any[]>([]);
|
||||
const [selectedHomeownerId, setSelectedHomeownerId] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const clientId = collection?.case?.client?.id ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !clientId) return;
|
||||
setLoading(true);
|
||||
(async () => {
|
||||
// Load case contacts (people on this case)
|
||||
const { data: cc } = await supabase
|
||||
.from("case_contacts")
|
||||
.select("contact:contacts(id, name, email, phone)")
|
||||
.eq("case_id", collection.case.id);
|
||||
const caseContacts = (cc ?? [])
|
||||
.map((r: any) => r.contact)
|
||||
.filter(Boolean);
|
||||
setContacts(caseContacts);
|
||||
|
||||
// Load existing homeowners for this client
|
||||
const { data: hos } = await supabase
|
||||
.from("homeowners")
|
||||
.select("id, first_name, last_name, unit_number, email, phone")
|
||||
.eq("client_id", clientId)
|
||||
.is("archived_at", null)
|
||||
.order("last_name");
|
||||
setHomeowners(hos ?? []);
|
||||
setSelectedHomeownerId(collection.homeowner_id ?? "");
|
||||
setLoading(false);
|
||||
})();
|
||||
}, [open, clientId, collection?.case?.id, collection?.homeowner_id]);
|
||||
|
||||
const applyExisting = async () => {
|
||||
if (!selectedHomeownerId) return toast.error("Select a homeowner");
|
||||
setSaving(true);
|
||||
const ho = homeowners.find((h) => h.id === selectedHomeownerId);
|
||||
const updates: any = { homeowner_id: selectedHomeownerId };
|
||||
// Refresh display name on the collection too
|
||||
if (ho) updates.name = `${ho.last_name}, ${ho.first_name}`;
|
||||
const { error } = await supabase
|
||||
.from("collections")
|
||||
.update(updates)
|
||||
.eq("id", collection.id);
|
||||
setSaving(false);
|
||||
if (error) {
|
||||
toast.error("Could not apply", { description: error.message });
|
||||
return;
|
||||
}
|
||||
toast.success("Homeowner applied");
|
||||
onOpenChange(false);
|
||||
onSaved();
|
||||
};
|
||||
|
||||
const createFromContact = async (contactId: string) => {
|
||||
const c = contacts.find((x) => x.id === contactId);
|
||||
if (!c || !clientId) return;
|
||||
setSaving(true);
|
||||
// Split name → first/last
|
||||
const parts = (c.name ?? "").trim().split(/\s+/);
|
||||
const first = parts.shift() ?? c.name ?? "Homeowner";
|
||||
const last = parts.join(" ") || "—";
|
||||
const { data: ho, error: insErr } = await supabase
|
||||
.from("homeowners")
|
||||
.insert({
|
||||
client_id: clientId,
|
||||
first_name: first,
|
||||
last_name: last,
|
||||
email: c.email,
|
||||
phone: c.phone,
|
||||
})
|
||||
.select("id, first_name, last_name")
|
||||
.single();
|
||||
if (insErr || !ho) {
|
||||
setSaving(false);
|
||||
toast.error("Could not create homeowner", { description: insErr?.message });
|
||||
return;
|
||||
}
|
||||
const { error: updErr } = await supabase
|
||||
.from("collections")
|
||||
.update({
|
||||
homeowner_id: ho.id,
|
||||
name: `${ho.last_name}, ${ho.first_name}`,
|
||||
})
|
||||
.eq("id", collection.id);
|
||||
setSaving(false);
|
||||
if (updErr) {
|
||||
toast.error("Created but could not apply", { description: updErr.message });
|
||||
return;
|
||||
}
|
||||
toast.success("Homeowner created and applied");
|
||||
onOpenChange(false);
|
||||
onSaved();
|
||||
};
|
||||
|
||||
const clearHomeowner = async () => {
|
||||
if (!confirm("Remove the homeowner from this collection?")) return;
|
||||
setSaving(true);
|
||||
const { error } = await supabase
|
||||
.from("collections")
|
||||
.update({ homeowner_id: null })
|
||||
.eq("id", collection.id);
|
||||
setSaving(false);
|
||||
if (error) {
|
||||
toast.error("Could not clear", { description: error.message });
|
||||
return;
|
||||
}
|
||||
toast.success("Homeowner removed");
|
||||
onOpenChange(false);
|
||||
onSaved();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-serif">
|
||||
{collection?.homeowner ? "Change homeowner" : "Apply homeowner"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Select an existing homeowner for this client, or promote a case contact into a homeowner record.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">Loading…</div>
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<Label className="mb-1.5 block">Existing homeowner</Label>
|
||||
{homeowners.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground italic">
|
||||
No homeowners on this client yet.
|
||||
</p>
|
||||
) : (
|
||||
<SearchableSelect
|
||||
value={selectedHomeownerId}
|
||||
onValueChange={setSelectedHomeownerId}
|
||||
placeholder="Select a homeowner…"
|
||||
options={homeowners.map((h) => ({
|
||||
value: h.id,
|
||||
label: `${h.last_name}, ${h.first_name}${h.unit_number ? ` · Unit ${h.unit_number}` : ""}`,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{contacts.length > 0 && (
|
||||
<div>
|
||||
<Label className="mb-1.5 block">Or create from a case contact</Label>
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto border rounded-md p-1">
|
||||
{contacts.map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => createFromContact(c.id)}
|
||||
disabled={saving}
|
||||
className="w-full text-left px-2 py-1.5 text-sm rounded hover:bg-muted/60 disabled:opacity-50"
|
||||
>
|
||||
<div className="font-medium">{c.name}</div>
|
||||
{(c.email || c.phone) && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{[c.email, c.phone].filter(Boolean).join(" · ")}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-2 sm:justify-between">
|
||||
{collection?.homeowner_id ? (
|
||||
<Button variant="ghost" onClick={clearHomeowner} disabled={saving} className="text-destructive">
|
||||
Remove homeowner
|
||||
</Button>
|
||||
) : <span />}
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
|
||||
<Button
|
||||
onClick={applyExisting}
|
||||
disabled={saving || !selectedHomeownerId || selectedHomeownerId === collection?.homeowner_id}
|
||||
>
|
||||
{saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Apply selected
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ function CollectionsIndexPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
const [stageFilter, setStageFilter] = useState<string>("all");
|
||||
const [statusFilter, setStatusFilter] = useState<string>("open");
|
||||
const [sortKey, setSortKey] = useState<"homeowner" | "case" | "stage" | "tasks" | "opened" | "balance">("opened");
|
||||
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
|
||||
|
||||
@@ -112,6 +113,8 @@ function CollectionsIndexPage() {
|
||||
stages.find((s) => s.key === key)?.label ?? key ?? "—";
|
||||
|
||||
const filtered = rows.filter((r) => {
|
||||
if (statusFilter === "open" && r.status === "closed") return false;
|
||||
if (statusFilter === "closed" && r.status !== "closed") return false;
|
||||
if (stageFilter !== "all" && r.current_stage !== stageFilter) return false;
|
||||
if (!search.trim()) return true;
|
||||
const q = search.toLowerCase();
|
||||
@@ -183,6 +186,16 @@ function CollectionsIndexPage() {
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[160px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="open">Open only</SelectItem>
|
||||
<SelectItem value="closed">Closed only</SelectItem>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={stageFilter} onValueChange={setStageFilter}>
|
||||
<SelectTrigger className="w-[260px]">
|
||||
<SelectValue />
|
||||
@@ -253,6 +266,11 @@ function CollectionsIndexPage() {
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
{r.status === "closed" && (
|
||||
<Badge variant="outline" className="ml-2 text-[10px] border-emerald-600 text-emerald-700">
|
||||
Closed
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
<div>{r.case?.client?.name}</div>
|
||||
|
||||
Reference in New Issue
Block a user