Files
immich-redaktions-plugin/src/app/redaktion/abrechnungen/page.tsx
T

188 lines
8.5 KiB
TypeScript

import { eq, desc, and, sql, inArray } from "drizzle-orm";
import { db } from "@/db/client";
import { billingReports, usages, editorialAccounts } from "@/db/schema";
import Link from "next/link";
import { formatBerlinDateTime } from "@/modules/downloads/format";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { FileText } from "lucide-react";
import { requireEditorial } from "../access";
export default async function AbrechnungenPage() {
const principal = await requireEditorial();
// 1. Hole alle PDF-Abrechnungen (abgeschlossene Reports)
const reports = await db
.select({
id: billingReports.id,
invoiceNumber: billingReports.invoiceNumber,
periodStartsAt: billingReports.periodStartsAt,
periodEndsAt: billingReports.periodEndsAt,
netTotalCents: billingReports.netTotalCents,
finalizedAt: billingReports.finalizedAt,
status: billingReports.status,
})
.from(billingReports)
.where(
and(
eq(billingReports.editorialAccountId, principal.editorialId),
eq(billingReports.status, "final")
)
)
.orderBy(desc(billingReports.finalizedAt));
// 2. Berechne den noch offenen Betrag des aktuellen Monats (oder insgesamt offen)
const [openUsages] = await db
.select({
totalCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
count: sql<number>`COUNT(${usages.id})::int`,
})
.from(usages)
.where(
and(
eq(usages.editorialAccountId, principal.editorialId),
eq(usages.billingStatus, "open")
)
);
const [editorial] = await db
.select({
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, principal.editorialId))
.limit(1);
// Zähle die bereits bezogenen Flatrate-Bilder (Preis = 0) im aktuellen Kalendermonat
let usedFlatrateImages = 0;
if (editorial?.flatrateActive && editorial.flatrateAssetLimit !== null) {
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 db
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(usages)
.where(
and(
eq(usages.editorialAccountId, principal.editorialId),
sql`${usages.createdAt} >= ${startOfMonth}`,
sql`${usages.createdAt} <= ${endOfMonth}`,
eq(usages.priceCents, 0),
inArray(usages.billingStatus, ["open", "billed", "reopened"])
)
);
usedFlatrateImages = count;
}
// Berechne gesamten offenen Betrag inkl. Flatrate (falls noch nicht abgerechnet)
// Normalerweise würde die Flatrate beim Report-Generieren hinzugefügt. Hier für die Vorschau:
// (Optional: Wenn man hier die Flatrate als "offen" anzeigen will)
const openTotalCents = (openUsages?.totalCents ?? 0);
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<div>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Finanzen</p>
<h1 className="text-4xl font-bold tracking-tight">Meine Abrechnungen</h1>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 my-8">
<Card className="bg-primary-50/50 dark:bg-primary-900/10 border-primary-100 dark:border-primary-900/30">
<CardHeader className="pb-2">
<CardTitle className="text-primary-900 dark:text-primary-100">Offener Betrag (Einzelabrufe)</CardTitle>
</CardHeader>
<CardContent>
<p className="text-4xl font-bold text-primary-700 dark:text-primary-400">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(openTotalCents / 100)}
</p>
<p className="text-sm text-primary-600/80 dark:text-primary-300/80 mt-2">
Für {openUsages?.count ?? 0} kostenpflichtige Bilder (noch nicht in Rechnung gestellt)
</p>
</CardContent>
</Card>
{editorial?.flatrateActive && editorial.flatratePriceCents !== null && (
<Card className="bg-emerald-50/50 dark:bg-emerald-900/10 border-emerald-100 dark:border-emerald-900/30">
<CardHeader className="pb-2">
<CardTitle className="text-emerald-900 dark:text-emerald-100">Aktiver Tarif: Flatrate</CardTitle>
</CardHeader>
<CardContent>
<p className="text-4xl font-bold text-emerald-700 dark:text-emerald-400 flex items-baseline gap-2">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(editorial.flatratePriceCents / 100)}
<span className="text-lg font-normal text-emerald-600/70 dark:text-emerald-400/70">/ Monat</span>
</p>
{editorial.flatrateAssetLimit === null ? (
<p className="text-sm text-emerald-700/80 dark:text-emerald-300/80 mt-2 font-medium">
Unbegrenzte Downloads inklusive
</p>
) : (
<div className="mt-4">
<div className="flex justify-between text-sm text-emerald-700 dark:text-emerald-300 font-medium mb-1.5">
<span>Inklusiv-Bilder diesen Monat</span>
<span>{usedFlatrateImages} / {editorial.flatrateAssetLimit}</span>
</div>
<div className="w-full bg-emerald-200/50 dark:bg-emerald-800/50 rounded-full h-2.5 overflow-hidden">
<div className="bg-emerald-500 dark:bg-emerald-400 h-full rounded-full transition-all duration-500" style={{ width: `${Math.min(100, (usedFlatrateImages / editorial.flatrateAssetLimit) * 100)}%` }} />
</div>
</div>
)}
</CardContent>
</Card>
)}
</div>
<div className="pt-4">
<h2 className="text-2xl font-bold mb-6">Bisherige Rechnungen</h2>
{reports.length === 0 ? (
<Card>
<CardContent className="pt-6">
<p className="text-muted-foreground text-center py-8">Es liegen noch keine abgerechneten Zeiträume vor.</p>
</CardContent>
</Card>
) : (
<Card>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Rechnungsnummer</th>
<th className="py-3 px-4 font-semibold">Zeitraum</th>
<th className="py-3 px-4 font-semibold text-right">Betrag (Netto)</th>
<th className="py-3 px-4 font-semibold text-center">Download</th>
</tr>
</thead>
<tbody>
{reports.map((report, i) => (
<tr key={report.id} className={i !== reports.length - 1 ? "border-b border-border hover:bg-muted/30 transition-colors" : "hover:bg-muted/30 transition-colors"}>
<td className="py-4 px-4 font-medium">{report.invoiceNumber}</td>
<td className="py-4 px-4 text-muted-foreground">
{new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" }).format(new Date(report.periodStartsAt))}
</td>
<td className="py-4 px-4 font-medium text-right tabular-nums">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(report.netTotalCents / 100)}
</td>
<td className="py-4 px-4 text-center">
<Link
href={`/api/editorials/reports/${report.id}/pdf`}
target="_blank"
className="inline-flex items-center gap-2 text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300 font-medium transition-colors"
>
<FileText className="w-4 h-4" />
<span>PDF</span>
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
)}
</div>
</div>
);
}