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

@@ -4,6 +4,7 @@ import { requireActiveEditorial, requireAdmin, PrincipalAuthorizationError } fro
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types";
import sharp from "sharp";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
@@ -45,8 +46,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
}
const thumbnail = await dependencies.immich.getThumbnail(assetId);
if (access.kind === "editorial") {
return watermarkedThumbnailResponse(thumbnail);
}
return thumbnailResponse(thumbnail);
} catch {
} catch (err) {
return genericNotFound();
}
};
@@ -112,6 +116,48 @@ function genericNotFound(): Response {
return new Response(null, { status: 404 });
}
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Response> {
const reader = thumbnail.body.getReader();
const chunks: Uint8Array[] = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) chunks.push(value);
}
const buffer = Buffer.concat(chunks);
const metadata = await sharp(buffer).metadata();
const width = metadata.width ?? 400;
const height = metadata.height ?? 300;
const svgText = `
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
<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})">
PREVIEW
</text>
</svg>
`;
const watermarked = await sharp(buffer)
.composite([
{
input: Buffer.from(svgText),
gravity: "center",
},
])
.webp({ quality: 80 })
.toBuffer();
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"content-type": "image/webp",
"content-length": String(watermarked.length),
"x-content-type-options": "nosniff",
});
return new Response(watermarked, { headers: responseHeaders });
}
function isSafeAssetId(assetId: string): boolean {
return /^[A-Za-z0-9_-]{1,200}$/.test(assetId);
}
@@ -8,6 +8,11 @@ import {
} from "@/modules/billing/reports";
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { emailService } from "@/modules/email/service";
import { getReportPdf } from "@/modules/billing/reports";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { eq } from "drizzle-orm";
const finalizePayload = z
.object({
@@ -45,6 +50,35 @@ export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies)
adminUserId: principal.userId,
});
// Email dispatch
try {
const [editorial] = await db
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
if (editorial?.email) {
const reportPdf = await getReportPdf(result.reportId);
if (reportPdf) {
const periodString = month
? `${month.toString().padStart(2, "0")}/${year}`
: `Q${quarter}/${year}`;
// Fire and forget (don't await or catch if we want to not block, but awaiting is safer for serverless if not in background)
await emailService.sendBillingReport(
editorial.email,
periodString,
reportPdf.bytes,
result.reportNumber
);
}
}
} catch (emailError) {
console.error("Failed to send billing email:", emailError);
// Do not fail the request if email fails
}
return Response.json(
{
reportId: result.reportId,
@@ -0,0 +1,63 @@
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { getReportPdf, reportService } from "@/modules/billing/reports";
import { db } from "@/db/client";
import { billingReports } from "@/db/schema";
import { eq } from "drizzle-orm";
export async function GET(
request: Request,
{ params }: { params: Promise<{ reportId: string }> }
): Promise<Response> {
try {
const principal = await requireActiveEditorial(request.headers);
const { reportId } = await params;
// Verify ownership
const [report] = await db
.select({ editorialAccountId: billingReports.editorialAccountId })
.from(billingReports)
.where(eq(billingReports.id, reportId))
.limit(1);
if (!report || report.editorialAccountId !== principal.editorialId) {
return notFound();
}
const reportPdf = await getReportPdf(reportId);
if (!reportPdf) return notFound();
const filename = buildFilename(reportPdf.invoiceNumber);
return new Response(new Uint8Array(reportPdf.bytes), {
status: 200,
headers: {
"content-type": "application/pdf",
"cache-control": "private, no-store",
"content-disposition": `attachment; filename="${filename}"`,
},
});
} catch (error) {
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
return jsonError(500, "REQUEST_FAILED");
}
}
function buildFilename(invoiceNumber: string): string {
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
return `${safe || "nutzungsnachweis"}.pdf`;
}
function notFound(): Response {
return new Response(null, {
status: 404,
headers: { "cache-control": "private, no-store" },
});
}
function jsonError(status: number, code: string): Response {
return Response.json(
{ code },
{ status, headers: { "cache-control": "private, no-store" } },
);
}