Files
immich-redaktions-plugin/src/components/download/usage-dialog.tsx
T
Leon TonhäuserandClaude Opus 5.5 9e938e4d07 feat: redesign portal UI with Sakani UI and add release notes
Replace the hand-rolled Tailwind/shadcn look with Sakani UI across the
editorial area, the admin area and all signed-out pages.

- AppShell (Sakani Sidebar + TopBar) for /redaktion and /admin, with a
  mobile drawer, theme toggle, sign-out, legal links and a "Was ist neu"
  button; PublicShell for login, registration, password, 2FA and errors.
- Shared primitives (Button, Card, Input, PageHeader) now render Sakani;
  components/ui/sakani.tsx is the client boundary for Server Components
  (Sakani ships no "use client") and adds FormSelect (native form value)
  and DataTable (element cells from the server).
- Legacy CSS variables map onto Sakani tokens; globals.css shrinks from
  ~2200 to ~700 lines. Geist replaces Inter. recharts/lucide-react dropped
  (charts via Sakani BarChart).
- Release notes popup per area, shown once per version (localStorage) and
  reopenable from the sidebar; native <dialog> for focus trapping.
- Fixes found while testing: TOTP field reused the typed password in
  clear text, modal dialogs sat top-left, invisible unchecked checkboxes
  in dark mode.
- Parallel run: compose.parallel.yaml, AUTO_RULE_SYNC_DISABLED switch and
  docs/operations.md §8 (start, rollback, cutover).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:24:05 +01:00

265 lines
8.8 KiB
TypeScript

"use client";
import { useRef, useState, type FormEvent } from "react";
import { Alert, Button } from "@sakaniui/react";
import { IconDownload } from "@sakaniui/react/icons";
import { formatBerlinDate } from "@/modules/downloads/format";
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
type UsageDialogProps = Readonly<{
albumId: string;
assetId: string;
filename: string;
newUsagePriceCents: number;
priorUsages: DownloadDialogUsage[];
}>;
type IntentResponse = {
downloadId: string;
fileUrl: string;
priceCents: number;
billable: boolean;
};
const priceFormatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
export function UsageDialog({
albumId,
assetId,
filename,
newUsagePriceCents,
priorUsages,
}: UsageDialogProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
const firstChoiceRef = useRef<HTMLInputElement>(null);
const idempotencyKeyRef = useRef<string | null>(null);
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
const [choice, setChoice] = useState(initialChoice);
const [purpose, setPurpose] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
function openDialog() {
setChoice(initialChoice);
setPurpose("");
setPending(false);
setError(null);
idempotencyKeyRef.current = null;
dialogRef.current?.showModal();
requestAnimationFrame(() => firstChoiceRef.current?.focus());
}
function closeDialog() {
if (!pending) dialogRef.current?.close();
}
function resetSubmission() {
idempotencyKeyRef.current = null;
setError(null);
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (pending) return;
setPending(true);
setError(null);
idempotencyKeyRef.current ??= crypto.randomUUID();
const payload = choice.startsWith("repeat:")
? {
kind: "repeat_download" as const,
usageId: choice.slice("repeat:".length),
idempotencyKey: idempotencyKeyRef.current,
}
: {
kind: "new_usage" as const,
assetId,
albumId,
purpose,
idempotencyKey: idempotencyKeyRef.current,
};
try {
const response = await fetch("/api/download-intents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const code = await readErrorCode(response);
setError(downloadErrorMessage(code, response.status));
return;
}
const intent = (await response.json()) as IntentResponse;
if (!isLocalDownloadUrl(intent.fileUrl, intent.downloadId)) {
throw new Error("invalid download url");
}
const link = document.createElement("a");
link.href = intent.fileUrl;
link.download = filename;
link.click();
dialogRef.current?.close();
idempotencyKeyRef.current = null;
} catch {
// Network failure / response not JSON — the server-code cases are
// handled above; this is only a transport-level failure.
setError("Der Download konnte nicht vorbereitet werden (Netzwerkfehler). Versuchen Sie es erneut.");
} finally {
setPending(false);
}
}
const isNewUsage = choice === "new_usage";
return (
<>
<Button leftIcon={<IconDownload size={16} />} onClick={openDialog} size="sm" type="button" variant="secondary">
Original laden
</Button>
<dialog
aria-labelledby={`usage-dialog-title-${assetId}`}
className="usage-dialog"
onCancel={(event) => {
if (pending) event.preventDefault();
}}
onClose={() => {
setError(null);
idempotencyKeyRef.current = null;
}}
ref={dialogRef}
>
<form onSubmit={submit}>
<div className="usage-dialog-heading">
<p className="editorial-kicker">Download · {filename}</p>
<h2 id={`usage-dialog-title-${assetId}`}>Nutzung auswählen</h2>
<p>Ordnen Sie das Original einer bestehenden oder einer neuen Nutzung zu.</p>
</div>
<fieldset className="usage-options" disabled={pending}>
<legend>Abrechnung</legend>
{priorUsages.map((usage, index) => (
<label className="usage-option" key={usage.id}>
<input
checked={choice === `repeat:${usage.id}`}
name={`usage-${assetId}`}
onChange={() => {
setChoice(`repeat:${usage.id}`);
resetSubmission();
}}
ref={index === 0 ? firstChoiceRef : undefined}
type="radio"
value={`repeat:${usage.id}`}
/>
<span>
<strong>{usage.purpose}</strong>
<small>Bestehende Nutzung · {formatDate(usage.createdAt)}</small>
</span>
<b>{priceFormatter.format(0)}</b>
</label>
))}
<label className="usage-option">
<input
checked={isNewUsage}
name={`usage-${assetId}`}
onChange={() => {
setChoice("new_usage");
resetSubmission();
}}
ref={priorUsages.length === 0 ? firstChoiceRef : undefined}
type="radio"
value="new_usage"
/>
<span>
<strong>Neue Nutzung</strong>
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
</span>
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
</label>
</fieldset>
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
Verwendungszweck
<textarea
disabled={!isNewUsage || pending}
id={`usage-purpose-${assetId}`}
maxLength={200}
minLength={3}
onChange={(event) => {
setPurpose(event.target.value);
resetSubmission();
}}
required={isNewUsage}
rows={3}
value={purpose}
/>
</label>
{error ? <Alert color="danger" description={error} /> : null}
<div className="usage-dialog-actions">
<Button disabled={pending} onClick={closeDialog} type="button" variant="ghost">
Abbrechen
</Button>
<Button disabled={pending} type="submit">
{pending
? "Download wird vorbereitet …"
: error
? "Download erneut anfordern"
: "Download anfordern"}
</Button>
</div>
</form>
</dialog>
</>
);
}
function formatDate(value: string): string {
const date = new Date(value);
return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : formatBerlinDate(date);
}
function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean {
return fileUrl === `/api/downloads/${encodeURIComponent(downloadId)}/file`;
}
async function readErrorCode(response: Response): Promise<string | null> {
try {
const data = (await response.json()) as { code?: unknown };
return typeof data.code === "string" ? data.code : null;
} catch {
return null;
}
}
// Map the server's stable error codes (see intent-handler.ts) to specific
// German messages so the editorial sees the real reason instead of a generic
// "try again". The fallback includes the raw code so unmapped failures are
// still actionable when reported back.
function downloadErrorMessage(code: string | null, status: number): string {
switch (code) {
case "FORBIDDEN":
return "Ihr Konto ist nicht freigegeben oder gesperrt.";
case "INVALID_REQUEST":
return "Die Anfrage war unvollständig. Bitte laden Sie die Seite neu und versuchen Sie es erneut.";
case "IDEMPOTENCY_CONFLICT":
return "Dieser Download wurde bereits registriert. Bitte laden Sie die Seite neu.";
case "NOT_FOUND":
return "Das Bild ist nicht im freigegebenen Album enthalten oder wurde daraus entfernt.";
case "UPSTREAM_UNAVAILABLE":
return "Immich ist momentan nicht erreichbar. Bitte versuchen Sie es in wenigen Minuten erneut.";
case "INVALID_ASSET":
return "Dieses Asset ist kein Bild und kann nicht lizenziert werden.";
case "ACCOUNTING_UNAVAILABLE":
return "Für Ihr Konto ist noch kein Preis hinterlegt. Bitte den Admin, einen Preis festzulegen.";
case "CROSS_ORIGIN_REQUEST":
return "Die Anfrage wurde aus einer unzulässigen Herkunft gestellt.";
default:
return `Download fehlgeschlagen (Code ${code ?? status}). Bitte erneut versuchen.`;
}
}