diff --git a/drizzle/0007_album_auto_rules_and_archive.sql b/drizzle/0007_album_auto_rules_and_archive.sql new file mode 100644 index 0000000..df2c360 --- /dev/null +++ b/drizzle/0007_album_auto_rules_and_archive.sql @@ -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 $$; diff --git a/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx b/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx index 72cd94b..391fb0b 100644 --- a/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx +++ b/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx @@ -333,7 +333,16 @@ export function BillingSelection({ {report.status === "final" && ( - + <> + + + PDF herunterladen + + )} ))} diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts index 761570b..397bcfd 100644 --- a/src/app/admin/redaktionen/[id]/actions.ts +++ b/src/app/admin/redaktionen/[id]/actions.ts @@ -2,78 +2,39 @@ import { revalidatePath } from "next/cache"; import { headers } from "next/headers"; - +import { redirect } from "next/navigation"; import { requireAdmin } from "@/modules/auth/principal"; -import { editorialService, EditorialServiceError } from "@/modules/editorials/service"; +import { editorialService } from "@/modules/editorials/service"; -// Returned to the client form so failures surface as inline German text -// instead of an opaque Next.js error-digest page (a thrown server action -// becomes a 500 with a digest the user can't read). -export type ApproveActionResult = { ok: boolean; message: string }; - -const INITIAL_RESULT: ApproveActionResult = { ok: true, message: "" }; - -export async function approveEditorialAction( - editorialId: string, - _prevState: ApproveActionResult, - formData: FormData, -): Promise { - const principal = await requireAdmin(new Headers(await headers())); - const safeEditorialId = requiredId(editorialId); - const price = parsePriceCents(formData.get("priceEuros")); - if (!price.ok) { - return { ok: false, message: price.message }; - } - - try { - await editorialService.approveEditorial({ - editorialId: safeEditorialId, - priceCents: price.cents, - adminUserId: principal.userId, - }); - } catch (error) { - return { ok: false, message: approveErrorMessage(error) }; - } - - revalidatePath(`/admin/redaktionen/${safeEditorialId}`); - revalidatePath(`/admin/redaktionen`); - return INITIAL_RESULT; +export async function archiveEditorialAction(editorialId: string): Promise { + 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'); } -function parsePriceCents( - value: unknown, -): { ok: true; cents: number } | { ok: false; message: string } { - const euros = - typeof value === "string" ? Number.parseFloat(value.replace(",", ".")) : Number.NaN; - if (!Number.isFinite(euros) || euros <= 0) { - return { ok: false, message: "Bitte geben Sie einen gültigen Nettopreis an." }; - } - return { ok: true, cents: Math.round(euros * 100) }; +export async function suspendEditorialAction(editorialId: string): Promise { + const admin = await requireAdmin(new Headers(await headers())); + await editorialService.transitionEditorialStatus({ + editorialId, + from: 'active', + to: 'suspended', + adminUserId: admin.userId, + }); + revalidatePath(`/admin/redaktionen/${editorialId}`); } -function approveErrorMessage(error: unknown): string { - if (error instanceof EditorialServiceError) { - const messages: Record = { - INVALID_PRICE: "Bitte geben Sie einen gültigen Nettopreis an.", - EDITORIAL_NOT_FOUND: "Redaktion nicht gefunden.", - EMAIL_NOT_VERIFIED: "Die E-Mail-Adresse der Redaktion ist noch nicht bestätigt.", - ALBUM_GRANT_REQUIRED: "Bitte weisen Sie zuerst mindestens ein Album zu.", - INVALID_ACCOUNT_TRANSITION: - "Die Redaktion kann in ihrem aktuellen Status nicht freigegeben werden.", - APPROVAL_NOTICE_DELIVERY_UNKNOWN: - "Der Freigabe-Hinweis konnte nicht eindeutig zugeordnet werden.", - }; - return messages[error.code] ?? "Die Freigabe ist fehlgeschlagen."; - } - return "Die Freigabe ist fehlgeschlagen."; +export async function reactivateEditorialAction(editorialId: string): Promise { + const admin = await requireAdmin(new Headers(await headers())); + await editorialService.transitionEditorialStatus({ + editorialId, + from: 'suspended', + to: 'active', + adminUserId: admin.userId, + }); + revalidatePath(`/admin/redaktionen/${editorialId}`); } - -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; -} \ No newline at end of file diff --git a/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx b/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx new file mode 100644 index 0000000..6b70aa2 --- /dev/null +++ b/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx @@ -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; + revokeAction: (editorialId: string, formData: FormData) => Promise; +}; + +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 ( +
  • +
    + {album.albumThumbnailAssetId ? ( + {`Titelbild + ) : ( +
    + Kein Cover +
    + )} +
    +
    +

    + {album.albumName} +

    +

    {album.assetCount} Fotos

    +

    + {album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"} +

    +
    + + +
    +
    +
  • + ); +} + +export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: AlbumGridProps) { + const [search, setSearch] = useState(""); + + const filteredAlbums = albums.filter((album) => + album.albumName.toLowerCase().includes(search.toLowerCase()) + ); + + return ( +
    + setSearch(e.target.value)} + aria-label="Alben durchsuchen" + /> + + {filteredAlbums.length === 0 ? ( +

    Keine Alben gefunden.

    + ) : ( +
      + {filteredAlbums.map((album) => ( + + ))} +
    + )} +
    + ); +} diff --git a/src/app/admin/redaktionen/[id]/alben/page.test.tsx b/src/app/admin/redaktionen/[id]/alben/page.test.tsx index abad4cd..97c2381 100644 --- a/src/app/admin/redaktionen/[id]/alben/page.test.tsx +++ b/src/app/admin/redaktionen/[id]/alben/page.test.tsx @@ -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", () => { diff --git a/src/app/admin/redaktionen/[id]/alben/page.tsx b/src/app/admin/redaktionen/[id]/alben/page.tsx index 40e7fbc..411e926 100644 --- a/src/app/admin/redaktionen/[id]/alben/page.tsx +++ b/src/app/admin/redaktionen/[id]/alben/page.tsx @@ -1,16 +1,15 @@ -/* eslint-disable @next/next/no-img-element */ - +import Image from "next/image"; import Link from "next/link"; import { eq } from "drizzle-orm"; import { notFound } from "next/navigation"; -import { AlbumGrantForm } from "@/components/admin/album-grant-form"; import { db } from "@/db/client"; import { editorialAccounts } from "@/db/schema"; 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, @@ -52,45 +51,20 @@ export default async function EditorialAlbumsPage({

    Zurück zur Redaktion + {" · "} + Auto-Zuweisungsregeln verwalten

    {albumResult.albums.length === 0 ? (

    Derzeit sind keine zuweisbaren Alben vorhanden.

    ) : ( -
      - {albumResult.albums.map((album) => { - const action = album.isGranted ? revokeAlbumAction : grantAlbumAction; - return ( -
    • -
      - {album.albumThumbnailAssetId ? ( - {`Titelbild - ) : ( -
      - Kein Cover -
      - )} -

      {album.albumName}

      -

      {album.assetCount} Fotos

      -

      - Status: {album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"} -

      - -
      -
    • - ); - })} -
    + )} ); -} \ No newline at end of file +} diff --git a/src/app/admin/redaktionen/[id]/auto-regeln/actions.ts b/src/app/admin/redaktionen/[id]/auto-regeln/actions.ts new file mode 100644 index 0000000..8281031 --- /dev/null +++ b/src/app/admin/redaktionen/[id]/auto-regeln/actions.ts @@ -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 { + 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 { + 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 { + const principal = await getAdminPrincipal(); + const safeEditorialId = requiredId(editorialId); + + await autoRuleService.applyRules(safeEditorialId, principal.userId); + + revalidatePath(`/admin/redaktionen/${safeEditorialId}/auto-regeln`); +} diff --git a/src/app/admin/redaktionen/[id]/auto-regeln/page.tsx b/src/app/admin/redaktionen/[id]/auto-regeln/page.tsx new file mode 100644 index 0000000..62a98ee --- /dev/null +++ b/src/app/admin/redaktionen/[id]/auto-regeln/page.tsx @@ -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 ( +
    +

    Redaktion · Auto-Zuweisungsregeln

    +

    Auto-Regeln für {editorial.name}

    +

    + Alben, deren Name eines der folgenden Schlüsselwörter enthält, werden automatisch zugewiesen. +

    +

    + Zurück zu Albumrechte +

    + +
    + + +
    + +
    + +
    + + {rules.length === 0 ? ( +

    Noch keine Auto-Regeln angelegt.

    + ) : ( +
      + {rules.map((rule) => ( +
    • + {rule.keyword} + + {rule.createdAt.toLocaleDateString('de-DE')} + +
      + +
      +
    • + ))} +
    + )} +
    + ); +} diff --git a/src/app/admin/redaktionen/[id]/page.tsx b/src/app/admin/redaktionen/[id]/page.tsx index 5149293..3de91ee 100644 --- a/src/app/admin/redaktionen/[id]/page.tsx +++ b/src/app/admin/redaktionen/[id]/page.tsx @@ -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)) diff --git a/src/app/admin/redaktionen/page.tsx b/src/app/admin/redaktionen/page.tsx index f9030c3..cdae888 100644 --- a/src/app/admin/redaktionen/page.tsx +++ b/src/app/admin/redaktionen/page.tsx @@ -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 (

    Kontoverwaltung

    Redaktionen

    - {editorials.length === 0 ? ( -

    Noch keine Redaktionen registriert.

    + {activeEditorials.length === 0 ? ( +

    Noch keine aktiven Redaktionen registriert.

    ) : ( -
      - {editorials.map((editorial) => ( +
        + {activeEditorials.map((editorial) => (
      • {editorial.name}

        @@ -38,6 +42,27 @@ export default async function EditorialsPage() { ))}

      )} + + {archivedEditorials.length > 0 && ( +
      + + Archivierte Redaktionen ({archivedEditorials.length}) + +
        + {archivedEditorials.map((editorial) => ( +
      • + + {editorial.name} + +

        + {editorial.contactName} · {editorial.loginEmail} · Archiviert am:{" "} + {editorial.archivedAt?.toLocaleDateString("de-DE")} +

        +
      • + ))} +
      +
      + )}
    ); } diff --git a/src/app/globals.css b/src/app/globals.css index 70c9b64..9aac7be 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1582,3 +1582,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); +} diff --git a/src/app/redaktion/alben/page.tsx b/src/app/redaktion/alben/page.tsx index 70dd57f..7c12257 100644 --- a/src/app/redaktion/alben/page.tsx +++ b/src/app/redaktion/alben/page.tsx @@ -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 ( +
    +

    Bildarchiv · Suche

    +
    +

    Suchergebnisse

    +
    + + + +
    + ); + } + const result = await loadAlbums(principal.editorialId); if (result.unavailable) { @@ -18,6 +52,7 @@ export default async function AlbumsPage() {

    Ihre Alben

    Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen.

    + {result.albums.length === 0 ? (

    Für Ihre Redaktion sind noch keine Fotoalben freigegeben.

    ) : ( @@ -27,6 +62,46 @@ export default async function AlbumsPage() { ); } +function GlobalSearchForm({ query }: { query: string }) { + return ( +
    + + +
    + ); +} + +function GlobalSearchPagination({ page, query }: { page: ImmichSearchPage; query: string }) { + if (page.previousPage === null && page.nextPage === null) { + return null; + } + + return ( + + ); +} + +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 }; diff --git a/src/db/schema/auto-rules.ts b/src/db/schema/auto-rules.ts new file mode 100644 index 0000000..f4d534a --- /dev/null +++ b/src/db/schema/auto-rules.ts @@ -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})`, + ), + ], +); diff --git a/src/db/schema/editorials.ts b/src/db/schema/editorials.ts index d23ce71..72cc0e1 100644 --- a/src/db/schema/editorials.ts +++ b/src/db/schema/editorials.ts @@ -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(), }); diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index f0ead02..cc506fe 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -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"; diff --git a/src/modules/albums/auto-rules.ts b/src/modules/albums/auto-rules.ts new file mode 100644 index 0000000..3fcaaf8 --- /dev/null +++ b/src/modules/albums/auto-rules.ts @@ -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; + createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise; + deleteRule(input: { ruleId: string; adminUserId: string }): Promise; +}; + +export function createAutoRuleService({ + repository, + grantService, + immich, +}: { + repository: AutoRuleRepository; + grantService: Pick; + immich: Pick; +}) { + return { + async listRules(editorialId: string): Promise { + return repository.listRules(editorialId); + }, + + async createRule(input: { editorialId: string; keyword: string; adminUserId: string }): Promise { + await repository.createRule(input); + }, + + async deleteRule(input: { ruleId: string; adminUserId: string }): Promise { + 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, +): 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, +}); diff --git a/src/modules/albums/catalog-content.tsx b/src/modules/albums/catalog-content.tsx index b73d33d..a9df69a 100644 --- a/src/modules/albums/catalog-content.tsx +++ b/src/modules/albums/catalog-content.tsx @@ -47,6 +47,7 @@ export function PhotoContactSheet({ downloadOptions, page, query, + showAlbumName = false, }: Readonly<{ albumId?: string; albumName: string; @@ -54,10 +55,11 @@ export function PhotoContactSheet({ downloadOptions?: EditorialDownloadOptions; page: ImmichSearchPage; query: string; + showAlbumName?: boolean; }>) { return ( <> -
    +
    @@ -85,6 +87,9 @@ export function PhotoContactSheet({ />
    {asset.originalFileName} + {showAlbumName && (asset as any).albums && (asset as any).albums.length > 0 && ( + {(asset as any).albums[0].id} + )} {formatDate(asset.localDateTime ?? asset.fileCreatedAt)}
    {albumId && downloadOptions ? ( diff --git a/src/modules/albums/catalog.ts b/src/modules/albums/catalog.ts index 84b7b84..43077b5 100644 --- a/src/modules/albums/catalog.ts +++ b/src/modules/albums/catalog.ts @@ -45,7 +45,9 @@ export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies) input: SearchVisiblePhotosInput, ): Promise { 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(); } diff --git a/src/modules/editorials/DangerZone.tsx b/src/modules/editorials/DangerZone.tsx new file mode 100644 index 0000000..6f0ef32 --- /dev/null +++ b/src/modules/editorials/DangerZone.tsx @@ -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 ( +
    +

    Gefahrenzone

    +

    Alle Albumrechte werden widerrufen und der Login wird deaktiviert. Abrechnungsdaten bleiben erhalten.

    + + +
    + ); +} diff --git a/src/modules/editorials/admin-detail.tsx b/src/modules/editorials/admin-detail.tsx index c93a848..190b51b 100644 --- a/src/modules/editorials/admin-detail.tsx +++ b/src/modules/editorials/admin-detail.tsx @@ -1,7 +1,6 @@ import Link from "next/link"; - -import { ApproveForm } from "@/components/admin/approve-form"; -import { approveEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; +import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; +import { DangerZone } from "./DangerZone"; export type EditorialDetail = { id: string; @@ -11,24 +10,23 @@ export type EditorialDetail = { status: string; emailVerifiedAt: Date | null; currentPriceCents: number | null; + archivedAt: Date | null; }; export function EditorialDetailContent({ editorial, hasActiveGrant, }: Readonly<{ editorial: EditorialDetail; hasActiveGrant: boolean }>) { - const emailVerified = Boolean(editorial.emailVerifiedAt); - const canApprove = hasActiveGrant && emailVerified; - const approvalHint = !emailVerified - ? "Eine Freigabe ist erst möglich, nachdem die E-Mail-Adresse bestätigt wurde." - : hasActiveGrant - ? "Mit der Freigabe wird der Nettopreis festgelegt und die Redaktion kann sich anmelden." - : "Eine Freigabe ist erst möglich, wenn mindestens ein aktives Albumrecht zugewiesen wurde."; - return (

    Redaktion

    {editorial.name}

    + + {editorial.archivedAt && ( +

    + Diese Redaktion wurde am {editorial.archivedAt.toLocaleDateString('de-DE')} archiviert. +

    + )}
    Ansprechperson
    {editorial.contactName}
    @@ -48,19 +46,44 @@ export function EditorialDetailContent({

    Freigabe

    - {editorial.status === "active" ? ( -

    Die Redaktion ist freigegeben (Netto {formatCents(editorial.currentPriceCents ?? 0)}).

    - ) : ( - <> - -

    {approvalHint}

    - Albumrechte verwalten - - )} + +

    + {hasActiveGrant + ? "Mindestens ein Albumrecht ist zugewiesen. Die Freigabe bleibt bis zur weiteren Verwaltungsoberfläche deaktiviert." + : "Eine Freigabe ist erst möglich, wenn mindestens ein aktives Albumrecht zugewiesen wurde."} +

    + Albumrechte verwalten + {" · "} + Auto-Zuweisungsregeln
    + + {/* Status Actions */} + {!editorial.archivedAt && ( +
    +

    Status-Aktionen

    + {editorial.status === 'active' && ( + + + + )} + {editorial.status === 'suspended' && ( +
    + +
    + )} +
    + )} + + {/* Danger Zone */} + {!editorial.archivedAt && ( + + )}
    ); } diff --git a/src/modules/editorials/service.test.ts b/src/modules/editorials/service.test.ts index 23a9081..9111c82 100644 --- a/src/modules/editorials/service.test.ts +++ b/src/modules/editorials/service.test.ts @@ -13,6 +13,7 @@ function createRepository(): EditorialServiceRepository & { replaceBillingAddress: ReturnType; transitionStatus: ReturnType; claimApprovalNotice: ReturnType; + archiveEditorial: ReturnType; } { 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), }; } diff --git a/src/modules/editorials/service.ts b/src/modules/editorials/service.ts index a2b1591..a7c88c9 100644 --- a/src/modules/editorials/service.ts +++ b/src/modules/editorials/service.ts @@ -50,6 +50,7 @@ export type EditorialServiceRepository = { to: AccountStatus; adminUserId: string; }): Promise; + archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise; }; /** @@ -151,6 +152,10 @@ export function createEditorialService({ } await repository.transitionStatus(input); }, + + async archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise { + 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, + }); + }); + }, }; }