File size: 4,123 Bytes
54bb2dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Backup API client.
 *
 * File     : frontend/src/api/backup.ts (new)
 * Purpose  : call the backend routes in backend/app/backup_routes.py.
 * Consumers: ExportBackupButton, ImportBackupPanel.
 *
 * Same-origin path, matching BASE = "/api/v1/protocols" in api/protocols.ts.
 */
const API_ROOT = "/api/v1";
const MAX_BACKUP_BYTES = 25 * 1024 * 1024;

export interface SectionPlan {
  total: number;
  new: number;
  duplicate: number;
}

export interface RestorePlan {
  protocol_id: string;
  protocol_exists: boolean;
  sections: Record<string, SectionPlan>;
  search_run: string;
  synthesis: string;
  warnings: string[];
  restored: boolean;
}

export type BackupDocument = Record<string, unknown>;

export class BackupApiError extends Error {}

/** Turn any error body the backend can send into one readable message. */
function describeError(status: number, body: unknown): string {
  const detail = (body as { detail?: unknown } | null)?.detail;
  if (typeof detail === "string") return detail;
  if (Array.isArray(detail)) {
    // FastAPI's own validation errors (e.g. the file isn't a backup at all)
    return "This file is not a valid backup file.";
  }
  if (detail && typeof detail === "object") {
    const d = detail as { message?: string; problems?: string[]; total_problems?: number };
    const problems = (d.problems ?? []).map((p) => `• ${p}`).join("\n");
    const more =
      d.total_problems && d.problems && d.total_problems > d.problems.length
        ? `\n…and ${d.total_problems - d.problems.length} more.`
        : "";
    return `${d.message ?? "The backup file has problems."}\n${problems}${more}`.trim();
  }
  return `Request failed (${status}).`;
}

async function readBody(res: Response): Promise<unknown> {
  try {
    return await res.json();
  } catch {
    return null;
  }
}

async function post<T>(path: string, body: BackupDocument): Promise<T> {
  let res: Response;
  try {
    res = await fetch(`${API_ROOT}${path}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
  } catch {
    throw new BackupApiError("Could not reach the server. Check your connection and try again.");
  }
  const data = await readBody(res);
  if (!res.ok) throw new BackupApiError(describeError(res.status, data));
  return data as T;
}

/** Read a chosen file and check it is JSON. Does not contact the server. */
export async function readBackupFile(file: File): Promise<BackupDocument> {
  if (file.size > MAX_BACKUP_BYTES) {
    throw new BackupApiError("This file is too large to be a backup (limit 25 MB).");
  }
  let parsed: unknown;
  try {
    parsed = JSON.parse(await file.text());
  } catch {
    throw new BackupApiError("This file is not valid JSON, so it cannot be a backup.");
  }
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
    throw new BackupApiError("This file is not a backup file.");
  }
  return parsed as BackupDocument;
}

export function previewBackup(doc: BackupDocument): Promise<RestorePlan> {
  return post<RestorePlan>("/backup/preview", doc);
}

export function restoreBackup(doc: BackupDocument, merge: boolean): Promise<RestorePlan> {
  return post<RestorePlan>(`/backup/restore?merge=${merge ? "true" : "false"}`, doc);
}

/** Download one project's backup as a saved file (not shown in the browser). */
export async function downloadBackup(protocolId: string): Promise<void> {
  let res: Response;
  try {
    res = await fetch(`${API_ROOT}/protocols/${encodeURIComponent(protocolId)}/backup`);
  } catch {
    throw new BackupApiError("Could not reach the server. Check your connection and try again.");
  }
  if (!res.ok) throw new BackupApiError(describeError(res.status, await readBody(res)));
  const blob = await res.blob();
  const safeId = protocolId.replace(/[^A-Za-z0-9_-]/g, "_");
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `project-backup-${safeId}.json`;
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
}