Precedent attachment UI in the compose screen

Surface the new POST/GET/DELETE /api/cases/{n}/precedents endpoints
in the compose screen as two insertion points:

1. A new case-level card "פסיקה כללית לדיון" at the top of the
   main column, for precedents that support the discussion intro
   rather than a specific threshold_claim / issue.
2. An inline "פסיקה תומכת" section inside each SubsectionCard,
   below the ChairEditor.

Both insertion points render a `<PrecedentsSection>` which shows a
list of `<PrecedentCard>` (citation + blockquote + optional chair
note + 📄 chip if a PDF was archived) followed by a `<PrecedentAttacher>`
popover trigger.

The Attacher is a Popover with cross-case typeahead: typing 2+
characters into the citation field hits /api/precedents/search and
shows distinct library matches; picking one prefills quote + chair
note but leaves them editable so customizing the quote for this
case doesn't mutate the library. An optional PDF/DOCX/DOC file can
be attached — it uploads first via POST .../upload-pdf and the
returned document_id is passed into the precedent create call.

The parent compose page issues a single useCasePrecedents query
and partitions the result by section_id into a Map so each
SubsectionCard renders its own slice without re-fetching.

shadcn Popover installed as a new primitive. sonner toasts wired
for success/error in both attach and delete flows.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-11 19:20:45 +00:00
parent aa0e608a4a
commit 6b8f002596
8 changed files with 656 additions and 2 deletions

View File

@@ -896,12 +896,24 @@
"priority": "high",
"subtasks": [],
"updatedAt": "2026-04-11T17:15:57.831Z"
},
{
"id": "91",
"title": "Precedent attachment in compose screen",
"description": "Add case_precedents table + FastAPI endpoints + MCP tools + Next.js compose UI for attaching legal precedents (quote + citation + optional archived PDF) to threshold_claims/issues and to the case as a whole. Plan: ~/.claude/plans/woolly-cooking-graham.md",
"details": "",
"testStrategy": "",
"status": "in-progress",
"dependencies": [],
"priority": "high",
"subtasks": [],
"updatedAt": "2026-04-11T19:13:41.219Z"
}
],
"metadata": {
"version": "1.0.0",
"lastModified": "2026-04-11T17:44:08.337Z",
"taskCount": 59,
"lastModified": "2026-04-11T19:13:41.220Z",
"taskCount": 60,
"completedCount": 56,
"tags": [
"master"

View File

@@ -7,8 +7,10 @@ import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { SubsectionCard } from "@/components/compose/subsection-card";
import { PrecedentsSection } from "@/components/compose/precedents-section";
import { useCase } from "@/lib/api/cases";
import { useResearchAnalysis } from "@/lib/api/research";
import { useCasePrecedents } from "@/lib/api/precedents";
function ProseSection({ title, content }: { title: string; content?: string }) {
if (!content?.trim()) return null;
@@ -32,6 +34,21 @@ export default function ComposePage({
const { caseNumber } = use(params);
const caseQuery = useCase(caseNumber);
const analysis = useResearchAnalysis(caseNumber);
const precedentsQuery = useCasePrecedents(caseNumber);
/* Partition the flat list into scopes so each child renders its own slice
* without re-fetching. Done once at the page level. */
const allPrecedents = precedentsQuery.data ?? [];
const caseLevelPrecedents = allPrecedents.filter((p) => p.section_id === null);
const precedentsBySection = new Map<string, typeof allPrecedents>();
for (const p of allPrecedents) {
if (p.section_id) {
const existing = precedentsBySection.get(p.section_id) ?? [];
existing.push(p);
precedentsBySection.set(p.section_id, existing);
}
}
const practiceArea = caseQuery.data?.practice_area ?? null;
const isNotFound =
analysis.error instanceof Error &&
@@ -101,6 +118,23 @@ export default function ComposePage({
<div className="grid gap-6 lg:grid-cols-[1fr_320px]">
{/* Main editable column */}
<div className="space-y-6">
{/* Case-level general precedents */}
<Card className="bg-surface border-rule shadow-sm">
<CardContent className="px-6 py-5">
<h2 className="text-navy text-xl mb-1">פסיקה כללית לדיון</h2>
<p className="text-[0.78rem] text-ink-muted mb-4">
ציטוטים התומכים בעמדה באופן רוחבי ישולבו בפתיחת בלוק י (דיון).
</p>
<PrecedentsSection
caseNumber={caseNumber}
sectionId={null}
precedents={caseLevelPrecedents}
practiceArea={practiceArea}
emptyHelperText="עדיין לא צורפה פסיקה כללית לתיק"
/>
</CardContent>
</Card>
{/* Threshold claims */}
{analysis.data.threshold_claims &&
analysis.data.threshold_claims.length > 0 && (
@@ -118,6 +152,8 @@ export default function ComposePage({
caseNumber={caseNumber}
item={tc}
defaultOpen={i === 0}
precedents={precedentsBySection.get(tc.id) ?? []}
practiceArea={practiceArea}
/>
))}
</div>
@@ -139,6 +175,8 @@ export default function ComposePage({
key={iss.id}
caseNumber={caseNumber}
item={iss}
precedents={precedentsBySection.get(iss.id) ?? []}
practiceArea={practiceArea}
/>
))}
</div>

View File

@@ -0,0 +1,229 @@
"use client";
import { useState } from "react";
import { Plus, Paperclip } from "lucide-react";
import { toast } from "sonner";
import {
Popover, PopoverContent, PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
useCreatePrecedent,
usePrecedentLibrarySearch,
uploadPrecedentPdf,
} from "@/lib/api/precedents";
import type { PracticeArea } from "@/lib/practice-area";
/*
* Inline form for adding a new precedent. Opens in a Popover adjacent
* to the trigger button so the user can see the surrounding context
* (the threshold_claim body, the chair editor) while they fill it in.
*
* The citation field has cross-case typeahead: once the user types
* 2+ characters, we hit /api/precedents/search and show distinct
* matches. Picking one prefills quote + chair_note but keeps them
* editable — the new row is a copy, so a customized quote for this
* case doesn't affect the library.
*/
export function PrecedentAttacher({
caseNumber,
sectionId,
practiceArea,
}: {
caseNumber: string;
sectionId: string | null;
practiceArea: PracticeArea | null | undefined;
}) {
const [open, setOpen] = useState(false);
const [citation, setCitation] = useState("");
const [quote, setQuote] = useState("");
const [chairNote, setChairNote] = useState("");
const [pdfFile, setPdfFile] = useState<File | null>(null);
const [submitting, setSubmitting] = useState(false);
const [picked, setPicked] = useState(false);
const create = useCreatePrecedent(caseNumber);
const library = usePrecedentLibrarySearch(
citation,
practiceArea,
/* pause typeahead once the user has picked one and we're just editing */
!picked,
);
const reset = () => {
setCitation("");
setQuote("");
setChairNote("");
setPdfFile(null);
setPicked(false);
};
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!quote.trim() || !citation.trim()) {
toast.error("ציטוט ומראה-מקום חובה");
return;
}
setSubmitting(true);
try {
let pdfDocumentId: string | undefined;
if (pdfFile) {
const res = await uploadPrecedentPdf(caseNumber, pdfFile);
pdfDocumentId = res.document_id;
}
await create.mutateAsync({
quote: quote.trim(),
citation: citation.trim(),
chair_note: chairNote.trim(),
section_id: sectionId ?? undefined,
pdf_document_id: pdfDocumentId,
});
toast.success("נוספה פסיקה");
reset();
setOpen(false);
} catch (err) {
toast.error(err instanceof Error ? err.message : "שגיאה בשמירה");
} finally {
setSubmitting(false);
}
};
return (
<Popover open={open} onOpenChange={(v) => { setOpen(v); if (!v) reset(); }}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="sm"
className="border-dashed border-gold/50 text-gold-deep hover:bg-gold-wash"
>
<Plus className="w-4 h-4 me-1" aria-hidden="true" />
הוסף פסיקה תומכת
</Button>
</PopoverTrigger>
<PopoverContent
className="w-[520px] max-w-[90vw] p-5"
align="start"
dir="rtl"
>
<form onSubmit={onSubmit} className="space-y-3" dir="rtl">
<div>
<Label htmlFor="prec-citation" className="text-navy">
מראה מקום <span className="text-danger">*</span>
</Label>
<Input
id="prec-citation"
value={citation}
onChange={(e) => {
setCitation(e.target.value);
setPicked(false);
}}
placeholder="ערר (ירושלים) 1126-08-25 ... נ' ... (נבו 9.3.2026)"
autoComplete="off"
className="mt-1"
/>
{!picked && library.data && library.data.length > 0 && citation.length >= 2 && (
<ul
className="
mt-1 rounded border border-rule bg-surface shadow-sm
max-h-44 overflow-y-auto divide-y divide-rule
"
role="listbox"
>
{library.data.map((m) => (
<li key={m.id}>
<button
type="button"
onClick={() => {
setCitation(m.citation);
setQuote(m.quote);
setChairNote(m.chair_note || "");
setPicked(true);
}}
className="w-full text-right px-3 py-2 hover:bg-gold-wash/60 transition-colors"
>
<div className="text-[0.78rem] text-gold-deep font-semibold truncate">
{m.citation}
</div>
<div className="text-[0.72rem] text-ink-muted truncate">
{m.quote}
</div>
</button>
</li>
))}
</ul>
)}
</div>
<div>
<Label htmlFor="prec-quote" className="text-navy">
ציטוט <span className="text-danger">*</span>
</Label>
<Textarea
id="prec-quote"
value={quote}
onChange={(e) => setQuote(e.target.value)}
rows={5}
placeholder="הטקסט המדויק שישולב בהחלטה"
className="mt-1"
/>
</div>
<div>
<Label htmlFor="prec-note" className="text-navy">
הערה (אופציונלי)
</Label>
<Textarea
id="prec-note"
value={chairNote}
onChange={(e) => setChairNote(e.target.value)}
rows={2}
placeholder="למה הציטוט הזה תומך בעמדה"
className="mt-1"
/>
</div>
<div>
<Label className="text-navy flex items-center gap-2">
<Paperclip className="w-3.5 h-3.5" aria-hidden="true" />
צירוף קובץ המקור (אופציונלי, לארכיון)
</Label>
<input
type="file"
accept=".pdf,.docx,.doc"
onChange={(e) => setPdfFile(e.target.files?.[0] ?? null)}
className="mt-1 w-full text-sm file:me-3 file:rounded file:border-0 file:bg-rule-soft file:px-3 file:py-1.5 file:text-navy file:text-sm hover:file:bg-rule"
/>
{pdfFile && (
<p className="text-[0.72rem] text-ink-muted mt-1">
{pdfFile.name} · {(pdfFile.size / 1024).toFixed(1)} KB
</p>
)}
</div>
<div className="flex items-center justify-end gap-2 pt-2">
<Button
type="button"
variant="ghost"
onClick={() => { setOpen(false); reset(); }}
disabled={submitting}
>
ביטול
</Button>
<Button
type="submit"
disabled={submitting}
className="bg-navy hover:bg-navy-soft text-parchment"
>
{submitting ? "שומר…" : "שמור פסיקה"}
</Button>
</div>
</form>
</PopoverContent>
</Popover>
);
}

View File

@@ -0,0 +1,77 @@
"use client";
import { Trash2, FileText } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { useDeletePrecedent, type CasePrecedent } from "@/lib/api/precedents";
/*
* Read-only display of a single attached precedent. Layout is:
*
* ┌───────────────────────────────────────────┐
* │ citation (gold semibold) [🗑] │
* │ ┌──┐ │
* │ │╎ │ "quote text…" │
* │ └──┘ │
* │ chair_note (muted) │
* │ 📄 קובץ מצורף │
* └───────────────────────────────────────────┘
*/
export function PrecedentCard({
caseNumber,
precedent,
}: {
caseNumber: string;
precedent: CasePrecedent;
}) {
const del = useDeletePrecedent(caseNumber);
const onDelete = async () => {
if (!window.confirm("להסיר פסיקה זו מהתיק?")) return;
try {
await del.mutateAsync(precedent.id);
toast.success("הפסיקה הוסרה");
} catch (e) {
toast.error(e instanceof Error ? e.message : "שגיאה בהסרה");
}
};
return (
<article className="rounded-lg border border-rule bg-parchment/40 px-4 py-3 space-y-2">
<div className="flex items-start gap-3">
<p className="flex-1 text-[0.82rem] text-gold-deep font-semibold leading-snug">
{precedent.citation}
</p>
<Button
type="button"
variant="ghost"
size="sm"
onClick={onDelete}
disabled={del.isPending}
aria-label="הסר פסיקה זו"
className="text-danger hover:text-danger hover:bg-danger-bg shrink-0 -mt-1 -me-2"
>
<Trash2 className="w-4 h-4" aria-hidden="true" />
</Button>
</div>
<blockquote className="border-e-2 border-gold pe-3 text-sm text-ink leading-relaxed whitespace-pre-line">
{precedent.quote}
</blockquote>
{precedent.chair_note && (
<p className="text-[0.78rem] text-ink-muted italic">
{precedent.chair_note}
</p>
)}
{precedent.pdf_document_id && (
<div className="flex items-center gap-1.5 text-[0.72rem] text-ink-muted">
<FileText className="w-3 h-3" aria-hidden="true" />
<span>קובץ מצורף</span>
</div>
)}
</article>
);
}

View File

@@ -0,0 +1,50 @@
"use client";
import { PrecedentCard } from "@/components/compose/precedent-card";
import { PrecedentAttacher } from "@/components/compose/precedent-attacher";
import type { CasePrecedent } from "@/lib/api/precedents";
import type { PracticeArea } from "@/lib/practice-area";
/*
* Wrapper that renders the list of precedents for one scope — either
* case-level (sectionId=null) or a specific threshold_claim / issue.
* The parent page fetches useCasePrecedents(caseNumber) once and
* passes a pre-filtered slice down, so each section doesn't re-query.
*/
export function PrecedentsSection({
caseNumber,
sectionId,
precedents,
practiceArea,
emptyHelperText,
}: {
caseNumber: string;
sectionId: string | null;
precedents: CasePrecedent[];
practiceArea: PracticeArea | null | undefined;
emptyHelperText?: string;
}) {
return (
<div className="space-y-3">
{precedents.length === 0 ? (
emptyHelperText && (
<p className="text-[0.78rem] text-ink-muted">{emptyHelperText}</p>
)
) : (
<ul className="space-y-2">
{precedents.map((p) => (
<li key={p.id}>
<PrecedentCard caseNumber={caseNumber} precedent={p} />
</li>
))}
</ul>
)}
<PrecedentAttacher
caseNumber={caseNumber}
sectionId={sectionId}
practiceArea={practiceArea}
/>
</div>
);
}

View File

@@ -3,16 +3,23 @@
import { useState } from "react";
import { ChevronDown } from "lucide-react";
import { ChairEditor } from "@/components/compose/chair-editor";
import { PrecedentsSection } from "@/components/compose/precedents-section";
import type { ResearchSubsection } from "@/lib/api/research";
import type { CasePrecedent } from "@/lib/api/precedents";
import type { PracticeArea } from "@/lib/practice-area";
export function SubsectionCard({
caseNumber,
item,
defaultOpen = false,
precedents = [],
practiceArea,
}: {
caseNumber: string;
item: ResearchSubsection;
defaultOpen?: boolean;
precedents?: CasePrecedent[];
practiceArea?: PracticeArea | null;
}) {
const [open, setOpen] = useState(defaultOpen);
const isFilled = Boolean(item.chair_position?.trim());
@@ -81,6 +88,18 @@ export function SubsectionCard({
sectionId={item.id}
initialValue={item.chair_position ?? ""}
/>
<div className="border-t border-rule pt-4 mt-2">
<h4 className="text-[0.78rem] uppercase tracking-wider text-gold-deep font-semibold mb-2">
פסיקה תומכת
</h4>
<PrecedentsSection
caseNumber={caseNumber}
sectionId={item.id}
precedents={precedents}
practiceArea={practiceArea}
emptyHelperText="עדיין לא צורפה פסיקה לסעיף זה"
/>
</div>
</div>
)}
</article>

View File

@@ -0,0 +1,89 @@
"use client"
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-0.5 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
return (
<div
data-slot="popover-title"
className={cn("font-heading font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: React.ComponentProps<"p">) {
return (
<p
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverAnchor,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
}

View File

@@ -0,0 +1,140 @@
/**
* Attached-precedent hooks — user-supplied case-law quotes that
* justify chair positions in the compose screen.
*
* Backed by POST/GET/DELETE /api/cases/{n}/precedents and the
* cross-case library search at GET /api/precedents/search. The
* optional PDF archive chains through POST .../upload-pdf before
* precedent creation; that's a plain async function, not a mutation
* hook, because it has no cache invalidation of its own.
*/
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest, ApiError } from "./client";
import type { PracticeArea } from "@/lib/practice-area";
export type CasePrecedent = {
id: string;
case_id: string;
section_id: string | null;
quote: string;
citation: string;
chair_note: string;
pdf_document_id: string | null;
practice_area: PracticeArea | null;
created_at: string;
updated_at: string;
};
export type PrecedentCreateInput = {
quote: string;
citation: string;
section_id?: string;
chair_note?: string;
pdf_document_id?: string;
};
export type LibraryMatch = {
id: string;
citation: string;
quote: string;
chair_note: string;
practice_area: PracticeArea | null;
created_at: string;
};
export const precedentKeys = {
all: ["precedents"] as const,
forCase: (caseNumber: string) =>
[...precedentKeys.all, "case", caseNumber] as const,
librarySearch: (q: string, area: string) =>
[...precedentKeys.all, "library", area, q] as const,
};
export function useCasePrecedents(caseNumber: string | undefined) {
return useQuery({
queryKey: precedentKeys.forCase(caseNumber ?? ""),
queryFn: ({ signal }) =>
apiRequest<CasePrecedent[]>(
`/api/cases/${caseNumber}/precedents`,
{ signal },
),
enabled: Boolean(caseNumber),
staleTime: 30_000,
});
}
export function useCreatePrecedent(caseNumber: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: (input: PrecedentCreateInput) =>
apiRequest<CasePrecedent>(`/api/cases/${caseNumber}/precedents`, {
method: "POST",
body: input,
}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: precedentKeys.forCase(caseNumber) });
qc.invalidateQueries({ queryKey: [...precedentKeys.all, "library"] });
},
});
}
export function useDeletePrecedent(caseNumber: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: (precedentId: string) =>
apiRequest<{ deleted: boolean }>(`/api/precedents/${precedentId}`, {
method: "DELETE",
}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: precedentKeys.forCase(caseNumber) });
},
});
}
export function usePrecedentLibrarySearch(
query: string,
practiceArea: PracticeArea | null | undefined,
enabled: boolean,
) {
return useQuery({
queryKey: precedentKeys.librarySearch(query, practiceArea ?? ""),
queryFn: ({ signal }) => {
const params = new URLSearchParams({ q: query });
if (practiceArea) params.set("practice_area", practiceArea);
return apiRequest<LibraryMatch[]>(
`/api/precedents/search?${params.toString()}`,
{ signal },
);
},
enabled: enabled && query.trim().length >= 2,
staleTime: 10_000,
placeholderData: (prev) => prev,
});
}
/**
* One-shot PDF archive upload. Returns the new document_id so the
* caller can pass it into useCreatePrecedent. No cache invalidation
* — we only care about the id as a handle.
*/
export async function uploadPrecedentPdf(
caseNumber: string,
file: File,
): Promise<{ document_id: string; filename: string }> {
const fd = new FormData();
fd.append("file", file);
const res = await fetch(
`/api/cases/${encodeURIComponent(caseNumber)}/precedents/upload-pdf`,
{ method: "POST", body: fd },
);
const parsed = await res.json().catch(() => null);
if (!res.ok) {
throw new ApiError(
`Upload failed with ${res.status}`,
res.status,
parsed,
);
}
return parsed as { document_id: string; filename: string };
}