feat: implement hard delete, email notifications, watermark, and fix bulk download

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 12:28:39 +02:00
1 parent 8dd1e10fea
commit 4667615ed0
15 files changed
+357 -53

No files matched your search

+35
View File
@@ -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 `<img>`-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`.
@@ -55,6 +55,13 @@ export async function archiveEditorialAction(editorialId: string): Promise<void>
redirect("/admin/redaktionen"); redirect("/admin/redaktionen");
} }
export async function hardDeleteEditorialAction(editorialId: string): Promise<void> {
await requireAdmin(new Headers(await headers()));
await editorialService.hardDeleteEditorial(editorialId);
revalidatePath("/admin/redaktionen");
redirect("/admin/redaktionen");
}
export async function suspendEditorialAction(editorialId: string): Promise<void> { export async function suspendEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers())); const admin = await requireAdmin(new Headers(await headers()));
await editorialService.transitionEditorialStatus({ await editorialService.transitionEditorialStatus({
@@ -22,20 +22,20 @@ type AlbumGridProps = {
editorialId: string; editorialId: string;
grantAction: AlbumGridAction; grantAction: AlbumGridAction;
revokeAction: AlbumGridAction; revokeAction: AlbumGridAction;
notifyAction: AlbumGridAction;
}; };
function AlbumCard({ type AlbumCardProps = {
album, album: AlbumGridProps["albums"][number];
editorialId,
grantAction,
revokeAction,
}: {
album: AlbumGridProps["albums"][0];
editorialId: string; editorialId: string;
grantAction: AlbumGridAction; grantAction: AlbumGridAction;
revokeAction: AlbumGridAction; revokeAction: AlbumGridAction;
}) { notifyAction: AlbumGridAction;
};
function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction }: AlbumCardProps) {
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
const [notifyStatus, setNotifyStatus] = useState<"idle" | "pending" | "success" | "error">("idle");
const handleAction = (formData: FormData) => { const handleAction = (formData: FormData) => {
startTransition(async () => { startTransition(async () => {
@@ -75,7 +75,7 @@ function AlbumCard({
{album.albumName} {album.albumName}
</h2> </h2>
<p className="text-sm text-gray-500 mb-4">{album.assetCount} Fotos</p> <p className="text-sm text-gray-500 mb-4">{album.assetCount} Fotos</p>
<div className="mt-auto"> <div className="mt-auto space-y-2">
<form action={handleAction}> <form action={handleAction}>
<input name="immichAlbumId" type="hidden" value={album.id} /> <input name="immichAlbumId" type="hidden" value={album.id} />
<button <button
@@ -90,13 +90,39 @@ function AlbumCard({
{isPending ? "Wird verarbeitet..." : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"} {isPending ? "Wird verarbeitet..." : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button> </button>
</form> </form>
{album.isGranted && (
<form action={(formData) => {
setNotifyStatus("pending");
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
setNotifyStatus(res.ok ? "success" : "error");
setTimeout(() => setNotifyStatus("idle"), 3000);
});
}}>
<input name="albumName" type="hidden" value={album.albumName} />
<button
type="submit"
className={`w-full py-2 px-4 rounded-lg font-semibold text-sm transition-colors duration-200 border ${
notifyStatus === "success" ? "bg-green-50 text-green-700 border-green-200" :
notifyStatus === "error" ? "bg-red-50 text-red-700 border-red-200" :
"bg-white text-gray-700 hover:bg-gray-50 border-gray-200 focus:ring-2 focus:ring-gray-200 focus:outline-none"
}`}
disabled={notifyStatus === "pending" || notifyStatus === "success"}
>
{notifyStatus === "pending" ? "Wird gesendet..." :
notifyStatus === "success" ? "E-Mail gesendet!" :
notifyStatus === "error" ? "Fehler beim Senden" :
"Redaktion benachrichtigen"}
</button>
</form>
)}
</div> </div>
</div> </div>
</li> </li>
); );
} }
export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: AlbumGridProps) { export function AlbumGrid({ albums, editorialId, grantAction, revokeAction, notifyAction }: AlbumGridProps) {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const filteredAlbums = albums.filter((album) => const filteredAlbums = albums.filter((album) =>
@@ -125,6 +151,7 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: Al
editorialId={editorialId} editorialId={editorialId}
grantAction={grantAction} grantAction={grantAction}
revokeAction={revokeAction} revokeAction={revokeAction}
notifyAction={notifyAction}
/> />
))} ))}
</ul> </ul>
@@ -5,6 +5,10 @@ import { headers } from "next/headers";
import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants"; import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants";
import { requireAdmin } from "@/modules/auth/principal"; 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 // 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 // instead of an opaque Next.js error-digest page (a thrown server action
@@ -55,6 +59,37 @@ export async function revokeAlbumAction(
return INITIAL_RESULT; return INITIAL_RESULT;
} }
export async function sendAlbumNotificationAction(
editorialId: string,
_prevState: AlbumActionResult,
formData: FormData,
): Promise<AlbumActionResult> {
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() { async function getAdminPrincipal() {
return requireAdmin(new Headers(await headers())); return requireAdmin(new Headers(await headers()));
} }
@@ -7,7 +7,7 @@ import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema"; import { editorialAccounts } from "@/db/schema";
import { albumGrantService } from "@/modules/albums/grants"; import { albumGrantService } from "@/modules/albums/grants";
import { grantAlbumAction, revokeAlbumAction } from "./actions"; import { grantAlbumAction, revokeAlbumAction, sendAlbumNotificationAction } from "./actions";
import { loadAssignableAlbums } from "./page-content"; import { loadAssignableAlbums } from "./page-content";
import { AlbumGrid } from "./AlbumGrid"; import { AlbumGrid } from "./AlbumGrid";
@@ -66,6 +66,7 @@ export default async function EditorialAlbumsPage({
editorialId={editorial.id} editorialId={editorial.id}
grantAction={grantAlbumAction} grantAction={grantAlbumAction}
revokeAction={revokeAlbumAction} revokeAction={revokeAlbumAction}
notifyAction={sendAlbumNotificationAction}
/> />
)} )}
</div> </div>
@@ -5,6 +5,8 @@ import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client"; import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types"; import type { ImmichBinary } from "@/modules/immich/types";
import sharp from "sharp"; import sharp from "sharp";
import fs from "node:fs/promises";
import path from "node:path";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>; type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
@@ -128,27 +130,48 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: st
} }
const buffer = Buffer.concat(chunks); const buffer = Buffer.concat(chunks);
const metadata = await sharp(buffer).metadata();
const width = metadata.width ?? 400;
const height = metadata.height ?? 300;
const svgText = ` // Skaliere das Bild auf 480px Breite (wie vom User gewünscht)
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg"> const targetWidth = 480;
<text x="50%" y="50%" font-family="Arial, sans-serif" font-size="${Math.max(24, width / 8)}" font-weight="bold" fill="white" opacity="0.5" text-anchor="middle" alignment-baseline="middle" transform="rotate(-30 ${width/2} ${height/2})"> const resizedBuffer = await sharp(buffer)
PREVIEW .resize({ width: targetWidth, withoutEnlargement: true })
</text> .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 = `
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
<image href="data:image/png;base64,${logoBase64}" x="${(width - logoWidth) / 2}" y="${(height - logoHeight) / 2}" width="${logoWidth}" height="${logoHeight}" opacity="0.6"/>
</svg> </svg>
`; `;
const watermarked = await sharp(buffer) watermarked = await sharp(resizedBuffer)
.composite([ .composite([{ input: Buffer.from(svgOverlay), gravity: "center" }])
{
input: Buffer.from(svgText),
gravity: "center",
},
])
.webp({ quality: 80 }) .webp({ quality: 80 })
.toBuffer(); .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({ const responseHeaders = new Headers({
"cache-control": "private, max-age=86400, stale-while-revalidate=604800", "cache-control": "private, max-age=86400, stale-while-revalidate=604800",
+25 -4
View File
@@ -31,7 +31,28 @@ export async function POST(request: NextRequest) {
const trimmedPurpose = purpose.trim(); const trimmedPurpose = purpose.trim();
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId); 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<string, string>();
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" }[] = []; 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; if (!asset) continue;
// Find the first album the editorial has access to // Find the first album the editorial has access to
const validAlbum = asset.albums.find((a: any) => grantedSet.has(a.id)); const validAlbumId = assetToGrantedAlbum.get(assetId);
if (!validAlbum) continue; // Editorial does not have access if (!validAlbumId) continue; // Editorial does not have access
// Check for prior usages to avoid double charging // Check for prior usages to avoid double charging
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId); const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
@@ -70,7 +91,7 @@ export async function POST(request: NextRequest) {
const newUsage = await usageService.createNewUsage({ const newUsage = await usageService.createNewUsage({
editorialId: principal.editorialId, editorialId: principal.editorialId,
assetId, assetId,
albumId: validAlbum.id, albumId: validAlbumId,
purpose: trimmedPurpose, purpose: trimmedPurpose,
reference: undefined, reference: undefined,
idempotencyKey, idempotencyKey,
-4
View File
@@ -6,16 +6,12 @@ export function BrandLogo() {
<img <img
alt="Leon Tonhäuser Sportfotografie" alt="Leon Tonhäuser Sportfotografie"
className="brand-logo brand-logo-light" className="brand-logo brand-logo-light"
height={1000}
src="/brand/logo-black.png" src="/brand/logo-black.png"
width={1000}
/> />
<img <img
alt="Leon Tonhäuser Sportfotografie" alt="Leon Tonhäuser Sportfotografie"
className="brand-logo brand-logo-dark" className="brand-logo brand-logo-dark"
height={1000}
src="/brand/logo-white.png" src="/brand/logo-white.png"
width={1000}
/> />
</> </>
); );
+24 -3
View File
@@ -2,7 +2,7 @@
import { useState, useTransition } from "react"; 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 { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -15,6 +15,7 @@ type DangerZoneProps = {
export function DangerZone({ editorialId, editorialName }: DangerZoneProps) { export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
const [confirmText, setConfirmText] = useState(""); const [confirmText, setConfirmText] = useState("");
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
const [isDeleting, setIsDeleting] = useState(false);
const isConfirmed = confirmText === editorialName; const isConfirmed = confirmText === editorialName;
function handleArchive() { 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 ( return (
<Card className="border-destructive/50 bg-destructive/5 dark:bg-destructive/10"> <Card className="border-destructive/50 bg-destructive/5 dark:bg-destructive/10">
<CardHeader> <CardHeader>
<CardTitle className="text-destructive">Gefahrenzone</CardTitle> <CardTitle className="text-destructive">Gefahrenzone</CardTitle>
<CardDescription> <CardDescription>
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!
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
@@ -46,14 +56,25 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
className="border-destructive/30 focus-visible:ring-destructive" className="border-destructive/30 focus-visible:ring-destructive"
/> />
</div> </div>
<div className="flex gap-4">
<Button <Button
type="button" type="button"
variant="destructive" variant="destructive"
disabled={!isConfirmed || isPending} disabled={!isConfirmed || isPending}
onClick={handleArchive} onClick={handleArchive}
> >
{isPending ? "Wird archiviert…" : "Redaktion archivieren"} {isPending && !isDeleting ? "Wird archiviert…" : "Redaktion archivieren"}
</Button> </Button>
<Button
type="button"
variant="outline"
className="border-destructive text-destructive hover:bg-destructive hover:text-white"
disabled={!isConfirmed || isPending}
onClick={handleDelete}
>
{isDeleting ? "Wird gelöscht…" : "Endgültig löschen"}
</Button>
</div>
</CardContent> </CardContent>
</Card> </Card>
); );
+1
View File
@@ -27,6 +27,7 @@ function createRepository(): EditorialServiceRepository & {
transitionStatus: vi.fn().mockResolvedValue(undefined), transitionStatus: vi.fn().mockResolvedValue(undefined),
claimApprovalNotice: vi.fn().mockResolvedValue(true), claimApprovalNotice: vi.fn().mockResolvedValue(true),
archiveEditorial: vi.fn().mockResolvedValue(undefined), archiveEditorial: vi.fn().mockResolvedValue(undefined),
hardDeleteEditorial: vi.fn().mockResolvedValue(undefined),
}; };
} }
+42
View File
@@ -9,6 +9,11 @@ import {
auditEvents, auditEvents,
billingAddressVersions, billingAddressVersions,
editorialAccounts, editorialAccounts,
downloadEvents,
usages,
lightboxItems,
billingReports,
albumAutoRules,
} from "@/db/schema"; } from "@/db/schema";
import type * as schema from "@/db/schema"; import type * as schema from "@/db/schema";
import type { AccountStatus } from "@/modules/auth/principal"; import type { AccountStatus } from "@/modules/auth/principal";
@@ -51,6 +56,7 @@ export type EditorialServiceRepository = {
adminUserId: string; adminUserId: string;
}): Promise<void>; }): Promise<void>;
archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void>; archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void>;
hardDeleteEditorial(editorialId: string): Promise<void>;
}; };
/** /**
@@ -156,6 +162,10 @@ export function createEditorialService({
async archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void> { async archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void> {
await repository.archiveEditorial(input); await repository.archiveEditorial(input);
}, },
async hardDeleteEditorial(editorialId: string): Promise<void> {
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));
}
});
},
}; };
} }
+41
View File
@@ -12,6 +12,45 @@ const transporter = nodemailer.createTransport({
}, },
}); });
function buildHtml(title: string, content: string, button?: { text: string, url: string }) {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f4f4f5; color: #18181b; line-height: 1.6; padding: 20px; }
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
.header { padding: 32px 32px 0 32px; text-align: center; }
.header img { max-height: 64px; }
.content { padding: 32px; font-size: 16px; }
.title { font-size: 24px; font-weight: 700; margin-bottom: 24px; text-align: center; }
.button { display: inline-block; background-color: #18181b; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 32px; }
.footer { padding: 32px; text-align: center; font-size: 14px; color: #71717a; border-top: 1px solid #e4e4e7; background: #fafafa; }
.footer a { color: #71717a; text-decoration: underline; margin: 0 8px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<img src="${env.BETTER_AUTH_URL}/brand/logo-black.png" alt="Logo" />
</div>
<div class="content">
<div class="title">${title}</div>
<p style="white-space: pre-line; color: #3f3f46; text-align: center;">${content}</p>
${button ? `<div style="text-align: center;"><a href="${button.url}" class="button">${button.text}</a></div>` : ''}
</div>
<div class="footer">
<p>
<a href="${env.LEGAL_IMPRINT_URL}">Impressum</a> |
<a href="${env.LEGAL_PRIVACY_URL}">Datenschutz</a> |
<a href="${env.LEGAL_TERMS_URL}">AGB</a>
</p>
</div>
</div>
</body>
</html>`;
}
export const emailService = { export const emailService = {
async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) { async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) {
const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf"; const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
@@ -21,6 +60,7 @@ export const emailService = {
to: toEmail, to: toEmail,
subject: `Ihre Abrechnung für ${reportMonth}`, 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`, 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: [ attachments: [
{ {
filename, filename,
@@ -37,6 +77,7 @@ export const emailService = {
to: toEmail, to: toEmail,
subject: `Neues Fotoalbum verfügbar: ${albumName}`, 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`, 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` }),
}); });
}, },
}; };
+2 -1
View File
@@ -381,7 +381,8 @@ export function createImmichClient({
); );
}, },
getThumbnail(assetId, signal) { 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) { getOriginal(assetId, signal) {
return requestBinary(`/assets/${encodeURIComponent(assetId)}/original`, signal); return requestBinary(`/assets/${encodeURIComponent(assetId)}/original`, signal);
+56 -6
View File
@@ -9,6 +9,7 @@ export type MailMessage = {
to: string; to: string;
subject: string; subject: string;
text: string; text: string;
html?: string;
}; };
export type MailTransport = { export type MailTransport = {
@@ -30,26 +31,75 @@ export function createMailer({ from, transport }: { from: string; transport: Mai
await transport.sendMail({ from, ...message }); await transport.sendMail({ from, ...message });
} }
function buildHtml(title: string, content: string, button?: { text: string, url: string }) {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f4f4f5; color: #18181b; line-height: 1.6; padding: 20px; }
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
.header { padding: 32px 32px 0 32px; text-align: center; }
.header img { max-height: 64px; }
.content { padding: 32px; font-size: 16px; }
.title { font-size: 24px; font-weight: 700; margin-bottom: 24px; text-align: center; }
.button { display: inline-block; background-color: #18181b; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 32px; }
.footer { padding: 32px; text-align: center; font-size: 14px; color: #71717a; border-top: 1px solid #e4e4e7; background: #fafafa; }
.footer a { color: #71717a; text-decoration: underline; margin: 0 8px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<img src="${env.BETTER_AUTH_URL}/brand/logo-black.png" alt="Logo" />
</div>
<div class="content">
<div class="title">${title}</div>
<p style="white-space: pre-line; color: #3f3f46; text-align: center;">${content}</p>
${button ? `<div style="text-align: center;"><a href="${button.url}" class="button">${button.text}</a></div>` : ''}
</div>
<div class="footer">
<p>
<a href="${env.LEGAL_IMPRINT_URL}">Impressum</a> |
<a href="${env.LEGAL_PRIVACY_URL}">Datenschutz</a> |
<a href="${env.LEGAL_TERMS_URL}">AGB</a>
</p>
</div>
</div>
</body>
</html>`;
}
return { return {
async sendVerification({ to, verificationUrl }) { 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({ await send({
to, to,
subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse", subject,
text: `Bitte bestätigen Sie Ihre E-Mail-Adresse für das Redaktionsportal:\n\n${verificationUrl}`, 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 }) { 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({ await send({
to, to,
subject: "Passwort für das Redaktionsportal zurücksetzen", subject,
text: `Setzen Sie Ihr Passwort für das Redaktionsportal zurück:\n\n${resetUrl}`, 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 }) { 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({ await send({
to, to,
subject: "Ihr Zugang zum Redaktionsportal ist freigegeben", subject,
text: `Der Zugang für ${editorialName} wurde freigegeben. Sie können sich jetzt im Redaktionsportal anmelden.`, 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 }),
}); });
}, },
}; };
+12 -9
View File
@@ -57,7 +57,7 @@ export type UsageRepository = {
}; };
type UsageImmich = { 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<{ getAsset(assetId: string): Promise<{
id: string; id: string;
originalFileName: string; originalFileName: string;
@@ -90,7 +90,7 @@ export function createUsageService({
if (existing) return resolveIntent(existing, fingerprint, "new_usage"); if (existing) return resolveIntent(existing, fingerprint, "new_usage");
const asset = await getValidatedAsset(immich, input.assetId); 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({ const persisted = await repository.createBillableIntent({
...input, ...input,
albumName: normalizeUpstreamSnapshot(album.albumName), albumName: normalizeUpstreamSnapshot(album.albumName),
@@ -98,7 +98,7 @@ export function createUsageService({
requestFingerprint: fingerprint, requestFingerprint: fingerprint,
}, async () => { }, async () => {
const currentAsset = await getValidatedAsset(immich, input.assetId); 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 { return {
albumName: normalizeUpstreamSnapshot(currentAlbum.albumName), albumName: normalizeUpstreamSnapshot(currentAlbum.albumName),
filename: normalizeUpstreamSnapshot(currentAsset.originalFileName), filename: normalizeUpstreamSnapshot(currentAsset.originalFileName),
@@ -330,18 +330,21 @@ function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput
async function loadRequestedAlbum( async function loadRequestedAlbum(
immich: UsageImmich, immich: UsageImmich,
asset: { albums: Array<{ id: string }> }, assetId: string,
albumId: string, albumId: string,
): Promise<{ id: string; albumName: string }> { ): Promise<{ id: string; albumName: string }> {
if (!asset.albums.some((a) => a.id === albumId)) { let album;
throw new UsageAccountingError("ASSET_NOT_IN_ALBUM");
}
try { try {
return await immich.getAlbum(albumId); album = await immich.getAlbum(albumId);
} catch { } catch {
throw new UsageAccountingError("IMMICH_UNAVAILABLE"); 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) { async function getValidatedAsset(immich: UsageImmich, assetId: string) {