feat: external precedent library with auto halacha extraction
All checks were successful
Build & Deploy / build-and-deploy (push) Successful in 1m27s

Adds a third corpus of legal authority distinct from style_corpus
(Daphna's prior decisions for voice) and case_precedents (chair-attached
quotes per case). The new corpus holds chair-uploaded court rulings and
other appeals committee decisions, with binding rules (הלכות) extracted
automatically and queued for chair approval.

Pipeline (web/app.py + services/precedent_library.py):
file → extract → chunk → Voyage embed → halacha_extractor → store +
publish progress over the existing Redis SSE channel.

Schema V7 (services/db.py): extends case_law with source_kind +
extraction status fields under a CHECK constraint pinning practice_area
to the three appeals committee domains (rishuy_uvniya, betterment_levy,
compensation_197). New precedent_chunks (vector(1024)) and halachot
tables (vector(1024) over rule_statement, IVFFlat indexes, gin on
practice_areas/subject_tags). Halachot start as pending_review; only
approved/published rows are visible to search_precedent_library.

Agents: legal-writer, legal-researcher, legal-analyst, legal-ceo,
legal-qa get search_precedent_library. legal-writer prompt explains
the three-corpus distinction and CREAC use; legal-qa now verifies that
every cited halacha resolves to an approved row in the corpus.

UI: /precedents page with four tabs — library / semantic search /
pending review (J/K nav, A/R/E shortcuts, badge count) / stats.
Reuses the existing upload-sheet progress + SSE pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-03 08:38:18 +00:00
parent a6edb75bbf
commit 7ee90dce31
23 changed files with 3853 additions and 67 deletions

View File

@@ -26,6 +26,7 @@ const NAV_ITEMS: NavItem[] = [
{ href: "/", label: "בית" },
{ href: "/archive", label: "ארכיון" },
{ href: "/training", label: "אימון סגנון" },
{ href: "/precedents", label: "ספריית פסיקה" },
{ href: "/methodology", label: "מתודולוגיה" },
{ href: "/skills", label: "מיומנויות" },
{ href: "/diagnostics", label: "אבחון" },

View File

@@ -0,0 +1,348 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { Check, X, Edit2, ChevronDown, ChevronUp, AlertTriangle } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import {
useHalachotPending, useUpdateHalacha, type Halacha,
} from "@/lib/api/precedent-library";
/**
* Halacha review queue — the chair-only path between automatic
* extraction and agent visibility. Per the project's review policy,
* NO halacha is auto-published; every row sits in pending_review until
* approved.
*
* UX is optimised for high-throughput approval:
* - Keyboard: J/K cycle rows, A approve, R reject, E edit, Esc cancel
* - Side-by-side: rule_statement vs supporting_quote
* - Quote-verified pill: green check or red triangle
* - Confidence sort: low-confidence rows shown first to be skeptical of
*/
function formatDate(iso: string | null | undefined) {
if (!iso) return "—";
try {
return new Date(iso).toLocaleDateString("he-IL");
} catch {
return iso;
}
}
type EditState = { rule_statement: string; reasoning_summary: string };
function HalachaCard({
h, focused, onApprove, onReject, onSave,
}: {
h: Halacha;
focused: boolean;
onApprove: () => void;
onReject: () => void;
onSave: (patch: Partial<EditState>) => Promise<void>;
}) {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState<EditState>({
rule_statement: h.rule_statement,
reasoning_summary: h.reasoning_summary,
});
// Reset the editable draft whenever the underlying halacha row changes
// (id or any of its synced fields). Cascade-render is intentional here —
// the form is keyed off the row so a re-mount would also work but loses
// editing affordances on rapid navigation.
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
setDraft({
rule_statement: h.rule_statement,
reasoning_summary: h.reasoning_summary,
});
}, [h.id, h.rule_statement, h.reasoning_summary]);
const onSubmitEdit = async () => {
await onSave(draft);
setEditing(false);
};
return (
<div
data-halacha-id={h.id}
className={`
rounded-lg border bg-surface p-4 space-y-3 transition-colors
${focused ? "border-gold ring-2 ring-gold/40 shadow-md" : "border-rule"}
`}
>
{/* Header */}
<div className="flex items-start gap-2 text-[0.78rem] text-ink-muted flex-wrap">
<span className="font-mono text-navy" dir="ltr">{h.case_number ?? "—"}</span>
{h.court && <span>· {h.court}</span>}
{h.decision_date && <span>· {formatDate(h.decision_date)}</span>}
{h.precedent_level && <span>· {h.precedent_level}</span>}
<span className="ms-auto flex items-center gap-2">
{h.quote_verified ? (
<Badge variant="outline" className="text-[0.65rem] bg-gold-wash text-gold-deep border-gold/40">
<Check className="w-3 h-3 me-1" /> ציטוט מאומת
</Badge>
) : (
<Badge variant="outline" className="text-[0.65rem] bg-danger-bg text-danger border-danger/40">
<AlertTriangle className="w-3 h-3 me-1" /> ציטוט לא מאומת
</Badge>
)}
<Badge variant="outline" className="text-[0.65rem] tabular-nums">
confidence {h.confidence.toFixed(2)}
</Badge>
<Badge variant="outline" className="text-[0.65rem]">
{h.rule_type}
</Badge>
</span>
</div>
{/* Side-by-side rule vs quote */}
<div className="grid md:grid-cols-2 gap-3">
<div>
<div className="text-[0.7rem] text-ink-muted mb-1">ניסוח הכלל</div>
{editing ? (
<Textarea
value={draft.rule_statement} rows={4} dir="rtl"
onChange={(e) => setDraft({ ...draft, rule_statement: e.target.value })}
className="bg-gold-wash/50 border-gold/30"
/>
) : (
<p className="text-navy font-medium leading-relaxed" dir="rtl">
{h.rule_statement}
</p>
)}
</div>
<div>
<div className="text-[0.7rem] text-ink-muted mb-1">
ציטוט תומך
{h.page_reference && (
<span className="ms-2 text-[0.65rem]">({h.page_reference})</span>
)}
</div>
<blockquote className="text-ink-soft text-sm leading-relaxed border-r-2 border-gold pr-3" dir="rtl">
&ldquo;{h.supporting_quote}&rdquo;
</blockquote>
</div>
</div>
{/* Reasoning + tags (collapsible) */}
{(editing || h.reasoning_summary) && (
<div>
<div className="text-[0.7rem] text-ink-muted mb-1">תמצית ההיגיון</div>
{editing ? (
<Textarea
value={draft.reasoning_summary} rows={2} dir="rtl"
onChange={(e) => setDraft({ ...draft, reasoning_summary: e.target.value })}
className="bg-gold-wash/50 border-gold/30"
/>
) : (
<p className="text-ink-soft text-sm leading-relaxed" dir="rtl">
{h.reasoning_summary}
</p>
)}
</div>
)}
<div className="flex items-center gap-2 flex-wrap">
{h.practice_areas?.map((p) => (
<Badge key={p} variant="outline" className="text-[0.65rem] bg-navy-soft/30 text-navy">
{p}
</Badge>
))}
{h.subject_tags?.map((t) => (
<Badge key={t} variant="outline" className="text-[0.65rem]">
{t}
</Badge>
))}
</div>
<div className="flex items-center gap-2 justify-end pt-1 border-t border-rule-soft">
{editing ? (
<>
<Button size="sm" variant="ghost" onClick={() => setEditing(false)}>
ביטול
</Button>
<Button size="sm" onClick={onSubmitEdit}
className="bg-navy text-parchment hover:bg-navy-soft">
שמור שינויים
</Button>
</>
) : (
<>
<Button size="sm" variant="ghost" onClick={() => setEditing(true)}>
<Edit2 className="w-3.5 h-3.5 me-1" />
ערוך (E)
</Button>
<Button size="sm" variant="ghost"
onClick={onReject}
className="text-danger hover:text-danger hover:bg-danger-bg">
<X className="w-3.5 h-3.5 me-1" />
דחה (R)
</Button>
<Button size="sm" onClick={onApprove}
className="bg-gold text-navy hover:bg-gold-deep">
<Check className="w-3.5 h-3.5 me-1" />
אשר (A)
</Button>
</>
)}
</div>
</div>
);
}
export function HalachaReviewPanel() {
const { data, isPending, error } = useHalachotPending(500);
const update = useUpdateHalacha();
const [focusIdx, setFocusIdx] = useState(0);
// Sort: low confidence first → forces the chair to scrutinize doubtful rows
const items = useMemo(() => {
const list = [...(data?.items ?? [])];
list.sort((a, b) => a.confidence - b.confidence);
return list;
}, [data]);
// Keep focus index in range as items change (e.g. after approve/reject
// shrinks the queue). Cascade-render is intentional and bounded.
useEffect(() => {
if (focusIdx >= items.length && items.length > 0) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setFocusIdx(items.length - 1);
}
}, [items.length, focusIdx]);
// Scroll the focused row into view
useEffect(() => {
if (!items.length) return;
const target = items[focusIdx];
if (!target) return;
const el = document.querySelector(`[data-halacha-id="${target.id}"]`);
el?.scrollIntoView({ block: "nearest", behavior: "smooth" });
}, [focusIdx, items]);
const focused = items[focusIdx];
const review = async (
h: Halacha,
status: "approved" | "rejected",
extra?: Partial<EditState>,
) => {
try {
await update.mutateAsync({
id: h.id,
patch: {
review_status: status,
...extra,
},
});
toast.success(status === "approved" ? "אושר" : "נדחה");
} catch (e) {
toast.error(e instanceof Error ? e.message : "שגיאה");
}
};
// Keyboard navigation
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement)?.tagName?.toLowerCase();
if (tag === "input" || tag === "textarea") return;
if (!focused) return;
if (e.key === "j") {
e.preventDefault();
setFocusIdx((i) => Math.min(items.length - 1, i + 1));
} else if (e.key === "k") {
e.preventDefault();
setFocusIdx((i) => Math.max(0, i - 1));
} else if (e.key === "a" || e.key === "A") {
e.preventDefault();
review(focused, "approved");
} else if (e.key === "r" || e.key === "R") {
e.preventDefault();
if (window.confirm("לדחות הלכה זו?")) {
review(focused, "rejected");
}
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [focused, items.length]);
if (error) {
return (
<div className="rounded bg-danger-bg border border-danger/40 px-6 py-5 text-danger text-center">
{error.message}
</div>
);
}
if (isPending) {
return (
<div className="space-y-3">
{[...Array(3)].map((_, i) => <Skeleton key={i} className="h-40 w-full" />)}
</div>
);
}
if (!items.length) {
return (
<div className="text-center text-ink-muted py-16">
<p className="text-lg">אין הלכות הממתינות לאישור.</p>
<p className="text-sm mt-2">העלה פסיקה חדשה ההלכות שיחולצו ממנה יופיעו כאן.</p>
</div>
);
}
return (
<div className="space-y-4">
<div className="flex items-center gap-3 text-sm text-ink-muted">
<span>
<span className="text-navy font-semibold">{items.length}</span> ממתינות לאישור
</span>
<span className="me-auto text-[0.72rem]">
ניווט: <kbd className="bg-rule-soft px-1.5 rounded">J</kbd>/<kbd className="bg-rule-soft px-1.5 rounded">K</kbd>
{" "}· אישור: <kbd className="bg-rule-soft px-1.5 rounded">A</kbd>
{" "}· דחייה: <kbd className="bg-rule-soft px-1.5 rounded">R</kbd>
{" "}· עריכה: <kbd className="bg-rule-soft px-1.5 rounded">E</kbd>
</span>
<Button
size="sm" variant="ghost"
onClick={() => setFocusIdx((i) => Math.max(0, i - 1))}
disabled={focusIdx === 0}>
<ChevronUp className="w-4 h-4" />
</Button>
<Button
size="sm" variant="ghost"
onClick={() => setFocusIdx((i) => Math.min(items.length - 1, i + 1))}
disabled={focusIdx >= items.length - 1}>
<ChevronDown className="w-4 h-4" />
</Button>
</div>
<div className="space-y-4">
{items.map((h, i) => (
<HalachaCard
key={h.id} h={h} focused={i === focusIdx}
onApprove={() => review(h, "approved")}
onReject={() => {
if (window.confirm("לדחות הלכה זו?")) review(h, "rejected");
}}
onSave={async (patch) => {
try {
await update.mutateAsync({ id: h.id, patch });
toast.success("נשמר");
} catch (e) {
toast.error(e instanceof Error ? e.message : "שגיאה");
}
}}
/>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,235 @@
"use client";
import { useState } from "react";
import { Trash2, Plus, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
usePrecedents,
useDeletePrecedent,
useReExtractHalachot,
type Precedent,
type PracticeArea,
} from "@/lib/api/precedent-library";
import { PRACTICE_AREAS, PRECEDENT_LEVELS, practiceAreaShort } from "./practice-area";
import { PrecedentUploadSheet } from "./precedent-upload-sheet";
function formatDate(iso: string | null) {
if (!iso) return "—";
try {
return new Date(iso).toLocaleDateString("he-IL");
} catch {
return iso;
}
}
function StatusPill({ p }: { p: Precedent }) {
if (p.extraction_status === "failed") {
return <Badge variant="outline" className="bg-danger-bg text-danger border-danger/40">נכשל</Badge>;
}
if (p.extraction_status !== "completed") {
return <Badge variant="outline" className="bg-rule-soft text-ink-muted">בעיבוד</Badge>;
}
if (p.halacha_extraction_status !== "completed") {
return <Badge variant="outline" className="bg-gold-wash text-gold-deep">מחלץ הלכות</Badge>;
}
if (p.halachot_count === 0) {
return <Badge variant="outline">ללא הלכות</Badge>;
}
return (
<Badge
variant="outline"
className="bg-gold-wash text-gold-deep border-gold/40"
>
{p.approved_count}/{p.halachot_count} מאושרות
</Badge>
);
}
function PrecedentRow({ p }: { p: Precedent }) {
const del = useDeletePrecedent();
const reExtract = useReExtractHalachot();
const onDelete = async () => {
if (!window.confirm(`למחוק את ${p.case_number}? cascade ימחק את ה-chunks וההלכות.`)) return;
try {
await del.mutateAsync(p.id);
toast.success("נמחק");
} catch (e) {
toast.error(e instanceof Error ? e.message : "שגיאה");
}
};
const onReExtract = async () => {
try {
await reExtract.mutateAsync(p.id);
toast.success("חילוץ הלכות החל");
} catch (e) {
toast.error(e instanceof Error ? e.message : "שגיאה");
}
};
return (
<TableRow className="border-rule hover:bg-gold-wash/30">
<TableCell className="font-semibold text-navy" dir="ltr">
{p.case_number}
</TableCell>
<TableCell className="text-ink">
<div className="font-medium">{p.case_name || "—"}</div>
<div className="text-[0.72rem] text-ink-muted">{p.court || "—"}</div>
</TableCell>
<TableCell className="text-ink-muted">{formatDate(p.date)}</TableCell>
<TableCell>
{p.practice_area ? (
<Badge variant="outline" className="bg-navy-soft/40 text-navy border-navy/30">
{practiceAreaShort(p.practice_area)}
</Badge>
) : (
<span className="text-ink-light"></span>
)}
</TableCell>
<TableCell className="text-ink-muted text-[0.78rem]">
{p.precedent_level || "—"}
</TableCell>
<TableCell>
<StatusPill p={p} />
</TableCell>
<TableCell className="text-end">
<div className="flex items-center gap-1 justify-end">
<Button
variant="ghost" size="sm" onClick={onReExtract}
disabled={reExtract.isPending}
aria-label="חלץ הלכות מחדש"
title="חלץ הלכות מחדש"
className="text-ink-muted hover:text-navy"
>
<RefreshCw className="w-4 h-4" />
</Button>
<Button
variant="ghost" size="sm" onClick={onDelete}
disabled={del.isPending}
aria-label={`מחק את ${p.case_number}`}
className="text-danger hover:text-danger hover:bg-danger-bg"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</TableCell>
</TableRow>
);
}
export function LibraryListPanel() {
const [practiceArea, setPracticeArea] = useState<PracticeArea>("");
const [precedentLevel, setPrecedentLevel] = useState("");
const [search, setSearch] = useState("");
const [uploadOpen, setUploadOpen] = useState(false);
const { data, isPending, error } = usePrecedents({
practiceArea: practiceArea || undefined,
precedentLevel: precedentLevel || undefined,
search: search.trim() || undefined,
limit: 200,
});
return (
<div className="space-y-4">
<div className="flex items-end gap-3 flex-wrap">
<div className="flex-1 min-w-[200px]">
<label className="text-[0.78rem] text-ink-muted">חיפוש (מספר תיק / שם / תקציר)</label>
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="עע&quot;מ 3975/22"
dir="rtl"
/>
</div>
<div className="min-w-[180px]">
<label className="text-[0.78rem] text-ink-muted">תחום</label>
<Select value={practiceArea || "_all"} onValueChange={(v) => setPracticeArea(v === "_all" ? "" : v as PracticeArea)}>
<SelectTrigger><SelectValue placeholder="הכל" /></SelectTrigger>
<SelectContent>
<SelectItem value="_all">הכל</SelectItem>
{PRACTICE_AREAS.map((a) => (
<SelectItem key={a.value} value={a.value}>{a.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="min-w-[170px]">
<label className="text-[0.78rem] text-ink-muted">רמת תקדים</label>
<Select value={precedentLevel || "_all"} onValueChange={(v) => setPrecedentLevel(v === "_all" ? "" : v)}>
<SelectTrigger><SelectValue placeholder="הכל" /></SelectTrigger>
<SelectContent>
<SelectItem value="_all">הכל</SelectItem>
{PRECEDENT_LEVELS.map((l) => (
<SelectItem key={l.value} value={l.value}>{l.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button onClick={() => setUploadOpen(true)} className="bg-navy text-parchment hover:bg-navy-soft">
<Plus className="w-4 h-4 me-1" />
העלאת פסיקה
</Button>
</div>
{error ? (
<div className="rounded bg-danger-bg border border-danger/40 px-6 py-5 text-danger text-center">
{error.message}
</div>
) : (
<div className="rounded-lg border border-rule bg-surface shadow-sm overflow-hidden">
<Table>
<TableHeader className="bg-rule-soft/60">
<TableRow className="border-rule">
<TableHead className="text-navy text-right">מס׳ / מראה מקום</TableHead>
<TableHead className="text-navy text-right">שם / ערכאה</TableHead>
<TableHead className="text-navy text-right">תאריך</TableHead>
<TableHead className="text-navy text-right">תחום</TableHead>
<TableHead className="text-navy text-right">רמה</TableHead>
<TableHead className="text-navy text-right">הלכות</TableHead>
<TableHead className="text-navy" />
</TableRow>
</TableHeader>
<TableBody>
{isPending ? (
[...Array(5)].map((_, i) => (
<TableRow key={i} className="border-rule">
{[...Array(7)].map((_, j) => (
<TableCell key={j}>
<Skeleton className="h-5 w-full" />
</TableCell>
))}
</TableRow>
))
) : !data?.items.length ? (
<TableRow className="border-rule">
<TableCell colSpan={7} className="text-center text-ink-muted py-10">
אין פסיקה בקורפוס. העלה את פסק הדין הראשון.
</TableCell>
</TableRow>
) : (
data.items.map((p) => <PrecedentRow key={p.id} p={p} />)
)}
</TableBody>
</Table>
</div>
)}
<PrecedentUploadSheet open={uploadOpen} onOpenChange={setUploadOpen} />
</div>
);
}

View File

@@ -0,0 +1,173 @@
"use client";
import { useState } from "react";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
useLibrarySearch, type PracticeArea, type SearchHit,
} from "@/lib/api/precedent-library";
import { PRACTICE_AREAS, PRECEDENT_LEVELS } from "./practice-area";
function formatDate(iso: string | null) {
if (!iso) return "—";
try {
return new Date(iso).toLocaleDateString("he-IL");
} catch {
return iso;
}
}
function HalachaCard({ hit }: { hit: Extract<SearchHit, { type: "halacha" }> }) {
return (
<div className="rounded-lg border border-gold/40 bg-gold-wash/40 p-4 space-y-2">
<div className="flex items-center gap-2 text-[0.78rem] text-ink-muted flex-wrap">
<Badge className="bg-gold text-navy border-0">הלכה</Badge>
<span className="font-mono" dir="ltr">{hit.case_number}</span>
{hit.court && <span>· {hit.court}</span>}
{hit.decision_date && <span>· {formatDate(hit.decision_date)}</span>}
{hit.precedent_level && <span>· {hit.precedent_level}</span>}
<span className="ms-auto tabular-nums">דירוג {hit.score.toFixed(2)}</span>
</div>
<p className="text-navy font-medium text-[0.95rem]" dir="rtl">
{hit.rule_statement}
</p>
<blockquote className="text-ink-soft text-sm border-r-2 border-gold pr-3" dir="rtl">
&ldquo;{hit.supporting_quote}&rdquo;
{hit.page_reference && <span className="text-ink-muted text-[0.72rem] ms-2">({hit.page_reference})</span>}
</blockquote>
{hit.subject_tags?.length > 0 && (
<div className="flex flex-wrap gap-1">
{hit.subject_tags.map((t) => (
<Badge key={t} variant="outline" className="text-[0.65rem] bg-surface">
{t}
</Badge>
))}
</div>
)}
</div>
);
}
function PassageCard({ hit }: { hit: Extract<SearchHit, { type: "passage" }> }) {
return (
<div className="rounded-lg border border-rule bg-surface p-4 space-y-2">
<div className="flex items-center gap-2 text-[0.78rem] text-ink-muted flex-wrap">
<Badge variant="outline" className="bg-rule-soft text-ink-muted">קטע</Badge>
<span className="font-mono" dir="ltr">{hit.case_number}</span>
{hit.court && <span>· {hit.court}</span>}
{hit.decision_date && <span>· {formatDate(hit.decision_date)}</span>}
<span className="text-[0.7rem]">· {hit.section_type}</span>
<span className="ms-auto tabular-nums">דירוג {hit.score.toFixed(2)}</span>
</div>
<p className="text-ink text-sm leading-relaxed" dir="rtl">
{hit.content.slice(0, 600)}
{hit.content.length > 600 && <span></span>}
</p>
</div>
);
}
export function LibrarySearchPanel() {
const [draft, setDraft] = useState("");
const [query, setQuery] = useState("");
const [practiceArea, setPracticeArea] = useState<PracticeArea>("");
const [precedentLevel, setPrecedentLevel] = useState("");
const [includeHalachot, setIncludeHalachot] = useState(true);
const { data, isFetching, error } = useLibrarySearch(query, {
practiceArea: practiceArea || undefined,
precedentLevel: precedentLevel || undefined,
includeHalachot,
limit: 20,
});
const onSubmit = (e: React.FormEvent) => {
e.preventDefault();
setQuery(draft.trim());
};
return (
<div className="space-y-4">
<form onSubmit={onSubmit} className="flex items-end gap-3 flex-wrap">
<div className="flex-1 min-w-[300px]">
<label className="text-[0.78rem] text-ink-muted">שאילתת חיפוש</label>
<Input value={draft} onChange={(e) => setDraft(e.target.value)}
placeholder="השבחה אובייקטיבית" dir="rtl" />
</div>
<div className="min-w-[180px]">
<label className="text-[0.78rem] text-ink-muted">תחום</label>
<Select value={practiceArea || "_all"}
onValueChange={(v) => setPracticeArea(v === "_all" ? "" : v as PracticeArea)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="_all">הכל</SelectItem>
{PRACTICE_AREAS.map((a) => (
<SelectItem key={a.value} value={a.value}>{a.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="min-w-[170px]">
<label className="text-[0.78rem] text-ink-muted">רמת תקדים</label>
<Select value={precedentLevel || "_all"}
onValueChange={(v) => setPrecedentLevel(v === "_all" ? "" : v)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="_all">הכל</SelectItem>
{PRECEDENT_LEVELS.map((l) => (
<SelectItem key={l.value} value={l.value}>{l.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button type="submit" className="bg-navy text-parchment hover:bg-navy-soft">
<Search className="w-4 h-4 me-1" />
חפש
</Button>
</form>
<label className="flex items-center gap-2 cursor-pointer text-sm text-ink-muted">
<input type="checkbox" checked={includeHalachot}
onChange={(e) => setIncludeHalachot(e.target.checked)} />
כלול הלכות (rule-level matches)
</label>
{!query.trim() ? (
<div className="text-center text-ink-muted py-12">
הקלד שאילתא כדי לחפש בקורפוס. החיפוש סמנטי לא טקסטואלי.
</div>
) : error ? (
<div className="rounded bg-danger-bg border border-danger/40 px-6 py-5 text-danger text-center">
{error.message}
</div>
) : isFetching ? (
<div className="space-y-3">
{[...Array(3)].map((_, i) => <Skeleton key={i} className="h-24 w-full" />)}
</div>
) : !data?.items.length ? (
<div className="text-center text-ink-muted py-12">
לא נמצאו תוצאות. נסה ניסוח אחר או הסר פילטרים.
</div>
) : (
<div className="space-y-3">
<p className="text-[0.78rem] text-ink-muted">
{data.count} תוצאות (הלכות מאושרות בלבד)
</p>
{data.items.map((hit, i) =>
hit.type === "halacha" ? (
<HalachaCard key={`h-${hit.halacha_id ?? i}`} hit={hit} />
) : (
<PassageCard key={`p-${hit.chunk_id ?? i}`} hit={hit} />
),
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,89 @@
"use client";
import { Skeleton } from "@/components/ui/skeleton";
import { useLibraryStats } from "@/lib/api/precedent-library";
import { practiceAreaLabel } from "./practice-area";
function StatCard({ label, value, accent }: { label: string; value: number | string; accent?: boolean }) {
return (
<div
className={`
rounded-lg border p-5 bg-surface shadow-sm
${accent ? "border-gold bg-gold-wash/40" : "border-rule"}
`}
>
<div className="text-[0.78rem] text-ink-muted mb-1">{label}</div>
<div className={`text-3xl font-bold tabular-nums ${accent ? "text-gold-deep" : "text-navy"}`}>
{value}
</div>
</div>
);
}
export function LibraryStatsPanel() {
const { data, isPending, error } = useLibraryStats();
if (error) {
return (
<div className="rounded bg-danger-bg border border-danger/40 px-6 py-5 text-danger text-center">
{error.message}
</div>
);
}
if (isPending || !data) {
return (
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{[...Array(4)].map((_, i) => <Skeleton key={i} className="h-28 w-full" />)}
</div>
);
}
return (
<div className="space-y-6">
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<StatCard label="פסיקה בקורפוס" value={data.precedents_total} />
<StatCard label="הלכות בסך הכל" value={data.halachot_total} />
<StatCard
label="ממתינות לאישור" value={data.halachot_pending}
accent={data.halachot_pending > 0}
/>
<StatCard label="מאושרות (זמינות לסוכנים)" value={data.halachot_approved} />
</div>
<div className="grid md:grid-cols-2 gap-4">
<div className="rounded-lg border border-rule bg-surface p-5">
<h3 className="text-navy font-semibold mb-3">פילוח לפי תחום</h3>
{data.by_practice_area.length === 0 ? (
<p className="text-ink-muted text-sm">אין נתונים</p>
) : (
<ul className="space-y-2">
{data.by_practice_area.map((row) => (
<li key={row.practice_area || "—"} className="flex items-center gap-2 text-sm">
<span className="text-ink">{practiceAreaLabel(row.practice_area || null)}</span>
<span className="ms-auto tabular-nums text-navy font-semibold">{row.count}</span>
</li>
))}
</ul>
)}
</div>
<div className="rounded-lg border border-rule bg-surface p-5">
<h3 className="text-navy font-semibold mb-3">פילוח לפי רמת תקדים</h3>
{data.by_precedent_level.length === 0 ? (
<p className="text-ink-muted text-sm">אין נתונים</p>
) : (
<ul className="space-y-2">
{data.by_precedent_level.map((row) => (
<li key={row.precedent_level || "—"} className="flex items-center gap-2 text-sm">
<span className="text-ink">{row.precedent_level || "—"}</span>
<span className="ms-auto tabular-nums text-navy font-semibold">{row.count}</span>
</li>
))}
</ul>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,37 @@
/**
* Practice-area constants for the precedent library.
*
* The chair confined the library to the three appeals committee
* domains — no national-insurance corpus. The DB enforces this
* via a CHECK constraint on case_law.practice_area.
*/
export const PRACTICE_AREAS = [
{ value: "rishuy_uvniya", label: "רישוי ובניה", short: "רישוי" },
{ value: "betterment_levy", label: "היטל השבחה", short: "השבחה" },
{ value: "compensation_197", label: "פיצויים לפי ס' 197", short: "פיצויים" },
] as const;
export const PRECEDENT_LEVELS = [
{ value: "עליון", label: "עליון" },
{ value: "מנהלי", label: "מנהלי" },
{ value: "ועדת_ערר_ארצית", label: "ועדת ערר ארצית" },
{ value: "ועדת_ערר_מחוזית", label: "ועדת ערר מחוזית" },
] as const;
export const SOURCE_TYPES = [
{ value: "court_ruling", label: "פסק דין" },
{ value: "appeals_committee", label: "החלטת ועדת ערר" },
] as const;
export function practiceAreaLabel(value: string | null | undefined): string {
if (!value) return "—";
const match = PRACTICE_AREAS.find((p) => p.value === value);
return match ? match.label : value;
}
export function practiceAreaShort(value: string | null | undefined): string {
if (!value) return "—";
const match = PRACTICE_AREAS.find((p) => p.value === value);
return match ? match.short : value;
}

View File

@@ -0,0 +1,290 @@
"use client";
import { useEffect, useState } from "react";
import { Upload, Loader2, CheckCircle2, AlertCircle } from "lucide-react";
import { toast } from "sonner";
import {
Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription,
} from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Progress } from "@/components/ui/progress";
import { useUploadPrecedent, type PracticeArea, type SourceType } from "@/lib/api/precedent-library";
import { useProgress } from "@/lib/api/documents";
import {
PRACTICE_AREAS, PRECEDENT_LEVELS, SOURCE_TYPES,
} from "./practice-area";
const ACCEPT = ".pdf,.docx,.doc,.rtf,.txt,.md";
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
};
export function PrecedentUploadSheet({ open, onOpenChange }: Props) {
const [file, setFile] = useState<File | null>(null);
const [citation, setCitation] = useState("");
const [caseName, setCaseName] = useState("");
const [court, setCourt] = useState("");
const [decisionDate, setDecisionDate] = useState("");
const [sourceType, setSourceType] = useState<SourceType>("");
const [precedentLevel, setPrecedentLevel] = useState("");
const [practiceArea, setPracticeArea] = useState<PracticeArea>("");
const [appealSubtype, setAppealSubtype] = useState("");
const [subjectTags, setSubjectTags] = useState("");
const [headnote, setHeadnote] = useState("");
const [isBinding, setIsBinding] = useState(true);
const [taskId, setTaskId] = useState<string | null>(null);
const upload = useUploadPrecedent();
const progress = useProgress(taskId);
// Reset form when the sheet closes — fields, file input, and any in-flight
// task subscription. We accept the cascade-render warning because resetting
// form state on close is exactly the intended side effect.
useEffect(() => {
if (open) return;
// eslint-disable-next-line react-hooks/set-state-in-effect
setFile(null); setCitation(""); setCaseName(""); setCourt("");
// eslint-disable-next-line react-hooks/set-state-in-effect
setDecisionDate(""); setSourceType(""); setPrecedentLevel("");
// eslint-disable-next-line react-hooks/set-state-in-effect
setPracticeArea(""); setAppealSubtype(""); setSubjectTags("");
// eslint-disable-next-line react-hooks/set-state-in-effect
setHeadnote(""); setIsBinding(true); setTaskId(null);
}, [open]);
// Auto-close on completion
useEffect(() => {
if (progress?.status === "completed") {
toast.success("הפסיקה הוכנסה לקורפוס. ההלכות ממתינות לאישור.");
const t = window.setTimeout(() => onOpenChange(false), 1200);
return () => window.clearTimeout(t);
}
if (progress?.status === "failed") {
toast.error(`כשל בעיבוד: ${progress.error || "שגיאה לא ידועה"}`);
}
}, [progress, onOpenChange]);
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!file) {
toast.error("בחר קובץ");
return;
}
if (!citation.trim()) {
toast.error("מראה המקום (citation) חובה");
return;
}
if (!practiceArea) {
toast.error("בחר תחום משפט");
return;
}
try {
const tags = subjectTags
.split(",")
.map((t) => t.trim())
.filter(Boolean);
const res = await upload.mutateAsync({
file,
citation: citation.trim(),
case_name: caseName.trim(),
court: court.trim(),
decision_date: decisionDate || undefined,
source_type: sourceType || undefined,
precedent_level: precedentLevel || undefined,
practice_area: practiceArea,
appeal_subtype: appealSubtype.trim(),
subject_tags: tags,
is_binding: isBinding,
headnote: headnote.trim(),
});
setTaskId(res.task_id);
} catch (err) {
toast.error(err instanceof Error ? err.message : "כשל בהעלאה");
}
};
const isProcessing = taskId !== null && progress?.status !== "completed" && progress?.status !== "failed";
const stage = (progress as { stage?: string; percent?: number; step?: string } | null)?.stage;
const percent = (progress as { percent?: number } | null)?.percent ?? 0;
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent side="left" className="w-full sm:max-w-2xl overflow-y-auto" dir="rtl">
<SheetHeader>
<SheetTitle className="text-navy">העלאת פסיקה לקורפוס הסמכותי</SheetTitle>
<SheetDescription className="text-ink-muted">
הקובץ יעבור חילוץ טקסט, יצירת embeddings, וחילוץ הלכות אוטומטי.
ההלכות יחכו לאישורך לפני שהן זמינות לסוכני הכתיבה.
</SheetDescription>
</SheetHeader>
<form onSubmit={onSubmit} className="px-6 pb-6 space-y-4 mt-4">
{/* File */}
<div className="space-y-1">
<Label htmlFor="file">קובץ (PDF / DOCX / DOC / RTF / TXT / MD)</Label>
<Input
id="file" type="file" accept={ACCEPT}
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
disabled={isProcessing}
/>
</div>
{/* Citation */}
<div className="space-y-1">
<Label htmlFor="citation">מראה המקום (חובה)</Label>
<Input
id="citation" value={citation}
onChange={(e) => setCitation(e.target.value)}
placeholder={`עע"מ 3975/22 ב. קרן-נכסים נ' ועדה מקומית`}
disabled={isProcessing} dir="rtl"
/>
</div>
{/* Two-col grid */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor="case-name">שם קצר</Label>
<Input id="case-name" value={caseName}
onChange={(e) => setCaseName(e.target.value)}
placeholder="ב. קרן-נכסים" disabled={isProcessing} />
</div>
<div className="space-y-1">
<Label htmlFor="court">ערכאה</Label>
<Input id="court" value={court}
onChange={(e) => setCourt(e.target.value)}
placeholder='בית משפט עליון / בג"ץ / מנהלי / ועדת ערר'
disabled={isProcessing} />
</div>
<div className="space-y-1">
<Label htmlFor="date">תאריך החלטה</Label>
<Input id="date" type="date" value={decisionDate}
onChange={(e) => setDecisionDate(e.target.value)}
disabled={isProcessing} />
</div>
<div className="space-y-1">
<Label htmlFor="appeal-subtype">תת-סוג (חופשי)</Label>
<Input id="appeal-subtype" value={appealSubtype}
onChange={(e) => setAppealSubtype(e.target.value)}
placeholder="שימוש חורג / סופיות ההחלטה" disabled={isProcessing} />
</div>
</div>
{/* Practice area (required radio) */}
<div className="space-y-1">
<Label>תחום משפט (חובה)</Label>
<div className="flex gap-4 flex-wrap">
{PRACTICE_AREAS.map((a) => (
<label key={a.value} className="flex items-center gap-2 cursor-pointer">
<input
type="radio" name="practice_area" value={a.value}
checked={practiceArea === a.value}
onChange={() => setPracticeArea(a.value as PracticeArea)}
disabled={isProcessing}
/>
<span className="text-sm text-ink">{a.label}</span>
</label>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label htmlFor="source-type">סוג מקור</Label>
<Select value={sourceType || "_none"}
onValueChange={(v) => setSourceType(v === "_none" ? "" : v as SourceType)}
disabled={isProcessing}>
<SelectTrigger><SelectValue placeholder="—" /></SelectTrigger>
<SelectContent>
<SelectItem value="_none"></SelectItem>
{SOURCE_TYPES.map((s) => (
<SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor="precedent-level">רמת תקדים</Label>
<Select value={precedentLevel || "_none"}
onValueChange={(v) => setPrecedentLevel(v === "_none" ? "" : v)}
disabled={isProcessing}>
<SelectTrigger><SelectValue placeholder="—" /></SelectTrigger>
<SelectContent>
<SelectItem value="_none"></SelectItem>
{PRECEDENT_LEVELS.map((l) => (
<SelectItem key={l.value} value={l.value}>{l.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-1">
<Label htmlFor="tags">תגיות נושא (מופרדות בפסיקים)</Label>
<Input id="tags" value={subjectTags}
onChange={(e) => setSubjectTags(e.target.value)}
placeholder="חניה, קווי בניין, שיקול דעת" disabled={isProcessing} />
</div>
<div className="space-y-1">
<Label htmlFor="headnote">תקציר / headnote (אופציונלי)</Label>
<Textarea id="headnote" value={headnote} rows={2}
onChange={(e) => setHeadnote(e.target.value)}
placeholder="תקציר חופשי שיוצג ברשימה" disabled={isProcessing} dir="rtl" />
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={isBinding}
onChange={(e) => setIsBinding(e.target.checked)}
disabled={isProcessing} />
<span className="text-sm">הלכה מחייבת</span>
</label>
{isProcessing && (
<div className="rounded-lg border border-rule bg-rule-soft/40 p-4 space-y-2">
<div className="flex items-center gap-2 text-sm text-navy">
<Loader2 className="w-4 h-4 animate-spin" />
<span>{(progress as { step?: string } | null)?.step || stage || "מעבד"}</span>
</div>
<Progress value={percent} className="h-1.5" />
</div>
)}
{progress?.status === "completed" && (
<div className="rounded-lg border border-gold/40 bg-gold-wash p-4 flex items-center gap-2 text-gold-deep text-sm">
<CheckCircle2 className="w-4 h-4" />
נכנס לקורפוס. ההלכות ממתינות בתור האישור.
</div>
)}
{progress?.status === "failed" && (
<div className="rounded-lg border border-danger/40 bg-danger-bg p-4 flex items-center gap-2 text-danger text-sm">
<AlertCircle className="w-4 h-4" />
{progress.error || "שגיאה"}
</div>
)}
<div className="flex gap-2 justify-end pt-2">
<Button type="button" variant="ghost"
onClick={() => onOpenChange(false)} disabled={upload.isPending}>
ביטול
</Button>
<Button type="submit"
disabled={upload.isPending || isProcessing}
className="bg-navy text-parchment hover:bg-navy-soft">
<Upload className="w-4 h-4 me-1" />
העלה
</Button>
</div>
</form>
</SheetContent>
</Sheet>
);
}