"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>({}); const [commonPurpose, setCommonPurpose] = useState(""); const [error, setError] = useState(null); const dialogRef = useRef(null); const inFlight = useRef(false); const intentKeys = useRef(new Map()); 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) { 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 ( <>

Nutzungen für ZIP-Download

setCommonPurpose(event.target.value)} value={commonPurpose} />
    {photos.map(({ assetId, filename }) => { const choice = choices[assetId]; return (
  • {choice?.selection === "new" && ( { const purpose = event.target.value; setChoices((previous) => ({ ...previous, [assetId]: { selection: "new", purpose } })); }} value={choice.purpose ?? ""} /> )}
  • ); })}
{newPhotos.length > 0 && (

{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.

)} {selected.length > 100 && } {error && }
); }