Systematic-tool-review / frontend /src /components /ImportRecordsForm.tsx
Sadum1's picture
Update frontend/src/components/ImportRecordsForm.tsx
07f067e verified
Raw History Blame Contribute Delete
5.55 kB
import { useState } from "react";
import type { ImportPreview, LiteratureSource, SearchRun } from "../types";
interface ImportRecordsFormProps {
protocolId: string;
source: LiteratureSource;
sourceLabel: string;
onImported: (run: SearchRun) => void;
onCancel: () => void;
}
const MAX_FILE_BYTES = 25 * 1024 * 1024;
/** Reads a text file, including ones saved as UTF-16 (Notepad's "Unicode"). */
async function readFileText(file: File): Promise<string> {
const buffer = await file.arrayBuffer();
const bytes = new Uint8Array(buffer);
if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(buffer);
if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(buffer);
return new TextDecoder("utf-8").decode(buffer);
}
async function errorMessage(response: Response): Promise<string> {
let message = `The import failed (status ${response.status}).`;
try {
const body: unknown = await response.json();
const detail = (body as { detail?: unknown }).detail;
if (typeof detail === "string") message = detail;
else if (Array.isArray(detail)) {
message = detail.map((d) => (d as { msg?: string }).msg ?? "invalid value").join("; ");
}
} catch {
/* keep the generic message */
}
return message;
}
export function ImportRecordsForm({
protocolId,
source,
sourceLabel,
onImported,
onCancel,
}: ImportRecordsFormProps) {
const [file, setFile] = useState<{ name: string; content: string } | null>(null);
const [preview, setPreview] = useState<ImportPreview | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const url = `/api/v1/protocols/${encodeURIComponent(protocolId)}/search/import/${encodeURIComponent(source)}`;
async function send(name: string, content: string, confirm: boolean): Promise<ImportPreview> {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ filename: name, content, confirm }),
});
if (!response.ok) throw new Error(await errorMessage(response));
return (await response.json()) as ImportPreview;
}
async function onPick(selected: File | undefined) {
setPreview(null);
setFile(null);
setError(null);
if (!selected) return;
if (selected.size > MAX_FILE_BYTES) {
setError("This file is larger than 25 MB. Export fewer records at a time.");
return;
}
setBusy(true);
try {
const content = await readFileText(selected);
const result = await send(selected.name, content, false);
setFile({ name: selected.name, content });
setPreview(result);
} catch (err) {
setError(err instanceof Error ? err.message : "Could not read the file.");
} finally {
setBusy(false);
}
}
async function confirmImport() {
if (!file) return;
setBusy(true);
setError(null);
try {
const result = await send(file.name, file.content, true);
if (result.run) onImported(result.run);
else setError("The import did not return the updated search. Reload the page.");
} catch (err) {
setError(err instanceof Error ? err.message : "The import failed.");
} finally {
setBusy(false);
}
}
return (
<div className="manual-search-panel">
<h3>Import records: {sourceLabel}</h3>
<p className="form-hint">
Export the results from {sourceLabel} as <strong>RIS</strong> (preferred) or{" "}
<strong>CSV</strong>, then choose the file here. You will see a preview first, and nothing
is saved until you confirm. Records already found in another source are merged, not
duplicated.
</p>
<input
type="file"
accept=".ris,.csv,.txt"
disabled={busy}
onChange={(e) => void onPick(e.target.files?.[0])}
/>
{busy && <p className="form-hint">Working…</p>}
{error && <div className="form-error">{error}</div>}
{preview && (
<div className="import-preview">
<strong>
{preview.parsed} records read from the {preview.format} file
</strong>
<ul>
<li>{preview.new_records} new records will be added</li>
<li>
{preview.already_in_tool} are already in your list from another source (merged, not
duplicated)
</li>
{preview.duplicates_within_file > 0 && (
<li>{preview.duplicates_within_file} repeated inside this file (merged)</li>
)}
<li>
{preview.with_abstract} have an abstract, {preview.with_doi} have a DOI
</li>
{preview.skipped_no_title > 0 && (
<li>{preview.skipped_no_title} skipped because they have no title</li>
)}
</ul>
<div className="form-hint">First records in the file:</div>
<ul>
{preview.sample_titles.map((t, i) => (
<li key={i}>{t}</li>
))}
</ul>
</div>
)}
<div className="form-actions">
<button className="secondary-btn" onClick={onCancel} disabled={busy}>
Cancel
</button>
<button
className="primary-btn"
onClick={() => void confirmImport()}
disabled={busy || !preview}
>
{preview ? `Import ${preview.parsed} records` : "Import"}
</button>
</div>
</div>
);
}