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

+9
View File
@@ -0,0 +1,9 @@
CREATE TABLE "lightbox_items" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"asset_id" text NOT NULL,
"added_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "lightbox_items" ADD CONSTRAINT "lightbox_items_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "lightbox_items_editorial_asset_idx" ON "lightbox_items" USING btree ("editorial_account_id","asset_id");
+4
View File
@@ -0,0 +1,4 @@
ALTER TABLE "billing_reports" ADD COLUMN "flatrate_cents_snapshot" integer;--> statement-breakpoint
ALTER TABLE "editorial_accounts" ADD COLUMN "flatrate_active" boolean DEFAULT false NOT NULL;--> statement-breakpoint
ALTER TABLE "editorial_accounts" ADD COLUMN "flatrate_price_cents" integer;--> statement-breakpoint
ALTER TABLE "editorial_accounts" ADD COLUMN "flatrate_asset_limit" integer;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -50,6 +50,20 @@
"when": 1786410282719,
"tag": "0006_chubby_screwball",
"breakpoints": true
},
{
"idx": 7,
"version": "7",
"when": 1786410724623,
"tag": "0007_amused_franklin_storm",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1786411419497,
"tag": "0008_overjoyed_wrecking_crew",
"breakpoints": true
}
]
}
+1
View File
@@ -27,6 +27,7 @@
"react": "^19.2.8",
"react-dom": "^19.2.8",
"server-only": "^0.0.1",
"sharp": "^0.35.3",
"zod": "^4.4.3"
},
"devDependencies": {
+4 -3
View File
@@ -41,6 +41,9 @@ importers:
server-only:
specifier: ^0.0.1
version: 0.0.1
sharp:
specifier: ^0.35.3
version: 0.35.3(@types/node@24.13.3)
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -4886,8 +4889,7 @@ snapshots:
'@humanwhocodes/retry@0.4.3': {}
'@img/colour@1.1.0':
optional: true
'@img/colour@1.1.0': {}
'@img/sharp-darwin-arm64@0.35.3':
optionalDependencies:
@@ -7782,7 +7784,6 @@ snapshots:
'@img/sharp-win32-ia32': 0.35.3
'@img/sharp-win32-x64': 0.35.3
'@types/node': 24.13.3
optional: true
shebang-command@2.0.0:
dependencies:
+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>
);
}
+1
View File
@@ -39,6 +39,7 @@ export const billingReports = pgTable(
billingAddressSnapshot: jsonb("billing_address_snapshot").notNull(),
invoiceNumber: text("invoice_number"),
netTotalCents: integer("net_total_cents").notNull(),
flatrateCentsSnapshot: integer("flatrate_cents_snapshot"),
status: reportStatus("status").notNull().default("draft"),
pdf: bytea("pdf"),
pdfSha256: varchar("pdf_sha256", { length: 64 }),
+4 -1
View File
@@ -1,5 +1,5 @@
import { relations } from "drizzle-orm";
import { type AnyPgColumn, integer, pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { type AnyPgColumn, boolean, integer, pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
@@ -23,6 +23,9 @@ export const editorialAccounts = pgTable("editorial_accounts", {
loginEmail: text("login_email").notNull().unique(),
status: accountStatus("status").notNull().default("pending_email"),
currentPriceCents: integer("current_price_cents"),
flatrateActive: boolean("flatrate_active").notNull().default(false),
flatratePriceCents: integer("flatrate_price_cents"),
flatrateAssetLimit: integer("flatrate_asset_limit"),
approvalNoticeStatus: text("approval_notice_status").notNull().default("not_requested"),
currentBillingAddressVersionId: uuid("current_billing_address_version_id").references(
(): AnyPgColumn => billingAddressVersions.id,
+1
View File
@@ -4,5 +4,6 @@ export * from "./auth";
export * from "./auto-rules";
export * from "./billing";
export * from "./editorials";
export * from "./lightbox";
export * from "./rate-limits";
export * from "./usages";
+31
View File
@@ -0,0 +1,31 @@
import { relations } from "drizzle-orm";
import { pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { editorialAccounts } from "./editorials";
export const lightboxItems = pgTable(
"lightbox_items",
{
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "cascade" }),
assetId: text("asset_id").notNull(),
addedAt: timestamp("added_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => {
return {
editorialAssetIdx: uniqueIndex("lightbox_items_editorial_asset_idx").on(
table.editorialAccountId,
table.assetId,
),
};
}
);
export const lightboxItemsRelations = relations(lightboxItems, ({ one }) => ({
editorialAccount: one(editorialAccounts, {
fields: [lightboxItems.editorialAccountId],
references: [editorialAccounts.id],
}),
}));
+18 -1
View File
@@ -4,11 +4,12 @@ import { eq, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { albumAutoRules } from "@/db/schema";
import { albumAutoRules, editorialAccounts } from "@/db/schema";
import type * as schema from "@/db/schema";
import { albumGrantService } from "./grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichClient } from "@/modules/immich/types";
import { emailService } from "@/modules/email/service";
export type AutoRule = {
id: string;
@@ -62,6 +63,18 @@ export function createAutoRuleService({
const grantedAlbumIds = new Set(await grantService.getGrantedAlbumIds(editorialId));
let newlyGranted = 0;
let editorialEmail: string | undefined;
try {
const [editorial] = await db
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
editorialEmail = editorial?.email;
} catch (e) {
// Ignore DB error
}
for (const album of albums) {
if (grantedAlbumIds.has(album.id)) {
continue;
@@ -75,6 +88,10 @@ export function createAutoRuleService({
await grantService.grantAlbum({ editorialId, immichAlbumId: album.id, adminUserId });
newlyGranted++;
grantedAlbumIds.add(album.id);
if (editorialEmail) {
await emailService.sendNewAlbumNotification(editorialEmail, album.albumName).catch(() => {});
}
} catch (error) {
// Ignore individual album grant failures
}
+8 -1
View File
@@ -3,6 +3,7 @@
import Link from "next/link";
import { UsageDialog } from "@/components/download/usage-dialog";
import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton";
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
import type { ImmichSearchPage } from "@/modules/immich/types";
@@ -56,6 +57,7 @@ export function PhotoContactSheet({
page: ImmichSearchPage;
query: string;
showAlbumName?: boolean;
lightboxAssetIds?: Set<string>;
}>) {
return (
<>
@@ -77,7 +79,7 @@ export function PhotoContactSheet({
<ul className="photo-contact-sheet" aria-label={`Fotos aus ${albumName}`}>
{page.items.map((asset) => (
<li key={asset.id}>
<figure className="photo-contact-frame">
<figure className="photo-contact-frame relative group">
<img
alt={asset.originalFileName}
className="contact-sheet-image"
@@ -85,6 +87,11 @@ export function PhotoContactSheet({
src={thumbnailUrl(asset.id)}
width="900"
/>
{lightboxAssetIds && (
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<LightboxToggleButton assetId={asset.id} initialInLightbox={lightboxAssetIds.has(asset.id)} />
</div>
)}
<figcaption className="contact-strip">
<span className="contact-strip-name">{asset.originalFileName}</span>
{showAlbumName && (asset as any).albums && (asset as any).albums.length > 0 && (
+31 -2
View File
@@ -155,6 +155,7 @@ export type FinalizeTransactionInput = {
address: BillingReportAddress;
repeatDownloads: BillingReportRepeatDownload[];
netTotalCents: number;
flatrateCentsSnapshot: number | null;
pdfBytes: Buffer;
pdfSha256: string;
documentId: string;
@@ -171,6 +172,7 @@ export type FinalizeTransactionResult = {
export type ReportRepository = {
// Snapshot building (pre-transaction)
getCurrentAddress(editorialId: string): Promise<BillingReportAddress | null>;
getEditorialFlatrate(editorialId: string): Promise<{ flatrateActive: boolean; flatratePriceCents: number | null; flatrateAssetLimit: number | null; } | null>;
getSelectedUsages(editorialId: string, usageIds: string[]): Promise<SelectedUsage[]>;
getRepeatDownloads(editorialId: string, period: BillingPeriod): Promise<BillingReportRepeatDownload[]>;
allocateReportNumber(): Promise<number>;
@@ -235,6 +237,7 @@ export function createReportService({
selectedPositions: selectedUsages.map(toReportPosition),
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
reportNumber: 0,
invoiceNumber: "VORSCHAU",
period: input.period,
@@ -273,6 +276,7 @@ export function createReportService({
selectedPositions: selectedUsages.map(toReportPosition),
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
reportNumber,
invoiceNumber,
period: input.period,
@@ -298,6 +302,7 @@ export function createReportService({
address,
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
pdfBytes: rendered.bytes,
pdfSha256: rendered.sha256,
documentId,
@@ -394,6 +399,7 @@ async function buildSnapshot(
address: BillingReportAddress;
repeatDownloads: BillingReportRepeatDownload[];
netTotalCents: number;
flatrateCentsSnapshot: number | null;
}> {
if (input.usageIds.length === 0) {
throw new ReportValidationError("NO_USAGES_SELECTED");
@@ -426,11 +432,20 @@ async function buildSnapshot(
throw new ReportValidationError("ADDRESS_NOT_FOUND");
}
const editorialFlatrate = await repo.getEditorialFlatrate(input.editorialId);
let flatrateCentsSnapshot: number | null = null;
if (editorialFlatrate && editorialFlatrate.flatrateActive && editorialFlatrate.flatratePriceCents !== null) {
flatrateCentsSnapshot = editorialFlatrate.flatratePriceCents;
}
const repeatDownloads = await repo.getRepeatDownloads(input.editorialId, input.period);
const netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0);
let netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0);
if (flatrateCentsSnapshot !== null) {
netTotalCents += flatrateCentsSnapshot;
}
return { usages: selectedUsages, address, repeatDownloads, netTotalCents };
return { usages: selectedUsages, address, repeatDownloads, netTotalCents, flatrateCentsSnapshot };
}
function toReportPosition(usage: SelectedUsage): BillingReportPosition {
@@ -484,6 +499,19 @@ export function createReportRepository(
return version;
},
async getEditorialFlatrate(editorialId) {
const [editorial] = await database
.select({
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
return editorial || null;
},
async getSelectedUsages(editorialId, usageIds) {
const rows = await database
.select({
@@ -581,6 +609,7 @@ export function createReportRepository(
billingAddressSnapshot: input.address,
invoiceNumber: input.invoiceNumber,
netTotalCents: input.netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
status: "final",
pdf: input.pdfBytes,
pdfSha256: input.pdfSha256,
+2
View File
@@ -72,4 +72,6 @@ export type BillingReportSnapshot = {
createdAt: Date;
/** Legal notice clarifying that the report is not a VAT invoice. */
legalSeparationNotice: string;
/** Flatrate amount snapshot, if applicable. */
flatrateCentsSnapshot?: number | null;
};
+52 -1
View File
@@ -1,5 +1,5 @@
import Link from "next/link";
import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction } from "@/app/admin/redaktionen/[id]/actions";
import { DangerZone } from "./DangerZone";
export type EditorialDetail = {
@@ -10,6 +10,9 @@ export type EditorialDetail = {
status: string;
emailVerifiedAt: Date | null;
currentPriceCents: number | null;
flatrateActive: boolean;
flatratePriceCents: number | null;
flatrateAssetLimit: number | null;
archivedAt: Date | null;
};
@@ -59,6 +62,54 @@ export function EditorialDetailContent({
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln</Link>
</section>
{/* Flatrate Settings */}
{!editorial.archivedAt && (
<section aria-labelledby="flatrate-title" className="mt-8">
<h2 id="flatrate-title">Flatrate-Einstellungen</h2>
<form action={updateFlatrateAction.bind(null, editorial.id)} className="space-y-4 max-w-lg mt-4">
<div>
<label className="flex items-center gap-2 font-semibold">
<input type="checkbox" name="flatrateActive" defaultChecked={editorial.flatrateActive} />
Flatrate aktivieren
</label>
<p className="text-sm text-gray-500 mt-1">Wenn aktiviert, werden Downloads nach einem Pauschalpreis abgerechnet.</p>
</div>
<div className="flex gap-4">
<div className="flex-1">
<label className="block font-semibold mb-1" htmlFor="flatratePriceEuros">Flatrate-Preis (Netto €)</label>
<input
type="number"
id="flatratePriceEuros"
name="flatratePriceEuros"
step="0.01"
min="0"
className="border p-2 rounded w-full"
defaultValue={editorial.flatratePriceCents ? (editorial.flatratePriceCents / 100).toFixed(2) : ""}
/>
</div>
<div className="flex-1">
<label className="block font-semibold mb-1" htmlFor="flatrateAssetLimit">Bild-Limit (pro Monat)</label>
<input
type="number"
id="flatrateAssetLimit"
name="flatrateAssetLimit"
min="1"
placeholder="Unbegrenzt"
className="border p-2 rounded w-full"
defaultValue={editorial.flatrateAssetLimit ?? ""}
/>
<p className="text-xs text-gray-500 mt-1">Leer lassen für unbegrenzte Flatrate.</p>
</div>
</div>
<button type="submit" className="px-4 py-2 bg-black text-white font-semibold rounded hover:bg-gray-800 transition">
Speichern
</button>
</form>
</section>
)}
{/* Status Actions */}
{!editorial.archivedAt && (
<section aria-labelledby="status-actions-title">
+42
View File
@@ -0,0 +1,42 @@
import "server-only";
import nodemailer from "nodemailer";
import { env } from "@/config/env";
const transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
port: env.SMTP_PORT,
secure: env.SMTP_PORT === 465,
auth: {
user: env.SMTP_USER,
pass: env.SMTP_PASSWORD,
},
});
export const emailService = {
async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) {
const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
await transporter.sendMail({
from: env.SMTP_FROM,
to: toEmail,
subject: `Ihre Abrechnung für ${reportMonth}`,
text: `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat ${reportMonth} als PDF-Dokument.\n\nViele Grüße,\nIhr Redaktions-Team`,
attachments: [
{
filename,
content: pdfBytes,
contentType: "application/pdf",
},
],
});
},
async sendNewAlbumNotification(toEmail: string, albumName: string) {
await transporter.sendMail({
from: env.SMTP_FROM,
to: toEmail,
subject: `Neues Fotoalbum verfügbar: ${albumName}`,
text: `Hallo,\n\nein neues Fotoalbum "${albumName}" wurde für Ihre Redaktion freigegeben. Sie können die Bilder ab sofort im Redaktionsportal ansehen und lizenzieren.\n\nViele Grüße,\nIhr Redaktions-Team`,
});
},
};
+4
View File
@@ -25,6 +25,10 @@ const assetSchema = z
localDateTime: nullableString,
fileCreatedAt: nullableString,
albums: z.array(z.object({ id: z.string() }).passthrough()).optional().default([]),
exifInfo: z.object({
exifImageWidth: z.number().optional().nullable(),
exifImageHeight: z.number().optional().nullable(),
}).passthrough().optional().nullable(),
})
.passthrough();
+62
View File
@@ -0,0 +1,62 @@
import { and, eq } from "drizzle-orm";
import { db } from "@/db/client";
import { lightboxItems } from "@/db/schema";
import { immichClient } from "@/modules/immich/client";
import type { PhotoAsset } from "@/modules/immich/types";
export type LightboxItem = {
assetId: string;
addedAt: Date;
asset?: PhotoAsset; // populated if joined
};
export const lightboxService = {
async getLightboxItems(editorialId: string): Promise<LightboxItem[]> {
const items = await db
.select({
assetId: lightboxItems.assetId,
addedAt: lightboxItems.addedAt,
})
.from(lightboxItems)
.where(eq(lightboxItems.editorialAccountId, editorialId))
.orderBy(lightboxItems.addedAt);
return items;
},
async addLightboxItem(editorialId: string, assetId: string): Promise<void> {
await db
.insert(lightboxItems)
.values({
editorialAccountId: editorialId,
assetId,
})
.onConflictDoNothing();
},
async removeLightboxItem(editorialId: string, assetId: string): Promise<void> {
await db
.delete(lightboxItems)
.where(
and(
eq(lightboxItems.editorialAccountId, editorialId),
eq(lightboxItems.assetId, assetId)
)
);
},
async isAssetInLightbox(editorialId: string, assetId: string): Promise<boolean> {
const result = await db
.select({ id: lightboxItems.id })
.from(lightboxItems)
.where(
and(
eq(lightboxItems.editorialAccountId, editorialId),
eq(lightboxItems.assetId, assetId)
)
)
.limit(1);
return result.length > 0;
}
};
+11
View File
@@ -65,6 +65,17 @@ function paidPositionsTable(snapshot: BillingReportSnapshot) {
const body = [headerRow];
if (snapshot.flatrateCentsSnapshot !== null && snapshot.flatrateCentsSnapshot !== undefined) {
body.push([
{ text: "Flatrate", style: "tableCell" },
{ text: "-", style: "tableCell" },
{ text: "Monatlicher Pauschalpreis", style: "tableCell" },
{ text: "-", style: "tableCell" },
{ text: "-", style: "tableCell", alignment: "right" as const },
{ text: formatCents(snapshot.flatrateCentsSnapshot), style: "tableCell", alignment: "right" as const },
]);
}
for (const pos of snapshot.selectedPositions) {
body.push([
{ text: pos.filename, style: "tableCell" },
+38 -3
View File
@@ -135,6 +135,8 @@ export function createUsageServiceRepository(
id: editorialAccounts.id,
status: editorialAccounts.status,
currentPriceCents: editorialAccounts.currentPriceCents,
flatrateActive: editorialAccounts.flatrateActive,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
@@ -164,6 +166,39 @@ export function createUsageServiceRepository(
.limit(1);
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
let priceCents = editorial.currentPriceCents!;
if (editorial.flatrateActive) {
if (editorial.flatrateAssetLimit === null) {
priceCents = 0; // Unlimited flatrate
} else {
// Limited flatrate - check how many usages this month
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 transaction
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(usages)
.where(
and(
eq(usages.editorialAccountId, input.editorialId),
sql`${usages.createdAt} >= ${startOfMonth}`,
sql`${usages.createdAt} <= ${endOfMonth}`,
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
// For flatrate, we only count usages that were originally free via the flatrate
// so we compare against priceCents = 0. Wait, any usage counts towards the limit?
// Yes, any billable usage this month counts towards the limit.
eq(usages.priceCents, 0)
)
);
if (count < editorial.flatrateAssetLimit) {
priceCents = 0;
}
}
}
// This is the last cross-system authorization snapshot available to the
// portal. Immich may still change after it returns, but no portal work is
// allowed between this refresh and the accounting inserts.
@@ -180,7 +215,7 @@ export function createUsageServiceRepository(
albumNameSnapshot: currentAsset.albumName,
purpose: input.purpose,
internalReference: input.reference,
priceCents: editorial.currentPriceCents!,
priceCents: priceCents,
billingStatus: "open",
createdAt,
})
@@ -214,7 +249,7 @@ export function createUsageServiceRepository(
editorialId: input.editorialId,
assetId: input.assetId,
albumId: input.albumId,
priceCents: editorial.currentPriceCents,
priceCents: priceCents,
downloadId: event.id,
},
occurredAt: createdAt,
@@ -224,7 +259,7 @@ export function createUsageServiceRepository(
id: event.id,
usageId: usage.id,
assetId: input.assetId,
priceCents: editorial.currentPriceCents!,
priceCents: priceCents,
billable: true,
status: "authorized" as const,
authorizedAt: createdAt,
+6
View File
@@ -0,0 +1,6 @@
import sharp from 'sharp';
async function run() {
console.log("Sharp loaded:", typeof sharp);
}
run();