From 4667615ed0758a4f882319cfb599c87f2ff76320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Tue, 11 Aug 2026 12:28:39 +0200 Subject: [PATCH] feat: implement hard delete, email notifications, watermark, and fix bulk download --- AI_MEMORY.md | 35 +++++++++++ src/app/admin/redaktionen/[id]/actions.ts | 7 +++ .../redaktionen/[id]/alben/AlbumGrid.tsx | 47 +++++++++++--- .../admin/redaktionen/[id]/alben/actions.ts | 35 +++++++++++ src/app/admin/redaktionen/[id]/alben/page.tsx | 3 +- .../[assetId]/thumbnail/thumbnail-handler.ts | 63 +++++++++++++------ src/app/api/lightbox/bulk-download/route.ts | 29 +++++++-- src/components/brand/logo.tsx | 4 -- src/modules/editorials/DangerZone.tsx | 41 +++++++++--- src/modules/editorials/service.test.ts | 1 + src/modules/editorials/service.ts | 42 +++++++++++++ src/modules/email/service.ts | 41 ++++++++++++ src/modules/immich/client.ts | 3 +- src/modules/mail/mailer.ts | 62 ++++++++++++++++-- src/modules/usages/service.ts | 21 ++++--- 15 files changed, 369 insertions(+), 65 deletions(-) create mode 100644 AI_MEMORY.md diff --git a/AI_MEMORY.md b/AI_MEMORY.md new file mode 100644 index 0000000..ced4381 --- /dev/null +++ b/AI_MEMORY.md @@ -0,0 +1,35 @@ +# AI Memory & Context für Immich-Redaktions-Plugin + +Dieses Dokument dient als zentrale Wissensbasis ("Memory") für zukünftige KI-Assistenten, die an diesem Projekt weiterarbeiten. + +## 1. Projekt-Überblick +Dieses Projekt ist ein Kundenportal für "Leon Tonhäuser Sportfotografie". Es verbindet sich mit einer bestehenden **Immich-Instanz** und erlaubt es, ausgewählten Redaktionen gezielt Zugriff auf spezifische Immich-Alben zu geben. +Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder herunterladen (mit Wasserzeichen versehen oder in Originalqualität lizenziert) und werden automatisch abgerechnet. + +**Tech-Stack:** +- **Framework:** Next.js (App Router, Server Actions) +- **Datenbank:** PostgreSQL via Drizzle ORM +- **Authentifizierung:** BetterAuth +- **Styling:** TailwindCSS, UI-Komponenten via shadcn/ui +- **E-Mails:** React Email (HTML Templates mit Resend/SMTP) +- **PDF-Generierung:** pdfmake (für Rechnungen) + +## 2. Immich API & Spezifische Eigenheiten (WICHTIG!) +- **Album-Zuordnung von Assets:** Die Immich-API gibt im Endpoint `getAsset` in der Response `asset.albums` oft einen **leeren Array** für ältere Bilder zurück. **Verlasse dich niemals auf `asset.albums` für die Berechtigungsprüfung!** + - *Best Practice:* Hole die für die Redaktion freigegebenen Alben (`getAlbum`) ab und iteriere durch deren `album.assets`, um zu prüfen, ob ein Bild lizenziert/heruntergeladen werden darf. Dies ist in `src/modules/usages/service.ts` so implementiert. +- **Wasserzeichen & Thumbnails:** Wasserzeichen für Vorschaubilder werden auf dem Server generiert. + - Hole Bilder aus Immich mit `size=preview` (ca. 1440px Auflösung), anstatt der kleinen Thumbnails, da sie sonst beim Skalieren sehr unscharf werden. + - Das Wasserzeichen (`logo-white.png`) wird mit `sharp` auf 60% Deckkraft und ca. 480px Auflösung als SVG-Overlay auf das Bild gerechnet (`src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts`). + +## 3. Datenbank-Struktur & Hard-Delete +- Die Datenbank verwendet strenges **`onDelete: "restrict"`** für alle Relationen. +- Wenn ein Redaktions-Account gelöscht wird, müssen alle abhängigen Tabellen **manuell und in korrekter Reihenfolge** in einer Transaktion gelöscht werden, um Foreign-Key-Constraints nicht zu verletzen. + - *Reihenfolge:* `downloadEvents` -> `usages` -> `lightboxItems` -> `billingReports` -> `albumAutoRules` -> `albumGrants` -> `billingAddressVersions` -> `auditEvents` -> `editorialAccounts` -> `accounts` / `sessions` / `users` (aus BetterAuth). + - Diese Logik befindet sich in `src/modules/editorials/service.ts` unter `hardDeleteEditorial`. + +## 4. UI & Styling Quirks +- **Logo Skalierung:** Das Hauptlogo (`logo-black.png` / `logo-white.png`) darf im ``-Tag **keine** harten `width` und `height`-Attribute (z.B. `1000`) haben, sonst wird das Layout in den Page-Headern gesprengt. Die Skalierung wird dynamisch in `src/app/globals.css` über `.brand-logo` (`max-height: 2.5rem; width: min(10rem, 35vw); object-fit: contain`) geregelt. +- **E-Mails:** Die E-Mail-Templates befinden sich in `src/modules/email/service.ts` und `src/modules/mail/mailer.ts`. Sie wrappen Inhalte automatisch in ein professionelles HTML-Gerüst (inkl. Logo und Legal-Footer). + +## 5. Laufende Prozesse & Downloads +- **Bulk Downloads:** Zip-Downloads (`archiver`) von mehreren Bildern nutzen Node.js Streams (`PassThrough`). Da Next.js die Response direkt an den Browser streamt, muss sichergestellt werden, dass der Stream nicht blockiert wird (`Readable.toWeb`). Siehe `src/app/api/lightbox/bulk-download/route.ts`. diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts index a4bbec9..f2ec50e 100644 --- a/src/app/admin/redaktionen/[id]/actions.ts +++ b/src/app/admin/redaktionen/[id]/actions.ts @@ -55,6 +55,13 @@ export async function archiveEditorialAction(editorialId: string): Promise redirect("/admin/redaktionen"); } +export async function hardDeleteEditorialAction(editorialId: string): Promise { + await requireAdmin(new Headers(await headers())); + await editorialService.hardDeleteEditorial(editorialId); + revalidatePath("/admin/redaktionen"); + redirect("/admin/redaktionen"); +} + export async function suspendEditorialAction(editorialId: string): Promise { const admin = await requireAdmin(new Headers(await headers())); await editorialService.transitionEditorialStatus({ diff --git a/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx b/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx index 4b096e3..9d87df6 100644 --- a/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx +++ b/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx @@ -22,20 +22,20 @@ type AlbumGridProps = { editorialId: string; grantAction: AlbumGridAction; revokeAction: AlbumGridAction; + notifyAction: AlbumGridAction; }; -function AlbumCard({ - album, - editorialId, - grantAction, - revokeAction, -}: { - album: AlbumGridProps["albums"][0]; +type AlbumCardProps = { + album: AlbumGridProps["albums"][number]; editorialId: string; grantAction: AlbumGridAction; revokeAction: AlbumGridAction; -}) { + notifyAction: AlbumGridAction; +}; + +function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction }: AlbumCardProps) { const [isPending, startTransition] = useTransition(); + const [notifyStatus, setNotifyStatus] = useState<"idle" | "pending" | "success" | "error">("idle"); const handleAction = (formData: FormData) => { startTransition(async () => { @@ -75,7 +75,7 @@ function AlbumCard({ {album.albumName}

{album.assetCount} Fotos

-
+
+ + )}
); } -export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: AlbumGridProps) { +export function AlbumGrid({ albums, editorialId, grantAction, revokeAction, notifyAction }: AlbumGridProps) { const [search, setSearch] = useState(""); const filteredAlbums = albums.filter((album) => @@ -125,6 +151,7 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: Al editorialId={editorialId} grantAction={grantAction} revokeAction={revokeAction} + notifyAction={notifyAction} /> ))} diff --git a/src/app/admin/redaktionen/[id]/alben/actions.ts b/src/app/admin/redaktionen/[id]/alben/actions.ts index af58f2c..77c5dac 100644 --- a/src/app/admin/redaktionen/[id]/alben/actions.ts +++ b/src/app/admin/redaktionen/[id]/alben/actions.ts @@ -5,6 +5,10 @@ import { headers } from "next/headers"; import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants"; import { requireAdmin } from "@/modules/auth/principal"; +import { emailService } from "@/modules/email/service"; +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; +import { eq } from "drizzle-orm"; // 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 @@ -55,6 +59,37 @@ export async function revokeAlbumAction( return INITIAL_RESULT; } +export async function sendAlbumNotificationAction( + editorialId: string, + _prevState: AlbumActionResult, + formData: FormData, +): Promise { + await getAdminPrincipal(); + const safeEditorialId = requiredId(editorialId); + const albumName = formData.get("albumName"); + + if (typeof albumName !== "string" || !albumName) { + return { ok: false, message: "Ungültiger Albumname." }; + } + + try { + const [editorial] = await db + .select({ loginEmail: editorialAccounts.loginEmail }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, safeEditorialId)); + + if (!editorial) { + return { ok: false, message: "Redaktion nicht gefunden." }; + } + + await emailService.sendNewAlbumNotification(editorial.loginEmail, albumName); + return { ok: true, message: "Benachrichtigung erfolgreich gesendet." }; + } catch (error) { + console.error("Failed to send album notification:", error); + return { ok: false, message: "E-Mail konnte nicht gesendet werden." }; + } +} + async function getAdminPrincipal() { return requireAdmin(new Headers(await headers())); } diff --git a/src/app/admin/redaktionen/[id]/alben/page.tsx b/src/app/admin/redaktionen/[id]/alben/page.tsx index 3a38fb2..5da690e 100644 --- a/src/app/admin/redaktionen/[id]/alben/page.tsx +++ b/src/app/admin/redaktionen/[id]/alben/page.tsx @@ -7,7 +7,7 @@ import { db } from "@/db/client"; import { editorialAccounts } from "@/db/schema"; import { albumGrantService } from "@/modules/albums/grants"; -import { grantAlbumAction, revokeAlbumAction } from "./actions"; +import { grantAlbumAction, revokeAlbumAction, sendAlbumNotificationAction } from "./actions"; import { loadAssignableAlbums } from "./page-content"; import { AlbumGrid } from "./AlbumGrid"; @@ -66,6 +66,7 @@ export default async function EditorialAlbumsPage({ editorialId={editorial.id} grantAction={grantAlbumAction} revokeAction={revokeAlbumAction} + notifyAction={sendAlbumNotificationAction} /> )} diff --git a/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts b/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts index 74fd74f..a1b30c4 100644 --- a/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts +++ b/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts @@ -5,6 +5,8 @@ import { albumGrantService } from "@/modules/albums/grants"; import { immichClient } from "@/modules/immich/client"; import type { ImmichBinary } from "@/modules/immich/types"; import sharp from "sharp"; +import fs from "node:fs/promises"; +import path from "node:path"; type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>; @@ -128,27 +130,48 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: st } const buffer = Buffer.concat(chunks); - const metadata = await sharp(buffer).metadata(); - const width = metadata.width ?? 400; - const height = metadata.height ?? 300; - - const svgText = ` - - - PREVIEW - - - `; - - const watermarked = await sharp(buffer) - .composite([ - { - input: Buffer.from(svgText), - gravity: "center", - }, - ]) - .webp({ quality: 80 }) + + // Skaliere das Bild auf 480px Breite (wie vom User gewünscht) + const targetWidth = 480; + const resizedBuffer = await sharp(buffer) + .resize({ width: targetWidth, withoutEnlargement: true }) .toBuffer(); + + const resizedMetadata = await sharp(resizedBuffer).metadata(); + const width = resizedMetadata.width ?? targetWidth; + const height = resizedMetadata.height ?? 300; + + let watermarked = resizedBuffer; + try { + const logoPath = path.join(process.cwd(), "public", "brand", "logo-white.png"); + const logoBuffer = await fs.readFile(logoPath); + + // Logo auf 60% der Bildbreite skalieren + const logoTargetWidth = Math.round(width * 0.6); + const resizedLogo = await sharp(logoBuffer) + .resize({ width: logoTargetWidth, withoutEnlargement: true }) + .toBuffer(); + + const logoBase64 = resizedLogo.toString("base64"); + const logoMetadata = await sharp(resizedLogo).metadata(); + const logoWidth = logoMetadata.width ?? logoTargetWidth; + const logoHeight = logoMetadata.height ?? (logoTargetWidth / 2); + + const svgOverlay = ` + + + + `; + + watermarked = await sharp(resizedBuffer) + .composite([{ input: Buffer.from(svgOverlay), gravity: "center" }]) + .webp({ quality: 80 }) + .toBuffer(); + } catch (err) { + console.error("Watermark logo error:", err); + // Fallback falls logo-white.png nicht existiert + watermarked = await sharp(resizedBuffer).webp({ quality: 80 }).toBuffer(); + } const responseHeaders = new Headers({ "cache-control": "private, max-age=86400, stale-while-revalidate=604800", diff --git a/src/app/api/lightbox/bulk-download/route.ts b/src/app/api/lightbox/bulk-download/route.ts index 9736b82..be37c5a 100644 --- a/src/app/api/lightbox/bulk-download/route.ts +++ b/src/app/api/lightbox/bulk-download/route.ts @@ -31,7 +31,28 @@ export async function POST(request: NextRequest) { const trimmedPurpose = purpose.trim(); const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId); - const grantedSet = new Set(grantedAlbumIds); + + // Fetch all granted albums to build a map of assetId -> validAlbumId + const assetToGrantedAlbum = new Map(); + const grantedAlbums = await Promise.all( + grantedAlbumIds.map(async (albumId) => { + try { + return await immichClient.getAlbum(albumId); + } catch (err) { + console.error("Failed to fetch granted album", albumId, err); + return null; + } + }) + ); + + for (const album of grantedAlbums) { + if (!album) continue; + for (const asset of album.assets) { + if (!assetToGrantedAlbum.has(asset.id)) { + assetToGrantedAlbum.set(asset.id, album.id); + } + } + } const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = []; @@ -53,8 +74,8 @@ export async function POST(request: NextRequest) { if (!asset) continue; // Find the first album the editorial has access to - const validAlbum = asset.albums.find((a: any) => grantedSet.has(a.id)); - if (!validAlbum) continue; // Editorial does not have access + const validAlbumId = assetToGrantedAlbum.get(assetId); + if (!validAlbumId) continue; // Editorial does not have access // Check for prior usages to avoid double charging const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId); @@ -70,7 +91,7 @@ export async function POST(request: NextRequest) { const newUsage = await usageService.createNewUsage({ editorialId: principal.editorialId, assetId, - albumId: validAlbum.id, + albumId: validAlbumId, purpose: trimmedPurpose, reference: undefined, idempotencyKey, diff --git a/src/components/brand/logo.tsx b/src/components/brand/logo.tsx index b76253f..fa91634 100644 --- a/src/components/brand/logo.tsx +++ b/src/components/brand/logo.tsx @@ -6,16 +6,12 @@ export function BrandLogo() { Leon Tonhäuser Sportfotografie Leon Tonhäuser Sportfotografie ); diff --git a/src/modules/editorials/DangerZone.tsx b/src/modules/editorials/DangerZone.tsx index ab17aff..5d01ff6 100644 --- a/src/modules/editorials/DangerZone.tsx +++ b/src/modules/editorials/DangerZone.tsx @@ -2,7 +2,7 @@ import { useState, useTransition } from "react"; -import { archiveEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; +import { archiveEditorialAction, hardDeleteEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; @@ -15,6 +15,7 @@ type DangerZoneProps = { export function DangerZone({ editorialId, editorialName }: DangerZoneProps) { const [confirmText, setConfirmText] = useState(""); const [isPending, startTransition] = useTransition(); + const [isDeleting, setIsDeleting] = useState(false); const isConfirmed = confirmText === editorialName; function handleArchive() { @@ -24,12 +25,21 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) { }); } + function handleDelete() { + if (!isConfirmed) return; + setIsDeleting(true); + startTransition(async () => { + await hardDeleteEditorialAction(editorialId); + }); + } + return ( Gefahrenzone - Alle Albumrechte werden widerrufen und der Login wird deaktiviert. Abrechnungsdaten bleiben erhalten. + Archivieren widerruft alle Albumrechte und deaktiviert den Login. + Endgültiges Löschen entfernt den Account inklusive aller verknüpften Daten unwiderruflich! @@ -46,14 +56,25 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) { className="border-destructive/30 focus-visible:ring-destructive" /> - +
+ + +
); diff --git a/src/modules/editorials/service.test.ts b/src/modules/editorials/service.test.ts index 9111c82..9fa5069 100644 --- a/src/modules/editorials/service.test.ts +++ b/src/modules/editorials/service.test.ts @@ -27,6 +27,7 @@ function createRepository(): EditorialServiceRepository & { transitionStatus: vi.fn().mockResolvedValue(undefined), claimApprovalNotice: vi.fn().mockResolvedValue(true), archiveEditorial: vi.fn().mockResolvedValue(undefined), + hardDeleteEditorial: vi.fn().mockResolvedValue(undefined), }; } diff --git a/src/modules/editorials/service.ts b/src/modules/editorials/service.ts index a7c88c9..645a41a 100644 --- a/src/modules/editorials/service.ts +++ b/src/modules/editorials/service.ts @@ -9,6 +9,11 @@ import { auditEvents, billingAddressVersions, editorialAccounts, + downloadEvents, + usages, + lightboxItems, + billingReports, + albumAutoRules, } from "@/db/schema"; import type * as schema from "@/db/schema"; import type { AccountStatus } from "@/modules/auth/principal"; @@ -51,6 +56,7 @@ export type EditorialServiceRepository = { adminUserId: string; }): Promise; archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise; + hardDeleteEditorial(editorialId: string): Promise; }; /** @@ -156,6 +162,10 @@ export function createEditorialService({ async archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise { await repository.archiveEditorial(input); }, + + async hardDeleteEditorial(editorialId: string): Promise { + await repository.hardDeleteEditorial(editorialId); + }, }; } @@ -510,6 +520,38 @@ export function createEditorialServiceRepository( }); }); }, + + async hardDeleteEditorial(editorialId: string) { + await db.transaction(async (transaction) => { + await lockEditorialForMutation(transaction, editorialId); + + const [editorial] = await transaction + .select({ userId: editorialAccounts.userId }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)); + + if (!editorial) return; + + // Cascade deletions manually due to restrict constraints + await transaction.delete(downloadEvents).where(eq(downloadEvents.editorialAccountId, editorialId)); + await transaction.delete(usages).where(eq(usages.editorialAccountId, editorialId)); + await transaction.delete(lightboxItems).where(eq(lightboxItems.editorialAccountId, editorialId)); + await transaction.delete(billingReports).where(eq(billingReports.editorialAccountId, editorialId)); + await transaction.delete(albumAutoRules).where(eq(albumAutoRules.editorialAccountId, editorialId)); + await transaction.delete(albumGrants).where(eq(albumGrants.editorialAccountId, editorialId)); + await transaction.delete(billingAddressVersions).where(eq(billingAddressVersions.editorialAccountId, editorialId)); + await transaction.delete(auditEvents).where(and(eq(auditEvents.entityId, editorialId), eq(auditEvents.entityType, "editorial_account"))); + + await transaction.delete(editorialAccounts).where(eq(editorialAccounts.id, editorialId)); + + if (editorial.userId) { + const { accounts, sessions, users } = await import("@/db/schema/auth"); + await transaction.delete(accounts).where(eq(accounts.userId, editorial.userId)); + await transaction.delete(sessions).where(eq(sessions.userId, editorial.userId)); + await transaction.delete(users).where(eq(users.id, editorial.userId)); + } + }); + }, }; } diff --git a/src/modules/email/service.ts b/src/modules/email/service.ts index f48b7cd..5d4625f 100644 --- a/src/modules/email/service.ts +++ b/src/modules/email/service.ts @@ -12,6 +12,45 @@ const transporter = nodemailer.createTransport({ }, }); +function buildHtml(title: string, content: string, button?: { text: string, url: string }) { + return ` + + + + + + +
+
+ Logo +
+
+
${title}
+

${content}

+ ${button ? `` : ''} +
+ +
+ +`; +} + export const emailService = { async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) { const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf"; @@ -21,6 +60,7 @@ export const emailService = { to: toEmail, subject: `Ihre Abrechnung für ${reportMonth}`, text: `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat ${reportMonth} als PDF-Dokument.\n\nViele Grüße,\nIhr Redaktions-Team`, + html: buildHtml("Ihre Abrechnung ist da", `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat **${reportMonth}** bequem als PDF-Dokument angehängt.\n\nViele Grüße,\nIhr Redaktions-Team`), attachments: [ { filename, @@ -37,6 +77,7 @@ export const emailService = { to: toEmail, subject: `Neues Fotoalbum verfügbar: ${albumName}`, text: `Hallo,\n\nein neues Fotoalbum "${albumName}" wurde für Ihre Redaktion freigegeben. Sie können die Bilder ab sofort im Redaktionsportal ansehen und lizenzieren.\n\nViele Grüße,\nIhr Redaktions-Team`, + html: buildHtml("Neues Album verfügbar", `Hallo,\n\nein neues Fotoalbum **"${albumName}"** wurde soeben für Ihre Redaktion freigegeben.\n\nSie können die Bilder ab sofort im Redaktionsportal ansehen und herunterladen.\n\nViele Grüße,\nIhr Redaktions-Team`, { text: "Zum Portal", url: `${env.BETTER_AUTH_URL}/login` }), }); }, }; diff --git a/src/modules/immich/client.ts b/src/modules/immich/client.ts index b300358..a56017a 100644 --- a/src/modules/immich/client.ts +++ b/src/modules/immich/client.ts @@ -381,7 +381,8 @@ export function createImmichClient({ ); }, getThumbnail(assetId, signal) { - return requestBinary(`/assets/${encodeURIComponent(assetId)}/thumbnail`, signal); + // Request 'preview' size to get a larger image, so we can resize it cleanly to 480px + return requestBinary(`/assets/${encodeURIComponent(assetId)}/thumbnail?size=preview`, signal); }, getOriginal(assetId, signal) { return requestBinary(`/assets/${encodeURIComponent(assetId)}/original`, signal); diff --git a/src/modules/mail/mailer.ts b/src/modules/mail/mailer.ts index 8d34b9f..fe5c4fb 100644 --- a/src/modules/mail/mailer.ts +++ b/src/modules/mail/mailer.ts @@ -9,6 +9,7 @@ export type MailMessage = { to: string; subject: string; text: string; + html?: string; }; export type MailTransport = { @@ -30,26 +31,75 @@ export function createMailer({ from, transport }: { from: string; transport: Mai await transport.sendMail({ from, ...message }); } + function buildHtml(title: string, content: string, button?: { text: string, url: string }) { + return ` + + + + + + +
+
+ Logo +
+
+
${title}
+

${content}

+ ${button ? `` : ''} +
+ +
+ +`; + } + return { async sendVerification({ to, verificationUrl }) { + const subject = "Bitte bestätigen Sie Ihre E-Mail-Adresse"; + const text = `Bitte bestätigen Sie Ihre E-Mail-Adresse für das Redaktionsportal:\n\n${verificationUrl}`; await send({ to, - subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse", - text: `Bitte bestätigen Sie Ihre E-Mail-Adresse für das Redaktionsportal:\n\n${verificationUrl}`, + subject, + text, + html: buildHtml("E-Mail bestätigen", "Bitte bestätigen Sie Ihre E-Mail-Adresse für das Redaktionsportal, um Ihren Account zu aktivieren.", { text: "Jetzt bestätigen", url: verificationUrl }), }); }, async sendPasswordReset({ to, resetUrl }) { + const subject = "Passwort für das Redaktionsportal zurücksetzen"; + const text = `Setzen Sie Ihr Passwort für das Redaktionsportal zurück:\n\n${resetUrl}`; await send({ to, - subject: "Passwort für das Redaktionsportal zurücksetzen", - text: `Setzen Sie Ihr Passwort für das Redaktionsportal zurück:\n\n${resetUrl}`, + subject, + text, + html: buildHtml("Passwort zurücksetzen", "Wir haben eine Anfrage zum Zurücksetzen Ihres Passworts erhalten. Klicken Sie auf den Button, um ein neues Passwort zu vergeben.", { text: "Passwort zurücksetzen", url: resetUrl }), }); }, async sendApprovalNotice({ to, editorialName }) { + const subject = "Ihr Zugang zum Redaktionsportal ist freigegeben"; + const text = `Der Zugang für ${editorialName} wurde freigegeben. Sie können sich jetzt im Redaktionsportal anmelden.`; + const loginUrl = `${env.BETTER_AUTH_URL}/login`; await send({ to, - subject: "Ihr Zugang zum Redaktionsportal ist freigegeben", - text: `Der Zugang für ${editorialName} wurde freigegeben. Sie können sich jetzt im Redaktionsportal anmelden.`, + subject, + text, + html: buildHtml("Account freigegeben", `Herzlichen Glückwunsch!\nDer Zugang für **${editorialName}** wurde soeben freigegeben.\n\nSie können sich ab sofort im Portal anmelden und auf freigegebene Bilder zugreifen.`, { text: "Zum Portal", url: loginUrl }), }); }, }; diff --git a/src/modules/usages/service.ts b/src/modules/usages/service.ts index 4b05da0..86a255b 100644 --- a/src/modules/usages/service.ts +++ b/src/modules/usages/service.ts @@ -57,7 +57,7 @@ export type UsageRepository = { }; type UsageImmich = { - getAlbum(albumId: string): Promise<{ id: string; albumName: string }>; + getAlbum(albumId: string): Promise<{ id: string; albumName: string; assets: Array<{ id: string }> }>; getAsset(assetId: string): Promise<{ id: string; originalFileName: string; @@ -90,7 +90,7 @@ export function createUsageService({ if (existing) return resolveIntent(existing, fingerprint, "new_usage"); const asset = await getValidatedAsset(immich, input.assetId); - const album = await loadRequestedAlbum(immich, asset, input.albumId); + const album = await loadRequestedAlbum(immich, input.assetId, input.albumId); const persisted = await repository.createBillableIntent({ ...input, albumName: normalizeUpstreamSnapshot(album.albumName), @@ -98,7 +98,7 @@ export function createUsageService({ requestFingerprint: fingerprint, }, async () => { const currentAsset = await getValidatedAsset(immich, input.assetId); - const currentAlbum = await loadRequestedAlbum(immich, currentAsset, input.albumId); + const currentAlbum = await loadRequestedAlbum(immich, input.assetId, input.albumId); return { albumName: normalizeUpstreamSnapshot(currentAlbum.albumName), filename: normalizeUpstreamSnapshot(currentAsset.originalFileName), @@ -330,18 +330,21 @@ function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput async function loadRequestedAlbum( immich: UsageImmich, - asset: { albums: Array<{ id: string }> }, + assetId: string, albumId: string, ): Promise<{ id: string; albumName: string }> { - if (!asset.albums.some((a) => a.id === albumId)) { - throw new UsageAccountingError("ASSET_NOT_IN_ALBUM"); - } - + let album; try { - return await immich.getAlbum(albumId); + album = await immich.getAlbum(albumId); } catch { throw new UsageAccountingError("IMMICH_UNAVAILABLE"); } + + if (!album.assets.some((a) => a.id === assetId)) { + throw new UsageAccountingError("ASSET_NOT_IN_ALBUM"); + } + + return album; } async function getValidatedAsset(immich: UsageImmich, assetId: string) {