ZIP lookup (GET /api/members/by-zip/{zip}):
- Two-step geocoding: Nominatim (ZIP → lat/lng) then Census TIGERweb
Legislative identify (lat/lng → congressional district via GEOID)
- Handles at-large states (AK, DE, MT, ND, SD, VT, WY)
- Added rep_lookup health check to admin External API Health panel
congress_api.py fixes:
- parse_member_from_api: normalize state full name → 2-letter code
(Congress.gov returns "Florida", DB expects "FL")
- parse_member_from_api: read district from top-level data field,
not current_term (district is not inside the term object)
Celery beat: schedule sync_members daily at 1 AM UTC so chamber,
district, and contact info stay current without manual triggering
Members page redesign: photo avatars, party/state/chamber chips,
phone + website links, ZIP lookup form to find your reps
Draft letter improvements: pass rep_name from ZIP lookup so letter
opens with "Dear Representative Franklin," instead of generic salutation;
add has_document filter to bills list endpoint
UX additions: HelpTip component, How It Works page, "How it works"
sidebar nav link, collections page description copy
Authored-By: Jack Levy
435 lines
17 KiB
TypeScript
435 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, useRef } from "react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { ChevronDown, ChevronRight, Copy, Check, ExternalLink, Loader2, Phone, PenLine } from "lucide-react";
|
|
import type { BriefSchema, CitedPoint, Member } from "@/lib/types";
|
|
import { billsAPI, membersAPI } from "@/lib/api";
|
|
import { useIsFollowing } from "@/lib/hooks/useFollows";
|
|
|
|
interface DraftLetterPanelProps {
|
|
billId: string;
|
|
brief: BriefSchema;
|
|
chamber?: string;
|
|
}
|
|
|
|
type Stance = "yes" | "no" | null;
|
|
type Tone = "short" | "polite" | "firm";
|
|
|
|
function pointText(p: string | CitedPoint): string {
|
|
return typeof p === "string" ? p : p.text;
|
|
}
|
|
|
|
function pointKey(p: string | CitedPoint, i: number): string {
|
|
return `${i}-${typeof p === "string" ? p.slice(0, 40) : p.text.slice(0, 40)}`;
|
|
}
|
|
|
|
function chamberToRecipient(chamber?: string): "house" | "senate" {
|
|
return chamber?.toLowerCase() === "senate" ? "senate" : "house";
|
|
}
|
|
|
|
function formatRepName(member: Member): string {
|
|
// DB stores name as "Last, First" — convert to "First Last" for the letter
|
|
if (member.name.includes(", ")) {
|
|
const [last, first] = member.name.split(", ");
|
|
return `${first} ${last}`;
|
|
}
|
|
return member.name;
|
|
}
|
|
|
|
export function DraftLetterPanel({ billId, brief, chamber }: DraftLetterPanelProps) {
|
|
const [open, setOpen] = useState(false);
|
|
const existing = useIsFollowing("bill", billId);
|
|
const [stance, setStance] = useState<Stance>(null);
|
|
const prevModeRef = useRef<string | undefined>(undefined);
|
|
|
|
// Keep stance in sync with follow mode changes (including unfollow → null)
|
|
useEffect(() => {
|
|
const newMode = existing?.follow_mode;
|
|
if (newMode === prevModeRef.current) return;
|
|
prevModeRef.current = newMode;
|
|
if (newMode === "pocket_boost") setStance("yes");
|
|
else if (newMode === "pocket_veto") setStance("no");
|
|
else setStance(null);
|
|
}, [existing?.follow_mode]);
|
|
|
|
const recipient = chamberToRecipient(chamber);
|
|
const [tone, setTone] = useState<Tone>("polite");
|
|
const [selected, setSelected] = useState<Set<number>>(new Set());
|
|
const [includeCitations, setIncludeCitations] = useState(true);
|
|
const [zipCode, setZipCode] = useState("");
|
|
const [loading, setLoading] = useState(false);
|
|
const [draft, setDraft] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [copied, setCopied] = useState(false);
|
|
|
|
// Zip → rep lookup (debounced via React Query enabled flag)
|
|
const zipTrimmed = zipCode.trim();
|
|
const isValidZip = /^\d{5}$/.test(zipTrimmed);
|
|
const { data: zipReps, isFetching: zipFetching } = useQuery({
|
|
queryKey: ["members-by-zip", zipTrimmed],
|
|
queryFn: () => membersAPI.byZip(zipTrimmed),
|
|
enabled: isValidZip,
|
|
staleTime: 24 * 60 * 60 * 1000,
|
|
retry: false,
|
|
});
|
|
|
|
// Filter reps to match the bill's chamber
|
|
const relevantReps = zipReps?.filter((m) =>
|
|
recipient === "senate"
|
|
? m.chamber === "Senate"
|
|
: m.chamber === "House of Representatives"
|
|
) ?? [];
|
|
|
|
// Use first matched rep's name for the letter salutation
|
|
const repName = relevantReps.length > 0 ? formatRepName(relevantReps[0]) : undefined;
|
|
|
|
const keyPoints = brief.key_points ?? [];
|
|
const risks = brief.risks ?? [];
|
|
const allPoints = [
|
|
...keyPoints.map((p, i) => ({ group: "key" as const, index: i, text: pointText(p), raw: p })),
|
|
...risks.map((p, i) => ({ group: "risk" as const, index: keyPoints.length + i, text: pointText(p), raw: p })),
|
|
];
|
|
|
|
function togglePoint(globalIndex: number) {
|
|
setSelected((prev) => {
|
|
const next = new Set(prev);
|
|
if (next.has(globalIndex)) {
|
|
next.delete(globalIndex);
|
|
} else if (next.size < 3) {
|
|
next.add(globalIndex);
|
|
}
|
|
return next;
|
|
});
|
|
}
|
|
|
|
async function handleGenerate() {
|
|
if (selected.size === 0 || stance === null) return;
|
|
|
|
const selectedPoints = allPoints
|
|
.filter((p) => selected.has(p.index))
|
|
.map((p) => {
|
|
if (includeCitations && typeof p.raw !== "string" && p.raw.citation) {
|
|
return `${p.text} (${p.raw.citation})`;
|
|
}
|
|
return p.text;
|
|
});
|
|
|
|
setLoading(true);
|
|
setError(null);
|
|
setDraft(null);
|
|
|
|
try {
|
|
const result = await billsAPI.generateDraft(billId, {
|
|
stance,
|
|
recipient,
|
|
tone,
|
|
selected_points: selectedPoints,
|
|
include_citations: includeCitations,
|
|
zip_code: zipCode.trim() || undefined,
|
|
rep_name: repName,
|
|
});
|
|
setDraft(result.draft);
|
|
} catch (err: unknown) {
|
|
const detail =
|
|
err &&
|
|
typeof err === "object" &&
|
|
"response" in err &&
|
|
err.response &&
|
|
typeof err.response === "object" &&
|
|
"data" in err.response &&
|
|
err.response.data &&
|
|
typeof err.response.data === "object" &&
|
|
"detail" in err.response.data
|
|
? String((err.response.data as { detail: string }).detail)
|
|
: "Failed to generate letter. Please try again.";
|
|
setError(detail);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
async function handleCopy() {
|
|
if (!draft) return;
|
|
await navigator.clipboard.writeText(draft);
|
|
setCopied(true);
|
|
setTimeout(() => setCopied(false), 2000);
|
|
}
|
|
|
|
return (
|
|
<div className="bg-card border border-border rounded-lg overflow-hidden">
|
|
<button
|
|
onClick={() => setOpen((o) => !o)}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors text-left"
|
|
>
|
|
{open ? (
|
|
<ChevronDown className="w-3.5 h-3.5 shrink-0" />
|
|
) : (
|
|
<ChevronRight className="w-3.5 h-3.5 shrink-0" />
|
|
)}
|
|
<PenLine className="w-3.5 h-3.5 shrink-0" />
|
|
Draft a letter to your {recipient === "senate" ? "senator" : "representative"}
|
|
</button>
|
|
|
|
{open && (
|
|
<div className="border-t border-border px-4 py-4 space-y-4">
|
|
{/* Stance + Tone */}
|
|
<div className="flex flex-wrap gap-4">
|
|
<div className="space-y-1">
|
|
<p className="text-xs font-medium text-muted-foreground">Stance</p>
|
|
<div className="flex rounded-md overflow-hidden border border-border text-xs">
|
|
{(["yes", "no"] as ("yes" | "no")[]).map((s) => (
|
|
<button
|
|
key={s}
|
|
onClick={() => setStance(s)}
|
|
className={`px-3 py-1.5 font-medium transition-colors ${
|
|
stance === s
|
|
? s === "yes"
|
|
? "bg-green-600 text-white"
|
|
: "bg-red-600 text-white"
|
|
: "bg-background text-muted-foreground hover:bg-accent/50"
|
|
}`}
|
|
>
|
|
{s === "yes" ? "Support (Vote YES)" : "Oppose (Vote NO)"}
|
|
</button>
|
|
))}
|
|
</div>
|
|
{stance === null && (
|
|
<p className="text-[10px] text-amber-500 mt-1">Select a position to continue</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-1">
|
|
<p className="text-xs font-medium text-muted-foreground">Tone</p>
|
|
<select
|
|
value={tone}
|
|
onChange={(e) => setTone(e.target.value as Tone)}
|
|
className="text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"
|
|
>
|
|
<option value="short">Short</option>
|
|
<option value="polite">Polite</option>
|
|
<option value="firm">Firm</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Point selector */}
|
|
<div className="space-y-1">
|
|
<p className="text-xs font-medium text-muted-foreground">
|
|
Select up to 3 points to include
|
|
{selected.size > 0 && (
|
|
<span className="ml-1 text-muted-foreground">({selected.size}/3)</span>
|
|
)}
|
|
</p>
|
|
<div className="border border-border rounded-md divide-y divide-border">
|
|
{keyPoints.length > 0 && (
|
|
<>
|
|
<p className="px-3 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/40">
|
|
Key Points
|
|
</p>
|
|
{keyPoints.map((p, i) => {
|
|
const globalIndex = i;
|
|
const isChecked = selected.has(globalIndex);
|
|
const isDisabled = !isChecked && selected.size >= 3;
|
|
return (
|
|
<label
|
|
key={pointKey(p, i)}
|
|
className={`flex items-start gap-2.5 px-3 py-2 cursor-pointer transition-colors ${
|
|
isDisabled ? "opacity-40 cursor-not-allowed" : "hover:bg-accent/40"
|
|
}`}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={isChecked}
|
|
disabled={isDisabled}
|
|
onChange={() => togglePoint(globalIndex)}
|
|
className="mt-0.5 shrink-0"
|
|
/>
|
|
<span className="text-xs text-foreground leading-snug">{pointText(p)}</span>
|
|
</label>
|
|
);
|
|
})}
|
|
</>
|
|
)}
|
|
|
|
{risks.length > 0 && (
|
|
<>
|
|
<p className="px-3 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/40">
|
|
Concerns
|
|
</p>
|
|
{risks.map((p, i) => {
|
|
const globalIndex = keyPoints.length + i;
|
|
const isChecked = selected.has(globalIndex);
|
|
const isDisabled = !isChecked && selected.size >= 3;
|
|
return (
|
|
<label
|
|
key={pointKey(p, keyPoints.length + i)}
|
|
className={`flex items-start gap-2.5 px-3 py-2 cursor-pointer transition-colors ${
|
|
isDisabled ? "opacity-40 cursor-not-allowed" : "hover:bg-accent/40"
|
|
}`}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={isChecked}
|
|
disabled={isDisabled}
|
|
onChange={() => togglePoint(globalIndex)}
|
|
className="mt-0.5 shrink-0"
|
|
/>
|
|
<span className="text-xs text-foreground leading-snug">{pointText(p)}</span>
|
|
</label>
|
|
);
|
|
})}
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Options row */}
|
|
<div className="flex flex-wrap items-start gap-4">
|
|
<div className="space-y-1">
|
|
<div className="flex items-center gap-2">
|
|
<input
|
|
type="text"
|
|
value={zipCode}
|
|
onChange={(e) => setZipCode(e.target.value)}
|
|
placeholder="ZIP code"
|
|
maxLength={10}
|
|
className="text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground w-28 placeholder:text-muted-foreground"
|
|
/>
|
|
{zipFetching && <Loader2 className="w-3.5 h-3.5 animate-spin text-muted-foreground" />}
|
|
</div>
|
|
<p className="text-[10px] text-muted-foreground">optional · not stored</p>
|
|
</div>
|
|
|
|
<label className="flex items-center gap-1.5 cursor-pointer text-xs text-muted-foreground mt-1.5">
|
|
<input
|
|
type="checkbox"
|
|
checked={includeCitations}
|
|
onChange={(e) => setIncludeCitations(e.target.checked)}
|
|
className="shrink-0"
|
|
/>
|
|
Include citations
|
|
</label>
|
|
</div>
|
|
|
|
{/* Rep lookup results */}
|
|
{isValidZip && !zipFetching && relevantReps.length > 0 && (
|
|
<div className="space-y-1.5">
|
|
<p className="text-xs font-medium text-muted-foreground">
|
|
Your {recipient === "senate" ? "senators" : "representative"}
|
|
</p>
|
|
{relevantReps.map((rep) => (
|
|
<div
|
|
key={rep.bioguide_id}
|
|
className="flex items-center gap-3 bg-muted/40 border border-border rounded-md px-3 py-2"
|
|
>
|
|
{rep.photo_url && (
|
|
<img
|
|
src={rep.photo_url}
|
|
alt={rep.name}
|
|
className="w-8 h-8 rounded-full object-cover shrink-0 border border-border"
|
|
/>
|
|
)}
|
|
<div className="flex-1 min-w-0">
|
|
<p className="text-xs font-medium">{formatRepName(rep)}</p>
|
|
{rep.party && (
|
|
<p className="text-[10px] text-muted-foreground">{rep.party} · {rep.state}</p>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-2 shrink-0">
|
|
{rep.phone && (
|
|
<a
|
|
href={`tel:${rep.phone.replace(/\D/g, "")}`}
|
|
className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
|
|
title="Office phone"
|
|
>
|
|
<Phone className="w-3 h-3" />
|
|
{rep.phone}
|
|
</a>
|
|
)}
|
|
{rep.official_url && (
|
|
<a
|
|
href={rep.official_url}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="flex items-center gap-1 text-[10px] text-primary hover:underline"
|
|
title="Contact form"
|
|
>
|
|
<ExternalLink className="w-3 h-3" />
|
|
Contact
|
|
</a>
|
|
)}
|
|
</div>
|
|
</div>
|
|
))}
|
|
{repName && (
|
|
<p className="text-[10px] text-muted-foreground">
|
|
Letter will be addressed to{" "}
|
|
{recipient === "senate" ? "Senator" : "Representative"} {repName}.
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{isValidZip && !zipFetching && relevantReps.length === 0 && zipReps !== undefined && (
|
|
<p className="text-[10px] text-amber-500">
|
|
Could not find your {recipient === "senate" ? "senators" : "representative"} for that ZIP.
|
|
The letter will use a generic salutation.
|
|
</p>
|
|
)}
|
|
|
|
{/* Generate button */}
|
|
<button
|
|
onClick={handleGenerate}
|
|
disabled={loading || selected.size === 0 || stance === null}
|
|
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground text-xs font-medium rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
|
>
|
|
{loading && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
|
|
{loading ? "Generating…" : "Generate letter"}
|
|
</button>
|
|
|
|
{error && (
|
|
<p className="text-xs text-destructive">{error}</p>
|
|
)}
|
|
|
|
{/* Draft output */}
|
|
{draft && (
|
|
<div className="space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<p className="text-xs text-muted-foreground italic">Edit before sending</p>
|
|
<button
|
|
onClick={handleCopy}
|
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
|
>
|
|
{copied ? (
|
|
<>
|
|
<Check className="w-3.5 h-3.5 text-green-500" />
|
|
<span className="text-green-500">Copied!</span>
|
|
</>
|
|
) : (
|
|
<>
|
|
<Copy className="w-3.5 h-3.5" />
|
|
Copy
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
<textarea
|
|
readOnly
|
|
value={draft}
|
|
rows={10}
|
|
className="w-full text-xs bg-muted/30 border border-border rounded-md px-3 py-2 text-foreground resize-y font-sans leading-relaxed"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{/* Footer */}
|
|
<p className="text-[10px] text-muted-foreground border-t border-border pt-3">
|
|
Based only on the bill's cited text · We don't store your location
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|