feat: Add flatrate billing model for editorial accounts

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 03:27:10 +02:00
1 parent 699580a6a0
commit 0b1ffdfdfc
39 files changed
+4900 -57

No files matched your search

+2 -1
View File
@@ -10,9 +10,10 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
return (
<PortalShell
brandHref="/admin/redaktionen"
brandHref="/admin"
sectionLabel="Administration"
nav={[
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/redaktionen", label: "Redaktionen" },
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
{ href: "/admin/audit", label: "Audit" },
+132 -5
View File
@@ -1,7 +1,134 @@
import { redirect } from "next/navigation";
import { eq, sql, and, desc, gte } from "drizzle-orm";
import { db } from "@/db/client";
import { usages, editorialAccounts } from "@/db/schema";
import { requireAdmin } from "@/modules/auth/principal";
import { headers } from "next/headers";
import Link from "next/link";
// /admin has no dashboard of its own; the admin layout's wordmark links here,
// so route authenticated admins to the editorials list instead of 404ing.
export default function AdminIndexPage() {
redirect("/admin/redaktionen");
export default async function AdminDashboardPage() {
await requireAdmin(new Headers(await headers()));
const now = new Date();
const firstDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth(), 1));
// 1. Umsatz diesen Monat (Offen + Abgerechnet, aber nur usages aus diesem Monat)
const [revenueStats] = await db
.select({
totalCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
count: sql<number>`COUNT(${usages.id})::int`,
})
.from(usages)
.where(gte(usages.createdAt, firstDayOfMonth));
// 2. Aktivste Redaktionen (nach Anzahl an Downloads insgesamt)
const topEditorials = await db
.select({
editorialId: usages.editorialAccountId,
name: editorialAccounts.name,
downloadCount: sql<number>`COUNT(${usages.id})::int`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
.groupBy(usages.editorialAccountId, editorialAccounts.name)
.orderBy(desc(sql`COUNT(${usages.id})`))
.limit(5);
// 3. Beliebteste Alben
const topAlbums = await db
.select({
albumName: usages.albumNameSnapshot,
downloadCount: sql<number>`COUNT(${usages.id})::int`,
})
.from(usages)
.groupBy(usages.albumNameSnapshot)
.orderBy(desc(sql`COUNT(${usages.id})`))
.limit(5);
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
return (
<section className="content-section">
<h1>Admin Dashboard</h1>
<p className="text-gray-600 mb-8">Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals.</p>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
<div className="bg-white p-6 rounded-xl border border-gray-200 shadow-sm">
<h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wide">Umsatz diesen Monat</h2>
<p className="text-4xl font-bold text-green-600 mt-2">
{formatter.format((revenueStats?.totalCents ?? 0) / 100)}
</p>
<p className="text-sm text-gray-500 mt-2">
{revenueStats?.count ?? 0} lizenzierte Bilder im {now.toLocaleString("de-DE", { month: "long" })}
</p>
</div>
<div className="bg-white p-6 rounded-xl border border-gray-200 shadow-sm flex flex-col justify-center">
<Link href="/admin/redaktionen" className="primary-action text-center m-0">
Redaktionen verwalten
</Link>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
<div>
<h3 className="text-xl font-bold mb-4">Aktivste Redaktionen</h3>
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
{topEditorials.length === 0 ? (
<p className="p-4 text-gray-500">Noch keine Daten vorhanden.</p>
) : (
<table className="w-full text-left border-collapse">
<thead className="bg-gray-50">
<tr>
<th className="py-3 px-4 font-semibold text-gray-700">Redaktion</th>
<th className="py-3 px-4 font-semibold text-gray-700 text-right">Downloads</th>
<th className="py-3 px-4 font-semibold text-gray-700 text-right">Umsatz</th>
</tr>
</thead>
<tbody>
{topEditorials.map(ed => (
<tr key={ed.editorialId} className="border-t border-gray-100">
<td className="py-3 px-4">
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="text-blue-600 hover:underline">
{ed.name}
</Link>
</td>
<td className="py-3 px-4 text-right">{ed.downloadCount}</td>
<td className="py-3 px-4 text-right">{formatter.format(ed.revenueCents / 100)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
<div>
<h3 className="text-xl font-bold mb-4">Beliebteste Alben</h3>
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
{topAlbums.length === 0 ? (
<p className="p-4 text-gray-500">Noch keine Daten vorhanden.</p>
) : (
<table className="w-full text-left border-collapse">
<thead className="bg-gray-50">
<tr>
<th className="py-3 px-4 font-semibold text-gray-700">Album</th>
<th className="py-3 px-4 font-semibold text-gray-700 text-right">Downloads</th>
</tr>
</thead>
<tbody>
{topAlbums.map(album => (
<tr key={album.albumName} className="border-t border-gray-100">
<td className="py-3 px-4 font-medium text-gray-800">{album.albumName}</td>
<td className="py-3 px-4 text-right text-gray-600">{album.downloadCount}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
</div>
</section>
);
}
+39
View File
@@ -3,6 +3,9 @@
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { requireAdmin } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
@@ -74,6 +77,42 @@ export async function reactivateEditorialAction(editorialId: string): Promise<vo
revalidatePath(`/admin/redaktionen/${editorialId}`);
}
export async function updateFlatrateAction(editorialId: string, formData: FormData): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId);
const flatrateActive = formData.get("flatrateActive") === "on";
let flatratePriceCents: number | null = null;
const rawPrice = formData.get("flatratePriceEuros");
if (rawPrice && typeof rawPrice === "string" && rawPrice.trim() !== "") {
const price = parsePriceCents(rawPrice);
if (price.ok) {
flatratePriceCents = price.cents;
}
}
let flatrateAssetLimit: number | null = null;
const rawLimit = formData.get("flatrateAssetLimit");
if (rawLimit && typeof rawLimit === "string" && rawLimit.trim() !== "") {
const limit = parseInt(rawLimit, 10);
if (Number.isFinite(limit) && limit >= 1) {
flatrateAssetLimit = limit;
}
}
await db
.update(editorialAccounts)
.set({
flatrateActive,
flatratePriceCents,
flatrateAssetLimit,
})
.where(eq(editorialAccounts.id, safeEditorialId));
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
}
function parsePriceCents(
value: unknown,
): { ok: true; cents: number } | { ok: false; message: string } {
@@ -49,40 +49,48 @@ function AlbumCard({
};
return (
<li className="album-card" data-granted={album.isGranted}>
<div className="album-card-image-container">
<li className={`flex flex-col bg-white border ${album.isGranted ? 'border-green-500 shadow-md ring-1 ring-green-500' : 'border-gray-200'} rounded-xl overflow-hidden transition-all duration-300 hover:shadow-lg`} data-granted={album.isGranted}>
<div className="relative aspect-[3/2] bg-gray-100 overflow-hidden">
{album.albumThumbnailAssetId ? (
<Image
className="album-card-image"
className="w-full h-full object-cover transition-transform duration-500 hover:scale-105"
alt={`Titelbild von ${album.albumName}`}
height={120}
height={200}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
width={160}
width={300}
/>
) : (
<div aria-label="Kein Albumcover verfügbar" className="album-card-placeholder" role="img">
<div aria-label="Kein Albumcover verfügbar" className="w-full h-full flex items-center justify-center text-gray-400 text-xs uppercase tracking-widest" role="img">
Kein Cover
</div>
)}
{album.isGranted && (
<div className="absolute top-2 right-2 bg-green-500 text-white text-xs font-bold px-2 py-1 rounded-full shadow-sm">
Zugewiesen
</div>
)}
</div>
<div className="album-card-body">
<h2 className="album-card-name" id={`album-${album.id}`} title={album.albumName}>
<div className="p-4 flex flex-col flex-grow">
<h2 className="text-base font-bold text-gray-900 mb-1 truncate" id={`album-${album.id}`} title={album.albumName}>
{album.albumName}
</h2>
<p className="album-card-count">{album.assetCount} Fotos</p>
<p className={`album-card-status ${album.isGranted ? "album-card-status--granted" : ""}`}>
{album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}
</p>
<form action={handleAction}>
<input name="immichAlbumId" type="hidden" value={album.id} />
<button
type="submit"
className={`album-card-action ${album.isGranted ? "album-card-action--revoke" : "album-card-action--grant"}`}
disabled={isPending}
>
{isPending ? "Lädt..." : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button>
</form>
<p className="text-sm text-gray-500 mb-4">{album.assetCount} Fotos</p>
<div className="mt-auto">
<form action={handleAction}>
<input name="immichAlbumId" type="hidden" value={album.id} />
<button
type="submit"
className={`w-full py-2 px-4 rounded-lg font-semibold text-sm transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-1 ${
album.isGranted
? "bg-red-50 text-red-600 hover:bg-red-100 focus:ring-red-500 border border-red-200"
: "bg-gray-900 text-white hover:bg-gray-800 focus:ring-gray-900"
}`}
disabled={isPending}
>
{isPending ? "Wird verarbeitet..." : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button>
</form>
</div>
</div>
</li>
);
@@ -109,7 +117,7 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: Al
{filteredAlbums.length === 0 ? (
<p>Keine Alben gefunden.</p>
) : (
<ul className="album-grid" aria-label="Zuweisbare Immich-Alben">
<ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6" aria-label="Zuweisbare Immich-Alben">
{filteredAlbums.map((album) => (
<AlbumCard
key={album.id}
+3
View File
@@ -18,6 +18,9 @@ export default async function EditorialDetailPage({
status: editorialAccounts.status,
emailVerifiedAt: editorialAccounts.emailVerifiedAt,
currentPriceCents: editorialAccounts.currentPriceCents,
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
archivedAt: editorialAccounts.archivedAt,
})
.from(editorialAccounts)
@@ -4,6 +4,7 @@ import { requireActiveEditorial, requireAdmin, PrincipalAuthorizationError } fro
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types";
import sharp from "sharp";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
@@ -45,8 +46,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
}
const thumbnail = await dependencies.immich.getThumbnail(assetId);
if (access.kind === "editorial") {
return watermarkedThumbnailResponse(thumbnail);
}
return thumbnailResponse(thumbnail);
} catch {
} catch (err) {
return genericNotFound();
}
};
@@ -112,6 +116,48 @@ function genericNotFound(): Response {
return new Response(null, { status: 404 });
}
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Response> {
const reader = thumbnail.body.getReader();
const chunks: Uint8Array[] = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) chunks.push(value);
}
const buffer = Buffer.concat(chunks);
const metadata = await sharp(buffer).metadata();
const width = metadata.width ?? 400;
const height = metadata.height ?? 300;
const svgText = `
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
<text x="50%" y="50%" font-family="Arial, sans-serif" font-size="${Math.max(24, width / 8)}" font-weight="bold" fill="white" opacity="0.5" text-anchor="middle" alignment-baseline="middle" transform="rotate(-30 ${width/2} ${height/2})">
PREVIEW
</text>
</svg>
`;
const watermarked = await sharp(buffer)
.composite([
{
input: Buffer.from(svgText),
gravity: "center",
},
])
.webp({ quality: 80 })
.toBuffer();
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"content-type": "image/webp",
"content-length": String(watermarked.length),
"x-content-type-options": "nosniff",
});
return new Response(watermarked, { headers: responseHeaders });
}
function isSafeAssetId(assetId: string): boolean {
return /^[A-Za-z0-9_-]{1,200}$/.test(assetId);
}
@@ -8,6 +8,11 @@ import {
} from "@/modules/billing/reports";
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { emailService } from "@/modules/email/service";
import { getReportPdf } from "@/modules/billing/reports";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { eq } from "drizzle-orm";
const finalizePayload = z
.object({
@@ -45,6 +50,35 @@ export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies)
adminUserId: principal.userId,
});
// Email dispatch
try {
const [editorial] = await db
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
if (editorial?.email) {
const reportPdf = await getReportPdf(result.reportId);
if (reportPdf) {
const periodString = month
? `${month.toString().padStart(2, "0")}/${year}`
: `Q${quarter}/${year}`;
// Fire and forget (don't await or catch if we want to not block, but awaiting is safer for serverless if not in background)
await emailService.sendBillingReport(
editorial.email,
periodString,
reportPdf.bytes,
result.reportNumber
);
}
}
} catch (emailError) {
console.error("Failed to send billing email:", emailError);
// Do not fail the request if email fails
}
return Response.json(
{
reportId: result.reportId,
@@ -0,0 +1,63 @@
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { getReportPdf, reportService } from "@/modules/billing/reports";
import { db } from "@/db/client";
import { billingReports } from "@/db/schema";
import { eq } from "drizzle-orm";
export async function GET(
request: Request,
{ params }: { params: Promise<{ reportId: string }> }
): Promise<Response> {
try {
const principal = await requireActiveEditorial(request.headers);
const { reportId } = await params;
// Verify ownership
const [report] = await db
.select({ editorialAccountId: billingReports.editorialAccountId })
.from(billingReports)
.where(eq(billingReports.id, reportId))
.limit(1);
if (!report || report.editorialAccountId !== principal.editorialId) {
return notFound();
}
const reportPdf = await getReportPdf(reportId);
if (!reportPdf) return notFound();
const filename = buildFilename(reportPdf.invoiceNumber);
return new Response(new Uint8Array(reportPdf.bytes), {
status: 200,
headers: {
"content-type": "application/pdf",
"cache-control": "private, no-store",
"content-disposition": `attachment; filename="${filename}"`,
},
});
} catch (error) {
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
return jsonError(500, "REQUEST_FAILED");
}
}
function buildFilename(invoiceNumber: string): string {
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
return `${safe || "nutzungsnachweis"}.pdf`;
}
function notFound(): Response {
return new Response(null, {
status: 404,
headers: { "cache-control": "private, no-store" },
});
}
function jsonError(status: number, code: string): Response {
return Response.json(
{ code },
{ status, headers: { "cache-control": "private, no-store" } },
);
}
+167
View File
@@ -0,0 +1,167 @@
import { eq, desc, and, sql, inArray } from "drizzle-orm";
import { db } from "@/db/client";
import { billingReports, usages, editorialAccounts } from "@/db/schema";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { headers } from "next/headers";
import Link from "next/link";
import { formatBerlinDateTime } from "@/modules/downloads/format";
export default async function AbrechnungenPage() {
const principal = await requireActiveEditorial(new Headers(await headers()));
// 1. Hole alle PDF-Abrechnungen (abgeschlossene Reports)
const reports = await db
.select({
id: billingReports.id,
invoiceNumber: billingReports.invoiceNumber,
periodStartsAt: billingReports.periodStartsAt,
periodEndsAt: billingReports.periodEndsAt,
netTotalCents: billingReports.netTotalCents,
finalizedAt: billingReports.finalizedAt,
status: billingReports.status,
})
.from(billingReports)
.where(
and(
eq(billingReports.editorialAccountId, principal.editorialId),
eq(billingReports.status, "final")
)
)
.orderBy(desc(billingReports.finalizedAt));
// 2. Berechne den noch offenen Betrag des aktuellen Monats (oder insgesamt offen)
const [openUsages] = await db
.select({
totalCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
count: sql<number>`COUNT(${usages.id})::int`,
})
.from(usages)
.where(
and(
eq(usages.editorialAccountId, principal.editorialId),
eq(usages.billingStatus, "open")
)
);
const [editorial] = await db
.select({
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, principal.editorialId))
.limit(1);
// Zähle die bereits bezogenen Flatrate-Bilder (Preis = 0) im aktuellen Kalendermonat
let usedFlatrateImages = 0;
if (editorial?.flatrateActive && editorial.flatrateAssetLimit !== null) {
const now = new Date();
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999));
const [{ count }] = await db
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(usages)
.where(
and(
eq(usages.editorialAccountId, principal.editorialId),
sql`${usages.createdAt} >= ${startOfMonth}`,
sql`${usages.createdAt} <= ${endOfMonth}`,
eq(usages.priceCents, 0),
inArray(usages.billingStatus, ["open", "billed", "reopened"])
)
);
usedFlatrateImages = count;
}
// Berechne gesamten offenen Betrag inkl. Flatrate (falls noch nicht abgerechnet)
// Normalerweise würde die Flatrate beim Report-Generieren hinzugefügt. Hier für die Vorschau:
// (Optional: Wenn man hier die Flatrate als "offen" anzeigen will)
const openTotalCents = (openUsages?.totalCents ?? 0);
return (
<section className="editorial-section">
<p className="editorial-kicker">Finanzen</p>
<h1>Meine Abrechnungen</h1>
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 my-8">
<div className="bg-blue-50 p-6 rounded-xl border border-blue-100">
<h2 className="text-xl font-semibold text-blue-900 mb-2">Offener Betrag (Einzelabrufe)</h2>
<p className="text-3xl font-bold text-blue-900">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(openTotalCents / 100)}
</p>
<p className="text-sm text-blue-700 mt-2">
Für {openUsages?.count ?? 0} kostenpflichtige Bilder (noch nicht in Rechnung gestellt)
</p>
</div>
{editorial?.flatrateActive && editorial.flatratePriceCents !== null && (
<div className="bg-green-50 p-6 rounded-xl border border-green-100">
<h2 className="text-xl font-semibold text-green-900 mb-2">Aktiver Tarif: Flatrate</h2>
<p className="text-3xl font-bold text-green-900">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(editorial.flatratePriceCents / 100)} <span className="text-lg font-normal">/ Monat</span>
</p>
{editorial.flatrateAssetLimit === null ? (
<p className="text-sm text-green-700 mt-2">
Unbegrenzte Downloads inklusive
</p>
) : (
<div className="mt-2">
<p className="text-sm text-green-700 font-semibold mb-1">
Inklusiv-Bilder diesen Monat: {usedFlatrateImages} / {editorial.flatrateAssetLimit}
</p>
<div className="w-full bg-green-200 rounded-full h-2.5">
<div className="bg-green-600 h-2.5 rounded-full" style={{ width: `${Math.min(100, (usedFlatrateImages / editorial.flatrateAssetLimit) * 100)}%` }}></div>
</div>
</div>
)}
</div>
)}
</div>
<h2 className="text-2xl font-bold mb-4 mt-12">Bisherige Rechnungen</h2>
{reports.length === 0 ? (
<p className="text-gray-500">Es liegen noch keine abgerechneten Zeiträume vor.</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b-2 border-gray-200">
<th className="py-3 px-4 font-semibold text-gray-700">Rechnungsnummer</th>
<th className="py-3 px-4 font-semibold text-gray-700">Zeitraum</th>
<th className="py-3 px-4 font-semibold text-gray-700">Betrag (Netto)</th>
<th className="py-3 px-4 font-semibold text-gray-700">Download</th>
</tr>
</thead>
<tbody>
{reports.map((report) => (
<tr key={report.id} className="border-b border-gray-100 hover:bg-gray-50">
<td className="py-4 px-4 font-medium">{report.invoiceNumber}</td>
<td className="py-4 px-4 text-gray-600">
{new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" }).format(report.periodStartsAt)}
</td>
<td className="py-4 px-4 font-medium">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(report.netTotalCents / 100)}
</td>
<td className="py-4 px-4">
<Link
href={`/api/editorials/reports/${report.id}/pdf`}
target="_blank"
className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-800 transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className="w-5 h-5">
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
</svg>
PDF anzeigen
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
+76 -2
View File
@@ -4,12 +4,13 @@ import { notFound } from "next/navigation";
import { AlbumCatalogError, albumCatalog, normalizePage } from "@/modules/albums/catalog";
import { PhotoContactSheet } from "@/modules/albums/catalog-content";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service";
import { requireEditorial } from "../../access";
type AlbumPageProps = Readonly<{
params: Promise<{ albumId: string }>;
searchParams: Promise<{ page?: string | string[]; suche?: string | string[] }>;
searchParams: Promise<{ page?: string | string[]; suche?: string | string[]; format?: string | string[]; jahr?: string | string[] }>;
}>;
export default async function AlbumPage({ params, searchParams }: AlbumPageProps) {
@@ -20,11 +21,15 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
]);
const query = normalizedQuery(singleValue(rawSearchParams.suche));
const currentPage = normalizePage(singleValue(rawSearchParams.page));
const format = singleValue(rawSearchParams.format);
const jahr = singleValue(rawSearchParams.jahr);
const result = await loadAlbumPage({
editorialId: principal.editorialId,
albumId,
query,
page: singleValue(rawSearchParams.page),
format,
jahr,
});
if (result.unavailable) {
@@ -43,6 +48,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
Alle Alben
</Link>
</div>
<AlbumSearchForm albumId={result.album.id} query={query} format={format} jahr={jahr} />
<PhotoContactSheet
albumId={result.album.id}
albumName={result.album.albumName}
@@ -50,21 +56,60 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
downloadOptions={result.downloadOptions}
page={result.page}
query={query}
lightboxAssetIds={result.lightboxAssetIds}
/>
</section>
);
}
function AlbumSearchForm({ albumId, query, format, jahr }: { albumId: string; query: string; format?: string; jahr?: string; }) {
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 10 }, (_, i) => currentYear - i);
return (
<form action={`/redaktion/alben/${albumId}`} className="global-search-form flex flex-wrap gap-4 items-center mb-8 bg-gray-50 p-4 rounded-xl border border-gray-200" role="search">
<div className="flex-grow">
<input
type="search"
name="suche"
defaultValue={query}
placeholder="Dieses Album durchsuchen..."
aria-label="Dieses Album durchsuchen"
className="w-full"
/>
</div>
<div className="flex gap-4">
<select name="format" defaultValue={format || ""} className="px-3 py-2 border border-gray-300 rounded-md">
<option value="">Alle Formate</option>
<option value="quer">Querformat</option>
<option value="hoch">Hochformat</option>
</select>
<select name="jahr" defaultValue={jahr || ""} className="px-3 py-2 border border-gray-300 rounded-md">
<option value="">Alle Jahre</option>
{years.map(y => (
<option key={y} value={y.toString()}>{y}</option>
))}
</select>
<button type="submit">Suchen</button>
</div>
</form>
);
}
async function loadAlbumPage({
editorialId,
albumId,
query,
page,
format,
jahr,
}: {
editorialId: string;
albumId: string;
query: string;
page: string | undefined;
format?: string;
jahr?: string;
}) {
try {
const albums = await albumCatalog.getVisibleAlbums(editorialId);
@@ -77,11 +122,40 @@ async function loadAlbumPage({
description: query,
page,
});
// Client-side filtering for format and year
if (format || jahr) {
results.items = results.items.filter(asset => {
let matches = true;
if (format) {
const width = asset.exifInfo?.exifImageWidth ?? 0;
const height = asset.exifInfo?.exifImageHeight ?? 0;
if (width > 0 && height > 0) {
const isLandscape = width >= height;
if (format === 'quer' && !isLandscape) matches = false;
if (format === 'hoch' && isLandscape) matches = false;
}
}
if (jahr && matches) {
const dateStr = asset.localDateTime ?? asset.fileCreatedAt;
if (!dateStr || !dateStr.startsWith(jahr)) {
matches = false;
}
}
return matches;
});
}
const downloadOptions = await loadEditorialDownloadOptions(
editorialId,
results.items.map((asset) => asset.id),
);
return { album, page: results, downloadOptions, unavailable: false as const };
const lightboxItems = await lightboxService.getLightboxItems(editorialId);
const lightboxAssetIds = new Set(lightboxItems.map(i => i.assetId));
return { album, page: results, downloadOptions, lightboxAssetIds, unavailable: false as const };
} catch (error) {
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
return { album: null, page: null, unavailable: true as const };
+65 -13
View File
@@ -1,38 +1,71 @@
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
import { AlbumContactSheet, PhotoContactSheet } from "@/modules/albums/catalog-content";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service";
import type { ImmichSearchPage } from "@/modules/immich/types";
import Link from "next/link";
import { requireEditorial } from "../access";
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[] }> }) {
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[]; format?: string | string[]; jahr?: string | string[] }> }) {
const principal = await requireEditorial();
const rawSearchParams = await searchParams;
const query = normalizedQuery(singleValue(rawSearchParams.suche));
const format = singleValue(rawSearchParams.format);
const jahr = singleValue(rawSearchParams.jahr);
if (query) {
const results = await albumCatalog.searchVisiblePhotos(principal.editorialId, {
description: query,
page: singleValue(rawSearchParams.page),
});
if (format || jahr) {
results.items = results.items.filter(asset => {
let matches = true;
if (format) {
const width = asset.exifInfo?.exifImageWidth ?? 0;
const height = asset.exifInfo?.exifImageHeight ?? 0;
if (width > 0 && height > 0) {
const isLandscape = width >= height;
if (format === 'quer' && !isLandscape) matches = false;
if (format === 'hoch' && isLandscape) matches = false;
}
}
if (jahr && matches) {
const dateStr = asset.localDateTime ?? asset.fileCreatedAt;
if (!dateStr || !dateStr.startsWith(jahr)) {
matches = false;
}
}
return matches;
});
}
const downloadOptions = await loadEditorialDownloadOptions(
principal.editorialId,
results.items.map((asset) => asset.id),
);
const lightboxItems = await lightboxService.getLightboxItems(principal.editorialId);
const lightboxAssetIds = new Set(lightboxItems.map(i => i.assetId));
return (
<section className="editorial-section" aria-labelledby="albums-title">
<p className="editorial-kicker">Bildarchiv · Suche</p>
<div className="editorial-title-row">
<h1 id="albums-title">Suchergebnisse</h1>
</div>
<GlobalSearchForm query={query} />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<PhotoContactSheet
albumName="Alle Alben"
downloadOptions={downloadOptions}
page={results}
query={query}
showAlbumName
lightboxAssetIds={lightboxAssetIds}
/>
<GlobalSearchPagination page={results} query={query} />
</section>
@@ -52,7 +85,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
<h1 id="albums-title">Ihre Alben</h1>
<p>Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen.</p>
</div>
<GlobalSearchForm query={query} />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
{result.albums.length === 0 ? (
<p className="catalog-empty">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
) : (
@@ -62,17 +95,36 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
);
}
function GlobalSearchForm({ query }: { query: string }) {
function GlobalSearchForm({ query, format, jahr }: { query: string; format?: string; jahr?: string; }) {
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 10 }, (_, i) => currentYear - i);
return (
<form action="/redaktion/alben" className="global-search-form" role="search">
<input
type="search"
name="suche"
defaultValue={query}
placeholder="Alle Alben durchsuchen..."
aria-label="Alle Alben durchsuchen"
/>
<button type="submit">Suchen</button>
<form action="/redaktion/alben" className="global-search-form flex flex-wrap gap-4 items-center mb-8 bg-gray-50 p-4 rounded-xl border border-gray-200" role="search">
<div className="flex-grow">
<input
type="search"
name="suche"
defaultValue={query}
placeholder="Alle Alben durchsuchen..."
aria-label="Alle Alben durchsuchen"
className="w-full"
/>
</div>
<div className="flex gap-4">
<select name="format" defaultValue={format || ""} className="px-3 py-2 border border-gray-300 rounded-md">
<option value="">Alle Formate</option>
<option value="quer">Querformat</option>
<option value="hoch">Hochformat</option>
</select>
<select name="jahr" defaultValue={jahr || ""} className="px-3 py-2 border border-gray-300 rounded-md">
<option value="">Alle Jahre</option>
{years.map(y => (
<option key={y} value={y.toString()}>{y}</option>
))}
</select>
<button type="submit">Suchen</button>
</div>
</form>
);
}
+1
View File
@@ -13,6 +13,7 @@ export default async function EditorialLayout({ children }: Readonly<{ children:
sectionLabel="Redaktionsarchiv"
nav={[
{ href: "/redaktion/alben", label: "Alben" },
{ href: "/redaktion/leuchtkasten", label: "Merkzettel" },
{ href: "/redaktion/nutzungen", label: "Nutzungen" },
{ href: "/redaktion/profil", label: "Profil" },
]}
@@ -0,0 +1,22 @@
"use client";
import { useState } from "react";
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
const [loading, setLoading] = useState(false);
function handleBulkDownload() {
alert("Bulk-Download ist aktuell in Entwicklung. Bitte klicke auf die Bilder, um sie einzeln herunterzuladen.");
}
return (
<button
type="button"
onClick={handleBulkDownload}
disabled={loading || assetIds.length === 0}
className="primary-action m-0"
>
Alle herunterladen
</button>
);
}
@@ -0,0 +1,56 @@
"use client";
import { useState, useTransition } from "react";
import { toggleLightboxItem } from "./actions";
type LightboxToggleButtonProps = {
assetId: string;
initialInLightbox: boolean;
};
export function LightboxToggleButton({ assetId, initialInLightbox }: LightboxToggleButtonProps) {
const [isPending, startTransition] = useTransition();
const [inLightbox, setInLightbox] = useState(initialInLightbox);
function handleClick(e: React.MouseEvent) {
e.preventDefault(); // prevent navigation if wrapped in a link
e.stopPropagation();
// Optimistic update
setInLightbox(!inLightbox);
startTransition(async () => {
try {
const result = await toggleLightboxItem(assetId);
setInLightbox(result.isNowInLightbox);
} catch {
// Revert on error
setInLightbox(inLightbox);
}
});
}
return (
<button
type="button"
onClick={handleClick}
disabled={isPending}
className={`lightbox-toggle-btn ${inLightbox ? 'in-lightbox' : ''}`}
aria-label={inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel"}
title={inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel"}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill={inLightbox ? "currentColor" : "none"}
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-5 h-5"
>
<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
</svg>
</button>
);
}
@@ -0,0 +1,38 @@
"use client";
import { useTransition } from "react";
import { removeLightboxItemAction } from "./actions";
export function RemoveLightboxItemButton({ assetId }: { assetId: string }) {
const [isPending, startTransition] = useTransition();
function handleRemove() {
startTransition(async () => {
await removeLightboxItemAction(assetId);
});
}
return (
<button
type="button"
onClick={handleRemove}
disabled={isPending}
className="p-1.5 bg-white rounded-full shadow hover:bg-gray-100 text-gray-500 hover:text-red-500 transition-colors"
title="Aus Merkzettel entfernen"
aria-label="Aus Merkzettel entfernen"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-4 h-4"
>
<path d="M18 6L6 18M6 6l12 12" />
</svg>
</button>
);
}
+31
View File
@@ -0,0 +1,31 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { lightboxService } from "@/modules/lightbox/service";
export async function toggleLightboxItem(assetId: string) {
const principal = await requireActiveEditorial(new Headers(await headers()));
const isInLightbox = await lightboxService.isAssetInLightbox(principal.editorialId, assetId);
if (isInLightbox) {
await lightboxService.removeLightboxItem(principal.editorialId, assetId);
} else {
await lightboxService.addLightboxItem(principal.editorialId, assetId);
}
// Revalidate routes where lightbox state is shown
revalidatePath("/redaktion/alben/[id]", "page");
revalidatePath("/redaktion/leuchtkasten", "page");
return { success: true, isNowInLightbox: !isInLightbox };
}
export async function removeLightboxItemAction(assetId: string) {
const principal = await requireActiveEditorial(new Headers(await headers()));
await lightboxService.removeLightboxItem(principal.editorialId, assetId);
revalidatePath("/redaktion/leuchtkasten", "page");
revalidatePath("/redaktion/alben/[id]", "page");
return { success: true };
}
+71
View File
@@ -0,0 +1,71 @@
import { headers } from "next/headers";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { lightboxService } from "@/modules/lightbox/service";
import { immichClient } from "@/modules/immich/client";
import Image from "next/image";
import Link from "next/link";
import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton";
import { DownloadLightboxForm } from "./DownloadLightboxForm";
export default async function LightboxPage() {
const principal = await requireActiveEditorial(new Headers(await headers()));
const items = await lightboxService.getLightboxItems(principal.editorialId);
// Fetch asset details for all items in the lightbox
const assets = items.length > 0
? await immichClient.searchAssets({
assetIds: items.map(i => i.assetId)
})
: [];
const assetMap = new Map(assets.map(a => [a.id, a]));
return (
<section className="editorial-section">
<p className="editorial-kicker">Merkzettel</p>
<h1>Dein Leuchtkasten</h1>
{items.length === 0 ? (
<p className="mt-8 text-gray-500">Dein Leuchtkasten ist leer.</p>
) : (
<>
<div className="flex justify-between items-center mb-8">
<p className="text-sm text-gray-600">
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
</p>
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
</div>
<ul className="photo-contact-sheet">
{items.map((item) => {
const asset = assetMap.get(item.assetId);
if (!asset) return null;
return (
<li key={item.assetId} className="photo-contact-frame relative group">
<Link href={`/redaktion/nutzungen/neu?assetId=${item.assetId}`} className="contact-sheet-link">
<Image
alt={asset.originalFileName}
className="contact-sheet-image"
height={200}
src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`}
width={300}
/>
<div className="contact-strip">
<span className="contact-strip-name" title={asset.originalFileName}>
{asset.originalFileName}
</span>
</div>
</Link>
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<RemoveLightboxItemButton assetId={item.assetId} />
</div>
</li>
);
})}
</ul>
</>
)}
</section>
);
}