Changes
Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
co-authored by
renee-png
parent
417068af7d
commit
29b1ef6e5f
@@ -0,0 +1,436 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { ProtectedLayout } from "@/components/protected-layout";
|
||||
import { PageContainer, PageHeader } from "@/components/app-shell";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogDescription,
|
||||
} from "@/components/ui/dialog";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { CreditCard, Plus, Copy, Mail, RefreshCw, X } from "lucide-react";
|
||||
import { formatCurrency, formatDateTime, statusBadgeClass } from "@/lib/format";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
createPaymentRequest,
|
||||
refreshPaymentStatus,
|
||||
cancelPaymentRequest,
|
||||
markPaymentEmailSent,
|
||||
} from "@/lib/payments.functions";
|
||||
import { useServerFn } from "@tanstack/react-start";
|
||||
|
||||
export const Route = createFileRoute("/payments/")({
|
||||
component: () => (
|
||||
<ProtectedLayout>
|
||||
<PaymentsIndex />
|
||||
</ProtectedLayout>
|
||||
),
|
||||
});
|
||||
|
||||
interface Homeowner {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string | null;
|
||||
client_id: string;
|
||||
}
|
||||
|
||||
function PaymentsIndex() {
|
||||
const [rows, setRows] = useState<any[]>([]);
|
||||
const [q, setQ] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const create = useServerFn(createPaymentRequest);
|
||||
const refresh = useServerFn(refreshPaymentStatus);
|
||||
const cancel = useServerFn(cancelPaymentRequest);
|
||||
const markSent = useServerFn(markPaymentEmailSent);
|
||||
|
||||
const load = async () => {
|
||||
const { data } = await supabase
|
||||
.from("payment_requests")
|
||||
.select("*, homeowner:homeowners(id, first_name, last_name)")
|
||||
.order("created_at", { ascending: false });
|
||||
setRows(data ?? []);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!q) return rows;
|
||||
const s = q.toLowerCase();
|
||||
return rows.filter(
|
||||
(r) =>
|
||||
r.recipient_name?.toLowerCase().includes(s) ||
|
||||
r.recipient_email?.toLowerCase().includes(s) ||
|
||||
r.description?.toLowerCase().includes(s),
|
||||
);
|
||||
}, [rows, q]);
|
||||
|
||||
const copyLink = async (r: any) => {
|
||||
const url = `${window.location.origin}/pay/${r.id}`;
|
||||
await navigator.clipboard.writeText(url);
|
||||
toast.success("Payment link copied");
|
||||
};
|
||||
|
||||
const sendEmail = async (r: any) => {
|
||||
if (!r.recipient_email) {
|
||||
toast.error("No recipient email on file");
|
||||
return;
|
||||
}
|
||||
const url = `${window.location.origin}/pay/${r.id}`;
|
||||
const html = `
|
||||
<p>Hello ${r.recipient_name},</p>
|
||||
<p>You have a payment request for <strong>${formatCurrency(r.total_amount_cents / 100)}</strong>${
|
||||
r.description ? ` (${r.description})` : ""
|
||||
}.</p>
|
||||
<p><a href="${url}" style="display:inline-block;padding:10px 16px;background:#2563eb;color:#fff;text-decoration:none;border-radius:6px;">Pay now</a></p>
|
||||
<p>Or open this link: <a href="${url}">${url}</a></p>
|
||||
`;
|
||||
const { error } = await supabase.functions.invoke("send-smtp-email", {
|
||||
body: {
|
||||
to: r.recipient_email,
|
||||
subject: `Payment request: ${formatCurrency(r.total_amount_cents / 100)}`,
|
||||
html,
|
||||
context: "payment_request",
|
||||
},
|
||||
});
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
return;
|
||||
}
|
||||
await markSent({ data: { id: r.id } });
|
||||
toast.success("Email sent");
|
||||
load();
|
||||
};
|
||||
|
||||
const onRefresh = async (id: string) => {
|
||||
await refresh({ data: { id } });
|
||||
load();
|
||||
};
|
||||
|
||||
const onCancel = async (id: string) => {
|
||||
if (!confirm("Cancel this payment request?")) return;
|
||||
await cancel({ data: { id } });
|
||||
load();
|
||||
};
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="Payments"
|
||||
description="Stripe payment requests for homeowners. Fees are added on top so the homeowner covers them."
|
||||
actions={
|
||||
<Button onClick={() => setOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" /> New payment request
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Card className="border-border/60 mb-4">
|
||||
<CardContent className="p-3">
|
||||
<Input
|
||||
placeholder="Search by recipient, email, or description"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-border/60 overflow-hidden">
|
||||
<CardContent className="p-0">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50 text-xs uppercase tracking-wider text-muted-foreground">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3 font-medium">Recipient</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Description</th>
|
||||
<th className="text-right px-4 py-3 font-medium">Base</th>
|
||||
<th className="text-right px-4 py-3 font-medium">Fee</th>
|
||||
<th className="text-right px-4 py-3 font-medium">Total</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Status</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Created</th>
|
||||
<th className="text-right px-4 py-3 font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && (
|
||||
<tr>
|
||||
<td colSpan={8} className="text-center py-12 text-muted-foreground">
|
||||
Loading…
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{!loading && filtered.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={8} className="text-center py-12 text-muted-foreground">
|
||||
<CreditCard className="h-8 w-8 mx-auto mb-2 opacity-40" />
|
||||
No payment requests yet.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{filtered.map((r) => (
|
||||
<tr key={r.id} className="border-t hover:bg-muted/30">
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-medium">{r.recipient_name}</div>
|
||||
{r.recipient_email && (
|
||||
<div className="text-xs text-muted-foreground">{r.recipient_email}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{r.description ?? "—"}</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums">
|
||||
{formatCurrency(r.base_amount_cents / 100)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums text-muted-foreground">
|
||||
{formatCurrency(r.fee_amount_cents / 100)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums font-medium">
|
||||
{formatCurrency(r.total_amount_cents / 100)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant="outline" className={statusBadgeClass(r.status)}>
|
||||
{r.status}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground text-xs">
|
||||
{formatDateTime(r.created_at)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button size="sm" variant="ghost" onClick={() => copyLink(r)} title="Copy link">
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => sendEmail(r)}
|
||||
title="Send email"
|
||||
disabled={!r.recipient_email}
|
||||
>
|
||||
<Mail className="h-4 w-4" />
|
||||
</Button>
|
||||
{r.status === "pending" && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => onRefresh(r.id)}
|
||||
title="Refresh status"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => onCancel(r.id)}
|
||||
title="Cancel"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<NewPaymentDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
onCreated={() => {
|
||||
setOpen(false);
|
||||
load();
|
||||
}}
|
||||
createFn={create}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function NewPaymentDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
createFn,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
onCreated: () => void;
|
||||
createFn: ReturnType<typeof useServerFn<typeof createPaymentRequest>>;
|
||||
}) {
|
||||
const [homeowners, setHomeowners] = useState<Homeowner[]>([]);
|
||||
const [homeownerId, setHomeownerId] = useState<string>("");
|
||||
const [recipientName, setRecipientName] = useState("");
|
||||
const [recipientEmail, setRecipientEmail] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [amount, setAmount] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
(async () => {
|
||||
const { data } = await supabase
|
||||
.from("homeowners")
|
||||
.select("id, first_name, last_name, email, client_id")
|
||||
.is("archived_at", null)
|
||||
.order("last_name");
|
||||
setHomeowners((data ?? []) as Homeowner[]);
|
||||
})();
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
const ho = homeowners.find((h) => h.id === homeownerId);
|
||||
if (ho) {
|
||||
setRecipientName(`${ho.first_name} ${ho.last_name}`.trim());
|
||||
setRecipientEmail(ho.email ?? "");
|
||||
}
|
||||
}, [homeownerId, homeowners]);
|
||||
|
||||
const baseCents = Math.round((parseFloat(amount) || 0) * 100);
|
||||
const preview = baseCents > 0 ? (baseCents + 30) / (1 - 0.029) : 0;
|
||||
const totalPreview = Math.ceil(preview) / 100;
|
||||
const feePreview = totalPreview - baseCents / 100;
|
||||
|
||||
const submit = async () => {
|
||||
if (!recipientName.trim() || baseCents < 100) {
|
||||
toast.error("Recipient and amount (≥ $1.00) required");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const ho = homeowners.find((h) => h.id === homeownerId);
|
||||
await createFn({
|
||||
data: {
|
||||
recipient_name: recipientName,
|
||||
recipient_email: recipientEmail || undefined,
|
||||
description: description || undefined,
|
||||
base_amount_cents: baseCents,
|
||||
homeowner_id: homeownerId || undefined,
|
||||
client_id: ho?.client_id || undefined,
|
||||
},
|
||||
});
|
||||
toast.success("Payment request created");
|
||||
setHomeownerId("");
|
||||
setRecipientName("");
|
||||
setRecipientEmail("");
|
||||
setDescription("");
|
||||
setAmount("");
|
||||
onCreated();
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to create");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New payment request</DialogTitle>
|
||||
<DialogDescription>
|
||||
A Stripe checkout link will be generated. The homeowner pays the base amount plus
|
||||
processing fees (2.9% + $0.30).
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-xs">Homeowner (optional)</Label>
|
||||
<select
|
||||
className="w-full mt-1 h-9 px-2 rounded-md border bg-background text-sm"
|
||||
value={homeownerId}
|
||||
onChange={(e) => setHomeownerId(e.target.value)}
|
||||
>
|
||||
<option value="">— Select a homeowner —</option>
|
||||
{homeowners.map((h) => (
|
||||
<option key={h.id} value={h.id}>
|
||||
{h.last_name}, {h.first_name}
|
||||
{h.email ? ` (${h.email})` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label className="text-xs">Recipient name</Label>
|
||||
<Input value={recipientName} onChange={(e) => setRecipientName(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Recipient email</Label>
|
||||
<Input
|
||||
type="email"
|
||||
value={recipientEmail}
|
||||
onChange={(e) => setRecipientEmail(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">Description</Label>
|
||||
<Textarea
|
||||
rows={2}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="e.g. Past due assessments — Unit 42"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs">Amount you want to receive (USD)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="1"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{baseCents > 0 && (
|
||||
<div className="rounded-md border border-border/60 bg-muted/30 p-3 text-sm space-y-1">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Base</span>
|
||||
<span className="tabular-nums">{formatCurrency(baseCents / 100)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Processing fee</span>
|
||||
<span className="tabular-nums">{formatCurrency(feePreview)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between font-medium border-t pt-1 mt-1">
|
||||
<span>Homeowner pays</span>
|
||||
<span className="tabular-nums">{formatCurrency(totalPreview)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={submitting}>
|
||||
{submitting ? "Creating…" : "Create payment request"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user