Files
velum-raycast/src/restore-project-files.tsx
2026-11-01 18:48:40 +01:00

568 lines
33 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Action, ActionPanel, Alert, confirmAlert, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
import { promises as fs } from "node:fs";
import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
import { useEffect, useState } from "react";
import { depseudonymizeDocument } from "./velum";
import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, updateProjectMapping, withUnambiguousHistoricalMappings } from "./lib/velum-project";
import type { ProjectFile, ProjectRun } from "./lib/velum-project";
import type { MappingEntry, PlaceholderMapping } from "./types";
import { canonicalPerson, mergePeople } from "./lib/project-review";
import { planProjectRevision, reviseProjectRun } from "./lib/project-revision";
import { TranslationTable } from "./show-translation-tables";
import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups";
import { releaseProjectMapping } from "./project-mapping-actions";
import { projectMappingCreatedAt } from "./lib/mapping-created-at";
import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection";
import type { RestorableFolder } from "./lib/restore-file-selection";
import { relocateProject } from "./lib/project-relocation";
type SavedRun = { run: ProjectRun; directory: string };
type RestoreDecision = MappingEntry | null;
class UnresolvedRestoreError extends Error {
constructor(readonly file: string, readonly ids: string[]) {
super(`${file}: ${ids.length} Platzhalter benötigen eine Zuordnung.`);
}
}
function RestoreDecisionForm(props: { file: string; id: string; candidates: MappingEntry[];
onSave: (decision: RestoreDecision) => void }) {
const { pop } = useNavigation();
async function save(values: { choice: string; original: string }) {
const original = values.original.trim();
const candidate = values.choice.startsWith("candidate:")
? props.candidates[Number(values.choice.slice("candidate:".length))] : undefined;
if (original) props.onSave({ original, type: candidate?.type ?? props.id.replace(/_\d+$/, "") });
else if (candidate) props.onSave(candidate);
else if (values.choice === "keep") props.onSave(null);
else {
await showToast({ style: Toast.Style.Failure, title: "Bitte einen Klartext wählen oder bewusst unverändert lassen" });
return;
}
pop();
}
return <Form navigationTitle={`${props.id} in ${props.file}`}
actions={<ActionPanel><Action.SubmitForm title="Entscheidung für diesen Export übernehmen" onSubmit={save} /></ActionPanel>}>
<Form.Description text={props.candidates.length > 1
? "Dieser Platzhalter hat in gespeicherten Projektständen unterschiedliche Bedeutungen. Wähle die passende Zuordnung für diese Datei."
: props.candidates.length === 1
? "Ein früherer Projektstand enthält diesen Eintrag. Prüfe, ob er zu dieser Datei gehört."
: "Für diesen Platzhalter gibt es in den gespeicherten Projektständen keine Zuordnung. Trage den Klartext ein oder bestätige, dass er absichtlich stehen bleiben soll."} />
<Form.Dropdown id="choice" title="Zuordnung" defaultValue="choose">
<Form.Dropdown.Item value="choose" title="Bitte auswählen" />
{props.candidates.map((entry, index) => <Form.Dropdown.Item key={index}
value={`candidate:${index}`} title={`${entry.original} · ${entry.type}`} />)}
<Form.Dropdown.Item value="keep" title="Platzhalter absichtlich unverändert lassen" />
</Form.Dropdown>
<Form.TextField id="original" title="Anderen Klartext eingeben" placeholder="Optional; überschreibt die Auswahl oben" />
</Form>;
}
function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }) {
const { pop } = useNavigation();
const { run, directory } = props.saved;
const [release, setRelease] = useState<Set<string>>(new Set());
const [merges, setMerges] = useState<Record<string, string>>({});
const [stage, setStage] = useState<"release" | "merge">("release");
const [busy, setBusy] = useState(false);
const entries = Object.entries(run.mapping);
const rootOf = (key: string): string => {
let current = key;
const seen = new Set<string>();
while (run.mapping[current]?.merged_into && !seen.has(current)) {
seen.add(current);
current = run.mapping[current].merged_into!;
}
return current;
};
const roots = entries.filter(([key]) => rootOf(key) === key);
const byType = new Map<string, typeof roots>();
for (const item of roots) {
const type = item[1].type;
if (!byType.has(type)) byType.set(type, []);
byType.get(type)!.push(item);
}
const people = roots.filter(([key, entry]) => entry.type === "PERSON" && !release.has(key));
const variants = (key: string) => entries.filter(([candidate]) => rootOf(candidate) === key)
.map(([, entry]) => entry.original);
function toggle(key: string) {
setRelease((current) => {
const next = new Set(current);
if (next.has(key)) next.delete(key); else next.add(key);
return next;
});
setMerges((current) => Object.fromEntries(Object.entries(current)
.filter(([source, target]) => source !== key && target !== key)));
}
async function apply() {
const plan = planProjectRevision(run.mapping, release, merges);
if (!plan.released.length && !plan.merged.length) {
await showToast({ style: Toast.Style.Failure, title: "Keine Änderung ausgewählt" });
return;
}
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
if (inPlace && !(await confirmAlert({
title: "Projektdateien aktualisieren?",
message: `Der vorhandene Projektordner wird mit dem neuen Stand aktualisiert. ${plan.released.length} Zuordnungen werden freigegeben. Vorher wird außerhalb des Projektordners eine Sicherung erstellt. Zwischenzeitlich geänderte Dateien werden nicht überschrieben.`,
primaryAction: { title: "Projekt aktualisieren", style: Alert.ActionStyle.Destructive },
}))) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Neuer Projektstand wird erstellt" });
try {
const result = await reviseProjectRun({ previous: run, previousDirectory: directory,
release, merges, rewriteDocument: depseudonymizeDocument });
await props.onSaved();
toast.style = Toast.Style.Success;
toast.title = "Projektstand aktualisiert";
toast.message = `${plan.released.length} freigegeben · ${plan.merged.length} zusammengeführt`;
pop();
await showInFinder(inPlace ? run.projectPath : runCopiesPath(result.run, result.directory)).catch(() => undefined);
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Nachbearbeitung fehlgeschlagen";
toast.message = (error as Error).message;
} finally { setBusy(false); }
}
if (stage === "release") return <List isLoading={busy} navigationTitle="Zuordnungen nachbearbeiten"
searchBarPlaceholder="Begriff, Typ oder Platzhalter suchen">
<List.Section title="Weiter">
<List.Item icon={Icon.ArrowRight} title="Personen zusammenführen und Änderungen anwenden"
subtitle={`${release.size} Begriffe oder Personengruppen freigeben`}
actions={<ActionPanel><Action title="Personen prüfen" onAction={() => setStage("merge")} /></ActionPanel>} />
</List.Section>
{[...byType].map(([type, items]) => <List.Section key={type}
title={`${type} · ${items.filter(([key]) => release.has(key)).length}/${items.length} freigeben`}>
{items.map(([key, entry]) => <List.Item key={key}
icon={release.has(key) ? Icon.CheckCircle : Icon.Circle}
title={entry.original} subtitle={`→ ${key}`}
accessories={[{ text: entry.type }, ...(entry.type === "PERSON" && variants(key).length > 1
? [{ text: `${variants(key).length} Varianten` }] : [])]}
keywords={[key, entry.type, ...variants(key)]}
actions={<ActionPanel>
<Action title={release.has(key) ? "Freigabe zurücknehmen" : "In Klartext umwandeln und ausnehmen"}
onAction={() => toggle(key)} />
<Action title="Personen prüfen" onAction={() => setStage("merge")} />
</ActionPanel>} />)}
</List.Section>)}
</List>;
return <List isLoading={busy} navigationTitle="Personen nachträglich zusammenführen"
searchBarPlaceholder="Person oder Platzhalter suchen">
<List.Section title="Abschluss">
<List.Item icon={Icon.Play} title="Neuen Projektstand erstellen"
subtitle={`${release.size} Freigaben · ${Object.keys(merges).length} Zusammenführungen`}
actions={<ActionPanel>
<Action title="Änderungen anwenden" onAction={apply} />
<Action title="Zur Freigabe zurück" onAction={() => setStage("release")} />
</ActionPanel>} />
</List.Section>
<List.Section title="Personen · optional zusammenfassen">
{people.map(([key]) => {
const target = canonicalPerson(key, merges);
const targets = people.filter(([other]) => canonicalPerson(other, merges) !== target);
return <List.Item key={key} icon={Icon.Person} title={variants(key).join(" · ")}
subtitle={`→ ${target}`}
accessories={target !== key ? [{ text: "Zusammengeführt" }] : []}
actions={<ActionPanel>
{targets.length > 0 && <ActionPanel.Submenu title="Mit Person zusammenfassen" icon={Icon.Link}>
{targets.map(([other]) => <Action key={other}
title={`${variants(other).join(" · ")} → ${canonicalPerson(other, merges)}`}
onAction={() => setMerges((current) => mergePeople(current, key, other))} />)}
</ActionPanel.Submenu>}
{target !== key && <Action title="Zusammenführung lösen" onAction={() => setMerges((current) => {
const next = { ...current }; delete next[key]; return next;
})} />}
<Action title="Änderungen anwenden" onAction={apply} />
</ActionPanel>} />;
})}
</List.Section>
</List>;
}
function FolderPicker(props: { folders: RestorableFolder[]; onSelect: (folder: string, includeDocuments: boolean) => void }) {
const { pop } = useNavigation();
function choose(folder: string, includeDocuments: boolean) {
props.onSelect(folder, includeDocuments);
pop();
}
return <List navigationTitle="Nur einen Ordner wiederherstellen" searchBarPlaceholder="Ordner suchen">
<List.Section title="Ordner samt Unterordnern · Textdateien zuerst">
{props.folders.map((folder) => <List.Item key={folder.path} icon={Icon.Folder}
title={folder.path} subtitle={`${folder.fileCount} Dateien · ${folder.textCount} Text · ${folder.documentCount} Office`}
actions={<ActionPanel>
{folder.textCount > 0 && <Action title="Nur Textdateien dieses Ordners auswählen" icon={Icon.CheckCircle}
onAction={() => choose(folder.path, false)} />}
{folder.documentCount > 0 && <Action title="Diesen Ordner inklusive Office auswählen" icon={Icon.Folder}
onAction={() => choose(folder.path, true)} />}
</ActionPanel>} />)}
</List.Section>
</List>;
}
function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: SavedRun[] }) {
const { push } = useNavigation();
const [files, setFiles] = useState<ProjectFile[]>([]);
const [sourceRoot, setSourceRoot] = useState("");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [skipped, setSkipped] = useState(0);
const [busy, setBusy] = useState(false);
const [unresolved, setUnresolved] = useState<Array<{ file: string; id: string }>>([]);
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]
.map(mappingForRestoration);
const baseMapping = withUnambiguousHistoricalMappings(mappings[0], mappings.slice(1));
const candidatesFor = (id: string): MappingEntry[] => {
const unique = new Map<string, MappingEntry>();
for (const mapping of mappings) for (const [key, entry] of Object.entries(mapping)) {
if (key.toUpperCase() === id.toUpperCase()) unique.set(`${entry.type}\0${entry.original}`, entry);
}
return [...unique.values()];
};
function saveDecision(file: string, id: string, decision: RestoreDecision) {
setDecisions((current) => ({ ...current,
[file]: { ...current[file], [id.toUpperCase()]: decision },
}));
setUnresolved((current) => current.filter((item) => item.file !== file || item.id !== id));
}
useEffect(() => {
let active = true;
async function load() {
const scan = await scanRestorableCopyFiles(props.run, props.directory, !props.historical);
if (!active) return;
setSourceRoot(scan.root);
setFiles(scan.files);
setSelected(new Set(scan.files.filter((file) => file.kind === "text").map((file) => file.relPath)));
setSkipped(scan.skipped);
}
load().catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Kopienordner nicht lesbar", message: error.message }));
return () => { active = false; };
}, [props.run, props.directory, props.historical]);
function toggle(path: string) {
setSelected((current) => {
const next = new Set(current);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
}
async function exportFiles() {
if (busy) return;
if (!selected.size) {
await showToast({ style: Toast.Style.Failure, title: "Keine Dateien ausgewählt" });
return;
}
if (!sourceRoot) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Klartext-Kopien werden erstellt" });
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const parent = join(homedir(), "Downloads", "Velum");
let targetRoot: string | undefined;
try {
if (!Object.keys(baseMapping).length && !Object.keys(decisions).length) {
throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
}
const names = new Set<string>();
const planned = files.filter((item) => selected.has(item.relPath));
let renamedFiles = 0;
let contentReplacements = 0;
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
targetRoot = await fs.mkdtemp(join(parent, `${basename(props.run.projectName)}-${stamp}-`));
for (const file of planned) {
const source = resolveWithin(sourceRoot, file.relPath);
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei: ${file.relPath}`);
const data = await fs.readFile(source);
const mapping: PlaceholderMapping = { ...baseMapping };
const manual = decisions[file.relPath] ?? {};
for (const [id, entry] of Object.entries(manual)) if (entry) mapping[id] = entry;
let restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
let result: Buffer;
if (file.kind === "document") {
result = await depseudonymizeDocument(basename(file.relPath), data, mapping);
} else {
const markdown = isMarkdownFile(file.relPath);
const text = data.toString("utf8");
let restored = restoreTextWithCount(text, mapping, props.run.matchModes, markdown);
if (markdown) {
let missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings)
.filter((id) => manual[id.toUpperCase()] !== null);
if (missing.length) {
const exactMapping = await mappingForMatchingSnapshots(file.relPath, digest(data), props.earlierRuns);
for (const id of missing) {
const match = Object.entries(exactMapping).find(([key]) => key.toUpperCase() === id.toUpperCase());
if (match && !Object.keys(mapping).some((key) => key.toUpperCase() === id.toUpperCase())) {
mapping[match[0]] = match[1];
}
}
restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
restored = restoreTextWithCount(text, mapping, props.run.matchModes, true);
missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings)
.filter((id) => manual[id.toUpperCase()] !== null);
}
if (missing.length) throw new UnresolvedRestoreError(file.relPath, missing);
}
contentReplacements += restored.replacements;
result = Buffer.from(restored.text, "utf8");
}
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
names.add(restoredName);
if (restoredName !== file.relPath) renamedFiles++;
const target = resolveWithin(targetRoot, restoredName);
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
await fs.writeFile(target, result, { flag: "wx", mode: 0o600 });
}
if (!renamedFiles && !contentReplacements && planned.every((file) => file.kind === "text")
&& !planned.some((file) => Object.values(decisions[file.relPath] ?? {}).includes(null))) {
throw new Error("Keine passenden Velum-Platzhalter in den ausgewählten Textdateien oder Dateinamen gefunden. Bitte Quelle und Projektstand prüfen.");
}
setUnresolved([]);
toast.style = Toast.Style.Success;
toast.title = `${selected.size} Klartext-Dateien in Downloads`;
const deliberatelyKept = planned.reduce((count, file) => count
+ Object.values(decisions[file.relPath] ?? {}).filter((entry) => entry === null).length, 0);
toast.message = `${contentReplacements} Textersetzungen · ${renamedFiles} Dateinamen geändert`
+ (deliberatelyKept ? ` · ${deliberatelyKept} Platzhalter bewusst belassen` : "")
+ (planned.some((file) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : "");
await showInFinder(targetRoot).catch(() => undefined);
} catch (error) {
if (targetRoot) await fs.rm(targetRoot, { recursive: true, force: true });
if (error instanceof UnresolvedRestoreError) setUnresolved(error.ids.map((id) => ({ file: error.file, id })));
toast.style = Toast.Style.Failure;
toast.title = error instanceof UnresolvedRestoreError ? "Platzhalter zuordnen" : "Klartext-Export fehlgeschlagen";
toast.message = error instanceof UnresolvedRestoreError
? `${error.file}: ${error.ids.join(", ")}. Bitte die Einträge unten klären und den Export erneut starten.`
: (error as Error).message;
} finally { setBusy(false); }
}
const textFiles = files.filter((file) => file.kind === "text");
const complexFiles = files.filter((file) => file.kind === "document");
const folders = listRestorableFolders(files);
const allSelected = files.length > 0 && selected.size === files.length;
const selectOnlyFolder = (folder: string, includeDocuments = false) =>
setSelected(selectRestorableFolder(files, folder, includeDocuments));
const openFolderPicker = () => push(<FolderPicker folders={folders} onSelect={selectOnlyFolder} />);
const selectionActions = () => <ActionPanel.Section title="Dateiauswahl">
<Action title={allSelected ? "Alle Dateien abwählen" : "Alle Dateien auswählen (inklusive Office)"}
shortcut={{ modifiers: ["cmd", "shift"], key: "a" }}
onAction={() => setSelected((current) => current.size === files.length
? new Set() : new Set(files.map((file) => file.relPath)))} />
<Action title="Nur Textdateien auswählen" onAction={() => setSelected(new Set(textFiles.map((item) => item.relPath)))} />
<Action title="Keine auswählen" onAction={() => setSelected(new Set())} />
{folders.length > 0 && <Action title="Nur einen Ordner auswählen" icon={Icon.Folder}
shortcut={{ modifiers: ["cmd", "shift"], key: "o" }} onAction={openFolderPicker} />}
</ActionPanel.Section>;
const sourceLabel = props.historical ? "Gespeicherter Projektstand"
: props.run.inPlace || props.run.sourceInPlace ? "Aktueller Projektordner" : "Pseudonymisierte Kopien";
const renderFile = (file: ProjectFile) => {
const fileFolder = folders.find((folder) => folder.path === dirname(file.relPath));
const displayMapping: PlaceholderMapping = { ...baseMapping };
for (const [id, entry] of Object.entries(decisions[file.relPath] ?? {})) if (entry) displayMapping[id] = entry;
return <List.Item key={file.relPath}
icon={selected.has(file.relPath) ? Icon.CheckCircle : Icon.Circle}
title={restorePath(file.relPath, displayMapping, props.run.matchModes)} subtitle={file.relPath}
accessories={file.kind === "document" ? [{ text: "Office · manuell auswählen" }] : []}
actions={<ActionPanel>
<Action title={selected.has(file.relPath) ? "Datei abwählen" : "Datei auswählen"} onAction={() => toggle(file.relPath)} />
<Action title="Auswahl nach Downloads wiederherstellen" icon={Icon.Download} onAction={exportFiles} />
{fileFolder && <Action title={fileFolder.textCount > 0
? "Nur Textdateien dieses Ordners auswählen" : "Diesen Ordner inklusive Office auswählen"}
icon={Icon.Folder} onAction={() => selectOnlyFolder(fileFolder.path, fileFolder.textCount === 0)} />}
{selectionActions()}
</ActionPanel>} />;
};
return <List isLoading={busy || !sourceRoot} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
searchBarPlaceholder="Dateien filtern">
<List.Section title={`${selected.size} von ${files.length} Dateien ausgewählt · ${skipped} übersprungen`}>
<List.Item key="export" icon={Icon.Download} title="Ausgewählte Dateien wiederherstellen"
subtitle="Klartext-Kopien in Downloads/Velum erstellen · Office-Dateien nur nach Auswahl"
actions={<ActionPanel><Action title="Auswahl nach Downloads wiederherstellen"
icon={Icon.Download} onAction={exportFiles} />{selectionActions()}</ActionPanel>} />
<List.Item key="source" icon={Icon.Folder} title={sourceLabel} subtitle={sourceRoot}
actions={<ActionPanel><Action title="Quellordner im Finder anzeigen" onAction={() => showInFinder(sourceRoot)} />
{selectionActions()}</ActionPanel>} />
</List.Section>
{unresolved.some((item) => selected.has(item.file)) && <List.Section title="Platzhalter für diesen Export klären">
{unresolved.filter((item) => selected.has(item.file)).map(({ file, id }) => {
const candidates = candidatesFor(id);
return <List.Item key={`${file}:${id}`} icon={Icon.ExclamationMark}
title={id} subtitle={file}
accessories={[{ text: candidates.length > 1 ? `${candidates.length} verschiedene alte Zuordnungen`
: candidates.length ? "Gespeicherter Eintrag – bitte prüfen" : "Kein gespeicherter Eintrag" }]}
actions={<ActionPanel><Action title="Zuordnung festlegen" icon={Icon.Pencil}
onAction={() => push(<RestoreDecisionForm file={file} id={id} candidates={candidates}
onSave={(decision) => saveDecision(file, id, decision)} />)} />{selectionActions()}</ActionPanel>} />;
})}
</List.Section>}
<List.Section title={`Textdateien · ${textFiles.length} · standardmäßig ausgewählt`}>
{textFiles.map(renderFile)}
</List.Section>
<List.Section title={`Office-Dateien · ${complexFiles.length} · bewusst auswählen`}>
{complexFiles.map(renderFile)}
</List.Section>
</List>;
}
function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
const { push } = useNavigation();
return <List navigationTitle={`${props.projectName}: frühere Stände`}
searchBarPlaceholder="Stand suchen">
<List.Section title="Frühere Stände · nur für Klartext-Export">
{props.entries.map(({ run, directory }, index) => <List.Item key={run.id} icon={Icon.Clock}
title={new Date(run.createdAt).toLocaleString("de-AT")}
subtitle={`${run.files.length} Dateien`}
actions={<ActionPanel>
<Action title="Gespeicherten Stand wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory} historical
earlierRuns={props.entries.slice(index + 1)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={`${props.projectName} · ${new Date(run.createdAt).toLocaleString("de-AT")}`}
mapping={run.mapping}
createdAtByKey={projectMappingCreatedAt(props.entries.slice(index).map((entry) => entry.run), run.mapping)} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
onAction={() => showInFinder(runCopiesPath(run, directory))} />
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
{run.copyPath && <Action title="Aktuelle Dateien dieses Kopienordners wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory}
earlierRuns={props.entries.slice(index + 1)} />)} />}
</ActionPanel>} />)}
</List.Section>
</List>;
}
function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise<void> }) {
const { pop } = useNavigation();
const [busy, setBusy] = useState(false);
async function save(values: { newPath: string[] }) {
const newPath = values.newPath[0];
if (!newPath) {
await showToast({ style: Toast.Style.Failure, title: "Bitte den neuen Projektordner wählen" });
return;
}
if (!(await confirmAlert({
title: "Projektordner aktualisieren?",
message: `Alle gespeicherten Projektstände und Regeln werden künftig ${newPath} zugeordnet. `
+ `Bisheriger Pfad: ${props.oldPath}. Die Dateien im gewählten Ordner werden nicht verändert.`,
primaryAction: { title: "Projektpfad aktualisieren" },
}))) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Projektpfad wird aktualisiert" });
try {
const result = await relocateProject(props.oldPath, newPath);
await props.onMoved();
toast.style = Toast.Style.Success;
toast.title = "Projektordner aktualisiert";
toast.message = `${result.runsMoved} Projektstände übernommen`
+ (result.copiesRelinked ? ` · ${result.copiesRelinked} Kopienordner neu gefunden` : "")
+ (result.copiesMissing ? ` · ${result.copiesMissing} Kopienordner nicht gefunden; gespeicherte Stände bleiben verfügbar` : "");
pop();
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Projektpfad nicht aktualisiert";
toast.message = (error as Error).message;
} finally { setBusy(false); }
}
return <Form isLoading={busy} navigationTitle={`${props.projectName}: Projektordner ändern`}
actions={<ActionPanel><Action.SubmitForm title="Projektpfad aktualisieren" icon={Icon.Folder}
onSubmit={save} /></ActionPanel>}>
<Form.Description title="Bisheriger Projektordner" text={props.oldPath} />
<Form.FilePicker id="newPath" title="Neuer Projektordner" allowMultipleSelection={false}
canChooseDirectories canChooseFiles={false} />
<Form.Description text="Gespeicherte Stände, Ausnahmen und Projektbegriffe bleiben erhalten. Dateien im neuen Ordner werden weder analysiert noch geändert." />
</Form>;
}
export default function Command() {
const { push } = useNavigation();
const [runs, setRuns] = useState<SavedRun[]>([]);
const [busy, setBusy] = useState(true);
useEffect(() => {
listAllRuns().then(setRuns).catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Projektstände nicht lesbar", message: error.message })).finally(() => setBusy(false));
}, []);
async function refresh() { setRuns(await listAllRuns()); }
async function repairMergedPeople(saved: SavedRun) {
const { run, directory } = saved;
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
if (inPlace && !(await confirmAlert({
title: "Zusammengeführte Personen in Projektdateien reparieren?",
message: "Der aktuelle Projektordner wird aktualisiert. Vorher erstellt Velum außerhalb des Projektordners eine Sicherung. Zwischenzeitlich geänderte Dateien werden nicht überschrieben.",
primaryAction: { title: "Projektdateien reparieren", style: Alert.ActionStyle.Destructive },
}))) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Personenplatzhalter werden bereinigt" });
try {
const result = await reviseProjectRun({ previous: run, previousDirectory: directory,
release: new Set(), merges: {}, reapplyMerges: true, rewriteDocument: depseudonymizeDocument });
await refresh();
toast.style = Toast.Style.Success;
toast.title = "Projektstand repariert";
toast.message = "Zusammengeführte Personen wurden in Dateien und Dateinamen erneut angewendet.";
await showInFinder(inPlace ? run.projectPath : runCopiesPath(result.run, result.directory)).catch(() => undefined);
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Reparatur fehlgeschlagen";
toast.message = (error as Error).message;
} finally { setBusy(false); }
}
const projects = new Map<string, SavedRun[]>();
for (const entry of runs) {
const path = canonicalProjectPath(entry.run.projectPath);
if (!projects.has(path)) projects.set(path, []);
projects.get(path)!.push(entry);
}
return <List isLoading={busy} navigationTitle="Projekte nachbearbeiten oder rückübersetzen" searchBarPlaceholder="Projekt suchen">
<List.EmptyView title="Noch keine Projektstände" description="Zuerst Dateien mit Velum pseudonymisieren." />
{[...projects].map(([path, entries]) => {
const [{ run, directory }] = entries;
return <List.Item key={path} icon={Icon.Folder}
title={run.projectName} subtitle={path}
accessories={[{ text: `${run.files.length} Dateien` }, { text: new Date(run.createdAt).toLocaleString("de-AT") },
...(entries.length > 1 ? [{ text: `${entries.length} Stände` }] : [])]}
actions={<ActionPanel>
<Action title="Projektdateien als Klartext wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory}
earlierRuns={entries.slice(1)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={run.projectName} mapping={run.mapping}
createdAtByKey={projectMappingCreatedAt(entries.map((entry) => entry.run), run.mapping)}
onAdd={async (input) => {
const updated = await addProjectMappingEntry(run.projectPath, input);
await refresh();
return updated.mapping;
}}
onMerge={async (from, into) => {
const updated = await updateProjectMapping(run.projectPath,
(current) => mergeMappingGroups(current, from, into));
await refresh();
return updated.mapping;
}}
onDetach={async (key) => {
const updated = await updateProjectMapping(run.projectPath,
(current) => detachMappingGroup(current, key));
await refresh();
return updated.mapping;
}}
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Auch zwischenzeitlich bearbeitete Projektdateien werden anhand ihres aktuellen Stands korrigiert und vorher gesichert."
onRemove={async (root) => {
const revised = await releaseProjectMapping(run.projectPath, root);
await refresh();
return revised.run.mapping;
}} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
onAction={() => showInFinder(runCopiesPath(run, directory))} />
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
<Action title="Aktuellen Stand nachbearbeiten" icon={Icon.Pencil}
onAction={() => push(<RevisionReview saved={{ run, directory }} onSaved={refresh} />)} />
<Action title="Projektordner ändern" icon={Icon.Folder}
onAction={() => push(<RelocateProjectForm projectName={run.projectName}
oldPath={path} onMoved={refresh} />)} />
{Object.values(run.mapping).some((entry) => entry.type === "PERSON" && entry.merged_into)
&& <Action title="Zusammengeführte Personen in Dateien reparieren" icon={Icon.Pencil}
onAction={() => repairMergedPeople({ run, directory })} />}
{entries.length > 1 && <Action title="Frühere Stände anzeigen" icon={Icon.Clock}
onAction={() => push(<ProjectHistory projectName={run.projectName} entries={entries.slice(1)} />)} />}
</ActionPanel>} />;
})}
</List>;
}