File size: 5,631 Bytes
834b620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/**
 * File     : frontend/src/components/ImportBackupPanel.tsx (new)
 * Purpose  : load a backup file: choose file -> preview -> confirm.
 * Consumers: App.tsx (protocol list view). onRestored refreshes the list.
 * Safety   : nothing is written until the person clicks Restore. Restoring
 *            into a project that already exists needs an explicit tick-box.
 * Styles   : existing classes from index.css only.
 */
import { useState } from "react";
import {
  BackupApiError,
  readBackupFile,
  previewBackup,
  restoreBackup,
  type BackupDocument,
  type RestorePlan,
} from "../api/backup";

interface Props {
  onRestored: () => void | Promise<void>;
}

const SECTION_LABELS: Record<string, string> = {
  screening: "Screening decisions",
  extraction: "Extraction records",
  rob: "Risk-of-bias assessments",
  confidence: "Confidence ratings",
};

function totalNew(plan: RestorePlan): number {
  return Object.values(plan.sections).reduce((sum, s) => sum + s.new, 0);
}

export function ImportBackupPanel({ onRestored }: Props) {
  const [doc, setDoc] = useState<BackupDocument | null>(null);
  const [fileName, setFileName] = useState("");
  const [plan, setPlan] = useState<RestorePlan | null>(null);
  const [merge, setMerge] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  function reset() {
    setDoc(null);
    setFileName("");
    setPlan(null);
    setMerge(false);
  }

  function fail(err: unknown) {
    setError(err instanceof BackupApiError ? err.message : "Something went wrong. Nothing was changed.");
  }

  async function handleFile(file: File | undefined) {
    reset();
    setError(null);
    setMessage(null);
    if (!file) return;
    setBusy(true);
    try {
      const parsed = await readBackupFile(file);
      const result = await previewBackup(parsed); // writes nothing
      setDoc(parsed);
      setFileName(file.name);
      setPlan(result);
    } catch (err) {
      fail(err);
    } finally {
      setBusy(false);
    }
  }

  async function handleRestore() {
    if (!doc || !plan) return;
    setBusy(true);
    setError(null);
    try {
      const result = await restoreBackup(doc, merge);
      setMessage(
        result.protocol_exists
          ? `Merged: ${totalNew(result)} new entries added. Nothing existing was changed.`
          : `Project restored with ${totalNew(result)} log entries.`,
      );
      reset();
      await onRestored();
    } catch (err) {
      fail(err);
    } finally {
      setBusy(false);
    }
  }

  const needsMergeTick = plan?.protocol_exists === true;
  const nothingToAdd = plan !== null && plan.protocol_exists && totalNew(plan) === 0;
  const canRestore = plan !== null && !busy && !nothingToAdd && (!needsMergeTick || merge);

  return (
    <section className="phase4-section" aria-label="Load a project backup">
      <h2>Load a project backup</h2>
      <p className="form-hint">
        Choose a backup file you exported earlier. You will see what it contains before anything is loaded.
      </p>
      <input
        type="file"
        accept=".json,application/json"
        disabled={busy}
        onChange={(e) => {
          void handleFile(e.target.files?.[0]);
          e.target.value = ""; // lets the same file be chosen again
        }}
      />
      {busy && <p className="form-hint" role="status">Working…</p>}
      {error && <div className="form-error" role="alert" style={{ whiteSpace: "pre-line" }}>{error}</div>}
      {message && <div className="locked-note" role="status">{message}</div>}

      {plan && (
        <div style={{ marginTop: 16 }}>
          <p>
            <strong>{fileName}</strong> —{" "}
            {plan.protocol_exists ? "this project already exists here." : "a new project that will be added."}
          </p>
          <div className="evidence-table-wrap">
            <table className="evidence-table">
              <thead>
                <tr><th>Section</th><th>In file</th><th>New</th><th>Already here</th></tr>
              </thead>
              <tbody>
                {Object.entries(plan.sections).map(([key, s]) => (
                  <tr key={key}>
                    <td>{SECTION_LABELS[key] ?? key}</td>
                    <td>{s.total}</td>
                    <td>{s.new}</td>
                    <td>{s.duplicate}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <p className="form-hint" style={{ marginTop: 10 }}>
            Search run: {plan.search_run}. Synthesis: {plan.synthesis}.
          </p>
          {plan.warnings.map((w) => (
            <div key={w} className="form-error" role="alert">{w}</div>
          ))}
          {needsMergeTick && !nothingToAdd && (
            <label className="source-checkbox" style={{ marginTop: 12 }}>
              <input type="checkbox" checked={merge} onChange={(e) => setMerge(e.target.checked)} />
              I understand: add the new entries to the existing project.
            </label>
          )}
          {nothingToAdd && <p className="form-hint">Everything in this file is already here, so there is nothing to add.</p>}
          <div className="form-actions">
            <button type="button" className="secondary-btn" onClick={reset} disabled={busy}>Cancel</button>
            <button type="button" className="primary-btn" onClick={handleRestore} disabled={!canRestore}>
              Restore
            </button>
          </div>
        </div>
      )}
    </section>
  );
}