feat: Add flatrate billing model for editorial accounts

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 03:27:10 +02:00
1 parent 699580a6a0
commit 0b1ffdfdfc
39 files changed
+4900 -57

No files matched your search

+18 -1
View File
@@ -4,11 +4,12 @@ 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 { albumAutoRules, editorialAccounts } 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";
import { emailService } from "@/modules/email/service";
export type AutoRule = {
id: string;
@@ -62,6 +63,18 @@ export function createAutoRuleService({
const grantedAlbumIds = new Set(await grantService.getGrantedAlbumIds(editorialId));
let newlyGranted = 0;
let editorialEmail: string | undefined;
try {
const [editorial] = await db
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
editorialEmail = editorial?.email;
} catch (e) {
// Ignore DB error
}
for (const album of albums) {
if (grantedAlbumIds.has(album.id)) {
continue;
@@ -75,6 +88,10 @@ export function createAutoRuleService({
await grantService.grantAlbum({ editorialId, immichAlbumId: album.id, adminUserId });
newlyGranted++;
grantedAlbumIds.add(album.id);
if (editorialEmail) {
await emailService.sendNewAlbumNotification(editorialEmail, album.albumName).catch(() => {});
}
} catch (error) {
// Ignore individual album grant failures
}
+8 -1
View File
@@ -3,6 +3,7 @@
import Link from "next/link";
import { UsageDialog } from "@/components/download/usage-dialog";
import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton";
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
import type { ImmichSearchPage } from "@/modules/immich/types";
@@ -56,6 +57,7 @@ export function PhotoContactSheet({
page: ImmichSearchPage;
query: string;
showAlbumName?: boolean;
lightboxAssetIds?: Set<string>;
}>) {
return (
<>
@@ -77,7 +79,7 @@ export function PhotoContactSheet({
<ul className="photo-contact-sheet" aria-label={`Fotos aus ${albumName}`}>
{page.items.map((asset) => (
<li key={asset.id}>
<figure className="photo-contact-frame">
<figure className="photo-contact-frame relative group">
<img
alt={asset.originalFileName}
className="contact-sheet-image"
@@ -85,6 +87,11 @@ export function PhotoContactSheet({
src={thumbnailUrl(asset.id)}
width="900"
/>
{lightboxAssetIds && (
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<LightboxToggleButton assetId={asset.id} initialInLightbox={lightboxAssetIds.has(asset.id)} />
</div>
)}
<figcaption className="contact-strip">
<span className="contact-strip-name">{asset.originalFileName}</span>
{showAlbumName && (asset as any).albums && (asset as any).albums.length > 0 && (
+31 -2
View File
@@ -155,6 +155,7 @@ export type FinalizeTransactionInput = {
address: BillingReportAddress;
repeatDownloads: BillingReportRepeatDownload[];
netTotalCents: number;
flatrateCentsSnapshot: number | null;
pdfBytes: Buffer;
pdfSha256: string;
documentId: string;
@@ -171,6 +172,7 @@ export type FinalizeTransactionResult = {
export type ReportRepository = {
// Snapshot building (pre-transaction)
getCurrentAddress(editorialId: string): Promise<BillingReportAddress | null>;
getEditorialFlatrate(editorialId: string): Promise<{ flatrateActive: boolean; flatratePriceCents: number | null; flatrateAssetLimit: number | null; } | null>;
getSelectedUsages(editorialId: string, usageIds: string[]): Promise<SelectedUsage[]>;
getRepeatDownloads(editorialId: string, period: BillingPeriod): Promise<BillingReportRepeatDownload[]>;
allocateReportNumber(): Promise<number>;
@@ -235,6 +237,7 @@ export function createReportService({
selectedPositions: selectedUsages.map(toReportPosition),
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
reportNumber: 0,
invoiceNumber: "VORSCHAU",
period: input.period,
@@ -273,6 +276,7 @@ export function createReportService({
selectedPositions: selectedUsages.map(toReportPosition),
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
reportNumber,
invoiceNumber,
period: input.period,
@@ -298,6 +302,7 @@ export function createReportService({
address,
repeatDownloads,
netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
pdfBytes: rendered.bytes,
pdfSha256: rendered.sha256,
documentId,
@@ -394,6 +399,7 @@ async function buildSnapshot(
address: BillingReportAddress;
repeatDownloads: BillingReportRepeatDownload[];
netTotalCents: number;
flatrateCentsSnapshot: number | null;
}> {
if (input.usageIds.length === 0) {
throw new ReportValidationError("NO_USAGES_SELECTED");
@@ -426,11 +432,20 @@ async function buildSnapshot(
throw new ReportValidationError("ADDRESS_NOT_FOUND");
}
const editorialFlatrate = await repo.getEditorialFlatrate(input.editorialId);
let flatrateCentsSnapshot: number | null = null;
if (editorialFlatrate && editorialFlatrate.flatrateActive && editorialFlatrate.flatratePriceCents !== null) {
flatrateCentsSnapshot = editorialFlatrate.flatratePriceCents;
}
const repeatDownloads = await repo.getRepeatDownloads(input.editorialId, input.period);
const netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0);
let netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0);
if (flatrateCentsSnapshot !== null) {
netTotalCents += flatrateCentsSnapshot;
}
return { usages: selectedUsages, address, repeatDownloads, netTotalCents };
return { usages: selectedUsages, address, repeatDownloads, netTotalCents, flatrateCentsSnapshot };
}
function toReportPosition(usage: SelectedUsage): BillingReportPosition {
@@ -484,6 +499,19 @@ export function createReportRepository(
return version;
},
async getEditorialFlatrate(editorialId) {
const [editorial] = await database
.select({
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
return editorial || null;
},
async getSelectedUsages(editorialId, usageIds) {
const rows = await database
.select({
@@ -581,6 +609,7 @@ export function createReportRepository(
billingAddressSnapshot: input.address,
invoiceNumber: input.invoiceNumber,
netTotalCents: input.netTotalCents,
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
status: "final",
pdf: input.pdfBytes,
pdfSha256: input.pdfSha256,
+2
View File
@@ -72,4 +72,6 @@ export type BillingReportSnapshot = {
createdAt: Date;
/** Legal notice clarifying that the report is not a VAT invoice. */
legalSeparationNotice: string;
/** Flatrate amount snapshot, if applicable. */
flatrateCentsSnapshot?: number | null;
};
+52 -1
View File
@@ -1,5 +1,5 @@
import Link from "next/link";
import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction } from "@/app/admin/redaktionen/[id]/actions";
import { DangerZone } from "./DangerZone";
export type EditorialDetail = {
@@ -10,6 +10,9 @@ export type EditorialDetail = {
status: string;
emailVerifiedAt: Date | null;
currentPriceCents: number | null;
flatrateActive: boolean;
flatratePriceCents: number | null;
flatrateAssetLimit: number | null;
archivedAt: Date | null;
};
@@ -59,6 +62,54 @@ export function EditorialDetailContent({
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln</Link>
</section>
{/* Flatrate Settings */}
{!editorial.archivedAt && (
<section aria-labelledby="flatrate-title" className="mt-8">
<h2 id="flatrate-title">Flatrate-Einstellungen</h2>
<form action={updateFlatrateAction.bind(null, editorial.id)} className="space-y-4 max-w-lg mt-4">
<div>
<label className="flex items-center gap-2 font-semibold">
<input type="checkbox" name="flatrateActive" defaultChecked={editorial.flatrateActive} />
Flatrate aktivieren
</label>
<p className="text-sm text-gray-500 mt-1">Wenn aktiviert, werden Downloads nach einem Pauschalpreis abgerechnet.</p>
</div>
<div className="flex gap-4">
<div className="flex-1">
<label className="block font-semibold mb-1" htmlFor="flatratePriceEuros">Flatrate-Preis (Netto €)</label>
<input
type="number"
id="flatratePriceEuros"
name="flatratePriceEuros"
step="0.01"
min="0"
className="border p-2 rounded w-full"
defaultValue={editorial.flatratePriceCents ? (editorial.flatratePriceCents / 100).toFixed(2) : ""}
/>
</div>
<div className="flex-1">
<label className="block font-semibold mb-1" htmlFor="flatrateAssetLimit">Bild-Limit (pro Monat)</label>
<input
type="number"
id="flatrateAssetLimit"
name="flatrateAssetLimit"
min="1"
placeholder="Unbegrenzt"
className="border p-2 rounded w-full"
defaultValue={editorial.flatrateAssetLimit ?? ""}
/>
<p className="text-xs text-gray-500 mt-1">Leer lassen für unbegrenzte Flatrate.</p>
</div>
</div>
<button type="submit" className="px-4 py-2 bg-black text-white font-semibold rounded hover:bg-gray-800 transition">
Speichern
</button>
</form>
</section>
)}
{/* Status Actions */}
{!editorial.archivedAt && (
<section aria-labelledby="status-actions-title">
+42
View File
@@ -0,0 +1,42 @@
import "server-only";
import nodemailer from "nodemailer";
import { env } from "@/config/env";
const transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
port: env.SMTP_PORT,
secure: env.SMTP_PORT === 465,
auth: {
user: env.SMTP_USER,
pass: env.SMTP_PASSWORD,
},
});
export const emailService = {
async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) {
const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
await transporter.sendMail({
from: env.SMTP_FROM,
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`,
attachments: [
{
filename,
content: pdfBytes,
contentType: "application/pdf",
},
],
});
},
async sendNewAlbumNotification(toEmail: string, albumName: string) {
await transporter.sendMail({
from: env.SMTP_FROM,
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`,
});
},
};
+4
View File
@@ -25,6 +25,10 @@ const assetSchema = z
localDateTime: nullableString,
fileCreatedAt: nullableString,
albums: z.array(z.object({ id: z.string() }).passthrough()).optional().default([]),
exifInfo: z.object({
exifImageWidth: z.number().optional().nullable(),
exifImageHeight: z.number().optional().nullable(),
}).passthrough().optional().nullable(),
})
.passthrough();
+62
View File
@@ -0,0 +1,62 @@
import { and, eq } from "drizzle-orm";
import { db } from "@/db/client";
import { lightboxItems } from "@/db/schema";
import { immichClient } from "@/modules/immich/client";
import type { PhotoAsset } from "@/modules/immich/types";
export type LightboxItem = {
assetId: string;
addedAt: Date;
asset?: PhotoAsset; // populated if joined
};
export const lightboxService = {
async getLightboxItems(editorialId: string): Promise<LightboxItem[]> {
const items = await db
.select({
assetId: lightboxItems.assetId,
addedAt: lightboxItems.addedAt,
})
.from(lightboxItems)
.where(eq(lightboxItems.editorialAccountId, editorialId))
.orderBy(lightboxItems.addedAt);
return items;
},
async addLightboxItem(editorialId: string, assetId: string): Promise<void> {
await db
.insert(lightboxItems)
.values({
editorialAccountId: editorialId,
assetId,
})
.onConflictDoNothing();
},
async removeLightboxItem(editorialId: string, assetId: string): Promise<void> {
await db
.delete(lightboxItems)
.where(
and(
eq(lightboxItems.editorialAccountId, editorialId),
eq(lightboxItems.assetId, assetId)
)
);
},
async isAssetInLightbox(editorialId: string, assetId: string): Promise<boolean> {
const result = await db
.select({ id: lightboxItems.id })
.from(lightboxItems)
.where(
and(
eq(lightboxItems.editorialAccountId, editorialId),
eq(lightboxItems.assetId, assetId)
)
)
.limit(1);
return result.length > 0;
}
};
+11
View File
@@ -65,6 +65,17 @@ function paidPositionsTable(snapshot: BillingReportSnapshot) {
const body = [headerRow];
if (snapshot.flatrateCentsSnapshot !== null && snapshot.flatrateCentsSnapshot !== undefined) {
body.push([
{ text: "Flatrate", style: "tableCell" },
{ text: "-", style: "tableCell" },
{ text: "Monatlicher Pauschalpreis", style: "tableCell" },
{ text: "-", style: "tableCell" },
{ text: "-", style: "tableCell", alignment: "right" as const },
{ text: formatCents(snapshot.flatrateCentsSnapshot), style: "tableCell", alignment: "right" as const },
]);
}
for (const pos of snapshot.selectedPositions) {
body.push([
{ text: pos.filename, style: "tableCell" },
+38 -3
View File
@@ -135,6 +135,8 @@ export function createUsageServiceRepository(
id: editorialAccounts.id,
status: editorialAccounts.status,
currentPriceCents: editorialAccounts.currentPriceCents,
flatrateActive: editorialAccounts.flatrateActive,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
@@ -164,6 +166,39 @@ export function createUsageServiceRepository(
.limit(1);
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
let priceCents = editorial.currentPriceCents!;
if (editorial.flatrateActive) {
if (editorial.flatrateAssetLimit === null) {
priceCents = 0; // Unlimited flatrate
} else {
// Limited flatrate - check how many usages this month
const now = new Date();
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999));
const [{ count }] = await transaction
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(usages)
.where(
and(
eq(usages.editorialAccountId, input.editorialId),
sql`${usages.createdAt} >= ${startOfMonth}`,
sql`${usages.createdAt} <= ${endOfMonth}`,
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
// For flatrate, we only count usages that were originally free via the flatrate
// so we compare against priceCents = 0. Wait, any usage counts towards the limit?
// Yes, any billable usage this month counts towards the limit.
eq(usages.priceCents, 0)
)
);
if (count < editorial.flatrateAssetLimit) {
priceCents = 0;
}
}
}
// This is the last cross-system authorization snapshot available to the
// portal. Immich may still change after it returns, but no portal work is
// allowed between this refresh and the accounting inserts.
@@ -180,7 +215,7 @@ export function createUsageServiceRepository(
albumNameSnapshot: currentAsset.albumName,
purpose: input.purpose,
internalReference: input.reference,
priceCents: editorial.currentPriceCents!,
priceCents: priceCents,
billingStatus: "open",
createdAt,
})
@@ -214,7 +249,7 @@ export function createUsageServiceRepository(
editorialId: input.editorialId,
assetId: input.assetId,
albumId: input.albumId,
priceCents: editorial.currentPriceCents,
priceCents: priceCents,
downloadId: event.id,
},
occurredAt: createdAt,
@@ -224,7 +259,7 @@ export function createUsageServiceRepository(
id: event.id,
usageId: usage.id,
assetId: input.assetId,
priceCents: editorial.currentPriceCents!,
priceCents: priceCents,
billable: true,
status: "authorized" as const,
authorizedAt: createdAt,