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

+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>
);
}