Add upload endpoint for updated analysis files
All checks were successful
Build & Deploy / build-and-deploy (push) Successful in 34s

PUT /api/cases/{n}/research/analysis/upload accepts a markdown file and
validates: UTF-8 encoding, parseable structure, at least one threshold
or issue section, matching case number. Backs up existing file before
replacing. UI adds "העלה ניתוח מעודכן" button with status feedback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-13 19:34:06 +00:00
parent 9da8dd2c4f
commit b248e1414d
2 changed files with 172 additions and 19 deletions

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { use } from "react"; import { use, useRef, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { AppShell } from "@/components/app-shell"; import { AppShell } from "@/components/app-shell";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
@@ -25,6 +25,91 @@ function ProseSection({ title, content }: { title: string; content?: string }) {
); );
} }
function AnalysisActions({
caseNumber,
hasAnalysis,
onUploaded,
}: {
caseNumber: string;
hasAnalysis: boolean;
onUploaded: () => void;
}) {
const fileRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [uploadMsg, setUploadMsg] = useState<{ ok: boolean; text: string } | null>(null);
async function handleUpload(file: File) {
setUploading(true);
setUploadMsg(null);
try {
const form = new FormData();
form.append("file", file);
const res = await fetch(`/api/cases/${caseNumber}/research/analysis/upload`, {
method: "PUT",
body: form,
});
const data = await res.json();
if (!res.ok) {
setUploadMsg({ ok: false, text: data.detail || "שגיאה בהעלאה" });
return;
}
setUploadMsg({
ok: true,
text: `הקובץ הועלה בהצלחה — ${data.sections.threshold_claims} טענות סף, ${data.sections.issues} סוגיות`,
});
onUploaded();
} catch {
setUploadMsg({ ok: false, text: "שגיאת רשת" });
} finally {
setUploading(false);
if (fileRef.current) fileRef.current.value = "";
}
}
return (
<div className="flex items-center gap-2 flex-wrap">
{uploadMsg && (
<span className={`text-xs ${uploadMsg.ok ? "text-green-700" : "text-red-600"}`}>
{uploadMsg.text}
</span>
)}
<input
ref={fileRef}
type="file"
accept=".md"
className="hidden"
onChange={(e) => {
const f = e.target.files?.[0];
if (f) handleUpload(f);
}}
/>
<Button
variant="outline"
disabled={uploading}
onClick={() => fileRef.current?.click()}
>
{uploading ? "מעלה..." : "העלה ניתוח מעודכן"}
</Button>
{hasAnalysis && (
<Button
variant="outline"
onClick={() => {
const a = document.createElement("a");
a.href = `/api/cases/${caseNumber}/research/analysis/download`;
a.download = `analysis-${caseNumber}.md`;
a.click();
}}
>
הורד ניתוח
</Button>
)}
<Button asChild variant="outline">
<Link href={`/cases/${caseNumber}`}>חזרה לתיק</Link>
</Button>
</div>
);
}
export default function ComposePage({ export default function ComposePage({
params, params,
}: { }: {
@@ -78,24 +163,7 @@ export default function ComposePage({
</p> </p>
)} )}
</div> </div>
<div className="flex items-center gap-2"> <AnalysisActions caseNumber={caseNumber} hasAnalysis={!!analysis.data} onUploaded={() => analysis.refetch()} />
{analysis.data && (
<Button
variant="outline"
onClick={() => {
const a = document.createElement("a");
a.href = `/api/cases/${caseNumber}/research/analysis/download`;
a.download = `analysis-${caseNumber}.md`;
a.click();
}}
>
הורד ניתוח
</Button>
)}
<Button asChild variant="outline">
<Link href={`/cases/${caseNumber}`}>חזרה לתיק</Link>
</Button>
</div>
</div> </div>
<div className="h-[2px] bg-gradient-to-l from-transparent via-gold to-transparent" /> <div className="h-[2px] bg-gradient-to-l from-transparent via-gold to-transparent" />

View File

@@ -1633,6 +1633,91 @@ async def api_research_analysis_download(case_number: str):
) )
@app.put("/api/cases/{case_number}/research/analysis/upload")
async def api_research_analysis_upload(
case_number: str,
file: UploadFile = File(...),
):
"""Upload an updated analysis-and-research.md file.
Validates that:
1. The file is markdown (text)
2. It can be parsed by the research_md parser
3. It contains at least one structural section (issues or threshold_claims)
4. The case number in the file matches the URL
On success, backs up the existing file and replaces it.
"""
if not file.filename or not file.filename.endswith(".md"):
raise HTTPException(400, "הקובץ חייב להיות בפורמט Markdown (.md)")
content = await file.read()
if len(content) > 5 * 1024 * 1024:
raise HTTPException(400, "הקובץ גדול מדי — מקסימום 5MB")
try:
text = content.decode("utf-8")
except UnicodeDecodeError:
raise HTTPException(400, "הקובץ חייב להיות בקידוד UTF-8")
if len(text.strip()) < 100:
raise HTTPException(400, "הקובץ ריק מדי — נראה שחסר תוכן")
# Write to a temp file so parse() can work on it
dest = _research_file_path(case_number)
tmp = dest.with_suffix(".md.upload-tmp")
try:
dest.parent.mkdir(parents=True, exist_ok=True)
tmp.write_text(text, encoding="utf-8")
parsed = research_md.parse(tmp)
except Exception as e:
tmp.unlink(missing_ok=True)
raise HTTPException(
400,
f"שגיאה בפרסור הקובץ — המבנה לא תקין: {e}",
)
# Validate structure
issues = parsed.get("issues", [])
thresholds = parsed.get("threshold_claims", [])
if not issues and not thresholds:
tmp.unlink(missing_ok=True)
raise HTTPException(
400,
"הקובץ חייב להכיל לפחות סעיף אחד של טענות סף או סוגיות להכרעה",
)
# Validate case number matches
file_case = parsed.get("header", {}).get("case_number", "")
if file_case and file_case != case_number:
tmp.unlink(missing_ok=True)
raise HTTPException(
400,
f"מספר התיק בקובץ ({file_case}) לא תואם לתיק הנוכחי ({case_number})",
)
# Backup existing file
if dest.exists():
backup_dir = dest.parent / "backup"
backup_dir.mkdir(exist_ok=True)
ts = time.strftime("%Y%m%d-%H%M%S")
backup_path = backup_dir / f"analysis-and-research-{ts}.md"
shutil.copy2(dest, backup_path)
# Replace with uploaded file
tmp.replace(dest)
return {
"status": "ok",
"sections": {
"threshold_claims": len(thresholds),
"issues": len(issues),
"has_conclusions": bool(parsed.get("conclusions", "").strip()),
},
"file_size": len(content),
}
class ChairPositionRequest(BaseModel): class ChairPositionRequest(BaseModel):
section_id: str section_id: str
position: str = "" position: str = ""