194 lines
8.0 KiB
TypeScript
194 lines
8.0 KiB
TypeScript
"use client";
|
|
|
|
import { useRef, useState, type FormEvent } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Alert, Button, Input } from "@sakaniui/react";
|
|
import { IconDownload } from "@sakaniui/react/icons";
|
|
|
|
import { formatBerlinDate } from "@/modules/downloads/format";
|
|
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
|
|
|
|
type Photo = { assetId: string; albumId: string; filename: string };
|
|
type Choice = { selection: string; purpose?: string };
|
|
|
|
const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
|
|
|
export function DownloadLightboxForm({
|
|
photos,
|
|
options,
|
|
}: {
|
|
photos: Photo[];
|
|
options: EditorialDownloadOptions;
|
|
}) {
|
|
const [loading, setLoading] = useState(false);
|
|
const [choices, setChoices] = useState<Record<string, Choice>>({});
|
|
const [commonPurpose, setCommonPurpose] = useState("");
|
|
const [error, setError] = useState<string | null>(null);
|
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
|
const inFlight = useRef(false);
|
|
const intentKeys = useRef(new Map<string, string>());
|
|
const router = useRouter();
|
|
|
|
const selected = photos.filter(({ assetId }) => {
|
|
const selection = choices[assetId]?.selection;
|
|
return Boolean(selection && selection !== "skip");
|
|
});
|
|
const newPhotos = selected.filter(({ assetId }) => choices[assetId].selection === "new");
|
|
const price = priceFormatter.format(options.priceCents / 100);
|
|
const ready = selected.length > 0 && selected.length <= 100 &&
|
|
photos.every(({ assetId }) => currentSelection(assetId)) &&
|
|
newPhotos.every(({ assetId }) => [...purposeFor(choices[assetId])].length >= 3);
|
|
|
|
function currentSelection(assetId: string) {
|
|
const selection = choices[assetId]?.selection;
|
|
if (selection === "new" || selection === "skip") return selection;
|
|
return options.priorUsagesByAsset[assetId]?.find(({ id }) => id === selection)?.id ?? "";
|
|
}
|
|
|
|
function purposeFor(choice: Choice) {
|
|
return choice.purpose?.trim() || commonPurpose.trim();
|
|
}
|
|
|
|
async function handleBulkDownload(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
if (!ready || inFlight.current) return;
|
|
inFlight.current = true;
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const items = selected.map(({ assetId, albumId }) => {
|
|
const choice = choices[assetId];
|
|
const purpose = choice.selection === "new" ? purposeFor(choice) : undefined;
|
|
const key = JSON.stringify([assetId, choice.selection, purpose]);
|
|
let idempotencyKey = intentKeys.current.get(key);
|
|
if (!idempotencyKey) {
|
|
idempotencyKey = crypto.randomUUID();
|
|
intentKeys.current.set(key, idempotencyKey);
|
|
}
|
|
return purpose
|
|
? { assetId, albumId, purpose, idempotencyKey }
|
|
: { assetId, usageId: choice.selection, idempotencyKey };
|
|
});
|
|
|
|
const response = await fetch("/api/lightbox/bulk-download", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ items, maxPriceCents: options.priceCents }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const payload = await response.json().catch(() => null);
|
|
if (payload?.code === "INVALID_PRICE") {
|
|
router.refresh();
|
|
throw new Error("Der Tarif hat sich geändert. Bitte prüfen Sie den aktualisierten Preis.");
|
|
}
|
|
if (payload?.code === "IDEMPOTENCY_CONFLICT") {
|
|
router.refresh();
|
|
throw new Error("Der Downloadversuch ist bereits erfasst. Prüfen Sie Ihre Nutzungen, bevor Sie einen neuen Zweck buchen.");
|
|
}
|
|
throw new Error("Bitte prüfen Sie die Auswahl und versuchen Sie es erneut.");
|
|
}
|
|
|
|
const blob = await response.blob();
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement("a");
|
|
link.href = url;
|
|
link.download = "leuchtkasten.zip";
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
|
|
intentKeys.current.clear();
|
|
dialogRef.current?.close();
|
|
setChoices({});
|
|
setCommonPurpose("");
|
|
router.refresh();
|
|
} catch (error) {
|
|
setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
|
|
} finally {
|
|
inFlight.current = false;
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Button leftIcon={<IconDownload size={16} />} onClick={() => dialogRef.current?.showModal()} type="button">
|
|
ZIP-Download vorbereiten
|
|
</Button>
|
|
|
|
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
|
|
<form className="flex flex-col gap-4 p-6" method="post" onSubmit={handleBulkDownload}>
|
|
<h2 id="bulk-download-title" className="text-xl font-semibold">Nutzungen für ZIP-Download</h2>
|
|
<Input
|
|
disabled={loading}
|
|
label="Gemeinsamer Zweck für neue Nutzungen"
|
|
maxLength={200}
|
|
onChange={(event) => setCommonPurpose(event.target.value)}
|
|
value={commonPurpose}
|
|
/>
|
|
<ul className="flex flex-col gap-4">
|
|
{photos.map(({ assetId, filename }) => {
|
|
const choice = choices[assetId];
|
|
return (
|
|
<li key={assetId} className="flex flex-col gap-2">
|
|
<label className="flex flex-col gap-1 text-sm font-medium">
|
|
{filename}
|
|
<select
|
|
className="rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-2 text-[var(--color-fg-default)]"
|
|
disabled={loading}
|
|
onChange={(event) => {
|
|
const selection = event.target.value;
|
|
setChoices((previous) => ({ ...previous, [assetId]: { selection } }));
|
|
}}
|
|
value={currentSelection(assetId)}
|
|
>
|
|
<option value="">Nutzung auswählen</option>
|
|
<option value="new">Neue Nutzung · bis {price} netto</option>
|
|
{(options.priorUsagesByAsset[assetId] ?? []).map((usage) => (
|
|
<option key={usage.id} value={usage.id}>
|
|
{usage.purpose} ({formatBerlinDate(new Date(usage.createdAt))}) · kostenlos wiederholen
|
|
</option>
|
|
))}
|
|
<option value="skip">Bild auslassen</option>
|
|
</select>
|
|
</label>
|
|
{choice?.selection === "new" && (
|
|
<Input
|
|
disabled={loading}
|
|
label={`Eigener Zweck für ${filename}`}
|
|
maxLength={200}
|
|
onChange={(event) => {
|
|
const purpose = event.target.value;
|
|
setChoices((previous) => ({ ...previous, [assetId]: { selection: "new", purpose } }));
|
|
}}
|
|
value={choice.purpose ?? ""}
|
|
/>
|
|
)}
|
|
</li>
|
|
);
|
|
})}
|
|
</ul>
|
|
{newPhotos.length > 0 && (
|
|
<p className="text-sm" role="status">
|
|
{newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} · bis{" "}
|
|
{priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto.
|
|
Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet.
|
|
</p>
|
|
)}
|
|
{selected.length > 100 && <Alert color="warning" description="Wählen Sie höchstens 100 Bilder pro ZIP aus." />}
|
|
{error && <Alert color="danger" description={error} />}
|
|
<div className="mt-4 flex justify-end gap-3">
|
|
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
|
|
Abbrechen
|
|
</Button>
|
|
<Button disabled={loading || !ready} type="submit">
|
|
{loading ? "Wird verpackt …" : newPhotos.length ? "Nutzungen bestätigen und laden" : "ZIP herunterladen"}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
</dialog>
|
|
</>
|
|
);
|
|
}
|