feat: add cross-album search, auto-rules, album UI redesign, editorial archiving and pdf download

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 02:53:15 +02:00
1 parent 9c0d43b1ec
commit 375e5b8b7d
23 files changed
+1153 -43

No files matched your search

@@ -0,0 +1,32 @@
-- 1. Create the album_auto_rules table
CREATE TABLE IF NOT EXISTS "album_auto_rules" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"editorial_account_id" uuid NOT NULL,
"keyword" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"created_by_user_id" uuid
);
DO $$ BEGIN
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
DO $$ BEGIN
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
CREATE UNIQUE INDEX IF NOT EXISTS "album_auto_rules_editorial_account_id_keyword_idx" ON "album_auto_rules" ("editorial_account_id", lower("keyword"));
-- 2. Add archived_at and archived_by_user_id to editorial_accounts
ALTER TABLE "editorial_accounts" ADD COLUMN "archived_at" timestamp with time zone;
ALTER TABLE "editorial_accounts" ADD COLUMN "archived_by_user_id" uuid;
DO $$ BEGIN
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_archived_by_user_id_users_id_fk" FOREIGN KEY ("archived_by_user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
+44
View File
@@ -0,0 +1,44 @@
import { eq } from "drizzle-orm";
import { auth } from "../src/modules/auth/auth";
import { db } from "../src/db/client";
import { users } from "../src/db/schema";
async function main() {
const email = process.argv[2] || "mail@leon-tonhaeuser.de";
const password = process.argv[3] || "AdminPassword123!";
const name = process.argv[4] || "Leon Tonhäuser";
console.log(`Creating Admin user: ${email}...`);
try {
const res = await auth.api.signUpEmail({
body: {
email,
name,
password,
},
});
const userId = res.user.id;
await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, userId));
console.log(`Successfully created Admin account!`);
console.log(`Email: ${email}`);
console.log(`Password: ${password}`);
} catch (error) {
console.error("Error creating admin user:", error);
// If user already exists, update to admin
const [existing] = await db.select().from(users).where(eq(users.email, email));
if (existing) {
await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, existing.id));
console.log(`Updated existing user ${email} to ADMIN role.`);
}
}
process.exit(0);
}
main().catch((err) => {
console.error("Fatal error:", err);
process.exit(1);
});
@@ -333,7 +333,16 @@ export function BillingSelection({
</span>
</div>
{report.status === "final" && (
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
<>
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
<a
href={`/api/billing-reports/${encodeURIComponent(report.id)}`}
className="billing-report-download"
download
>
PDF herunterladen
</a>
</>
)}
</li>
))}
+40
View File
@@ -0,0 +1,40 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { requireAdmin } from "@/modules/auth/principal";
import { editorialService } from "@/modules/editorials/service";
export async function archiveEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.archiveEditorial({
editorialId,
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
revalidatePath('/admin/redaktionen');
redirect('/admin/redaktionen');
}
export async function suspendEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.transitionEditorialStatus({
editorialId,
from: 'active',
to: 'suspended',
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
}
export async function reactivateEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.transitionEditorialStatus({
editorialId,
from: 'suspended',
to: 'active',
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
}
@@ -0,0 +1,117 @@
"use client";
import { useState, useTransition } from "react";
import Image from "next/image";
type AlbumGridProps = {
albums: Array<{
id: string;
albumName: string;
albumThumbnailAssetId: string | null;
assetCount: number;
isGranted: boolean;
}>;
editorialId: string;
grantAction: (editorialId: string, formData: FormData) => Promise<void>;
revokeAction: (editorialId: string, formData: FormData) => Promise<void>;
};
function AlbumCard({
album,
editorialId,
grantAction,
revokeAction,
}: {
album: AlbumGridProps["albums"][0];
editorialId: string;
grantAction: AlbumGridProps["grantAction"];
revokeAction: AlbumGridProps["revokeAction"];
}) {
const [isPending, startTransition] = useTransition();
const handleAction = (formData: FormData) => {
startTransition(async () => {
if (album.isGranted) {
await revokeAction(editorialId, formData);
} else {
await grantAction(editorialId, formData);
}
});
};
return (
<li className="album-card" data-granted={album.isGranted}>
<div className="album-card-image-container">
{album.albumThumbnailAssetId ? (
<Image
className="album-card-image"
alt={`Titelbild von ${album.albumName}`}
height={120}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
width={160}
/>
) : (
<div aria-label="Kein Albumcover verfügbar" className="album-card-placeholder" role="img">
Kein Cover
</div>
)}
</div>
<div className="album-card-body">
<h2 className="album-card-name" 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>
</div>
</li>
);
}
export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: AlbumGridProps) {
const [search, setSearch] = useState("");
const filteredAlbums = albums.filter((album) =>
album.albumName.toLowerCase().includes(search.toLowerCase())
);
return (
<div>
<input
type="search"
className="album-grid-search"
placeholder="Alben suchen..."
value={search}
onChange={(e) => setSearch(e.target.value)}
aria-label="Alben durchsuchen"
/>
{filteredAlbums.length === 0 ? (
<p>Keine Alben gefunden.</p>
) : (
<ul className="album-grid" aria-label="Zuweisbare Immich-Alben">
{filteredAlbums.map((album) => (
<AlbumCard
key={album.id}
album={album}
editorialId={editorialId}
grantAction={grantAction}
revokeAction={revokeAction}
/>
))}
</ul>
)}
</div>
);
}
@@ -14,7 +14,7 @@ const editorial = {
loginEmail: "mara@example.com",
status: "pending_approval" as const,
emailVerifiedAt: null,
currentPriceCents: null,
currentPriceCents: null, archivedAt: null,
};
test("the editorial detail links admins to its album-assignment page", () => {
+9 -34
View File
@@ -9,6 +9,7 @@ import { albumGrantService } from "@/modules/albums/grants";
import { grantAlbumAction, revokeAlbumAction } from "./actions";
import { loadAssignableAlbums } from "./page-content";
import { AlbumGrid } from "./AlbumGrid";
export default async function EditorialAlbumsPage({
params,
@@ -50,45 +51,19 @@ export default async function EditorialAlbumsPage({
</p>
<p>
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
{" · "}
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln verwalten</Link>
</p>
{albumResult.albums.length === 0 ? (
<p>Derzeit sind keine zuweisbaren Alben vorhanden.</p>
) : (
<ul aria-label="Zuweisbare Immich-Alben">
{albumResult.albums.map((album) => {
const action = album.isGranted ? revokeAlbumAction : grantAlbumAction;
return (
<li key={album.id}>
<article aria-labelledby={`album-${album.id}`}>
{album.albumThumbnailAssetId ? (
<Image
alt={`Titelbild von ${album.albumName}`}
height={120}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
width={160}
/>
) : (
<div aria-label="Kein Albumcover verfügbar" role="img">
Kein Cover
</div>
)}
<h2 id={`album-${album.id}`}>{album.albumName}</h2>
<p>{album.assetCount} Fotos</p>
<p>
Status: <strong>{album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}</strong>
</p>
<form action={action.bind(null, editorial.id)}>
<input name="immichAlbumId" type="hidden" value={album.id} />
<button type="submit">
{album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button>
</form>
</article>
</li>
);
})}
</ul>
<AlbumGrid
albums={albumResult.albums}
editorialId={editorial.id}
grantAction={grantAlbumAction}
revokeAction={revokeAlbumAction}
/>
)}
</section>
);
@@ -0,0 +1,61 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { autoRuleService } from "@/modules/albums/auto-rules";
import { requireAdmin } from "@/modules/auth/principal";
async function getAdminPrincipal() {
return requireAdmin(new Headers(await headers()));
}
function requiredId(value: unknown): string {
if (
typeof value !== "string" ||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
) {
throw new Error("INVALID_ID");
}
return value;
}
export async function createAutoRuleAction(editorialId: string, formData: FormData): Promise<void> {
const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId);
const keyword = formData.get("keyword");
if (typeof keyword !== "string" || !keyword.trim()) {
throw new Error("INVALID_KEYWORD");
}
await autoRuleService.createRule({
editorialId: safeEditorialId,
keyword: keyword.trim(),
adminUserId: principal.userId,
});
revalidatePath(`/admin/redaktionen/${safeEditorialId}/auto-regeln`);
}
export async function deleteAutoRuleAction(editorialId: string, ruleId: string): Promise<void> {
const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId);
const safeRuleId = requiredId(ruleId);
await autoRuleService.deleteRule({
ruleId: safeRuleId,
adminUserId: principal.userId,
});
revalidatePath(`/admin/redaktionen/${safeEditorialId}/auto-regeln`);
}
export async function applyAutoRulesAction(editorialId: string): Promise<void> {
const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId);
await autoRuleService.applyRules(safeEditorialId, principal.userId);
revalidatePath(`/admin/redaktionen/${safeEditorialId}/auto-regeln`);
}
@@ -0,0 +1,72 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { autoRuleService } from "@/modules/albums/auto-rules";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { eq } from "drizzle-orm";
import { applyAutoRulesAction, createAutoRuleAction, deleteAutoRuleAction } from "./actions";
type AutoRulesPageProps = Readonly<{
params: Promise<{ id: string }>;
}>;
export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
await requireAdmin(new Headers(await headers()));
const { id } = await params;
const [editorial] = await db
.select()
.from(editorialAccounts)
.where(eq(editorialAccounts.id, id));
if (!editorial) {
notFound();
}
const rules = await autoRuleService.listRules(id);
return (
<section className="content-section" aria-labelledby="auto-rules-title">
<p className="eyebrow">Redaktion · Auto-Zuweisungsregeln</p>
<h1 id="auto-rules-title">Auto-Regeln für {editorial.name}</h1>
<p>
Alben, deren Name eines der folgenden Schlüsselwörter enthält, werden automatisch zugewiesen.
</p>
<p>
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Zurück zu Albumrechte</Link>
</p>
<form action={createAutoRuleAction.bind(null, editorial.id)}>
<label>
<span>Neues Schlüsselwort</span>
<input name="keyword" type="text" required placeholder="z.B. FC Bayern" />
</label>
<button type="submit">Regel hinzufügen</button>
</form>
<form action={applyAutoRulesAction.bind(null, editorial.id)}>
<button type="submit">Regeln jetzt anwenden</button>
</form>
{rules.length === 0 ? (
<p>Noch keine Auto-Regeln angelegt.</p>
) : (
<ul className="auto-rules-list">
{rules.map((rule) => (
<li key={rule.id} className="auto-rule-item">
<span className="auto-rule-keyword">{rule.keyword}</span>
<span className="auto-rule-date">
{rule.createdAt.toLocaleDateString('de-DE')}
</span>
<form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}>
<button type="submit" className="auto-rule-delete">Entfernen</button>
</form>
</li>
))}
</ul>
)}
</section>
);
}
+1
View File
@@ -18,6 +18,7 @@ export default async function EditorialDetailPage({
status: editorialAccounts.status,
emailVerifiedAt: editorialAccounts.emailVerifiedAt,
currentPriceCents: editorialAccounts.currentPriceCents,
archivedAt: editorialAccounts.archivedAt,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, id))
+28 -3
View File
@@ -13,19 +13,23 @@ export default async function EditorialsPage() {
status: editorialAccounts.status,
currentPriceCents: editorialAccounts.currentPriceCents,
createdAt: editorialAccounts.createdAt,
archivedAt: editorialAccounts.archivedAt,
})
.from(editorialAccounts)
.orderBy(desc(editorialAccounts.createdAt));
const activeEditorials = editorials.filter((e) => !e.archivedAt);
const archivedEditorials = editorials.filter((e) => e.archivedAt);
return (
<section className="content-section" aria-labelledby="editorials-title">
<p className="eyebrow">Kontoverwaltung</p>
<h1 id="editorials-title">Redaktionen</h1>
{editorials.length === 0 ? (
<p>Noch keine Redaktionen registriert.</p>
{activeEditorials.length === 0 ? (
<p>Noch keine aktiven Redaktionen registriert.</p>
) : (
<ul>
{editorials.map((editorial) => (
{activeEditorials.map((editorial) => (
<li key={editorial.id}>
<a href={`/admin/redaktionen/${editorial.id}`}>{editorial.name}</a>
<p>
@@ -38,6 +42,27 @@ export default async function EditorialsPage() {
))}
</ul>
)}
{archivedEditorials.length > 0 && (
<details className="mt-8">
<summary className="cursor-pointer text-sm font-semibold text-gray-500 uppercase tracking-widest">
Archivierte Redaktionen ({archivedEditorials.length})
</summary>
<ul className="mt-4 opacity-75">
{archivedEditorials.map((editorial) => (
<li key={editorial.id}>
<a href={`/admin/redaktionen/${editorial.id}`} className="text-gray-600">
{editorial.name}
</a>
<p className="text-gray-500">
{editorial.contactName} · {editorial.loginEmail} · Archiviert am:{" "}
{editorial.archivedAt?.toLocaleDateString("de-DE")}
</p>
</li>
))}
</ul>
</details>
)}
</section>
);
}
+318
View File
@@ -1492,3 +1492,321 @@ a {
align-items: stretch;
}
}
/* ------------------------------------------------------------------ */
/* Admin Album Grid */
/* ------------------------------------------------------------------ */
.album-grid-search {
display: block;
width: 100%;
max-width: 24rem;
margin-bottom: 2rem;
padding: 0.75rem 1rem;
border: 1px solid var(--ink);
background: var(--paper);
color: var(--ink);
font: inherit;
font-size: 0.875rem;
border-radius: 0;
}
.album-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
gap: 1rem;
margin: 0;
padding: 0;
list-style: none;
}
.album-card {
display: flex;
flex-direction: column;
background: var(--paper);
border: 1px solid var(--line);
transition: background-color 150ms ease;
}
.album-card[data-granted="true"] {
border-left: 3px solid var(--ink);
}
.album-card-image-container {
aspect-ratio: 4/3;
width: 100%;
border-bottom: 1px solid var(--line);
}
.album-card-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.album-card-placeholder {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: var(--contact-sheet);
color: var(--metadata);
font-size: 0.75rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.album-card-body {
display: flex;
flex-direction: column;
flex: 1;
padding: 1rem;
}
.album-card-name {
margin: 0 0 0.5rem 0;
font-size: 0.875rem;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.album-card-count {
margin: 0 0 0.75rem 0;
font-size: 0.75rem;
color: var(--muted);
}
.album-card-status {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 0 1.25rem 0;
font-size: 0.75rem;
font-weight: 600;
}
.album-card-status::before {
content: "";
display: block;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--line);
}
.album-card-status--granted::before {
background: var(--ink);
}
.album-card-action {
margin-top: auto;
width: 100%;
padding: 0.75rem;
font: inherit;
font-size: 0.75rem;
font-weight: 600;
cursor: pointer;
border: 1px solid var(--ink);
border-radius: 0;
transition: all 150ms ease;
}
.album-card-action:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.album-card-action--grant {
background: var(--ink);
color: var(--paper);
}
.album-card-action--grant:hover:not(:disabled) {
background: var(--graphite);
}
.album-card-action--revoke {
background: transparent;
color: var(--metadata);
border-color: var(--line);
}
.album-card-action--revoke:hover:not(:disabled) {
border-color: var(--ink);
color: var(--ink);
}
@media (max-width: 639px) {
.album-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.billing-report-download {
display: inline-block;
margin-top: 1rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--line);
background: transparent;
color: var(--ink);
font-size: 0.75rem;
font-weight: 650;
text-decoration: none;
text-transform: uppercase;
letter-spacing: 0.05em;
transition: all 150ms ease;
}
.billing-report-download:hover {
border-color: var(--ink);
background: var(--soft);
}
/* ------------------------------------------------------------------ */
/* Danger Zone & Status Actions */
/* ------------------------------------------------------------------ */
.danger-banner {
padding: 0.75rem 1rem;
border: 1px solid #c44;
color: #922;
font-weight: 600;
font-size: 0.875rem;
margin: 1rem 0;
}
.action-button {
padding: 0.5rem 1.25rem;
background: var(--ink);
color: var(--paper);
border: 1px solid var(--ink);
font-size: 0.8125rem;
font-weight: 600;
font-family: inherit;
cursor: pointer;
margin-top: 0.5rem;
}
.action-button:hover {
opacity: 0.85;
}
.action-button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.action-button--warning {
background: #b45309;
border-color: #b45309;
}
.action-button--danger {
background: #b91c1c;
border-color: #b91c1c;
}
.danger-zone {
margin-top: 3rem;
padding-top: 2rem;
border-top: 2px solid #b91c1c;
}
.danger-zone h2 {
color: #b91c1c;
font-size: 1rem;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.danger-zone p {
color: var(--metadata);
font-size: 0.875rem;
margin: 0.5rem 0 1rem;
}
.danger-zone label {
display: block;
margin-bottom: 1rem;
}
.danger-zone label span {
display: block;
font-size: 0.8125rem;
color: var(--metadata);
margin-bottom: 0.25rem;
}
.danger-zone-input {
width: 100%;
max-width: 24rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--line);
font-family: inherit;
font-size: 0.875rem;
}
.danger-zone-input:focus {
border-color: #b91c1c;
outline: 2px solid #b91c1c;
outline-offset: 1px;
}
/* Global search form on album overview */
.global-search-form {
display: flex;
gap: 0.5rem;
margin-bottom: 2rem;
max-width: 36rem;
}
.global-search-form input[type="search"] {
flex: 1;
padding: 0.625rem 0.875rem;
border: 1px solid var(--line);
font-size: 0.875rem;
font-family: inherit;
}
.global-search-form button {
padding: 0.625rem 1.25rem;
background: var(--ink);
color: var(--paper);
border: 1px solid var(--ink);
font-size: 0.8125rem;
font-weight: 600;
font-family: inherit;
cursor: pointer;
letter-spacing: 0.02em;
}
.auto-rules-list { list-style: none; padding: 0; margin: 1.5rem 0; }
.auto-rule-item {
display: flex; align-items: center; gap: 1rem;
padding: 0.75rem 0;
border-bottom: 1px solid var(--line);
}
.auto-rule-keyword {
font-weight: 600;
flex: 1;
}
.auto-rule-date {
color: var(--muted);
font-size: 0.8125rem;
}
.auto-rule-delete {
background: transparent;
border: 1px solid var(--line);
padding: 0.25rem 0.75rem;
font-size: 0.75rem;
cursor: pointer;
color: var(--metadata);
font-family: inherit;
}
.auto-rule-delete:hover {
border-color: var(--ink);
color: var(--ink);
}
+77 -2
View File
@@ -1,10 +1,44 @@
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
import { AlbumContactSheet } from "@/modules/albums/catalog-content";
import { AlbumContactSheet, PhotoContactSheet } from "@/modules/albums/catalog-content";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import type { ImmichSearchPage } from "@/modules/immich/types";
import Link from "next/link";
import { requireEditorial } from "../access";
export default async function AlbumsPage() {
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[] }> }) {
const principal = await requireEditorial();
const rawSearchParams = await searchParams;
const query = normalizedQuery(singleValue(rawSearchParams.suche));
if (query) {
const results = await albumCatalog.searchVisiblePhotos(principal.editorialId, {
description: query,
page: singleValue(rawSearchParams.page),
});
const downloadOptions = await loadEditorialDownloadOptions(
principal.editorialId,
results.items.map((asset) => asset.id),
);
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} />
<PhotoContactSheet
albumName="Alle Alben"
downloadOptions={downloadOptions}
page={results}
query={query}
showAlbumName
/>
<GlobalSearchPagination page={results} query={query} />
</section>
);
}
const result = await loadAlbums(principal.editorialId);
if (result.unavailable) {
@@ -18,6 +52,7 @@ export default async function AlbumsPage() {
<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} />
{result.albums.length === 0 ? (
<p className="catalog-empty">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
) : (
@@ -27,6 +62,46 @@ export default async function AlbumsPage() {
);
}
function GlobalSearchForm({ query }: { query: string }) {
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>
);
}
function GlobalSearchPagination({ page, query }: { page: ImmichSearchPage; query: string }) {
if (page.previousPage === null && page.nextPage === null) {
return null;
}
return (
<nav aria-label="Suchergebnisseiten" className="photo-pagination">
{page.previousPage === null ? null : (
<Link href={`/redaktion/alben?suche=${encodeURIComponent(query)}&page=${page.previousPage}`}>Vorherige Seite</Link>
)}
{page.nextPage === null ? null : (
<Link href={`/redaktion/alben?suche=${encodeURIComponent(query)}&page=${page.nextPage}`}>Nächste Seite</Link>
)}
</nav>
);
}
function singleValue(value: string | string[] | undefined): string | undefined {
return typeof value === "string" ? value : undefined;
}
function normalizedQuery(value: string | undefined): string {
return (value ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
}
async function loadAlbums(editorialId: string) {
try {
return { albums: await albumCatalog.getVisibleAlbums(editorialId), unavailable: false as const };
+26
View File
@@ -0,0 +1,26 @@
import { sql } from "drizzle-orm";
import { index, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
import { editorialAccounts } from "./editorials";
export const albumAutoRules = pgTable(
"album_auto_rules",
{
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
keyword: text("keyword").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
},
(table) => [
uniqueIndex("album_auto_rules_editorial_account_id_keyword_idx").on(
table.editorialAccountId,
sql`lower(${table.keyword})`,
),
],
);
+4
View File
@@ -32,6 +32,10 @@ export const editorialAccounts = pgTable("editorial_accounts", {
acceptedTermsVersion: text("accepted_terms_version"),
acceptedTermsAt: timestamp("accepted_terms_at", { withTimezone: true }),
privacyAcknowledgedAt: timestamp("privacy_acknowledged_at", { withTimezone: true }),
archivedAt: timestamp("archived_at", { withTimezone: true }),
archivedByUserId: uuid("archived_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
+1
View File
@@ -1,6 +1,7 @@
export * from "./albums";
export * from "./audit";
export * from "./auth";
export * from "./auto-rules";
export * from "./billing";
export * from "./editorials";
export * from "./rate-limits";
+121
View File
@@ -0,0 +1,121 @@
import "server-only";
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 type * as schema from "@/db/schema";
import { albumGrantService } from "./grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichClient } from "@/modules/immich/types";
export type AutoRule = {
id: string;
editorialAccountId: string;
keyword: string;
createdAt: Date;
createdByUserId: string | null;
};
export type AutoRuleRepository = {
listRules(editorialId: string): Promise<AutoRule[]>;
createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise<void>;
deleteRule(input: { ruleId: string; adminUserId: string }): Promise<void>;
};
export function createAutoRuleService({
repository,
grantService,
immich,
}: {
repository: AutoRuleRepository;
grantService: Pick<typeof albumGrantService, "getGrantedAlbumIds" | "grantAlbum">;
immich: Pick<ImmichClient, "listAlbums">;
}) {
return {
async listRules(editorialId: string): Promise<AutoRule[]> {
return repository.listRules(editorialId);
},
async createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise<void> {
await repository.createRule(input);
},
async deleteRule(input: { ruleId: string; adminUserId: string }): Promise<void> {
await repository.deleteRule(input);
},
async applyRules(editorialId: string, adminUserId: string): Promise<{ granted: number }> {
const rules = await repository.listRules(editorialId);
if (rules.length === 0) {
return { granted: 0 };
}
let albums;
try {
albums = await immich.listAlbums();
} catch (error) {
return { granted: 0 };
}
const grantedAlbumIds = new Set(await grantService.getGrantedAlbumIds(editorialId));
let newlyGranted = 0;
for (const album of albums) {
if (grantedAlbumIds.has(album.id)) {
continue;
}
const albumNameLower = album.albumName.toLowerCase();
const matchesRule = rules.some((rule) => albumNameLower.includes(rule.keyword.toLowerCase()));
if (matchesRule) {
try {
await grantService.grantAlbum({ editorialId, immichAlbumId: album.id, adminUserId });
newlyGranted++;
grantedAlbumIds.add(album.id);
} catch (error) {
// Ignore individual album grant failures
}
}
}
return { granted: newlyGranted };
},
};
}
export function createAutoRuleRepository(
database: NodePgDatabase<typeof schema>,
): AutoRuleRepository {
return {
async listRules(editorialId: string) {
return database
.select()
.from(albumAutoRules)
.where(eq(albumAutoRules.editorialAccountId, editorialId));
},
async createRule({ editorialId, keyword, adminUserId }) {
await database
.insert(albumAutoRules)
.values({
editorialAccountId: editorialId,
keyword,
createdByUserId: adminUserId,
})
.onConflictDoNothing();
},
async deleteRule({ ruleId, adminUserId }) {
await database.delete(albumAutoRules).where(eq(albumAutoRules.id, ruleId));
},
};
}
export const autoRuleService = createAutoRuleService({
repository: createAutoRuleRepository(db),
grantService: albumGrantService,
immich: immichClient,
});
+6 -1
View File
@@ -46,16 +46,18 @@ export function PhotoContactSheet({
downloadOptions,
page,
query,
showAlbumName = false,
}: Readonly<{
albumId?: string;
albumName: string;
downloadOptions?: EditorialDownloadOptions;
page: ImmichSearchPage;
query: string;
showAlbumName?: boolean;
}>) {
return (
<>
<form aria-label={`Fotos in ${albumName} durchsuchen`} className="photo-search" role="search">
<form action={albumId ? `/redaktion/alben/${encodeURIComponent(albumId)}` : '/redaktion/alben'} aria-label={`Fotos in ${albumName} durchsuchen`} className="photo-search" role="search">
<label htmlFor="photo-query">Suchbegriff</label>
<div className="photo-search-controls">
<input defaultValue={query} id="photo-query" name="suche" type="search" />
@@ -83,6 +85,9 @@ export function PhotoContactSheet({
/>
<figcaption className="contact-strip">
<span className="contact-strip-name">{asset.originalFileName}</span>
{showAlbumName && (asset as any).albums && (asset as any).albums.length > 0 && (
<span className="contact-strip-album">{(asset as any).albums[0].id}</span>
)}
<span>{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span>
</figcaption>
{albumId && downloadOptions ? (
+3 -1
View File
@@ -45,7 +45,9 @@ export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies)
input: SearchVisiblePhotosInput,
): Promise<ImmichSearchPage> {
const grantedAlbumIds = await currentGrantIds(grants, editorialId);
const albumIds = authorizedSearchAlbums(grantedAlbumIds, input.requestedAlbumId);
const albumIds = input.requestedAlbumId
? authorizedSearchAlbums(grantedAlbumIds, input.requestedAlbumId)
: grantedAlbumIds;
if (albumIds.length === 0) {
return emptySearchPage();
}
+49
View File
@@ -0,0 +1,49 @@
"use client";
import { useState, useTransition } from "react";
import { archiveEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
type DangerZoneProps = {
editorialId: string;
editorialName: string;
};
export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
const [confirmText, setConfirmText] = useState("");
const [isPending, startTransition] = useTransition();
const isConfirmed = confirmText === editorialName;
function handleArchive() {
if (!isConfirmed) return;
startTransition(async () => {
await archiveEditorialAction(editorialId);
});
}
return (
<section className="danger-zone" aria-labelledby="danger-title">
<h2 id="danger-title">Gefahrenzone</h2>
<p>Alle Albumrechte werden widerrufen und der Login wird deaktiviert. Abrechnungsdaten bleiben erhalten.</p>
<label>
<span>Redaktionsname zur Bestätigung eingeben:</span>
<input
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
placeholder={editorialName}
className="danger-zone-input"
disabled={isPending}
/>
</label>
<button
type="button"
className="action-button action-button--danger"
disabled={!isConfirmed || isPending}
onClick={handleArchive}
>
{isPending ? "Wird archiviert…" : "Redaktion archivieren"}
</button>
</section>
);
}
+37
View File
@@ -1,4 +1,6 @@
import Link from "next/link";
import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
import { DangerZone } from "./DangerZone";
export type EditorialDetail = {
id: string;
@@ -8,6 +10,7 @@ export type EditorialDetail = {
status: string;
emailVerifiedAt: Date | null;
currentPriceCents: number | null;
archivedAt: Date | null;
};
export function EditorialDetailContent({
@@ -18,6 +21,12 @@ export function EditorialDetailContent({
<section className="content-section" aria-labelledby="editorial-title">
<p className="eyebrow">Redaktion</p>
<h1 id="editorial-title">{editorial.name}</h1>
{editorial.archivedAt && (
<p className="danger-banner" role="status">
Diese Redaktion wurde am {editorial.archivedAt.toLocaleDateString('de-DE')} archiviert.
</p>
)}
<dl>
<dt>Ansprechperson</dt>
<dd>{editorial.contactName}</dd>
@@ -46,7 +55,35 @@ export function EditorialDetailContent({
: "Eine Freigabe ist erst möglich, wenn mindestens ein aktives Albumrecht zugewiesen wurde."}
</p>
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Albumrechte verwalten</Link>
{" · "}
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln</Link>
</section>
{/* Status Actions */}
{!editorial.archivedAt && (
<section aria-labelledby="status-actions-title">
<h2 id="status-actions-title">Status-Aktionen</h2>
{editorial.status === 'active' && (
<form action={suspendEditorialAction.bind(null, editorial.id)}>
<button type="submit" className="action-button action-button--warning">
Zugang sperren
</button>
</form>
)}
{editorial.status === 'suspended' && (
<form action={reactivateEditorialAction.bind(null, editorial.id)}>
<button type="submit" className="action-button">
Zugang reaktivieren
</button>
</form>
)}
</section>
)}
{/* Danger Zone */}
{!editorial.archivedAt && (
<DangerZone editorialId={editorial.id} editorialName={editorial.name} />
)}
</section>
);
}
+2
View File
@@ -13,6 +13,7 @@ function createRepository(): EditorialServiceRepository & {
replaceBillingAddress: ReturnType<typeof vi.fn>;
transitionStatus: ReturnType<typeof vi.fn>;
claimApprovalNotice: ReturnType<typeof vi.fn>;
archiveEditorial: ReturnType<typeof vi.fn>;
} {
return {
prepareApproval: vi.fn().mockResolvedValue({
@@ -25,6 +26,7 @@ function createRepository(): EditorialServiceRepository & {
replaceBillingAddress: vi.fn().mockResolvedValue("address-2"),
transitionStatus: vi.fn().mockResolvedValue(undefined),
claimApprovalNotice: vi.fn().mockResolvedValue(true),
archiveEditorial: vi.fn().mockResolvedValue(undefined),
};
}
+94
View File
@@ -50,6 +50,7 @@ export type EditorialServiceRepository = {
to: AccountStatus;
adminUserId: string;
}): Promise<void>;
archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void>;
};
/**
@@ -151,6 +152,10 @@ export function createEditorialService({
}
await repository.transitionStatus(input);
},
async archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void> {
await repository.archiveEditorial(input);
},
};
}
@@ -416,6 +421,95 @@ export function createEditorialServiceRepository(
});
});
},
async archiveEditorial({ editorialId, adminUserId }) {
await database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction
.select({
id: editorialAccounts.id,
status: editorialAccounts.status,
archivedAt: editorialAccounts.archivedAt,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1);
if (!editorial) {
throw new EditorialServiceError("EDITORIAL_NOT_FOUND");
}
if (editorial.archivedAt) {
return;
}
const activeGrants = await transaction
.select({ id: albumGrants.id, immichAlbumId: albumGrants.immichAlbumId })
.from(albumGrants)
.where(
and(
eq(albumGrants.editorialAccountId, editorialId),
isNull(albumGrants.revokedAt),
),
)
.for("update");
const changedAt = new Date();
const newStatus = editorial.status === "active" ? "suspended" : editorial.status;
await transaction
.update(editorialAccounts)
.set({
archivedAt: changedAt,
archivedByUserId: adminUserId,
status: newStatus,
updatedAt: changedAt,
})
.where(eq(editorialAccounts.id, editorialId));
if (activeGrants.length > 0) {
const grantIds = activeGrants.map((g) => g.id);
await transaction
.update(albumGrants)
.set({ revokedAt: changedAt })
.where(inArray(albumGrants.id, grantIds));
for (const grant of activeGrants) {
await transaction.insert(auditEvents).values({
eventType: "album_revoked",
actorUserId: adminUserId,
actorType: "admin",
entityType: "album_grant",
entityId: grant.immichAlbumId,
previousValues: {
editorialId: editorialId,
immichAlbumId: grant.immichAlbumId,
granted: true,
},
newValues: {
editorialId: editorialId,
immichAlbumId: grant.immichAlbumId,
granted: false,
},
occurredAt: changedAt,
});
}
}
await transaction.insert(auditEvents).values({
eventType: "editorial_archived",
actorUserId: adminUserId,
actorType: "admin",
entityType: "editorial_account",
entityId: editorialId,
previousValues: { status: editorial.status, archived: false },
newValues: { status: newStatus, archived: true },
occurredAt: changedAt,
});
});
},
};
}