Files
myeasycms-v2/apps/web/app/[locale]/home/[account]/finance/page.tsx
T. Zehetbauer 7b078f298b
Some checks failed
Workflow / ʦ TypeScript (push) Failing after 4m50s
Workflow / ⚫️ Test (push) Has been skipped
feat: enhance API response handling and add new components for module management
2026-04-01 15:18:24 +02:00

352 lines
12 KiB
TypeScript

import Link from 'next/link';
import {
Landmark,
FileText,
Euro,
ArrowRight,
Plus,
ChevronLeft,
ChevronRight,
} from 'lucide-react';
import { createFinanceApi } from '@kit/finance/api';
import { formatDate } from '@kit/shared/dates';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Button } from '@kit/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
import { ListToolbar } from '@kit/ui/list-toolbar';
import { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';
import { EmptyState } from '~/components/empty-state';
import { StatsCard } from '~/components/stats-card';
import {
BATCH_STATUS_VARIANT,
BATCH_STATUS_LABEL,
INVOICE_STATUS_VARIANT,
INVOICE_STATUS_LABEL,
} from '~/lib/status-badges';
const PAGE_SIZE = 25;
interface PageProps {
params: Promise<{ account: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}
function buildQuery(
base: Record<string, string | undefined>,
overrides: Record<string, string | number | undefined>,
): string {
const params = new URLSearchParams();
for (const [key, value] of Object.entries({ ...base, ...overrides })) {
if (value !== undefined && value !== '') {
params.set(key, String(value));
}
}
const qs = params.toString();
return qs ? `?${qs}` : '';
}
export default async function FinancePage({ params, searchParams }: PageProps) {
const { account } = await params;
const search = await searchParams;
const client = getSupabaseServerClient();
const { data: acct } = await client
.from('accounts')
.select('id')
.eq('slug', account)
.single();
if (!acct) return <AccountNotFound />;
const q = typeof search.q === 'string' ? search.q : undefined;
const status = typeof search.status === 'string' ? search.status : undefined;
const page = Math.max(1, Number(search.page) || 1);
const api = createFinanceApi(client);
const [batchesResult, invoicesResult] = await Promise.all([
api.listBatches(acct.id, { search: q, status, page, pageSize: PAGE_SIZE }),
api.listInvoices(acct.id, { search: q, status, page, pageSize: PAGE_SIZE }),
]);
const batches = batchesResult.data;
const invoices = invoicesResult.data;
const openAmount = invoices
.filter(
(inv: Record<string, unknown>) =>
inv.status === 'sent' || inv.status === 'overdue',
)
.reduce(
(sum: number, inv: Record<string, unknown>) =>
sum + (Number(inv.total_amount) || 0),
0,
);
// Use the larger of the two totals for pagination
const totalPages = Math.max(
batchesResult.totalPages,
invoicesResult.totalPages,
);
const safePage = page;
const queryBase = { q, status };
return (
<CmsPageShell account={account} title="Finanzen">
<div className="flex w-full flex-col gap-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Finanzen</h1>
<p className="text-muted-foreground">SEPA-Einzüge und Rechnungen</p>
</div>
<div className="flex gap-2">
<Link href={`/home/${account}/finance/invoices/new`}>
<Button variant="outline">
<Plus className="mr-2 h-4 w-4" />
Neue Rechnung
</Button>
</Link>
<Link href={`/home/${account}/finance/sepa/new`}>
<Button>
<Plus className="mr-2 h-4 w-4" />
Neuer SEPA-Einzug
</Button>
</Link>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<StatsCard
title="SEPA-Einzüge"
value={batchesResult.total}
icon={<Landmark className="h-5 w-5" />}
/>
<StatsCard
title="Rechnungen"
value={invoicesResult.total}
icon={<FileText className="h-5 w-5" />}
/>
<StatsCard
title="Offener Betrag"
value={`${openAmount.toFixed(2)}`}
icon={<Euro className="h-5 w-5" />}
/>
</div>
{/* Toolbar */}
<ListToolbar
searchPlaceholder="Finanzen durchsuchen..."
filters={[
{
param: 'status',
label: 'Status',
options: [
{ value: '', label: 'Alle' },
{ value: 'draft', label: 'Entwurf' },
{ value: 'ready', label: 'Bereit' },
{ value: 'sent', label: 'Gesendet' },
{ value: 'paid', label: 'Bezahlt' },
{ value: 'overdue', label: 'Überfällig' },
{ value: 'cancelled', label: 'Storniert' },
],
},
]}
/>
{/* SEPA Batches */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Letzte SEPA-Einzüge ({batchesResult.total})</CardTitle>
<Link href={`/home/${account}/finance/sepa`}>
<Button variant="ghost" size="sm">
Alle anzeigen
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
</Link>
</CardHeader>
<CardContent>
{batches.length === 0 ? (
<EmptyState
icon={<Landmark className="h-8 w-8" />}
title="Keine SEPA-Einzüge"
description="Erstellen Sie Ihren ersten SEPA-Einzug."
actionLabel="Neuer SEPA-Einzug"
actionHref={`/home/${account}/finance/sepa/new`}
/>
) : (
<div className="rounded-md border">
<table className="w-full text-sm">
<thead>
<tr className="bg-muted/50 border-b">
<th className="p-3 text-left font-medium">Status</th>
<th className="p-3 text-left font-medium">Typ</th>
<th className="p-3 text-right font-medium">Betrag</th>
<th className="p-3 text-left font-medium">Datum</th>
</tr>
</thead>
<tbody>
{batches.map((batch: Record<string, unknown>) => (
<tr
key={String(batch.id)}
className="hover:bg-muted/30 border-b"
>
<td className="p-3">
<Badge
variant={
BATCH_STATUS_VARIANT[String(batch.status)] ??
'secondary'
}
>
{BATCH_STATUS_LABEL[String(batch.status)] ??
String(batch.status)}
</Badge>
</td>
<td className="p-3">
{batch.batch_type === 'direct_debit'
? 'Lastschrift'
: 'Überweisung'}
</td>
<td className="p-3 text-right">
{batch.total_amount != null
? `${Number(batch.total_amount).toFixed(2)}`
: '—'}
</td>
<td className="p-3">
{formatDate(batch.execution_date ?? batch.created_at)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
{/* Invoices */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Letzte Rechnungen ({invoicesResult.total})</CardTitle>
<Link href={`/home/${account}/finance/invoices`}>
<Button variant="ghost" size="sm">
Alle anzeigen
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
</Link>
</CardHeader>
<CardContent>
{invoices.length === 0 ? (
<EmptyState
icon={<FileText className="h-8 w-8" />}
title="Keine Rechnungen"
description="Erstellen Sie Ihre erste Rechnung."
actionLabel="Neue Rechnung"
actionHref={`/home/${account}/finance/invoices/new`}
/>
) : (
<div className="rounded-md border">
<table className="w-full text-sm">
<thead>
<tr className="bg-muted/50 border-b">
<th className="p-3 text-left font-medium">Nr.</th>
<th className="p-3 text-left font-medium">Empfänger</th>
<th className="p-3 text-right font-medium">Betrag</th>
<th className="p-3 text-left font-medium">Status</th>
</tr>
</thead>
<tbody>
{invoices.map((invoice: Record<string, unknown>) => (
<tr
key={String(invoice.id)}
className="hover:bg-muted/30 border-b"
>
<td className="p-3 font-mono text-xs">
<Link
href={`/home/${account}/finance/invoices/${String(invoice.id)}`}
className="hover:underline"
>
{String(invoice.invoice_number ?? '—')}
</Link>
</td>
<td className="p-3">
{String(invoice.recipient_name ?? '—')}
</td>
<td className="p-3 text-right">
{invoice.total_amount != null
? `${Number(invoice.total_amount).toFixed(2)}`
: '—'}
</td>
<td className="p-3">
<Badge
variant={
INVOICE_STATUS_VARIANT[String(invoice.status)] ??
'secondary'
}
>
{INVOICE_STATUS_LABEL[String(invoice.status)] ??
String(invoice.status)}
</Badge>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between">
<p className="text-muted-foreground text-sm">
Seite {safePage} von {totalPages}
</p>
<div className="flex items-center gap-1">
{safePage > 1 ? (
<Link
href={`/home/${account}/finance${buildQuery(queryBase, { page: safePage - 1 })}`}
>
<Button variant="outline" size="sm">
<ChevronLeft className="h-4 w-4" />
</Button>
</Link>
) : (
<Button variant="outline" size="sm" disabled>
<ChevronLeft className="h-4 w-4" />
</Button>
)}
<span className="px-3 text-sm font-medium">
{safePage} / {totalPages}
</span>
{safePage < totalPages ? (
<Link
href={`/home/${account}/finance${buildQuery(queryBase, { page: safePage + 1 })}`}
>
<Button variant="outline" size="sm">
<ChevronRight className="h-4 w-4" />
</Button>
</Link>
) : (
<Button variant="outline" size="sm" disabled>
<ChevronRight className="h-4 w-4" />
</Button>
)}
</div>
</div>
)}
</div>
</CmsPageShell>
);
}