Merge branch 'codex/immich-redaktionsportal' into main
This commit is contained in:
commit
64147a3282
13 files changed
+909
-106
No files matched your search
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes";
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
} from "recharts";
|
||||
|
||||
type DownloadsChartProps = {
|
||||
data: { date: string; downloads: number }[];
|
||||
};
|
||||
|
||||
export function DownloadsChart({ data }: DownloadsChartProps) {
|
||||
const { theme } = useTheme();
|
||||
|
||||
// Indigo primary color variables
|
||||
const primaryColor = theme === "dark" ? "#6366f1" : "#4f46e5"; // indigo-500 : indigo-600
|
||||
|
||||
return (
|
||||
<div className="h-[300px] w-full mt-4">
|
||||
{data.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-muted-foreground">
|
||||
Keine Download-Daten in den letzten 30 Tagen verfügbar.
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={data} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={theme === "dark" ? "#333" : "#e5e5e5"} />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
stroke="#888888"
|
||||
fontSize={12}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={(value) => {
|
||||
const date = new Date(value);
|
||||
return date.toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
stroke="#888888"
|
||||
fontSize={12}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={(value) => `${value}`}
|
||||
allowDecimals={false}
|
||||
/>
|
||||
<Tooltip
|
||||
cursor={{ fill: theme === "dark" ? "#ffffff10" : "#00000005" }}
|
||||
contentStyle={{
|
||||
backgroundColor: theme === "dark" ? "#1f2937" : "#ffffff",
|
||||
borderColor: theme === "dark" ? "#374151" : "#e5e7eb",
|
||||
borderRadius: "8px",
|
||||
color: theme === "dark" ? "#f3f4f6" : "#111827",
|
||||
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
|
||||
}}
|
||||
labelFormatter={(label: any) => {
|
||||
const date = new Date(label as string);
|
||||
return date.toLocaleDateString("de-DE", { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' });
|
||||
}}
|
||||
formatter={(value: any) => [value as number, "Downloads"]}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="downloads"
|
||||
fill={primaryColor}
|
||||
radius={[4, 4, 0, 0]}
|
||||
maxBarSize={40}
|
||||
animationDuration={1000}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import Link from "next/link";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DownloadsChart } from "./downloads-chart";
|
||||
|
||||
export default async function AdminDashboardPage() {
|
||||
await requireAdmin(new Headers(await headers()));
|
||||
@@ -48,6 +49,33 @@ export default async function AdminDashboardPage() {
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5);
|
||||
|
||||
// 4. Time-series data for the last 30 days
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
|
||||
const dailyDownloads = await db
|
||||
.select({
|
||||
date: sql<string>`DATE_TRUNC('day', ${usages.createdAt})::date::text`,
|
||||
downloads: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, thirtyDaysAgo))
|
||||
.groupBy(sql`DATE_TRUNC('day', ${usages.createdAt})`)
|
||||
.orderBy(sql`DATE_TRUNC('day', ${usages.createdAt})`);
|
||||
|
||||
// Fill in missing days
|
||||
const chartData = [];
|
||||
for (let i = 29; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const dateStr = d.toISOString().split('T')[0];
|
||||
const record = dailyDownloads.find(r => r.date === dateStr);
|
||||
chartData.push({
|
||||
date: dateStr,
|
||||
downloads: record ? record.downloads : 0,
|
||||
});
|
||||
}
|
||||
|
||||
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
return (
|
||||
@@ -83,6 +111,16 @@ export default async function AdminDashboardPage() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Downloads der letzten 30 Tage</CardTitle>
|
||||
<CardDescription>Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DownloadsChart data={chartData} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { desc } from "drizzle-orm";
|
||||
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import Link from "next/link";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
|
||||
export default async function EditorialsPage() {
|
||||
const editorials = await db
|
||||
@@ -24,51 +24,88 @@ export default async function EditorialsPage() {
|
||||
const archivedEditorials = editorials.filter((e) => e.archivedAt);
|
||||
|
||||
return (
|
||||
<section className="content-section" aria-labelledby="editorials-title">
|
||||
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500 max-w-7xl">
|
||||
<PageHeader
|
||||
kicker="Kontoverwaltung"
|
||||
title="Redaktionen"
|
||||
titleId="editorials-title"
|
||||
description="Verwalte hier alle registrierten und archivierten Redaktionszugänge."
|
||||
/>
|
||||
|
||||
{activeEditorials.length === 0 ? (
|
||||
<p>Noch keine aktiven Redaktionen registriert.</p>
|
||||
<p className="text-muted-foreground">Noch keine aktiven Redaktionen registriert.</p>
|
||||
) : (
|
||||
<ul>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{activeEditorials.map((editorial) => (
|
||||
<li key={editorial.id}>
|
||||
<a href={`/admin/redaktionen/${editorial.id}`}>{editorial.name}</a>
|
||||
<p>
|
||||
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
|
||||
{editorial.currentPriceCents === null
|
||||
? " · Preis noch nicht festgelegt"
|
||||
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||
</p>
|
||||
</li>
|
||||
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group">
|
||||
<Card className="h-full transition-all duration-300 hover:shadow-md hover:border-primary-500/50 hover:-translate-y-1">
|
||||
<CardContent className="p-6 flex flex-col h-full justify-between">
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
|
||||
{editorial.name}
|
||||
</h3>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">Kontakt:</span> {editorial.contactName}
|
||||
</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">E-Mail:</span> {editorial.loginEmail}
|
||||
</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">Status:</span>
|
||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
|
||||
editorial.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" :
|
||||
editorial.status === "pending_approval" ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" :
|
||||
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
|
||||
}`}>
|
||||
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 pt-4 border-t border-border">
|
||||
<p className="text-sm font-medium">
|
||||
{editorial.currentPriceCents === null
|
||||
? "Preis noch nicht festgelegt"
|
||||
: `Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{archivedEditorials.length > 0 && (
|
||||
<details className="mt-8">
|
||||
<summary className="cursor-pointer text-sm font-semibold text-gray-500 uppercase tracking-widest">
|
||||
<details className="mt-12 group">
|
||||
<summary className="cursor-pointer flex items-center gap-2 text-sm font-semibold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-colors mb-6 list-none">
|
||||
<span className="bg-muted p-1 rounded-sm group-open:rotate-90 transition-transform">
|
||||
▶
|
||||
</span>
|
||||
Archivierte Redaktionen ({archivedEditorials.length})
|
||||
</summary>
|
||||
<ul className="mt-4 opacity-75">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 opacity-75 grayscale hover:grayscale-0 transition-all duration-500">
|
||||
{archivedEditorials.map((editorial) => (
|
||||
<li key={editorial.id}>
|
||||
<a href={`/admin/redaktionen/${editorial.id}`} className="text-gray-600">
|
||||
{editorial.name}
|
||||
</a>
|
||||
<p className="text-gray-500">
|
||||
{editorial.contactName} · {editorial.loginEmail} · Archiviert am:{" "}
|
||||
{editorial.archivedAt?.toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
</li>
|
||||
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group">
|
||||
<Card className="h-full transition-all duration-300 hover:shadow-sm">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-2 text-muted-foreground group-hover:text-foreground transition-colors">
|
||||
{editorial.name}
|
||||
</h3>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p>{editorial.contactName} · {editorial.loginEmail}</p>
|
||||
<p className="pt-2">
|
||||
Archiviert am: {editorial.archivedAt?.toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,17 @@ import { expect, test, vi } from "vitest";
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { createThumbnailHandler } from "./thumbnail-handler";
|
||||
|
||||
vi.mock("sharp", () => {
|
||||
return {
|
||||
default: () => ({
|
||||
metadata: vi.fn().mockResolvedValue({ width: 100, height: 100 }),
|
||||
composite: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
toBuffer: vi.fn().mockResolvedValue(Buffer.from(new Uint8Array([1, 2, 3]))),
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const grantedAlbum = {
|
||||
id: "allowed",
|
||||
albumName: "Freigegebenes Heimspiel",
|
||||
@@ -42,9 +53,15 @@ function createHandler(options?: {
|
||||
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
|
||||
immich: {
|
||||
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
|
||||
getAsset: vi.fn().mockImplementation(async () => {
|
||||
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
|
||||
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({ id }));
|
||||
return {
|
||||
id: "asset-1",
|
||||
originalFileName: "foo.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
type: "IMAGE",
|
||||
albums: (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({ id })),
|
||||
};
|
||||
}),
|
||||
getAlbum: vi.fn().mockImplementation(async () => {
|
||||
return {
|
||||
@@ -88,7 +105,7 @@ test("refuses a thumbnail immediately after its last grant is revoked", async ()
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getAsset).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -147,8 +164,8 @@ test("uses one asset-album membership lookup for a 60-photo gallery regardless o
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.getAsset).toHaveBeenCalledTimes(1);
|
||||
expect(dependencies.immich.getAsset).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
|
||||
type ThumbnailImmich = {
|
||||
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
|
||||
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
|
||||
getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>;
|
||||
getThumbnail(assetId: string): Promise<ImmichBinary>;
|
||||
};
|
||||
|
||||
@@ -83,7 +84,8 @@ async function isGrantedEditorialAsset(
|
||||
return false;
|
||||
}
|
||||
|
||||
const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
|
||||
const asset = await dependencies.immich.getAsset(assetId);
|
||||
const assetAlbums = asset.albums;
|
||||
const granted = new Set(grantedAlbumIds);
|
||||
return assetAlbums.some((album) => granted.has(album.id));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { usageService } from "@/modules/usages/service";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { albumGrantService } from "@/modules/albums/grants";
|
||||
const archiver = require("archiver");
|
||||
import { Readable } from "stream";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const principal = await requireActiveEditorial(request.headers);
|
||||
const { assetIds, purpose } = await request.json();
|
||||
|
||||
if (!Array.isArray(assetIds) || assetIds.length === 0 || !purpose) {
|
||||
return new Response("Invalid request", { status: 400 });
|
||||
}
|
||||
|
||||
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId);
|
||||
const grantedSet = new Set(grantedAlbumIds);
|
||||
|
||||
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
|
||||
|
||||
for (const assetId of assetIds) {
|
||||
// 1. Fetch asset to find its albums
|
||||
let asset;
|
||||
try {
|
||||
asset = await immichClient.getAsset(assetId);
|
||||
} catch (err) {
|
||||
console.error("Asset fetch failed", assetId, err);
|
||||
continue; // Skip unavailable assets
|
||||
}
|
||||
|
||||
// 2. Find the first album the editorial has access to
|
||||
const validAlbum = asset.albums.find(a => grantedSet.has(a.id));
|
||||
if (!validAlbum) continue; // Editorial does not have access
|
||||
|
||||
// 3. Check for prior usages to avoid double charging
|
||||
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
|
||||
const isRepeat = priorUsages.length > 0;
|
||||
|
||||
// 4. Create new usage (or repeat download if prior usages exist)
|
||||
// Since createNewUsage handles idempotent repeats automatically, we just need to pass an idempotency key.
|
||||
const idempotencyKey = `${principal.editorialId}-${assetId}-${purpose}`;
|
||||
|
||||
const newUsage = await usageService.createNewUsage({
|
||||
editorialId: principal.editorialId,
|
||||
assetId,
|
||||
albumId: validAlbum.id,
|
||||
purpose,
|
||||
reference: undefined,
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
downloadsToProcess.push({
|
||||
assetId,
|
||||
downloadId: newUsage.id,
|
||||
filename: asset.originalFileName,
|
||||
intentKind: isRepeat ? "repeat" : "new_usage",
|
||||
});
|
||||
}
|
||||
|
||||
if (downloadsToProcess.length === 0) {
|
||||
return new Response("No valid assets found for download", { status: 404 });
|
||||
}
|
||||
|
||||
// Create a streaming response with archiver
|
||||
const archive = archiver('zip', { zlib: { level: 0 } }); // No compression, images are already compressed
|
||||
|
||||
// We must return a ReadableStream to Next.js
|
||||
const transformStream = new TransformStream();
|
||||
|
||||
// Pipe archiver output to the writable side of the TransformStream
|
||||
const writableNodeStream = new WritableStreamToNodeStream(transformStream.writable);
|
||||
archive.pipe(writableNodeStream);
|
||||
|
||||
// Start appending files asynchronously
|
||||
(async () => {
|
||||
for (const download of downloadsToProcess) {
|
||||
// Claim the download to verify it's authorized
|
||||
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
|
||||
if (claim.outcome !== "claimed") continue;
|
||||
|
||||
try {
|
||||
const original = await immichClient.getOriginal(download.assetId);
|
||||
|
||||
// Track bytes read for accounting
|
||||
let transferredBytes = 0;
|
||||
const trackingTransform = new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
transferredBytes += chunk.length;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
async flush() {
|
||||
await downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes);
|
||||
}
|
||||
});
|
||||
|
||||
const trackedStream = original.body.pipeThrough(trackingTransform);
|
||||
const nodeStream = Readable.fromWeb(trackedStream as any);
|
||||
|
||||
archive.append(nodeStream, { name: download.filename });
|
||||
} catch (err) {
|
||||
console.error("Failed to append original for asset", download.assetId, err);
|
||||
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
|
||||
voidNewUsage: download.intentKind === "new_usage"
|
||||
});
|
||||
}
|
||||
}
|
||||
archive.finalize();
|
||||
})();
|
||||
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
return new Response(transformStream.readable, {
|
||||
headers: {
|
||||
"Content-Type": "application/zip",
|
||||
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
||||
},
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error("Bulk download failed", err);
|
||||
return new Response("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to convert Web WritableStream to Node Writable Stream
|
||||
import { Writable } from "stream";
|
||||
class WritableStreamToNodeStream extends Writable {
|
||||
private writer: WritableStreamDefaultWriter<any>;
|
||||
|
||||
constructor(writableStream: WritableStream) {
|
||||
super();
|
||||
this.writer = writableStream.getWriter();
|
||||
}
|
||||
|
||||
_write(chunk: any, encoding: string, callback: (error?: Error | null) => void) {
|
||||
this.writer.write(chunk).then(() => callback()).catch(callback);
|
||||
}
|
||||
|
||||
_final(callback: (error?: Error | null) => void) {
|
||||
this.writer.close().then(() => callback()).catch(callback);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const [purpose, setPurpose] = useState("");
|
||||
const router = useRouter();
|
||||
|
||||
function handleBulkDownload() {
|
||||
alert("Bulk-Download ist aktuell in Entwicklung. Bitte klicke auf die Bilder, um sie einzeln herunterzuladen.");
|
||||
async function handleBulkDownload(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!purpose.trim() || assetIds.length === 0) return;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/lightbox/bulk-download", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assetIds, purpose }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Download fehlgeschlagen");
|
||||
}
|
||||
|
||||
// Download the ZIP file
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `leuchtkasten-${new Date().toISOString().split("T")[0]}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
dialogRef.current?.close();
|
||||
setPurpose("");
|
||||
router.refresh(); // Refresh to update usage history
|
||||
} catch (err) {
|
||||
alert("Es gab einen Fehler beim Bulk-Download. Bitte versuche es später erneut.");
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleBulkDownload}
|
||||
disabled={loading || assetIds.length === 0}
|
||||
className="primary-action m-0"
|
||||
>
|
||||
Alle herunterladen
|
||||
</button>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dialogRef.current?.showModal()}
|
||||
disabled={assetIds.length === 0}
|
||||
className="primary-action m-0"
|
||||
>
|
||||
Alle herunterladen
|
||||
</button>
|
||||
|
||||
<dialog ref={dialogRef} className="rounded-xl p-0 backdrop:bg-black/50 shadow-2xl border border-border bg-card text-card-foreground overflow-hidden max-w-md w-full">
|
||||
<div className="p-6">
|
||||
<h2 className="text-xl font-bold mb-4">Verwendungszweck angeben</h2>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen.
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleBulkDownload}>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="purpose" className="block text-sm font-medium mb-1">
|
||||
Verwendungszweck
|
||||
</label>
|
||||
<input
|
||||
id="purpose"
|
||||
type="text"
|
||||
required
|
||||
placeholder="z.B. Webseite, Social Media"
|
||||
value={purpose}
|
||||
onChange={(e) => setPurpose(e.target.value)}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dialogRef.current?.close()}
|
||||
className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2"
|
||||
disabled={loading}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2"
|
||||
disabled={loading || !purpose.trim()}
|
||||
>
|
||||
{loading ? "Wird verpackt..." : "Download starten (ZIP)"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +1,23 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import React from "react";
|
||||
|
||||
export interface PageHeaderProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
kicker?: React.ReactNode;
|
||||
title: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
titleId?: string;
|
||||
}
|
||||
type PageHeaderProps = {
|
||||
kicker: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export function PageHeader({
|
||||
className,
|
||||
kicker,
|
||||
title,
|
||||
description,
|
||||
titleId,
|
||||
children,
|
||||
...props
|
||||
}: PageHeaderProps) {
|
||||
export function PageHeader({ kicker, title, description }: PageHeaderProps) {
|
||||
return (
|
||||
<header className={cn("mb-8", className)} {...props}>
|
||||
{kicker && <p className="editorial-kicker">{kicker}</p>}
|
||||
<div className="editorial-title-row">
|
||||
<h1 id={titleId}>{title}</h1>
|
||||
{description && <p>{description}</p>}
|
||||
{children}
|
||||
<div className="editorial-section">
|
||||
<p className="editorial-kicker text-sm font-semibold text-muted-foreground tracking-widest uppercase mb-2">{kicker}</p>
|
||||
<div className="editorial-title-row mb-6">
|
||||
<h1 className="text-4xl font-bold tracking-tight text-foreground">{title}</h1>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
{description && (
|
||||
<p className="text-lg text-muted-foreground max-w-3xl mb-8">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -101,8 +101,6 @@ function createService() {
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
albums: [{ id: albumId }],
|
||||
}),
|
||||
};
|
||||
@@ -157,7 +155,7 @@ test("canonicalizes every UUID before fingerprinting, lookup, Immich calls, and
|
||||
expect(second).toEqual(first);
|
||||
expect(usages).toHaveLength(1);
|
||||
expect(usages[0]).toMatchObject({ editorialId, assetId, albumId, idempotencyKey });
|
||||
expect(immich.getAlbum).toHaveBeenCalledWith(albumId);
|
||||
expect(immich.listAlbumsForAsset).toHaveBeenCalledWith(assetId);
|
||||
expect(immich.getAsset).toHaveBeenCalledWith(assetId);
|
||||
});
|
||||
|
||||
@@ -226,8 +224,8 @@ test.each([
|
||||
}),
|
||||
).rejects.toMatchObject({ code });
|
||||
expect(findIntent).not.toHaveBeenCalled();
|
||||
expect(immich.getAlbum).not.toHaveBeenCalled();
|
||||
expect(immich.getAsset).not.toHaveBeenCalled();
|
||||
expect(immich.getAlbum).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -235,8 +233,9 @@ test("rejects an asset outside the exact requested album", async () => {
|
||||
const { service, immich, usages } = createService();
|
||||
immich.getAsset.mockResolvedValue({
|
||||
id: assetId,
|
||||
type: "IMAGE",
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
albums: [{ id: otherAlbumId }],
|
||||
});
|
||||
|
||||
@@ -249,18 +248,21 @@ test("rejects an asset outside the exact requested album", async () => {
|
||||
|
||||
test("rejects removal from the requested album between preflight and locked refresh", async () => {
|
||||
const { service, immich, usages } = createService();
|
||||
const currentAsset = {
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
albums: [{ id: albumId }],
|
||||
};
|
||||
immich.getAsset
|
||||
.mockResolvedValueOnce(currentAsset)
|
||||
.mockResolvedValueOnce({ ...currentAsset, albums: [] });
|
||||
.mockResolvedValueOnce({
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
albums: [{ id: albumId }],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
albums: [],
|
||||
});
|
||||
|
||||
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
|
||||
code: "ASSET_NOT_IN_ALBUM",
|
||||
@@ -271,9 +273,23 @@ test("rejects removal from the requested album between preflight and locked refr
|
||||
|
||||
test("persists metadata from the locked final Immich refresh", async () => {
|
||||
const { service, immich, usages } = createService();
|
||||
immich.getAlbum
|
||||
.mockResolvedValueOnce({ id: albumId, albumName: "Presse 2026" })
|
||||
.mockResolvedValueOnce({ id: albumId, albumName: "Presse final" });
|
||||
immich.getAsset
|
||||
.mockResolvedValueOnce({
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
albums: [{ id: albumId }],
|
||||
})
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: albumId,
|
||||
albumName: "Presse final",
|
||||
description: null,
|
||||
albumThumbnailAssetId: assetId,
|
||||
assetCount: 1,
|
||||
},
|
||||
]);
|
||||
const currentAsset = {
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
@@ -294,7 +310,6 @@ test("persists metadata from the locked final Immich refresh", async () => {
|
||||
await service.createNewUsage(newUsageInput);
|
||||
|
||||
expect(immich.getAsset).toHaveBeenCalledTimes(2);
|
||||
expect(immich.getAlbum).toHaveBeenCalledTimes(2);
|
||||
expect(usages).toEqual([
|
||||
expect.objectContaining({ albumName: "Presse final", filename: "final.jpg" }),
|
||||
]);
|
||||
|
||||
@@ -60,9 +60,10 @@ type UsageImmich = {
|
||||
getAlbum(albumId: string): Promise<{ id: string; albumName: string }>;
|
||||
getAsset(assetId: string): Promise<{
|
||||
id: string;
|
||||
type: string;
|
||||
originalFileName: string;
|
||||
albums?: { id: string }[];
|
||||
originalMimeType: string;
|
||||
type: string;
|
||||
albums: Array<{ id: string }>;
|
||||
}>;
|
||||
};
|
||||
|
||||
@@ -88,16 +89,16 @@ export function createUsageService({
|
||||
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
|
||||
if (existing) return resolveIntent(existing, fingerprint, "new_usage");
|
||||
|
||||
const album = await loadRequestedAlbum(immich, input.assetId, input.albumId);
|
||||
const asset = await loadImageAsset(immich, input.assetId);
|
||||
const album = await loadRequestedAlbum(immich, asset, input.albumId);
|
||||
const persisted = await repository.createBillableIntent({
|
||||
...input,
|
||||
albumName: normalizeUpstreamSnapshot(album.albumName),
|
||||
filename: normalizeUpstreamSnapshot(asset.originalFileName),
|
||||
requestFingerprint: fingerprint,
|
||||
}, async () => {
|
||||
const currentAlbum = await loadRequestedAlbum(immich, input.assetId, input.albumId);
|
||||
const currentAsset = await loadImageAsset(immich, input.assetId);
|
||||
const currentAlbum = await loadRequestedAlbum(immich, currentAsset, input.albumId);
|
||||
return {
|
||||
albumName: normalizeUpstreamSnapshot(currentAlbum.albumName),
|
||||
filename: normalizeUpstreamSnapshot(currentAsset.originalFileName),
|
||||
@@ -329,18 +330,27 @@ function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput
|
||||
|
||||
async function loadRequestedAlbum(
|
||||
immich: UsageImmich,
|
||||
asset: Awaited<ReturnType<UsageImmich["getAsset"]>>,
|
||||
assetId: string,
|
||||
albumId: string,
|
||||
): Promise<{ id: string; albumName: string }> {
|
||||
if (!asset.albums?.some((a) => a.id === albumId)) {
|
||||
let asset;
|
||||
try {
|
||||
asset = await immich.getAsset(assetId);
|
||||
} catch {
|
||||
throw new UsageAccountingError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
|
||||
if (!asset.albums.some((a) => a.id === albumId)) {
|
||||
throw new UsageAccountingError("ASSET_NOT_IN_ALBUM");
|
||||
}
|
||||
|
||||
let album;
|
||||
try {
|
||||
album = await immich.getAlbum(albumId);
|
||||
} catch {
|
||||
throw new UsageAccountingError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
|
||||
return album;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user