feat: enhance API response handling and add new components for module management
This commit is contained in:
@@ -16,6 +16,7 @@ import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -50,7 +51,12 @@ export default async function CoursesPage({ params, searchParams }: PageProps) {
|
|||||||
const page = Number(search.page) || 1;
|
const page = Number(search.page) || 1;
|
||||||
|
|
||||||
const [courses, stats] = await Promise.all([
|
const [courses, stats] = await Promise.all([
|
||||||
api.listCourses(acct.id, { page, pageSize: PAGE_SIZE }),
|
api.listCourses(acct.id, {
|
||||||
|
search: search.q as string,
|
||||||
|
status: search.status as string,
|
||||||
|
page,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
}),
|
||||||
api.getStatistics(acct.id),
|
api.getStatistics(acct.id),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -95,6 +101,25 @@ export default async function CoursesPage({ params, searchParams }: PageProps) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Search & Filters */}
|
||||||
|
<ListToolbar
|
||||||
|
searchPlaceholder="Kurs suchen..."
|
||||||
|
filters={[
|
||||||
|
{
|
||||||
|
param: 'status',
|
||||||
|
label: 'Status',
|
||||||
|
options: [
|
||||||
|
{ value: '', label: 'Alle' },
|
||||||
|
{ value: 'planned', label: 'Geplant' },
|
||||||
|
{ value: 'open', label: 'Offen' },
|
||||||
|
{ value: 'running', label: 'Laufend' },
|
||||||
|
{ value: 'completed', label: 'Abgeschlossen' },
|
||||||
|
{ value: 'cancelled', label: 'Abgesagt' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Table or Empty State */}
|
{/* Table or Empty State */}
|
||||||
{courses.data.length === 0 ? (
|
{courses.data.length === 0 ? (
|
||||||
<EmptyState
|
<EmptyState
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ export default async function InvoicesPage({ params }: PageProps) {
|
|||||||
if (!acct) return <AccountNotFound />;
|
if (!acct) return <AccountNotFound />;
|
||||||
|
|
||||||
const api = createFinanceApi(client);
|
const api = createFinanceApi(client);
|
||||||
const invoices = await api.listInvoices(acct.id);
|
const invoicesResult = await api.listInvoices(acct.id);
|
||||||
|
const invoices = invoicesResult.data;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Rechnungen">
|
<CmsPageShell account={account} title="Rechnungen">
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { Landmark, FileText, Euro, ArrowRight, Plus } from 'lucide-react';
|
import {
|
||||||
|
Landmark,
|
||||||
|
FileText,
|
||||||
|
Euro,
|
||||||
|
ArrowRight,
|
||||||
|
Plus,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
import { createFinanceApi } from '@kit/finance/api';
|
import { createFinanceApi } from '@kit/finance/api';
|
||||||
import { formatDate } from '@kit/shared/dates';
|
import { formatDate } from '@kit/shared/dates';
|
||||||
@@ -8,6 +16,7 @@ import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -20,12 +29,30 @@ import {
|
|||||||
INVOICE_STATUS_LABEL,
|
INVOICE_STATUS_LABEL,
|
||||||
} from '~/lib/status-badges';
|
} from '~/lib/status-badges';
|
||||||
|
|
||||||
|
const PAGE_SIZE = 25;
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: Promise<{ account: string }>;
|
params: Promise<{ account: string }>;
|
||||||
|
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function FinancePage({ params }: PageProps) {
|
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 { account } = await params;
|
||||||
|
const search = await searchParams;
|
||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
|
|
||||||
const { data: acct } = await client
|
const { data: acct } = await client
|
||||||
@@ -36,13 +63,20 @@ export default async function FinancePage({ params }: PageProps) {
|
|||||||
|
|
||||||
if (!acct) return <AccountNotFound />;
|
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 api = createFinanceApi(client);
|
||||||
|
|
||||||
const [batches, invoices] = await Promise.all([
|
const [batchesResult, invoicesResult] = await Promise.all([
|
||||||
api.listBatches(acct.id),
|
api.listBatches(acct.id, { search: q, status, page, pageSize: PAGE_SIZE }),
|
||||||
api.listInvoices(acct.id),
|
api.listInvoices(acct.id, { search: q, status, page, pageSize: PAGE_SIZE }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const batches = batchesResult.data;
|
||||||
|
const invoices = invoicesResult.data;
|
||||||
|
|
||||||
const openAmount = invoices
|
const openAmount = invoices
|
||||||
.filter(
|
.filter(
|
||||||
(inv: Record<string, unknown>) =>
|
(inv: Record<string, unknown>) =>
|
||||||
@@ -54,6 +88,15 @@ export default async function FinancePage({ params }: PageProps) {
|
|||||||
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 (
|
return (
|
||||||
<CmsPageShell account={account} title="Finanzen">
|
<CmsPageShell account={account} title="Finanzen">
|
||||||
<div className="flex w-full flex-col gap-6">
|
<div className="flex w-full flex-col gap-6">
|
||||||
@@ -83,12 +126,12 @@ export default async function FinancePage({ params }: PageProps) {
|
|||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
<StatsCard
|
<StatsCard
|
||||||
title="SEPA-Einzüge"
|
title="SEPA-Einzüge"
|
||||||
value={batches.length}
|
value={batchesResult.total}
|
||||||
icon={<Landmark className="h-5 w-5" />}
|
icon={<Landmark className="h-5 w-5" />}
|
||||||
/>
|
/>
|
||||||
<StatsCard
|
<StatsCard
|
||||||
title="Rechnungen"
|
title="Rechnungen"
|
||||||
value={invoices.length}
|
value={invoicesResult.total}
|
||||||
icon={<FileText className="h-5 w-5" />}
|
icon={<FileText className="h-5 w-5" />}
|
||||||
/>
|
/>
|
||||||
<StatsCard
|
<StatsCard
|
||||||
@@ -98,10 +141,30 @@ export default async function FinancePage({ params }: PageProps) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</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 */}
|
{/* SEPA Batches */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between">
|
<CardHeader className="flex flex-row items-center justify-between">
|
||||||
<CardTitle>Letzte SEPA-Einzüge</CardTitle>
|
<CardTitle>Letzte SEPA-Einzüge ({batchesResult.total})</CardTitle>
|
||||||
<Link href={`/home/${account}/finance/sepa`}>
|
<Link href={`/home/${account}/finance/sepa`}>
|
||||||
<Button variant="ghost" size="sm">
|
<Button variant="ghost" size="sm">
|
||||||
Alle anzeigen
|
Alle anzeigen
|
||||||
@@ -171,7 +234,7 @@ export default async function FinancePage({ params }: PageProps) {
|
|||||||
{/* Invoices */}
|
{/* Invoices */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between">
|
<CardHeader className="flex flex-row items-center justify-between">
|
||||||
<CardTitle>Letzte Rechnungen</CardTitle>
|
<CardTitle>Letzte Rechnungen ({invoicesResult.total})</CardTitle>
|
||||||
<Link href={`/home/${account}/finance/invoices`}>
|
<Link href={`/home/${account}/finance/invoices`}>
|
||||||
<Button variant="ghost" size="sm">
|
<Button variant="ghost" size="sm">
|
||||||
Alle anzeigen
|
Alle anzeigen
|
||||||
@@ -240,6 +303,48 @@ export default async function FinancePage({ params }: PageProps) {
|
|||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</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>
|
</div>
|
||||||
</CmsPageShell>
|
</CmsPageShell>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -35,10 +35,12 @@ export default async function PaymentsPage({ params }: PageProps) {
|
|||||||
|
|
||||||
const api = createFinanceApi(client);
|
const api = createFinanceApi(client);
|
||||||
|
|
||||||
const [batches, invoices] = await Promise.all([
|
const [batchesResult, invoicesResult] = await Promise.all([
|
||||||
api.listBatches(acct.id),
|
api.listBatches(acct.id),
|
||||||
api.listInvoices(acct.id),
|
api.listInvoices(acct.id),
|
||||||
]);
|
]);
|
||||||
|
const batches = batchesResult.data;
|
||||||
|
const invoices = invoicesResult.data;
|
||||||
|
|
||||||
const paidInvoices = invoices.filter(
|
const paidInvoices = invoices.filter(
|
||||||
(inv: Record<string, unknown>) => inv.status === 'paid',
|
(inv: Record<string, unknown>) => inv.status === 'paid',
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ export default async function SepaPage({ params }: PageProps) {
|
|||||||
if (!acct) return <AccountNotFound />;
|
if (!acct) return <AccountNotFound />;
|
||||||
|
|
||||||
const api = createFinanceApi(client);
|
const api = createFinanceApi(client);
|
||||||
const batches = await api.listBatches(acct.id);
|
const batchesResult = await api.listBatches(acct.id);
|
||||||
|
const batches = batchesResult.data;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="SEPA-Lastschriften">
|
<CmsPageShell account={account} title="SEPA-Lastschriften">
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
CatchBooksDataTable,
|
CatchBooksDataTable,
|
||||||
} from '@kit/fischerei/components';
|
} from '@kit/fischerei/components';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -28,7 +29,18 @@ export default async function CatchBooksPage({ params, searchParams }: Props) {
|
|||||||
|
|
||||||
const api = createFischereiApi(client);
|
const api = createFischereiApi(client);
|
||||||
const page = Number(search.page) || 1;
|
const page = Number(search.page) || 1;
|
||||||
|
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
const yearOptions = [
|
||||||
|
{ value: '', label: 'Alle Jahre' },
|
||||||
|
...Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
value: String(currentYear - i),
|
||||||
|
label: String(currentYear - i),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
const result = await api.listCatchBooks(acct.id, {
|
const result = await api.listCatchBooks(acct.id, {
|
||||||
|
search: search.q as string,
|
||||||
year: search.year ? Number(search.year) : undefined,
|
year: search.year ? Number(search.year) : undefined,
|
||||||
status: search.status as string,
|
status: search.status as string,
|
||||||
page,
|
page,
|
||||||
@@ -38,6 +50,22 @@ export default async function CatchBooksPage({ params, searchParams }: Props) {
|
|||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Fischerei - Fangbücher">
|
<CmsPageShell account={account} title="Fischerei - Fangbücher">
|
||||||
<FischereiTabNavigation account={account} activeTab="catch-books" />
|
<FischereiTabNavigation account={account} activeTab="catch-books" />
|
||||||
|
<ListToolbar
|
||||||
|
searchPlaceholder="Mitglied suchen..."
|
||||||
|
filters={[
|
||||||
|
{ param: 'year', label: 'Jahr', options: yearOptions },
|
||||||
|
{
|
||||||
|
param: 'status',
|
||||||
|
label: 'Status',
|
||||||
|
options: [
|
||||||
|
{ value: '', label: 'Alle' },
|
||||||
|
{ value: 'open', label: 'Offen' },
|
||||||
|
{ value: 'submitted', label: 'Eingereicht' },
|
||||||
|
{ value: 'checked', label: 'Geprüft' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
<CatchBooksDataTable
|
<CatchBooksDataTable
|
||||||
data={result.data}
|
data={result.data}
|
||||||
total={result.total}
|
total={result.total}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
CompetitionsDataTable,
|
CompetitionsDataTable,
|
||||||
} from '@kit/fischerei/components';
|
} from '@kit/fischerei/components';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -31,7 +32,19 @@ export default async function CompetitionsPage({
|
|||||||
|
|
||||||
const api = createFischereiApi(client);
|
const api = createFischereiApi(client);
|
||||||
const page = Number(search.page) || 1;
|
const page = Number(search.page) || 1;
|
||||||
|
const yearParam = search.year ? Number(search.year) : undefined;
|
||||||
|
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
const yearOptions = [
|
||||||
|
{ value: '', label: 'Alle Jahre' },
|
||||||
|
...Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
value: String(currentYear - i),
|
||||||
|
label: String(currentYear - i),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
const result = await api.listCompetitions(acct.id, {
|
const result = await api.listCompetitions(acct.id, {
|
||||||
|
year: yearParam,
|
||||||
page,
|
page,
|
||||||
pageSize: 25,
|
pageSize: 25,
|
||||||
});
|
});
|
||||||
@@ -39,6 +52,10 @@ export default async function CompetitionsPage({
|
|||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Fischerei - Wettbewerbe">
|
<CmsPageShell account={account} title="Fischerei - Wettbewerbe">
|
||||||
<FischereiTabNavigation account={account} activeTab="competitions" />
|
<FischereiTabNavigation account={account} activeTab="competitions" />
|
||||||
|
<ListToolbar
|
||||||
|
showSearch={false}
|
||||||
|
filters={[{ param: 'year', label: 'Jahr', options: yearOptions }]}
|
||||||
|
/>
|
||||||
<CompetitionsDataTable
|
<CompetitionsDataTable
|
||||||
data={result.data}
|
data={result.data}
|
||||||
total={result.total}
|
total={result.total}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { formatDate } from '@kit/shared/dates';
|
|||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -29,10 +30,28 @@ export default async function LeasesPage({ params, searchParams }: Props) {
|
|||||||
|
|
||||||
const api = createFischereiApi(client);
|
const api = createFischereiApi(client);
|
||||||
const page = Number(search.page) || 1;
|
const page = Number(search.page) || 1;
|
||||||
const result = await api.listLeases(acct.id, {
|
const waterId = (search.waterId as string) || undefined;
|
||||||
page,
|
const activeParam = search.active as string | undefined;
|
||||||
pageSize: 25,
|
const active =
|
||||||
});
|
activeParam === 'true' ? true : activeParam === 'false' ? false : undefined;
|
||||||
|
|
||||||
|
const [result, watersResult] = await Promise.all([
|
||||||
|
api.listLeases(acct.id, {
|
||||||
|
waterId,
|
||||||
|
active,
|
||||||
|
page,
|
||||||
|
pageSize: 25,
|
||||||
|
}),
|
||||||
|
api.listWaters(acct.id, { pageSize: 200 }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const waterOptions = [
|
||||||
|
{ value: '', label: 'Alle Gewässer' },
|
||||||
|
...watersResult.data.map((w) => ({
|
||||||
|
value: String(w.id),
|
||||||
|
label: String(w.name),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Fischerei - Pachten">
|
<CmsPageShell account={account} title="Fischerei - Pachten">
|
||||||
@@ -44,6 +63,21 @@ export default async function LeasesPage({ params, searchParams }: Props) {
|
|||||||
Gewässerpachtverträge verwalten
|
Gewässerpachtverträge verwalten
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<ListToolbar
|
||||||
|
showSearch={false}
|
||||||
|
filters={[
|
||||||
|
{ param: 'waterId', label: 'Gewässer', options: waterOptions },
|
||||||
|
{
|
||||||
|
param: 'active',
|
||||||
|
label: 'Status',
|
||||||
|
options: [
|
||||||
|
{ value: '', label: 'Alle' },
|
||||||
|
{ value: 'true', label: 'Aktiv' },
|
||||||
|
{ value: 'false', label: 'Archiviert' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Pachten ({result.total})</CardTitle>
|
<CardTitle>Pachten ({result.total})</CardTitle>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
SpeciesDataTable,
|
SpeciesDataTable,
|
||||||
} from '@kit/fischerei/components';
|
} from '@kit/fischerei/components';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -28,8 +29,13 @@ export default async function SpeciesPage({ params, searchParams }: Props) {
|
|||||||
|
|
||||||
const api = createFischereiApi(client);
|
const api = createFischereiApi(client);
|
||||||
const page = Number(search.page) || 1;
|
const page = Number(search.page) || 1;
|
||||||
|
const activeParam = search.active as string | undefined;
|
||||||
|
const active =
|
||||||
|
activeParam === 'true' ? true : activeParam === 'false' ? false : undefined;
|
||||||
|
|
||||||
const result = await api.listSpecies(acct.id, {
|
const result = await api.listSpecies(acct.id, {
|
||||||
search: search.q as string,
|
search: search.q as string,
|
||||||
|
active,
|
||||||
page,
|
page,
|
||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
});
|
});
|
||||||
@@ -37,6 +43,20 @@ export default async function SpeciesPage({ params, searchParams }: Props) {
|
|||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Fischerei - Fischarten">
|
<CmsPageShell account={account} title="Fischerei - Fischarten">
|
||||||
<FischereiTabNavigation account={account} activeTab="species" />
|
<FischereiTabNavigation account={account} activeTab="species" />
|
||||||
|
<ListToolbar
|
||||||
|
searchPlaceholder="Fischart suchen..."
|
||||||
|
filters={[
|
||||||
|
{
|
||||||
|
param: 'active',
|
||||||
|
label: 'Status',
|
||||||
|
options: [
|
||||||
|
{ value: '', label: 'Alle' },
|
||||||
|
{ value: 'true', label: 'Aktiv' },
|
||||||
|
{ value: 'false', label: 'Inaktiv' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
<SpeciesDataTable
|
<SpeciesDataTable
|
||||||
data={result.data}
|
data={result.data}
|
||||||
total={result.total}
|
total={result.total}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
StockingDataTable,
|
StockingDataTable,
|
||||||
} from '@kit/fischerei/components';
|
} from '@kit/fischerei/components';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -28,14 +29,58 @@ export default async function StockingPage({ params, searchParams }: Props) {
|
|||||||
|
|
||||||
const api = createFischereiApi(client);
|
const api = createFischereiApi(client);
|
||||||
const page = Number(search.page) || 1;
|
const page = Number(search.page) || 1;
|
||||||
const result = await api.listStocking(acct.id, {
|
const waterId = (search.waterId as string) || undefined;
|
||||||
page,
|
const speciesId = (search.speciesId as string) || undefined;
|
||||||
pageSize: 25,
|
const yearParam = search.year ? Number(search.year) : undefined;
|
||||||
});
|
|
||||||
|
const [result, watersResult, speciesResult] = await Promise.all([
|
||||||
|
api.listStocking(acct.id, {
|
||||||
|
waterId,
|
||||||
|
speciesId,
|
||||||
|
year: yearParam,
|
||||||
|
page,
|
||||||
|
pageSize: 25,
|
||||||
|
}),
|
||||||
|
api.listWaters(acct.id, { pageSize: 200 }),
|
||||||
|
api.listSpecies(acct.id, { pageSize: 200 }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
const yearOptions = [
|
||||||
|
{ value: '', label: 'Alle Jahre' },
|
||||||
|
...Array.from({ length: 4 }, (_, i) => ({
|
||||||
|
value: String(currentYear - i),
|
||||||
|
label: String(currentYear - i),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
const waterOptions = [
|
||||||
|
{ value: '', label: 'Alle Gewässer' },
|
||||||
|
...watersResult.data.map((w) => ({
|
||||||
|
value: String(w.id),
|
||||||
|
label: String(w.name),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
const speciesOptions = [
|
||||||
|
{ value: '', label: 'Alle Arten' },
|
||||||
|
...speciesResult.data.map((s) => ({
|
||||||
|
value: String(s.id),
|
||||||
|
label: String(s.name),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Fischerei - Besatz">
|
<CmsPageShell account={account} title="Fischerei - Besatz">
|
||||||
<FischereiTabNavigation account={account} activeTab="stocking" />
|
<FischereiTabNavigation account={account} activeTab="stocking" />
|
||||||
|
<ListToolbar
|
||||||
|
showSearch={false}
|
||||||
|
filters={[
|
||||||
|
{ param: 'waterId', label: 'Gewässer', options: waterOptions },
|
||||||
|
{ param: 'speciesId', label: 'Fischart', options: speciesOptions },
|
||||||
|
{ param: 'year', label: 'Jahr', options: yearOptions },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
<StockingDataTable
|
<StockingDataTable
|
||||||
data={result.data}
|
data={result.data}
|
||||||
total={result.total}
|
total={result.total}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { useCallback, useState } from 'react';
|
|||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { Plus } from 'lucide-react';
|
import { Plus } from 'lucide-react';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
|
|
||||||
import { createDepartment } from '@kit/member-management/actions/member-actions';
|
import { createDepartment } from '@kit/member-management/actions/member-actions';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -20,7 +19,7 @@ import {
|
|||||||
} from '@kit/ui/dialog';
|
} from '@kit/ui/dialog';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { Label } from '@kit/ui/label';
|
import { Label } from '@kit/ui/label';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
interface CreateDepartmentDialogProps {
|
interface CreateDepartmentDialogProps {
|
||||||
accountId: string;
|
accountId: string;
|
||||||
@@ -34,18 +33,14 @@ export function CreateDepartmentDialog({
|
|||||||
const [name, setName] = useState('');
|
const [name, setName] = useState('');
|
||||||
const [description, setDescription] = useState('');
|
const [description, setDescription] = useState('');
|
||||||
|
|
||||||
const { execute, isPending } = useAction(createDepartment, {
|
const { execute, isPending } = useActionWithToast(createDepartment, {
|
||||||
onSuccess: ({ data }) => {
|
successMessage: 'Abteilung erstellt',
|
||||||
if (data?.success) {
|
errorMessage: 'Fehler beim Erstellen der Abteilung',
|
||||||
toast.success('Abteilung erstellt');
|
onSuccess: () => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
setName('');
|
setName('');
|
||||||
setDescription('');
|
setDescription('');
|
||||||
router.refresh();
|
router.refresh();
|
||||||
}
|
|
||||||
},
|
|
||||||
onError: ({ error }) => {
|
|
||||||
toast.error(error.serverError ?? 'Fehler beim Erstellen der Abteilung');
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ export default async function MembersPage({ params, searchParams }: Props) {
|
|||||||
page={page}
|
page={page}
|
||||||
pageSize={PAGE_SIZE}
|
pageSize={PAGE_SIZE}
|
||||||
account={account}
|
account={account}
|
||||||
|
accountId={acct.id}
|
||||||
duesCategories={(duesCategories ?? []).map(
|
duesCategories={(duesCategories ?? []).map(
|
||||||
(c: Record<string, unknown>) => ({
|
(c: Record<string, unknown>) => ({
|
||||||
id: String(c.id),
|
id: String(c.id),
|
||||||
|
|||||||
@@ -1,17 +1,12 @@
|
|||||||
import Link from 'next/link';
|
|
||||||
|
|
||||||
import { Pencil, Trash2, Lock, Unlock } from 'lucide-react';
|
|
||||||
|
|
||||||
import { createModuleBuilderApi } from '@kit/module-builder/api';
|
import { createModuleBuilderApi } from '@kit/module-builder/api';
|
||||||
import { ModuleForm } from '@kit/module-builder/components';
|
import { ModuleForm } from '@kit/module-builder/components';
|
||||||
import { formatDate } from '@kit/shared/dates';
|
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
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 { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
|
|
||||||
|
import { RecordDetailClient } from './record-detail-client';
|
||||||
|
|
||||||
interface RecordDetailPageProps {
|
interface RecordDetailPageProps {
|
||||||
params: Promise<{ account: string; moduleId: string; recordId: string }>;
|
params: Promise<{ account: string; moduleId: string; recordId: string }>;
|
||||||
}
|
}
|
||||||
@@ -23,6 +18,14 @@ export default async function RecordDetailPage({
|
|||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
const api = createModuleBuilderApi(client);
|
const api = createModuleBuilderApi(client);
|
||||||
|
|
||||||
|
const { data: accountData } = await client
|
||||||
|
.from('accounts')
|
||||||
|
.select('id')
|
||||||
|
.eq('slug', account)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (!accountData) return <AccountNotFound />;
|
||||||
|
|
||||||
const [moduleWithFields, record] = await Promise.all([
|
const [moduleWithFields, record] = await Promise.all([
|
||||||
api.modules.getModuleWithFields(moduleId),
|
api.modules.getModuleWithFields(moduleId),
|
||||||
api.records.getRecord(recordId),
|
api.records.getRecord(recordId),
|
||||||
@@ -49,68 +52,23 @@ export default async function RecordDetailPage({
|
|||||||
}
|
}
|
||||||
).fields;
|
).fields;
|
||||||
|
|
||||||
const data = (record.data ?? {}) as Record<string, unknown>;
|
|
||||||
const isLocked = record.status === 'locked';
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell
|
<CmsPageShell
|
||||||
account={account}
|
account={account}
|
||||||
title={`${String(moduleWithFields.display_name)} — Datensatz`}
|
title={`${String(moduleWithFields.display_name)} — Datensatz`}
|
||||||
>
|
>
|
||||||
<div className="space-y-6">
|
<RecordDetailClient
|
||||||
<div className="flex items-center justify-between">
|
fields={fields as Parameters<typeof ModuleForm>[0]['fields']}
|
||||||
<div className="flex items-center gap-2">
|
record={{
|
||||||
<Badge
|
id: record.id as string,
|
||||||
variant={
|
data: (record.data ?? {}) as Record<string, unknown>,
|
||||||
isLocked
|
status: record.status as string,
|
||||||
? 'destructive'
|
created_at: record.created_at as string,
|
||||||
: record.status === 'active'
|
}}
|
||||||
? 'default'
|
moduleId={moduleId}
|
||||||
: 'secondary'
|
accountId={accountData.id}
|
||||||
}
|
accountSlug={account}
|
||||||
>
|
/>
|
||||||
{String(record.status)}
|
|
||||||
</Badge>
|
|
||||||
<span className="text-muted-foreground text-sm">
|
|
||||||
Erstellt: {formatDate(record.created_at)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{isLocked ? (
|
|
||||||
<Button variant="outline" size="sm">
|
|
||||||
<Unlock className="mr-2 h-4 w-4" />
|
|
||||||
Entsperren
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Button variant="outline" size="sm">
|
|
||||||
<Lock className="mr-2 h-4 w-4" />
|
|
||||||
Sperren
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button variant="destructive" size="sm">
|
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
|
||||||
Löschen
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center gap-2">
|
|
||||||
<Pencil className="h-4 w-4" />
|
|
||||||
Datensatz bearbeiten
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<ModuleForm
|
|
||||||
fields={fields as Parameters<typeof ModuleForm>[0]['fields']}
|
|
||||||
initialData={data}
|
|
||||||
onSubmit={async () => {}}
|
|
||||||
isLoading={false}
|
|
||||||
/>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</CmsPageShell>
|
</CmsPageShell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useTransition } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
import { Pencil, Trash2, Lock, Unlock } from 'lucide-react';
|
||||||
|
|
||||||
|
import {
|
||||||
|
updateRecord,
|
||||||
|
deleteRecord,
|
||||||
|
lockRecord,
|
||||||
|
} from '@kit/module-builder/actions/record-actions';
|
||||||
|
import { ModuleForm } from '@kit/module-builder/components';
|
||||||
|
import { formatDate } from '@kit/shared/dates';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
} from '@kit/ui/alert-dialog';
|
||||||
|
import { Badge } from '@kit/ui/badge';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
|
type FieldDef = Parameters<typeof ModuleForm>[0]['fields'][number];
|
||||||
|
|
||||||
|
interface RecordDetailClientProps {
|
||||||
|
fields: FieldDef[];
|
||||||
|
record: {
|
||||||
|
id: string;
|
||||||
|
data: Record<string, unknown>;
|
||||||
|
status: string;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
moduleId: string;
|
||||||
|
accountId: string;
|
||||||
|
accountSlug: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RecordDetailClient({
|
||||||
|
fields,
|
||||||
|
record,
|
||||||
|
moduleId,
|
||||||
|
accountId,
|
||||||
|
accountSlug,
|
||||||
|
}: RecordDetailClientProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const isLocked = record.status === 'locked';
|
||||||
|
|
||||||
|
const lockSuccessMessage = isLocked
|
||||||
|
? 'Datensatz entsperrt'
|
||||||
|
: 'Datensatz gesperrt';
|
||||||
|
|
||||||
|
const { execute: execUpdate, isPending: isUpdating } = useActionWithToast(
|
||||||
|
updateRecord,
|
||||||
|
{
|
||||||
|
successMessage: 'Datensatz aktualisiert',
|
||||||
|
errorMessage: 'Fehler beim Aktualisieren',
|
||||||
|
onSuccess: () => {
|
||||||
|
startTransition(() => {
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const { execute: execDelete, isPending: isDeleting } = useActionWithToast(
|
||||||
|
deleteRecord,
|
||||||
|
{
|
||||||
|
successMessage: 'Datensatz gelöscht',
|
||||||
|
errorMessage: 'Fehler beim Löschen',
|
||||||
|
onSuccess: () => {
|
||||||
|
startTransition(() => {
|
||||||
|
router.push(`/home/${accountSlug}/modules/${moduleId}`);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const { execute: execLock, isPending: isLocking } = useActionWithToast(
|
||||||
|
lockRecord,
|
||||||
|
{
|
||||||
|
successMessage: lockSuccessMessage,
|
||||||
|
errorMessage: 'Fehler beim Sperren',
|
||||||
|
onSuccess: () => {
|
||||||
|
startTransition(() => {
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const isBusy = isUpdating || isDeleting || isLocking || isPending;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge
|
||||||
|
variant={
|
||||||
|
isLocked
|
||||||
|
? 'destructive'
|
||||||
|
: record.status === 'active'
|
||||||
|
? 'default'
|
||||||
|
: 'secondary'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{record.status}
|
||||||
|
</Badge>
|
||||||
|
<span className="text-muted-foreground text-sm">
|
||||||
|
Erstellt: {formatDate(record.created_at)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={isBusy}
|
||||||
|
onClick={() =>
|
||||||
|
execLock({
|
||||||
|
recordId: record.id,
|
||||||
|
lock: !isLocked,
|
||||||
|
accountId,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{isLocked ? (
|
||||||
|
<>
|
||||||
|
<Unlock className="mr-2 h-4 w-4" />
|
||||||
|
Entsperren
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Lock className="mr-2 h-4 w-4" />
|
||||||
|
Sperren
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<AlertDialog>
|
||||||
|
<AlertDialogTrigger asChild>
|
||||||
|
<Button variant="destructive" size="sm" disabled={isBusy}>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Löschen
|
||||||
|
</Button>
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Datensatz löschen?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Dieser Datensatz wird unwiderruflich gelöscht. Diese Aktion
|
||||||
|
kann nicht rückgängig gemacht werden.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={() =>
|
||||||
|
execDelete({
|
||||||
|
recordId: record.id,
|
||||||
|
hard: false,
|
||||||
|
accountId,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Löschen
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
Datensatz bearbeiten
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ModuleForm
|
||||||
|
fields={fields}
|
||||||
|
initialData={record.data}
|
||||||
|
onSubmit={async (data) => {
|
||||||
|
execUpdate({
|
||||||
|
recordId: record.id,
|
||||||
|
data,
|
||||||
|
accountId,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
isLoading={isBusy}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
interface FilterValue {
|
||||||
|
field: string;
|
||||||
|
operator: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeFilters(filters: FilterValue[]): string {
|
||||||
|
return filters
|
||||||
|
.map((f) => `${f.field}:${f.operator}:${encodeURIComponent(f.value)}`)
|
||||||
|
.join(',');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeFilters(raw: string | undefined | null): FilterValue[] {
|
||||||
|
if (!raw) return [];
|
||||||
|
return raw.split(',').map((segment) => {
|
||||||
|
const [field, operator, ...rest] = segment.split(':');
|
||||||
|
return {
|
||||||
|
field: field ?? '',
|
||||||
|
operator: operator ?? 'eq',
|
||||||
|
value: decodeURIComponent(rest.join(':')),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
|
||||||
|
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
|
||||||
|
|
||||||
|
import { ModuleSearch } from '@kit/module-builder/components';
|
||||||
|
|
||||||
|
import { encodeFilters, decodeFilters } from './_lib/filter-params';
|
||||||
|
|
||||||
|
interface FieldOption {
|
||||||
|
name: string;
|
||||||
|
display_name: string;
|
||||||
|
show_in_filter: boolean;
|
||||||
|
show_in_search: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ModuleSearchBarProps {
|
||||||
|
fields: FieldOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ModuleSearchBar({ fields }: ModuleSearchBarProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
|
const currentSearch = searchParams.get('q') ?? '';
|
||||||
|
const currentFilters = decodeFilters(searchParams.get('f') ?? '');
|
||||||
|
|
||||||
|
const updateParams = useCallback(
|
||||||
|
(updates: Record<string, string | null>) => {
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
// Reset to page 1 when search/filters change
|
||||||
|
params.delete('page');
|
||||||
|
for (const [key, value] of Object.entries(updates)) {
|
||||||
|
if (value === null || value === '') {
|
||||||
|
params.delete(key);
|
||||||
|
} else {
|
||||||
|
params.set(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
router.push(`${pathname}?${params.toString()}`);
|
||||||
|
},
|
||||||
|
[router, pathname, searchParams],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ModuleSearch
|
||||||
|
fields={fields}
|
||||||
|
initialSearch={currentSearch}
|
||||||
|
initialFilters={currentFilters}
|
||||||
|
onSearch={(search) => updateParams({ q: search || null })}
|
||||||
|
onFilter={(filters) =>
|
||||||
|
updateParams({ f: filters.length > 0 ? encodeFilters(filters) : null })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useTransition } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
import { createRecord } from '@kit/module-builder/actions/record-actions';
|
||||||
|
import { ModuleForm } from '@kit/module-builder/components';
|
||||||
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
|
type FieldDef = Parameters<typeof ModuleForm>[0]['fields'][number];
|
||||||
|
|
||||||
|
interface CreateRecordFormProps {
|
||||||
|
fields: FieldDef[];
|
||||||
|
moduleId: string;
|
||||||
|
accountId: string;
|
||||||
|
accountSlug: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CreateRecordForm({
|
||||||
|
fields,
|
||||||
|
moduleId,
|
||||||
|
accountId,
|
||||||
|
accountSlug,
|
||||||
|
}: CreateRecordFormProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const { execute, isPending: isExecuting } = useActionWithToast(createRecord, {
|
||||||
|
successMessage: 'Datensatz erstellt',
|
||||||
|
errorMessage: 'Fehler beim Erstellen',
|
||||||
|
onSuccess: () => {
|
||||||
|
startTransition(() => {
|
||||||
|
router.push(`/home/${accountSlug}/modules/${moduleId}`);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ModuleForm
|
||||||
|
fields={fields}
|
||||||
|
onSubmit={async (data) => {
|
||||||
|
execute({ moduleId, accountId, data });
|
||||||
|
}}
|
||||||
|
isLoading={isExecuting || isPending}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,8 +2,11 @@ import { createModuleBuilderApi } from '@kit/module-builder/api';
|
|||||||
import { ModuleForm } from '@kit/module-builder/components';
|
import { ModuleForm } from '@kit/module-builder/components';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
|
|
||||||
|
import { CreateRecordForm } from './create-record-form';
|
||||||
|
|
||||||
interface NewRecordPageProps {
|
interface NewRecordPageProps {
|
||||||
params: Promise<{ account: string; moduleId: string }>;
|
params: Promise<{ account: string; moduleId: string }>;
|
||||||
}
|
}
|
||||||
@@ -13,6 +16,14 @@ export default async function NewRecordPage({ params }: NewRecordPageProps) {
|
|||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
const api = createModuleBuilderApi(client);
|
const api = createModuleBuilderApi(client);
|
||||||
|
|
||||||
|
const { data: accountData } = await client
|
||||||
|
.from('accounts')
|
||||||
|
.select('id')
|
||||||
|
.eq('slug', account)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (!accountData) return <AccountNotFound />;
|
||||||
|
|
||||||
const moduleWithFields = await api.modules.getModuleWithFields(moduleId);
|
const moduleWithFields = await api.modules.getModuleWithFields(moduleId);
|
||||||
if (!moduleWithFields) return <div>Modul nicht gefunden</div>;
|
if (!moduleWithFields) return <div>Modul nicht gefunden</div>;
|
||||||
|
|
||||||
@@ -41,10 +52,11 @@ export default async function NewRecordPage({ params }: NewRecordPageProps) {
|
|||||||
title={`${String(moduleWithFields.display_name)} — Neuer Datensatz`}
|
title={`${String(moduleWithFields.display_name)} — Neuer Datensatz`}
|
||||||
>
|
>
|
||||||
<div className="mx-auto max-w-3xl">
|
<div className="mx-auto max-w-3xl">
|
||||||
<ModuleForm
|
<CreateRecordForm
|
||||||
fields={fields as Parameters<typeof ModuleForm>[0]['fields']}
|
fields={fields as Parameters<typeof ModuleForm>[0]['fields']}
|
||||||
onSubmit={async () => {}}
|
moduleId={moduleId}
|
||||||
isLoading={false}
|
accountId={accountData.id}
|
||||||
|
accountSlug={account}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</CmsPageShell>
|
</CmsPageShell>
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
import { Plus } from 'lucide-react';
|
||||||
|
|
||||||
import { createModuleBuilderApi } from '@kit/module-builder/api';
|
import { createModuleBuilderApi } from '@kit/module-builder/api';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
|
||||||
|
import { decodeFilters } from './_lib/filter-params';
|
||||||
|
import { ModuleSearchBar } from './module-search-bar';
|
||||||
|
|
||||||
interface ModuleDetailPageProps {
|
interface ModuleDetailPageProps {
|
||||||
params: Promise<{ account: string; moduleId: string }>;
|
params: Promise<{ account: string; moduleId: string }>;
|
||||||
@@ -25,6 +33,8 @@ export default async function ModuleDetailPage({
|
|||||||
const pageSize =
|
const pageSize =
|
||||||
Number(search.pageSize) || moduleWithFields.default_page_size || 25;
|
Number(search.pageSize) || moduleWithFields.default_page_size || 25;
|
||||||
|
|
||||||
|
const filters = decodeFilters(search.f as string | undefined);
|
||||||
|
|
||||||
const result = await api.query.query({
|
const result = await api.query.query({
|
||||||
moduleId,
|
moduleId,
|
||||||
page,
|
page,
|
||||||
@@ -38,9 +48,20 @@ export default async function ModuleDetailPage({
|
|||||||
(moduleWithFields.default_sort_direction as 'asc' | 'desc') ??
|
(moduleWithFields.default_sort_direction as 'asc' | 'desc') ??
|
||||||
'asc',
|
'asc',
|
||||||
search: (search.q as string) ?? undefined,
|
search: (search.q as string) ?? undefined,
|
||||||
filters: [],
|
filters,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const fields = (
|
||||||
|
moduleWithFields as unknown as {
|
||||||
|
fields: Array<{
|
||||||
|
name: string;
|
||||||
|
display_name: string;
|
||||||
|
show_in_filter: boolean;
|
||||||
|
show_in_search: boolean;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
).fields;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
@@ -54,14 +75,21 @@ export default async function ModuleDetailPage({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<Button asChild>
|
||||||
|
<Link href={`/home/${account}/modules/${moduleId}/new`}>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Neuer Datensatz
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ModuleSearchBar fields={fields} />
|
||||||
|
|
||||||
<div className="text-muted-foreground text-sm">
|
<div className="text-muted-foreground text-sm">
|
||||||
{result.pagination.total} Datensätze — Seite {result.pagination.page}{' '}
|
{result.pagination.total} Datensätze — Seite {result.pagination.page}{' '}
|
||||||
von {result.pagination.totalPages}
|
von {result.pagination.totalPages}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Phase 3 will replace this with module-table component */}
|
|
||||||
<div className="rounded-lg border">
|
<div className="rounded-lg border">
|
||||||
<pre className="max-h-96 overflow-auto p-4 text-xs">
|
<pre className="max-h-96 overflow-auto p-4 text-xs">
|
||||||
{JSON.stringify(result.data, null, 2)}
|
{JSON.stringify(result.data, null, 2)}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useTransition } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
import { Trash2 } from 'lucide-react';
|
||||||
|
|
||||||
|
import { deleteModule } from '@kit/module-builder/actions/module-actions';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
} from '@kit/ui/alert-dialog';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
|
interface DeleteModuleButtonProps {
|
||||||
|
moduleId: string;
|
||||||
|
moduleName: string;
|
||||||
|
accountSlug: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DeleteModuleButton({
|
||||||
|
moduleId,
|
||||||
|
moduleName,
|
||||||
|
accountSlug,
|
||||||
|
}: DeleteModuleButtonProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const { execute, isPending: isDeleting } = useActionWithToast(deleteModule, {
|
||||||
|
successMessage: `Modul "${moduleName}" wurde archiviert`,
|
||||||
|
errorMessage: 'Fehler beim Löschen',
|
||||||
|
onSuccess: () => {
|
||||||
|
startTransition(() => {
|
||||||
|
router.push(`/home/${accountSlug}/modules`);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AlertDialog>
|
||||||
|
<AlertDialogTrigger asChild>
|
||||||
|
<Button variant="destructive" disabled={isDeleting || isPending}>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Modul archivieren
|
||||||
|
</Button>
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Modul archivieren?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Das Modul "{moduleName}" wird archiviert und ist nicht
|
||||||
|
mehr sichtbar. Diese Aktion kann durch einen Administrator
|
||||||
|
rückgängig gemacht werden.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={() => execute({ moduleId })}>
|
||||||
|
Archivieren
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@ import { Label } from '@kit/ui/label';
|
|||||||
|
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
|
|
||||||
|
import { DeleteModuleButton } from './delete-module-button';
|
||||||
|
|
||||||
interface ModuleSettingsPageProps {
|
interface ModuleSettingsPageProps {
|
||||||
params: Promise<{ account: string; moduleId: string }>;
|
params: Promise<{ account: string; moduleId: string }>;
|
||||||
}
|
}
|
||||||
@@ -178,6 +180,25 @@ export default async function ModuleSettingsPage({
|
|||||||
</p>
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Danger Zone */}
|
||||||
|
<Card className="border-destructive/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-destructive flex items-center gap-2">
|
||||||
|
Gefahrenbereich
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex items-center justify-between">
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Das Modul wird archiviert und ist nicht mehr sichtbar.
|
||||||
|
</p>
|
||||||
|
<DeleteModuleButton
|
||||||
|
moduleId={moduleId}
|
||||||
|
moduleName={String(mod.display_name)}
|
||||||
|
accountSlug={account}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</CmsPageShell>
|
</CmsPageShell>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useTransition } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
import { Send } from 'lucide-react';
|
||||||
|
|
||||||
|
import { dispatchNewsletter } from '@kit/newsletter/actions/newsletter-actions';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
} from '@kit/ui/alert-dialog';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
|
interface DispatchNewsletterButtonProps {
|
||||||
|
newsletterId: string;
|
||||||
|
recipientCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DispatchNewsletterButton({
|
||||||
|
newsletterId,
|
||||||
|
recipientCount,
|
||||||
|
}: DispatchNewsletterButtonProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const { execute, isPending: isDispatching } = useActionWithToast(
|
||||||
|
dispatchNewsletter,
|
||||||
|
{
|
||||||
|
successMessage: 'Newsletter wird versendet',
|
||||||
|
errorMessage: 'Fehler beim Versenden',
|
||||||
|
onSuccess: () => {
|
||||||
|
startTransition(() => {
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AlertDialog>
|
||||||
|
<AlertDialogTrigger asChild>
|
||||||
|
<Button
|
||||||
|
disabled={isDispatching || isPending || recipientCount === 0}
|
||||||
|
data-test="newsletter-send-btn"
|
||||||
|
>
|
||||||
|
<Send className="mr-2 h-4 w-4" />
|
||||||
|
Newsletter versenden
|
||||||
|
</Button>
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Newsletter versenden?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Der Newsletter wird an {recipientCount} Empfänger versendet. Dieser
|
||||||
|
Vorgang kann nicht rückgängig gemacht werden.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={() => execute({ newsletterId })}>
|
||||||
|
Jetzt versenden
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,7 +5,6 @@ import { ArrowLeft, Send, Users } from 'lucide-react';
|
|||||||
import { createNewsletterApi } from '@kit/newsletter/api';
|
import { createNewsletterApi } from '@kit/newsletter/api';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
@@ -18,6 +17,8 @@ import {
|
|||||||
NEWSLETTER_RECIPIENT_STATUS_LABEL,
|
NEWSLETTER_RECIPIENT_STATUS_LABEL,
|
||||||
} from '~/lib/status-badges';
|
} from '~/lib/status-badges';
|
||||||
|
|
||||||
|
import { DispatchNewsletterButton } from './dispatch-newsletter-button';
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: Promise<{ account: string; campaignId: string }>;
|
params: Promise<{ account: string; campaignId: string }>;
|
||||||
}
|
}
|
||||||
@@ -99,10 +100,10 @@ export default async function NewsletterDetailPage({ params }: PageProps) {
|
|||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
{status === 'draft' && (
|
{status === 'draft' && (
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<Button data-test="newsletter-send-btn">
|
<DispatchNewsletterButton
|
||||||
<Send className="mr-2 h-4 w-4" />
|
newsletterId={campaignId}
|
||||||
Newsletter versenden
|
recipientCount={recipients.length}
|
||||||
</Button>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
|
import { ListToolbar } from '@kit/ui/list-toolbar';
|
||||||
|
|
||||||
import { AccountNotFound } from '~/components/account-not-found';
|
import { AccountNotFound } from '~/components/account-not-found';
|
||||||
import { CmsPageShell } from '~/components/cms-page-shell';
|
import { CmsPageShell } from '~/components/cms-page-shell';
|
||||||
@@ -32,6 +33,20 @@ interface PageProps {
|
|||||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
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 NewsletterPage({
|
export default async function NewsletterPage({
|
||||||
params,
|
params,
|
||||||
searchParams,
|
searchParams,
|
||||||
@@ -48,26 +63,34 @@ export default async function NewsletterPage({
|
|||||||
|
|
||||||
if (!acct) return <AccountNotFound />;
|
if (!acct) return <AccountNotFound />;
|
||||||
|
|
||||||
const api = createNewsletterApi(client);
|
const q = typeof search.q === 'string' ? search.q : undefined;
|
||||||
const allNewsletters = await api.listNewsletters(acct.id);
|
const status = typeof search.status === 'string' ? search.status : undefined;
|
||||||
|
const page = Math.max(1, Number(search.page) || 1);
|
||||||
|
|
||||||
const sentCount = allNewsletters.filter(
|
const api = createNewsletterApi(client);
|
||||||
|
const result = await api.listNewsletters(acct.id, {
|
||||||
|
search: q,
|
||||||
|
status,
|
||||||
|
page,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
|
|
||||||
|
const newsletters = result.data;
|
||||||
|
const totalItems = result.total;
|
||||||
|
const totalPages = result.totalPages;
|
||||||
|
const safePage = result.page;
|
||||||
|
|
||||||
|
const sentCount = newsletters.filter(
|
||||||
(n: Record<string, unknown>) => n.status === 'sent',
|
(n: Record<string, unknown>) => n.status === 'sent',
|
||||||
).length;
|
).length;
|
||||||
|
|
||||||
const totalRecipients = allNewsletters.reduce(
|
const totalRecipients = newsletters.reduce(
|
||||||
(sum: number, n: Record<string, unknown>) =>
|
(sum: number, n: Record<string, unknown>) =>
|
||||||
sum + (Number(n.total_recipients) || 0),
|
sum + (Number(n.total_recipients) || 0),
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Pagination
|
const queryBase = { q, status };
|
||||||
const currentPage = Math.max(1, Number(search.page) || 1);
|
|
||||||
const totalItems = allNewsletters.length;
|
|
||||||
const totalPages = Math.max(1, Math.ceil(totalItems / PAGE_SIZE));
|
|
||||||
const safePage = Math.min(currentPage, totalPages);
|
|
||||||
const startIdx = (safePage - 1) * PAGE_SIZE;
|
|
||||||
const newsletters = allNewsletters.slice(startIdx, startIdx + PAGE_SIZE);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Newsletter">
|
<CmsPageShell account={account} title="Newsletter">
|
||||||
@@ -108,6 +131,25 @@ export default async function NewsletterPage({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Toolbar */}
|
||||||
|
<ListToolbar
|
||||||
|
searchPlaceholder="Newsletter suchen..."
|
||||||
|
filters={[
|
||||||
|
{
|
||||||
|
param: 'status',
|
||||||
|
label: 'Status',
|
||||||
|
options: [
|
||||||
|
{ value: '', label: 'Alle' },
|
||||||
|
{ value: 'draft', label: 'Entwurf' },
|
||||||
|
{ value: 'scheduled', label: 'Geplant' },
|
||||||
|
{ value: 'sending', label: 'Wird gesendet' },
|
||||||
|
{ value: 'sent', label: 'Gesendet' },
|
||||||
|
{ value: 'failed', label: 'Fehlgeschlagen' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Table or Empty State */}
|
{/* Table or Empty State */}
|
||||||
{totalItems === 0 ? (
|
{totalItems === 0 ? (
|
||||||
<EmptyState
|
<EmptyState
|
||||||
@@ -176,13 +218,12 @@ export default async function NewsletterPage({
|
|||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<div className="flex items-center justify-between pt-4">
|
<div className="flex items-center justify-between pt-4">
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground text-sm">
|
||||||
{startIdx + 1}–{Math.min(startIdx + PAGE_SIZE, totalItems)}{' '}
|
Seite {safePage} von {totalPages}
|
||||||
von {totalItems}
|
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
{safePage > 1 ? (
|
{safePage > 1 ? (
|
||||||
<Link
|
<Link
|
||||||
href={`/home/${account}/newsletter?page=${safePage - 1}`}
|
href={`/home/${account}/newsletter${buildQuery(queryBase, { page: safePage - 1 })}`}
|
||||||
>
|
>
|
||||||
<Button variant="outline" size="sm">
|
<Button variant="outline" size="sm">
|
||||||
<ChevronLeft className="h-4 w-4" />
|
<ChevronLeft className="h-4 w-4" />
|
||||||
@@ -200,7 +241,7 @@ export default async function NewsletterPage({
|
|||||||
|
|
||||||
{safePage < totalPages ? (
|
{safePage < totalPages ? (
|
||||||
<Link
|
<Link
|
||||||
href={`/home/${account}/newsletter?page=${safePage + 1}`}
|
href={`/home/${account}/newsletter${buildQuery(queryBase, { page: safePage + 1 })}`}
|
||||||
>
|
>
|
||||||
<Button variant="outline" size="sm">
|
<Button variant="outline" size="sm">
|
||||||
<ChevronRight className="h-4 w-4" />
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
|||||||
@@ -29,7 +29,8 @@ export default async function NewsletterTemplatesPage({ params }: PageProps) {
|
|||||||
if (!acct) return <AccountNotFound />;
|
if (!acct) return <AccountNotFound />;
|
||||||
|
|
||||||
const api = createNewsletterApi(client);
|
const api = createNewsletterApi(client);
|
||||||
const templates = await api.listTemplates(acct.id);
|
const templatesResult = await api.listTemplates(acct.id);
|
||||||
|
const templates = templatesResult.data;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CmsPageShell account={account} title="Newsletter-Vorlagen">
|
<CmsPageShell account={account} title="Newsletter-Vorlagen">
|
||||||
|
|||||||
@@ -86,10 +86,12 @@ export default async function TeamAccountHomePage({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const openInvoices =
|
const openInvoices =
|
||||||
invoicesResult.status === 'fulfilled' ? invoicesResult.value : [];
|
invoicesResult.status === 'fulfilled' ? invoicesResult.value.data : [];
|
||||||
|
|
||||||
const newsletters =
|
const newsletters =
|
||||||
newslettersResult.status === 'fulfilled' ? newslettersResult.value : [];
|
newslettersResult.status === 'fulfilled'
|
||||||
|
? newslettersResult.value.data
|
||||||
|
: [];
|
||||||
|
|
||||||
const bookings =
|
const bookings =
|
||||||
bookingsResult.status === 'fulfilled'
|
bookingsResult.status === 'fulfilled'
|
||||||
|
|||||||
@@ -3,12 +3,11 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
import { Plus, Pencil, Trash2, Settings } from 'lucide-react';
|
import { Plus, Pencil, Trash2, Settings } from 'lucide-react';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
import {
|
import {
|
||||||
createRole,
|
createRole,
|
||||||
updateRole,
|
updateRole,
|
||||||
@@ -185,63 +184,45 @@ export default function SettingsContent({
|
|||||||
feeTypes,
|
feeTypes,
|
||||||
}: SettingsContentProps) {
|
}: SettingsContentProps) {
|
||||||
// Roles
|
// Roles
|
||||||
const { execute: execCreateRole, isPending: isCreatingRole } = useAction(
|
const { execute: execCreateRole, isPending: isCreatingRole } =
|
||||||
createRole,
|
useActionWithToast(createRole, {
|
||||||
{
|
successMessage: 'Funktion erstellt',
|
||||||
onSuccess: () => toast.success('Funktion erstellt'),
|
});
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
const { execute: execUpdateRole, isPending: isUpdatingRole } =
|
||||||
},
|
useActionWithToast(updateRole, {
|
||||||
);
|
successMessage: 'Funktion aktualisiert',
|
||||||
const { execute: execUpdateRole, isPending: isUpdatingRole } = useAction(
|
});
|
||||||
updateRole,
|
const { execute: execDeleteRole } = useActionWithToast(deleteRole, {
|
||||||
{
|
successMessage: 'Funktion gelöscht',
|
||||||
onSuccess: () => toast.success('Funktion aktualisiert'),
|
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const { execute: execDeleteRole } = useAction(deleteRole, {
|
|
||||||
onSuccess: () => toast.success('Funktion gelöscht'),
|
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Types
|
// Types
|
||||||
const { execute: execCreateType, isPending: isCreatingType } = useAction(
|
const { execute: execCreateType, isPending: isCreatingType } =
|
||||||
createAssociationType,
|
useActionWithToast(createAssociationType, {
|
||||||
|
successMessage: 'Vereinstyp erstellt',
|
||||||
|
});
|
||||||
|
const { execute: execUpdateType, isPending: isUpdatingType } =
|
||||||
|
useActionWithToast(updateAssociationType, {
|
||||||
|
successMessage: 'Vereinstyp aktualisiert',
|
||||||
|
});
|
||||||
|
const { execute: execDeleteType } = useActionWithToast(
|
||||||
|
deleteAssociationType,
|
||||||
{
|
{
|
||||||
onSuccess: () => toast.success('Vereinstyp erstellt'),
|
successMessage: 'Vereinstyp gelöscht',
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const { execute: execUpdateType, isPending: isUpdatingType } = useAction(
|
|
||||||
updateAssociationType,
|
|
||||||
{
|
|
||||||
onSuccess: () => toast.success('Vereinstyp aktualisiert'),
|
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const { execute: execDeleteType } = useAction(deleteAssociationType, {
|
|
||||||
onSuccess: () => toast.success('Vereinstyp gelöscht'),
|
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fee Types
|
// Fee Types
|
||||||
const { execute: execCreateFeeType, isPending: isCreatingFee } = useAction(
|
const { execute: execCreateFeeType, isPending: isCreatingFee } =
|
||||||
createFeeType,
|
useActionWithToast(createFeeType, {
|
||||||
{
|
successMessage: 'Beitragsart erstellt',
|
||||||
onSuccess: () => toast.success('Beitragsart erstellt'),
|
});
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
const { execute: execUpdateFeeType, isPending: isUpdatingFee } =
|
||||||
},
|
useActionWithToast(updateFeeType, {
|
||||||
);
|
successMessage: 'Beitragsart aktualisiert',
|
||||||
const { execute: execUpdateFeeType, isPending: isUpdatingFee } = useAction(
|
});
|
||||||
updateFeeType,
|
const { execute: execDeleteFeeType } = useActionWithToast(deleteFeeType, {
|
||||||
{
|
successMessage: 'Beitragsart gelöscht',
|
||||||
onSuccess: () => toast.success('Beitragsart aktualisiert'),
|
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const { execute: execDeleteFeeType } = useAction(deleteFeeType, {
|
|
||||||
onSuccess: () => toast.success('Beitragsart gelöscht'),
|
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server';
|
|||||||
|
|
||||||
import { createClient } from '@supabase/supabase-js';
|
import { createClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
import { apiError } from '@kit/next/route-helpers';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
@@ -113,6 +114,6 @@ export async function POST(request: Request) {
|
|||||||
{ error: err, context: 'accept-invite' },
|
{ error: err, context: 'accept-invite' },
|
||||||
'[accept-invite] Error',
|
'[accept-invite] Error',
|
||||||
);
|
);
|
||||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
|
return apiError('Serverfehler', 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,28 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import * as z from 'zod';
|
||||||
|
|
||||||
|
import { apiError, apiSuccess, emailSchema } from '@kit/next/route-helpers';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
|
|
||||||
|
const ContactSchema = z.object({
|
||||||
|
recipientEmail: z.string().optional(),
|
||||||
|
name: z.string().optional(),
|
||||||
|
email: emailSchema,
|
||||||
|
subject: z.string().optional(),
|
||||||
|
message: z.string().min(1, 'Nachricht ist erforderlich'),
|
||||||
|
});
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { recipientEmail, name, email, subject, message } = body;
|
const parsed = ContactSchema.safeParse(body);
|
||||||
|
|
||||||
if (!email || !message) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return apiError(parsed.error.issues[0]?.message ?? 'Ungültige Eingabe');
|
||||||
{ error: 'E-Mail und Nachricht sind erforderlich' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
const { recipientEmail, name, email, subject, message } = parsed.data;
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Ungültige E-Mail-Adresse' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// In production: use @kit/mailers to send the email
|
// In production: use @kit/mailers to send the email
|
||||||
// For now: log and return success
|
// For now: log and return success
|
||||||
@@ -45,9 +46,9 @@ export async function POST(request: Request) {
|
|||||||
// text: `Name: ${name}\nE-Mail: ${email}\n\n${message}`,
|
// text: `Name: ${name}\nE-Mail: ${email}\n\n${message}`,
|
||||||
// });
|
// });
|
||||||
|
|
||||||
return NextResponse.json({ success: true, message: 'Nachricht gesendet' });
|
return apiSuccess({ message: 'Nachricht gesendet' });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error({ error: err, context: 'contact' }, '[contact] Error');
|
logger.error({ error: err, context: 'contact' }, '[contact] Error');
|
||||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
|
return apiError('Serverfehler', 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,34 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import * as z from 'zod';
|
||||||
|
|
||||||
|
import {
|
||||||
|
apiError,
|
||||||
|
apiSuccess,
|
||||||
|
emailSchema,
|
||||||
|
requiredString,
|
||||||
|
} from '@kit/next/route-helpers';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||||
|
|
||||||
|
const CourseRegisterSchema = z.object({
|
||||||
|
courseId: requiredString('Kurs-ID'),
|
||||||
|
firstName: requiredString('Vorname'),
|
||||||
|
lastName: requiredString('Nachname'),
|
||||||
|
email: emailSchema,
|
||||||
|
phone: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { courseId, firstName, lastName, email, phone } = body;
|
const parsed = CourseRegisterSchema.safeParse(body);
|
||||||
|
|
||||||
if (!courseId || !firstName || !lastName || !email) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return apiError(parsed.error.issues[0]?.message ?? 'Ungültige Eingabe');
|
||||||
{ error: 'Kurs-ID, Vorname, Nachname und E-Mail sind erforderlich' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
const { courseId, firstName, lastName, email, phone } = parsed.data;
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Ungültige E-Mail-Adresse' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = getSupabaseServerAdminClient();
|
const supabase = getSupabaseServerAdminClient();
|
||||||
|
|
||||||
@@ -41,21 +47,15 @@ export async function POST(request: Request) {
|
|||||||
{ error, context: 'course-register-insert' },
|
{ error, context: 'course-register-insert' },
|
||||||
'[course-register] Insert error',
|
'[course-register] Insert error',
|
||||||
);
|
);
|
||||||
return NextResponse.json(
|
return apiError('Anmeldung fehlgeschlagen', 500);
|
||||||
{ error: 'Anmeldung fehlgeschlagen' },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return apiSuccess({ message: 'Anmeldung erfolgreich' });
|
||||||
success: true,
|
|
||||||
message: 'Anmeldung erfolgreich',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(
|
logger.error(
|
||||||
{ error: err, context: 'course-register' },
|
{ error: err, context: 'course-register' },
|
||||||
'[course-register] Error',
|
'[course-register] Error',
|
||||||
);
|
);
|
||||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
|
return apiError('Serverfehler', 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,36 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import * as z from 'zod';
|
||||||
|
|
||||||
|
import {
|
||||||
|
apiError,
|
||||||
|
apiSuccess,
|
||||||
|
emailSchema,
|
||||||
|
requiredString,
|
||||||
|
} from '@kit/next/route-helpers';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||||
|
|
||||||
|
const EventRegisterSchema = z.object({
|
||||||
|
eventId: requiredString('Event-ID'),
|
||||||
|
firstName: requiredString('Vorname'),
|
||||||
|
lastName: requiredString('Nachname'),
|
||||||
|
email: emailSchema,
|
||||||
|
phone: z.string().optional(),
|
||||||
|
dateOfBirth: z.string().optional(),
|
||||||
|
parentName: z.string().optional(),
|
||||||
|
parentPhone: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
const parsed = EventRegisterSchema.safeParse(body);
|
||||||
|
|
||||||
|
if (!parsed.success) {
|
||||||
|
return apiError(parsed.error.issues[0]?.message ?? 'Ungültige Eingabe');
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
eventId,
|
eventId,
|
||||||
firstName,
|
firstName,
|
||||||
@@ -17,21 +40,7 @@ export async function POST(request: Request) {
|
|||||||
dateOfBirth,
|
dateOfBirth,
|
||||||
parentName,
|
parentName,
|
||||||
parentPhone,
|
parentPhone,
|
||||||
} = body;
|
} = parsed.data;
|
||||||
|
|
||||||
if (!eventId || !firstName || !lastName || !email) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Event-ID, Vorname, Nachname und E-Mail sind erforderlich' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Ungültige E-Mail-Adresse' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = getSupabaseServerAdminClient();
|
const supabase = getSupabaseServerAdminClient();
|
||||||
|
|
||||||
@@ -53,21 +62,15 @@ export async function POST(request: Request) {
|
|||||||
{ error, context: 'event-register-insert' },
|
{ error, context: 'event-register-insert' },
|
||||||
'[event-register] Insert error',
|
'[event-register] Insert error',
|
||||||
);
|
);
|
||||||
return NextResponse.json(
|
return apiError('Anmeldung fehlgeschlagen', 500);
|
||||||
{ error: 'Anmeldung fehlgeschlagen' },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return apiSuccess({ message: 'Anmeldung erfolgreich' });
|
||||||
success: true,
|
|
||||||
message: 'Anmeldung erfolgreich',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(
|
logger.error(
|
||||||
{ error: err, context: 'event-register' },
|
{ error: err, context: 'event-register' },
|
||||||
'[event-register] Error',
|
'[event-register] Error',
|
||||||
);
|
);
|
||||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
|
return apiError('Serverfehler', 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,38 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import * as z from 'zod';
|
||||||
|
|
||||||
|
import {
|
||||||
|
apiError,
|
||||||
|
apiSuccess,
|
||||||
|
emailSchema,
|
||||||
|
requiredString,
|
||||||
|
} from '@kit/next/route-helpers';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||||
|
|
||||||
|
const MembershipApplySchema = z.object({
|
||||||
|
accountId: requiredString('Konto-ID'),
|
||||||
|
firstName: requiredString('Vorname'),
|
||||||
|
lastName: requiredString('Nachname'),
|
||||||
|
email: emailSchema,
|
||||||
|
phone: z.string().optional(),
|
||||||
|
street: z.string().optional(),
|
||||||
|
postalCode: z.string().optional(),
|
||||||
|
city: z.string().optional(),
|
||||||
|
dateOfBirth: z.string().optional(),
|
||||||
|
message: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
const parsed = MembershipApplySchema.safeParse(body);
|
||||||
|
|
||||||
|
if (!parsed.success) {
|
||||||
|
return apiError(parsed.error.issues[0]?.message ?? 'Ungültige Eingabe');
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
accountId,
|
accountId,
|
||||||
firstName,
|
firstName,
|
||||||
@@ -19,23 +44,7 @@ export async function POST(request: Request) {
|
|||||||
city,
|
city,
|
||||||
dateOfBirth,
|
dateOfBirth,
|
||||||
message,
|
message,
|
||||||
} = body;
|
} = parsed.data;
|
||||||
|
|
||||||
if (!accountId || !firstName || !lastName || !email) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error: 'Konto-ID, Vorname, Nachname und E-Mail sind erforderlich',
|
|
||||||
},
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Ungültige E-Mail-Adresse' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = getSupabaseServerAdminClient();
|
const supabase = getSupabaseServerAdminClient();
|
||||||
|
|
||||||
@@ -58,21 +67,15 @@ export async function POST(request: Request) {
|
|||||||
{ error, context: 'membership-apply-insert' },
|
{ error, context: 'membership-apply-insert' },
|
||||||
'[membership-apply] Insert error',
|
'[membership-apply] Insert error',
|
||||||
);
|
);
|
||||||
return NextResponse.json(
|
return apiError('Bewerbung fehlgeschlagen', 500);
|
||||||
{ error: 'Bewerbung fehlgeschlagen' },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return apiSuccess({ message: 'Bewerbung erfolgreich eingereicht' });
|
||||||
success: true,
|
|
||||||
message: 'Bewerbung erfolgreich eingereicht',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(
|
logger.error(
|
||||||
{ error: err, context: 'membership-apply' },
|
{ error: err, context: 'membership-apply' },
|
||||||
'[membership-apply] Error',
|
'[membership-apply] Error',
|
||||||
);
|
);
|
||||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
|
return apiError('Serverfehler', 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,33 @@
|
|||||||
import { NextResponse } from 'next/server';
|
|
||||||
|
|
||||||
import { createClient } from '@supabase/supabase-js';
|
import { createClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
import * as z from 'zod';
|
||||||
|
|
||||||
|
import {
|
||||||
|
apiError,
|
||||||
|
apiSuccess,
|
||||||
|
emailSchema,
|
||||||
|
requiredString,
|
||||||
|
} from '@kit/next/route-helpers';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
|
|
||||||
|
const NewsletterSchema = z.object({
|
||||||
|
accountId: requiredString('accountId'),
|
||||||
|
email: emailSchema,
|
||||||
|
name: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { accountId, email, name } = body;
|
const parsed = NewsletterSchema.safeParse(body);
|
||||||
|
|
||||||
if (!accountId || !email) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return apiError(parsed.error.issues[0]?.message ?? 'Ungültige Eingabe');
|
||||||
{ error: 'accountId und email sind erforderlich' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate email format
|
const { accountId, email, name } = parsed.data;
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Ungültige E-Mail-Adresse' },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = createClient(
|
const supabase = createClient(
|
||||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||||
@@ -49,18 +52,12 @@ export async function POST(request: Request) {
|
|||||||
{ error, context: 'newsletter-subscription' },
|
{ error, context: 'newsletter-subscription' },
|
||||||
'[newsletter] Subscription error',
|
'[newsletter] Subscription error',
|
||||||
);
|
);
|
||||||
return NextResponse.json(
|
return apiError('Anmeldung fehlgeschlagen', 500);
|
||||||
{ error: 'Anmeldung fehlgeschlagen' },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return apiSuccess({ message: 'Erfolgreich angemeldet' });
|
||||||
success: true,
|
|
||||||
message: 'Erfolgreich angemeldet',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error({ error: err, context: 'newsletter' }, '[newsletter] Error');
|
logger.error({ error: err, context: 'newsletter' }, '[newsletter] Error');
|
||||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
|
return apiError('Serverfehler', 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,7 +64,14 @@ export const generateSepaXml = authActionClient
|
|||||||
creditorId: input.creditorId,
|
creditorId: input.creditorId,
|
||||||
});
|
});
|
||||||
logger.info({ name: 'finance.generateSepaXml' }, 'SEPA XML generated');
|
logger.info({ name: 'finance.generateSepaXml' }, 'SEPA XML generated');
|
||||||
return { success: true, xml: result };
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
content: result,
|
||||||
|
filename: `sepa-einzug-${new Date().toISOString().split('T')[0]}.xml`,
|
||||||
|
mimeType: 'application/xml',
|
||||||
|
},
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
export const createInvoice = authActionClient
|
export const createInvoice = authActionClient
|
||||||
@@ -99,5 +106,5 @@ export const populateBatchFromMembers = authActionClient
|
|||||||
{ name: 'sepa.populate', count: result.addedCount },
|
{ name: 'sepa.populate', count: result.addedCount },
|
||||||
'Populated',
|
'Populated',
|
||||||
);
|
);
|
||||||
return { success: true, addedCount: result.addedCount };
|
return { success: true, data: { addedCount: result.addedCount } };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -20,14 +20,43 @@ export function createFinanceApi(client: SupabaseClient<Database>) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
// --- SEPA Batches ---
|
// --- SEPA Batches ---
|
||||||
async listBatches(accountId: string) {
|
async listBatches(
|
||||||
const { data, error } = await client
|
accountId: string,
|
||||||
|
opts?: {
|
||||||
|
search?: string;
|
||||||
|
status?: string;
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const page = opts?.page ?? 1;
|
||||||
|
const pageSize = opts?.pageSize ?? 25;
|
||||||
|
|
||||||
|
let query = client
|
||||||
.from('sepa_batches')
|
.from('sepa_batches')
|
||||||
.select('*')
|
.select('*', { count: 'exact' })
|
||||||
.eq('account_id', accountId)
|
.eq('account_id', accountId)
|
||||||
.order('created_at', { ascending: false });
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
|
if (opts?.search) {
|
||||||
|
query = query.ilike('description', `%${opts.search}%`);
|
||||||
|
}
|
||||||
|
if (opts?.status) {
|
||||||
|
query = query.eq('status', opts.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.range((page - 1) * pageSize, page * pageSize - 1);
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
return data ?? [];
|
|
||||||
|
return {
|
||||||
|
data: data ?? [],
|
||||||
|
total: count ?? 0,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async getBatch(batchId: string) {
|
async getBatch(batchId: string) {
|
||||||
@@ -148,20 +177,48 @@ export function createFinanceApi(client: SupabaseClient<Database>) {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// --- Invoices ---
|
// --- Invoices ---
|
||||||
async listInvoices(accountId: string, opts?: { status?: string }) {
|
async listInvoices(
|
||||||
|
accountId: string,
|
||||||
|
opts?: {
|
||||||
|
search?: string;
|
||||||
|
status?: string;
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const page = opts?.page ?? 1;
|
||||||
|
const pageSize = opts?.pageSize ?? 25;
|
||||||
|
|
||||||
let query = client
|
let query = client
|
||||||
.from('invoices')
|
.from('invoices')
|
||||||
.select('*')
|
.select('*', { count: 'exact' })
|
||||||
.eq('account_id', accountId)
|
.eq('account_id', accountId)
|
||||||
.order('issue_date', { ascending: false });
|
.order('issue_date', { ascending: false });
|
||||||
if (opts?.status)
|
|
||||||
|
if (opts?.status) {
|
||||||
query = query.eq(
|
query = query.eq(
|
||||||
'status',
|
'status',
|
||||||
opts.status as Database['public']['Enums']['invoice_status'],
|
opts.status as Database['public']['Enums']['invoice_status'],
|
||||||
);
|
);
|
||||||
const { data, error } = await query;
|
}
|
||||||
|
if (opts?.search) {
|
||||||
|
query = query.or(
|
||||||
|
`invoice_number.ilike.%${opts.search}%,recipient_name.ilike.%${opts.search}%`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.range((page - 1) * pageSize, page * pageSize - 1);
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
return data ?? [];
|
|
||||||
|
return {
|
||||||
|
data: data ?? [],
|
||||||
|
total: count ?? 0,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async createInvoice(input: CreateInvoiceInput, userId: string) {
|
async createInvoice(input: CreateInvoiceInput, userId: string) {
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@kit/ui/alert-dialog';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||||
import {
|
import {
|
||||||
@@ -17,7 +28,7 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@kit/ui/form';
|
} from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import { CreateMemberSchema } from '../schema/member.schema';
|
import { CreateMemberSchema } from '../schema/member.schema';
|
||||||
import { createMember } from '../server/actions/member-actions';
|
import { createMember } from '../server/actions/member-actions';
|
||||||
@@ -28,12 +39,19 @@ interface Props {
|
|||||||
duesCategories: Array<{ id: string; name: string; amount: number }>;
|
duesCategories: Array<{ id: string; name: string; amount: number }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DuplicateEntry {
|
||||||
|
field: string;
|
||||||
|
message: string;
|
||||||
|
id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export function CreateMemberForm({
|
export function CreateMemberForm({
|
||||||
accountId,
|
accountId,
|
||||||
account,
|
account,
|
||||||
duesCategories,
|
duesCategories,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const [duplicates, setDuplicates] = useState<DuplicateEntry[]>([]);
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
resolver: zodResolver(CreateMemberSchema),
|
resolver: zodResolver(CreateMemberSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -59,15 +77,16 @@ export function CreateMemberForm({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { execute, isPending } = useAction(createMember, {
|
const { execute, isPending } = useActionWithToast(createMember, {
|
||||||
onSuccess: ({ data }) => {
|
successMessage: 'Mitglied erfolgreich erstellt',
|
||||||
if (data?.success) {
|
errorMessage: 'Fehler beim Erstellen',
|
||||||
toast.success('Mitglied erfolgreich erstellt');
|
onSuccess: () => {
|
||||||
router.push(`/home/${account}/members-cms`);
|
router.push(`/home/${account}/members-cms`);
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onError: ({ error }) => {
|
onError: (_error, data) => {
|
||||||
toast.error(error.serverError ?? 'Fehler beim Erstellen');
|
if (data?.validationErrors) {
|
||||||
|
setDuplicates(data.validationErrors as DuplicateEntry[]);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -586,6 +605,37 @@ export function CreateMemberForm({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<AlertDialog
|
||||||
|
open={duplicates.length > 0}
|
||||||
|
onOpenChange={() => setDuplicates([])}
|
||||||
|
>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Mögliches Duplikat gefunden</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Es wurden ähnliche Mitglieder gefunden:
|
||||||
|
<ul className="mt-2 list-inside list-disc">
|
||||||
|
{duplicates.map((d, i) => (
|
||||||
|
<li key={d.id ?? i}>{d.message}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={() => {
|
||||||
|
router.push(
|
||||||
|
`/home/${account}/members-cms/${duplicates[0]?.id}`,
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Zum bestehenden Mitglied
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
</Form>
|
</Form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,20 @@ import { useCallback } from 'react';
|
|||||||
|
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
import { Download } from 'lucide-react';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { formatDate } from '@kit/shared/dates';
|
import { formatDate } from '@kit/shared/dates';
|
||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useFileDownloadAction } from '@kit/ui/use-file-download-action';
|
||||||
|
|
||||||
import { STATUS_LABELS, getMemberStatusColor } from '../lib/member-utils';
|
import { STATUS_LABELS, getMemberStatusColor } from '../lib/member-utils';
|
||||||
|
import {
|
||||||
|
exportMembers,
|
||||||
|
exportMembersExcel,
|
||||||
|
} from '../server/actions/member-actions';
|
||||||
|
|
||||||
interface MembersDataTableProps {
|
interface MembersDataTableProps {
|
||||||
data: Array<Record<string, unknown>>;
|
data: Array<Record<string, unknown>>;
|
||||||
@@ -21,6 +25,7 @@ interface MembersDataTableProps {
|
|||||||
page: number;
|
page: number;
|
||||||
pageSize: number;
|
pageSize: number;
|
||||||
account: string;
|
account: string;
|
||||||
|
accountId: string;
|
||||||
duesCategories: Array<{ id: string; name: string }>;
|
duesCategories: Array<{ id: string; name: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,6 +43,7 @@ export function MembersDataTable({
|
|||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
account,
|
account,
|
||||||
|
accountId,
|
||||||
duesCategories,
|
duesCategories,
|
||||||
}: MembersDataTableProps) {
|
}: MembersDataTableProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -102,6 +108,20 @@ export function MembersDataTable({
|
|||||||
[router, account],
|
[router, account],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const { execute: execCsvExport, isPending: isCsvExporting } =
|
||||||
|
useFileDownloadAction(exportMembers, {
|
||||||
|
successMessage: 'CSV-Export heruntergeladen',
|
||||||
|
errorMessage: 'CSV-Export fehlgeschlagen',
|
||||||
|
});
|
||||||
|
|
||||||
|
const { execute: execExcelExport, isPending: isExcelExporting } =
|
||||||
|
useFileDownloadAction(exportMembersExcel, {
|
||||||
|
successMessage: 'Excel-Export heruntergeladen',
|
||||||
|
errorMessage: 'Excel-Export fehlgeschlagen',
|
||||||
|
});
|
||||||
|
|
||||||
|
const isExporting = isCsvExporting || isExcelExporting;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Toolbar */}
|
{/* Toolbar */}
|
||||||
@@ -137,6 +157,34 @@ export function MembersDataTable({
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={isExporting}
|
||||||
|
onClick={() =>
|
||||||
|
execCsvExport({
|
||||||
|
accountId,
|
||||||
|
status: currentStatus || undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Download className="mr-1 h-4 w-4" />
|
||||||
|
CSV
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={isExporting}
|
||||||
|
onClick={() =>
|
||||||
|
execExcelExport({
|
||||||
|
accountId,
|
||||||
|
status: currentStatus || undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Download className="mr-1 h-4 w-4" />
|
||||||
|
Excel
|
||||||
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
data-test="members-new-btn"
|
data-test="members-new-btn"
|
||||||
|
|||||||
@@ -30,6 +30,26 @@ export const createMember = authActionClient
|
|||||||
const api = createMemberManagementApi(client);
|
const api = createMemberManagementApi(client);
|
||||||
const userId = ctx.user.id;
|
const userId = ctx.user.id;
|
||||||
|
|
||||||
|
// Check for duplicates before creating
|
||||||
|
const duplicates = await api.checkDuplicate(
|
||||||
|
input.accountId,
|
||||||
|
input.firstName,
|
||||||
|
input.lastName,
|
||||||
|
input.dateOfBirth,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (duplicates.length > 0) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Mögliche Duplikate gefunden',
|
||||||
|
validationErrors: duplicates.map((d: Record<string, unknown>) => ({
|
||||||
|
field: 'name',
|
||||||
|
message: `${d.first_name} ${d.last_name}${d.member_number ? ` (Nr. ${d.member_number})` : ''}`,
|
||||||
|
id: String(d.id),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
logger.info({ name: 'member.create' }, 'Creating member...');
|
logger.info({ name: 'member.create' }, 'Creating member...');
|
||||||
const result = await api.createMember(input, userId);
|
const result = await api.createMember(input, userId);
|
||||||
logger.info({ name: 'member.create' }, 'Member created');
|
logger.info({ name: 'member.create' }, 'Member created');
|
||||||
@@ -217,7 +237,14 @@ export const exportMembers = authActionClient
|
|||||||
const csv = await api.exportMembersCsv(input.accountId, {
|
const csv = await api.exportMembersCsv(input.accountId, {
|
||||||
status: input.status,
|
status: input.status,
|
||||||
});
|
});
|
||||||
return { success: true, csv };
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
content: csv,
|
||||||
|
filename: `mitglieder_${new Date().toISOString().split('T')[0]}.csv`,
|
||||||
|
mimeType: 'text/csv',
|
||||||
|
},
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// Gap 5: Department assignments
|
// Gap 5: Department assignments
|
||||||
@@ -248,11 +275,14 @@ export const exportMembersExcel = authActionClient
|
|||||||
const buffer = await api.exportMembersExcel(input.accountId, {
|
const buffer = await api.exportMembersExcel(input.accountId, {
|
||||||
status: input.status,
|
status: input.status,
|
||||||
});
|
});
|
||||||
// Return base64 for client-side download
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
base64: buffer.toString('base64'),
|
data: {
|
||||||
filename: `mitglieder_${new Date().toISOString().split('T')[0]}.xlsx`,
|
content: buffer.toString('base64'),
|
||||||
|
filename: `mitglieder_${new Date().toISOString().split('T')[0]}.xlsx`,
|
||||||
|
mimeType:
|
||||||
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -295,8 +325,11 @@ export const generateMemberCards = authActionClient
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
base64: buffer.toString('base64'),
|
data: {
|
||||||
filename: `mitgliedsausweise_${new Date().toISOString().split('T')[0]}.pdf`,
|
content: buffer.toString('base64'),
|
||||||
|
filename: `mitgliedsausweise_${new Date().toISOString().split('T')[0]}.pdf`,
|
||||||
|
mimeType: 'application/pdf',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"./schema/*": "./src/schema/*.ts",
|
"./schema/*": "./src/schema/*.ts",
|
||||||
"./hooks/*": "./src/hooks/*.ts",
|
"./hooks/*": "./src/hooks/*.ts",
|
||||||
"./components": "./src/components/index.ts",
|
"./components": "./src/components/index.ts",
|
||||||
|
"./actions/*": "./src/server/actions/*.ts",
|
||||||
"./services/*": "./src/server/services/*.ts"
|
"./services/*": "./src/server/services/*.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -22,14 +22,14 @@ export const createModule = authActionClient
|
|||||||
'Creating module...',
|
'Creating module...',
|
||||||
);
|
);
|
||||||
|
|
||||||
const module = await api.modules.createModule(input);
|
const data = await api.modules.createModule(input);
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
{ name: 'modules.create', moduleId: module.id },
|
{ name: 'modules.create', moduleId: data.id },
|
||||||
'Module created',
|
'Module created',
|
||||||
);
|
);
|
||||||
|
|
||||||
return { success: true, module };
|
return { success: true, data };
|
||||||
});
|
});
|
||||||
|
|
||||||
export const updateModule = authActionClient
|
export const updateModule = authActionClient
|
||||||
@@ -44,14 +44,14 @@ export const updateModule = authActionClient
|
|||||||
'Updating module...',
|
'Updating module...',
|
||||||
);
|
);
|
||||||
|
|
||||||
const module = await api.modules.updateModule(input);
|
const data = await api.modules.updateModule(input);
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
{ name: 'modules.update', moduleId: module.id },
|
{ name: 'modules.update', moduleId: data.id },
|
||||||
'Module updated',
|
'Module updated',
|
||||||
);
|
);
|
||||||
|
|
||||||
return { success: true, module };
|
return { success: true, data };
|
||||||
});
|
});
|
||||||
|
|
||||||
export const deleteModule = authActionClient
|
export const deleteModule = authActionClient
|
||||||
|
|||||||
@@ -52,7 +52,11 @@ export const createRecord = authActionClient
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (!validation.success) {
|
if (!validation.success) {
|
||||||
return { success: false, errors: validation.errors };
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Validierungsfehler',
|
||||||
|
validationErrors: validation.errors,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -72,7 +76,7 @@ export const createRecord = authActionClient
|
|||||||
newData: input.data as Record<string, unknown>,
|
newData: input.data as Record<string, unknown>,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true, record };
|
return { success: true, data: record };
|
||||||
});
|
});
|
||||||
|
|
||||||
export const updateRecord = authActionClient
|
export const updateRecord = authActionClient
|
||||||
@@ -86,6 +90,40 @@ export const updateRecord = authActionClient
|
|||||||
// Get existing record for audit
|
// Get existing record for audit
|
||||||
const existing = await api.records.getRecord(input.recordId);
|
const existing = await api.records.getRecord(input.recordId);
|
||||||
|
|
||||||
|
// Validate data against field definitions
|
||||||
|
const moduleId = existing.module_id as string;
|
||||||
|
const moduleWithFields = await api.modules.getModuleWithFields(moduleId);
|
||||||
|
|
||||||
|
if (!moduleWithFields) {
|
||||||
|
throw new Error('Module not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const fields = (
|
||||||
|
moduleWithFields as unknown as {
|
||||||
|
fields: Array<{
|
||||||
|
name: string;
|
||||||
|
field_type: string;
|
||||||
|
is_required: boolean;
|
||||||
|
min_value?: number | null;
|
||||||
|
max_value?: number | null;
|
||||||
|
max_length?: number | null;
|
||||||
|
regex_pattern?: string | null;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
).fields;
|
||||||
|
const validation = validateRecordData(
|
||||||
|
input.data as Record<string, unknown>,
|
||||||
|
fields as Parameters<typeof validateRecordData>[1],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!validation.success) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Validierungsfehler',
|
||||||
|
validationErrors: validation.errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
{ name: 'records.update', recordId: input.recordId },
|
{ name: 'records.update', recordId: input.recordId },
|
||||||
'Updating record...',
|
'Updating record...',
|
||||||
@@ -104,7 +142,7 @@ export const updateRecord = authActionClient
|
|||||||
newData: input.data as Record<string, unknown>,
|
newData: input.data as Record<string, unknown>,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true, record };
|
return { success: true, data: record };
|
||||||
});
|
});
|
||||||
|
|
||||||
export const deleteRecord = authActionClient
|
export const deleteRecord = authActionClient
|
||||||
@@ -156,5 +194,5 @@ export const lockRecord = authActionClient
|
|||||||
newData: { locked: input.lock },
|
newData: { locked: input.lock },
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true, record };
|
return { success: true, data: record };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -26,14 +26,35 @@ export function createNewsletterApi(client: SupabaseClient<Database>) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
// --- Templates ---
|
// --- Templates ---
|
||||||
async listTemplates(accountId: string) {
|
async listTemplates(
|
||||||
const { data, error } = await client
|
accountId: string,
|
||||||
|
opts?: { search?: string; page?: number; pageSize?: number },
|
||||||
|
) {
|
||||||
|
const page = opts?.page ?? 1;
|
||||||
|
const pageSize = opts?.pageSize ?? 25;
|
||||||
|
|
||||||
|
let query = client
|
||||||
.from('newsletter_templates')
|
.from('newsletter_templates')
|
||||||
.select('*')
|
.select('*', { count: 'exact' })
|
||||||
.eq('account_id', accountId)
|
.eq('account_id', accountId)
|
||||||
.order('name');
|
.order('name');
|
||||||
|
|
||||||
|
if (opts?.search) {
|
||||||
|
query = query.ilike('name', `%${opts.search}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.range((page - 1) * pageSize, page * pageSize - 1);
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
return data ?? [];
|
|
||||||
|
return {
|
||||||
|
data: data ?? [],
|
||||||
|
total: count ?? 0,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async createTemplate(input: {
|
async createTemplate(input: {
|
||||||
@@ -61,14 +82,43 @@ export function createNewsletterApi(client: SupabaseClient<Database>) {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// --- Newsletters ---
|
// --- Newsletters ---
|
||||||
async listNewsletters(accountId: string) {
|
async listNewsletters(
|
||||||
const { data, error } = await client
|
accountId: string,
|
||||||
|
opts?: {
|
||||||
|
search?: string;
|
||||||
|
status?: string;
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const page = opts?.page ?? 1;
|
||||||
|
const pageSize = opts?.pageSize ?? 25;
|
||||||
|
|
||||||
|
let query = client
|
||||||
.from('newsletters')
|
.from('newsletters')
|
||||||
.select('*')
|
.select('*', { count: 'exact' })
|
||||||
.eq('account_id', accountId)
|
.eq('account_id', accountId)
|
||||||
.order('created_at', { ascending: false });
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
|
if (opts?.search) {
|
||||||
|
query = query.ilike('subject', `%${opts.search}%`);
|
||||||
|
}
|
||||||
|
if (opts?.status) {
|
||||||
|
query = query.eq('status', opts.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
query = query.range((page - 1) * pageSize, page * pageSize - 1);
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
return data ?? [];
|
|
||||||
|
return {
|
||||||
|
data: data ?? [],
|
||||||
|
total: count ?? 0,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async createNewsletter(input: CreateNewsletterInput, userId: string) {
|
async createNewsletter(input: CreateNewsletterInput, userId: string) {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -17,7 +16,7 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@kit/ui/form';
|
} from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import { CreatePageSchema } from '../schema/site.schema';
|
import { CreatePageSchema } from '../schema/site.schema';
|
||||||
import { createPage } from '../server/actions/site-builder-actions';
|
import { createPage } from '../server/actions/site-builder-actions';
|
||||||
@@ -51,15 +50,14 @@ export function CreatePageForm({ accountId, account }: Props) {
|
|||||||
.replace(/ß/g, 'ss')
|
.replace(/ß/g, 'ss')
|
||||||
.replace(/^-|-$/g, '');
|
.replace(/^-|-$/g, '');
|
||||||
|
|
||||||
const { execute, isPending } = useAction(createPage, {
|
const { execute, isPending } = useActionWithToast(createPage, {
|
||||||
onSuccess: ({ data }) => {
|
successMessage: 'Seite erstellt — Editor wird geöffnet',
|
||||||
if (data?.success && data.data) {
|
errorMessage: 'Fehler beim Erstellen',
|
||||||
toast.success('Seite erstellt — Editor wird geöffnet');
|
onSuccess: (data) => {
|
||||||
|
if (data?.data) {
|
||||||
router.push(`/home/${account}/site-builder/${data.data.id}/edit`);
|
router.push(`/home/${account}/site-builder/${data.data.id}/edit`);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onError: ({ error }) =>
|
|
||||||
toast.error(error.serverError ?? 'Fehler beim Erstellen'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -17,7 +16,7 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@kit/ui/form';
|
} from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import { CreatePostSchema } from '../schema/site.schema';
|
import { CreatePostSchema } from '../schema/site.schema';
|
||||||
import { createPost } from '../server/actions/site-builder-actions';
|
import { createPost } from '../server/actions/site-builder-actions';
|
||||||
@@ -53,12 +52,11 @@ export function CreatePostForm({ accountId, account }: Props) {
|
|||||||
.replace(/ü/g, 'ue')
|
.replace(/ü/g, 'ue')
|
||||||
.replace(/ß/g, 'ss');
|
.replace(/ß/g, 'ss');
|
||||||
|
|
||||||
const { execute, isPending } = useAction(createPost, {
|
const { execute, isPending } = useActionWithToast(createPost, {
|
||||||
|
successMessage: 'Beitrag erstellt',
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success('Beitrag erstellt');
|
|
||||||
router.push(`/home/${account}/site-builder/posts`);
|
router.push(`/home/${account}/site-builder/posts`);
|
||||||
},
|
},
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -3,9 +3,7 @@
|
|||||||
import { Puck } from '@measured/puck';
|
import { Puck } from '@measured/puck';
|
||||||
|
|
||||||
import '@measured/puck/puck.css';
|
import '@measured/puck/puck.css';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import { toast } from '@kit/ui/sonner';
|
|
||||||
|
|
||||||
import { clubPuckConfig } from '../config/puck-config';
|
import { clubPuckConfig } from '../config/puck-config';
|
||||||
import { publishPage } from '../server/actions/site-builder-actions';
|
import { publishPage } from '../server/actions/site-builder-actions';
|
||||||
@@ -17,9 +15,8 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function SiteEditor({ pageId, accountId, initialData }: Props) {
|
export function SiteEditor({ pageId, accountId, initialData }: Props) {
|
||||||
const { execute: execPublish } = useAction(publishPage, {
|
const { execute: execPublish } = useActionWithToast(publishPage, {
|
||||||
onSuccess: () => toast.success('Seite veröffentlicht'),
|
successMessage: 'Seite veröffentlicht',
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const PuckAny = Puck as any;
|
const PuckAny = Puck as any;
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -17,7 +16,7 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@kit/ui/form';
|
} from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import { SiteSettingsSchema } from '../schema/site.schema';
|
import { SiteSettingsSchema } from '../schema/site.schema';
|
||||||
import { updateSiteSettings } from '../server/actions/site-builder-actions';
|
import { updateSiteSettings } from '../server/actions/site-builder-actions';
|
||||||
@@ -50,12 +49,11 @@ export function SiteSettingsForm({ accountId, account, settings }: Props) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { execute, isPending } = useAction(updateSiteSettings, {
|
const { execute, isPending } = useActionWithToast(updateSiteSettings, {
|
||||||
|
successMessage: 'Einstellungen gespeichert',
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success('Einstellungen gespeichert');
|
|
||||||
router.refresh();
|
router.refresh();
|
||||||
},
|
},
|
||||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import React from 'react';
|
|||||||
import type { Config } from '@measured/puck';
|
import type { Config } from '@measured/puck';
|
||||||
|
|
||||||
import { formatDate, formatMonthShort } from '@kit/shared/dates';
|
import { formatDate, formatMonthShort } from '@kit/shared/dates';
|
||||||
|
import { toast } from '@kit/ui/sonner';
|
||||||
|
|
||||||
import { useSiteData } from '../context/site-data-context';
|
import { useSiteData } from '../context/site-data-context';
|
||||||
|
|
||||||
@@ -71,13 +72,13 @@ const ContactFormBlock = ({
|
|||||||
});
|
});
|
||||||
const result = await res.json();
|
const result = await res.json();
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
alert('Nachricht erfolgreich gesendet!');
|
toast.success('Nachricht erfolgreich gesendet!');
|
||||||
form.reset();
|
form.reset();
|
||||||
} else {
|
} else {
|
||||||
alert(result.error || 'Fehler beim Senden');
|
toast.error(result.error || 'Fehler beim Senden');
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
alert('Verbindungsfehler');
|
toast.error('Verbindungsfehler');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -219,13 +220,15 @@ const NewsletterSignupBlock = ({
|
|||||||
});
|
});
|
||||||
const result = await res.json();
|
const result = await res.json();
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
alert('Erfolgreich angemeldet! Bitte bestätigen Sie Ihre E-Mail.');
|
toast.success(
|
||||||
|
'Erfolgreich angemeldet! Bitte bestätigen Sie Ihre E-Mail.',
|
||||||
|
);
|
||||||
form.reset();
|
form.reset();
|
||||||
} else {
|
} else {
|
||||||
alert(result.error || 'Fehler bei der Anmeldung');
|
toast.error(result.error || 'Fehler bei der Anmeldung');
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
alert('Verbindungsfehler');
|
toast.error('Verbindungsfehler');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -399,6 +402,8 @@ const EventListBlock = ({
|
|||||||
email: '',
|
email: '',
|
||||||
phone: '',
|
phone: '',
|
||||||
dateOfBirth: '',
|
dateOfBirth: '',
|
||||||
|
parentName: '',
|
||||||
|
parentPhone: '',
|
||||||
});
|
});
|
||||||
const [submitting, setSubmitting] = React.useState(false);
|
const [submitting, setSubmitting] = React.useState(false);
|
||||||
const [successId, setSuccessId] = React.useState<string | null>(null);
|
const [successId, setSuccessId] = React.useState<string | null>(null);
|
||||||
@@ -426,6 +431,8 @@ const EventListBlock = ({
|
|||||||
email: formData.email,
|
email: formData.email,
|
||||||
phone: formData.phone || undefined,
|
phone: formData.phone || undefined,
|
||||||
dateOfBirth: formData.dateOfBirth || undefined,
|
dateOfBirth: formData.dateOfBirth || undefined,
|
||||||
|
parentName: formData.parentName || undefined,
|
||||||
|
parentPhone: formData.parentPhone || undefined,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
const result = await res.json();
|
const result = await res.json();
|
||||||
@@ -438,6 +445,8 @@ const EventListBlock = ({
|
|||||||
email: '',
|
email: '',
|
||||||
phone: '',
|
phone: '',
|
||||||
dateOfBirth: '',
|
dateOfBirth: '',
|
||||||
|
parentName: '',
|
||||||
|
parentPhone: '',
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
setErrorMsg(result.error || 'Anmeldung fehlgeschlagen.');
|
setErrorMsg(result.error || 'Anmeldung fehlgeschlagen.');
|
||||||
@@ -574,6 +583,29 @@ const EventListBlock = ({
|
|||||||
}
|
}
|
||||||
className="rounded-md border px-3 py-2 text-sm"
|
className="rounded-md border px-3 py-2 text-sm"
|
||||||
/>
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Name Erziehungsberechtigter"
|
||||||
|
value={formData.parentName}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((p) => ({
|
||||||
|
...p,
|
||||||
|
parentName: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="rounded-md border px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="Telefon Erziehungsberechtigter"
|
||||||
|
type="tel"
|
||||||
|
value={formData.parentPhone}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((p) => ({
|
||||||
|
...p,
|
||||||
|
parentPhone: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="rounded-md border px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
{errorMsg && (
|
{errorMsg && (
|
||||||
<p className="mt-2 text-sm text-red-600">{errorMsg}</p>
|
<p className="mt-2 text-sm text-red-600">{errorMsg}</p>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useAction } from 'next-safe-action/hooks';
|
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -17,7 +16,7 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@kit/ui/form';
|
} from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import { CreateMemberClubSchema } from '../schema/verband.schema';
|
import { CreateMemberClubSchema } from '../schema/verband.schema';
|
||||||
import { createClub } from '../server/actions/verband-actions';
|
import { createClub } from '../server/actions/verband-actions';
|
||||||
@@ -62,15 +61,11 @@ export function CreateClubForm({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { execute, isPending } = useAction(createClub, {
|
const { execute, isPending } = useActionWithToast(createClub, {
|
||||||
onSuccess: ({ data }) => {
|
successMessage: isEdit ? 'Verein aktualisiert' : 'Verein erstellt',
|
||||||
if (data?.success) {
|
errorMessage: 'Fehler beim Speichern',
|
||||||
toast.success(isEdit ? 'Verein aktualisiert' : 'Verein erstellt');
|
onSuccess: () => {
|
||||||
router.push(`/home/${account}/verband/clubs`);
|
router.push(`/home/${account}/verband/clubs`);
|
||||||
}
|
|
||||||
},
|
|
||||||
onError: ({ error }) => {
|
|
||||||
toast.error(error.serverError ?? 'Fehler beim Speichern');
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from '@kit/ui/dialog';
|
} from '@kit/ui/dialog';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
|
||||||
import { Textarea } from '@kit/ui/textarea';
|
import { Textarea } from '@kit/ui/textarea';
|
||||||
|
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getTransferPreview,
|
getTransferPreview,
|
||||||
@@ -90,7 +90,7 @@ export function CrossOrgMemberSearch({
|
|||||||
|
|
||||||
const { execute: executePreview } = useAction(getTransferPreview, {
|
const { execute: executePreview } = useAction(getTransferPreview, {
|
||||||
onSuccess: ({ data }) => {
|
onSuccess: ({ data }) => {
|
||||||
if (data) setPreview(data);
|
if (data?.data) setPreview(data.data);
|
||||||
setPreviewLoading(false);
|
setPreviewLoading(false);
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
@@ -98,22 +98,18 @@ export function CrossOrgMemberSearch({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { execute: executeTransfer, isPending: isTransferring } = useAction(
|
const { execute: executeTransfer, isPending: isTransferring } =
|
||||||
transferMember,
|
useActionWithToast(transferMember, {
|
||||||
{
|
successMessage: 'Mitglied erfolgreich transferiert',
|
||||||
|
errorMessage: 'Fehler beim Transfer',
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success('Mitglied erfolgreich transferiert');
|
|
||||||
setTransferTarget(null);
|
setTransferTarget(null);
|
||||||
setTargetAccountId('');
|
setTargetAccountId('');
|
||||||
setTransferReason('');
|
setTransferReason('');
|
||||||
setKeepSepa(true);
|
setKeepSepa(true);
|
||||||
setPreview(null);
|
setPreview(null);
|
||||||
},
|
},
|
||||||
onError: ({ error }) => {
|
});
|
||||||
toast.error(error.serverError ?? 'Fehler beim Transfer');
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const buildUrl = useCallback(
|
const buildUrl = useCallback(
|
||||||
(params: Record<string, string | number | null>) => {
|
(params: Record<string, string | number | null>) => {
|
||||||
|
|||||||
@@ -135,7 +135,8 @@ export const getTransferPreview = authActionClient
|
|||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
const api = createVerbandApi(client);
|
const api = createVerbandApi(client);
|
||||||
|
|
||||||
return api.getTransferPreview(input.memberId);
|
const data = await api.getTransferPreview(input.memberId);
|
||||||
|
return { success: true, data };
|
||||||
});
|
});
|
||||||
|
|
||||||
export const transferMember = authActionClient
|
export const transferMember = authActionClient
|
||||||
@@ -169,7 +170,7 @@ export const transferMember = authActionClient
|
|||||||
);
|
);
|
||||||
|
|
||||||
revalidatePath(REVALIDATE_PATH, 'page');
|
revalidatePath(REVALIDATE_PATH, 'page');
|
||||||
return { success: true, transferId };
|
return { success: true, data: { transferId } };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message =
|
const message =
|
||||||
err instanceof Error ? err.message : 'Fehler beim Transfer';
|
err instanceof Error ? err.message : 'Fehler beim Transfer';
|
||||||
@@ -202,5 +203,5 @@ export const cloneTemplate = authActionClient
|
|||||||
);
|
);
|
||||||
|
|
||||||
revalidatePath(REVALIDATE_PATH, 'page');
|
revalidatePath(REVALIDATE_PATH, 'page');
|
||||||
return { success: true, newTemplateId };
|
return { success: true, data: { newTemplateId } };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,7 +12,8 @@
|
|||||||
"exports": {
|
"exports": {
|
||||||
"./actions": "./src/actions/index.ts",
|
"./actions": "./src/actions/index.ts",
|
||||||
"./safe-action": "./src/actions/safe-action-client.ts",
|
"./safe-action": "./src/actions/safe-action-client.ts",
|
||||||
"./routes": "./src/routes/index.ts"
|
"./routes": "./src/routes/index.ts",
|
||||||
|
"./route-helpers": "./src/routes/api-helpers.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "git clean -xdf .turbo node_modules",
|
"clean": "git clean -xdf .turbo node_modules",
|
||||||
|
|||||||
28
packages/next/src/routes/api-helpers.ts
Normal file
28
packages/next/src/routes/api-helpers.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import 'server-only';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import * as z from 'zod';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared Zod schemas for public API route validation.
|
||||||
|
*/
|
||||||
|
export const emailSchema = z.string().email('Ungültige E-Mail-Adresse');
|
||||||
|
|
||||||
|
export const requiredString = (fieldName: string) =>
|
||||||
|
z.string().min(1, `${fieldName} ist erforderlich`);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a success JSON response.
|
||||||
|
* Shape: { success: true, data: T }
|
||||||
|
*/
|
||||||
|
export function apiSuccess<T>(data: T, status = 200) {
|
||||||
|
return NextResponse.json({ success: true, data }, { status });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an error JSON response.
|
||||||
|
* Shape: { success: false, error: string }
|
||||||
|
*/
|
||||||
|
export function apiError(error: string, status = 400) {
|
||||||
|
return NextResponse.json({ success: false, error }, { status });
|
||||||
|
}
|
||||||
@@ -16,7 +16,8 @@
|
|||||||
"./registry": "./src/registry/index.ts",
|
"./registry": "./src/registry/index.ts",
|
||||||
"./env": "./src/env/index.ts",
|
"./env": "./src/env/index.ts",
|
||||||
"./dates": "./src/dates/index.ts",
|
"./dates": "./src/dates/index.ts",
|
||||||
"./formatters": "./src/dates/index.ts"
|
"./formatters": "./src/dates/index.ts",
|
||||||
|
"./api-response": "./src/api-response.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "git clean -xdf .turbo node_modules",
|
"clean": "git clean -xdf .turbo node_modules",
|
||||||
|
|||||||
46
packages/shared/src/api-response.ts
Normal file
46
packages/shared/src/api-response.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
/**
|
||||||
|
* Canonical API response types for all server actions and route handlers.
|
||||||
|
* Every action/endpoint should return one of these shapes.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Successful action result */
|
||||||
|
export type ActionSuccess<T = void> = T extends void
|
||||||
|
? { success: true }
|
||||||
|
: { success: true; data: T };
|
||||||
|
|
||||||
|
/** Failed action result */
|
||||||
|
export interface ActionError {
|
||||||
|
success: false;
|
||||||
|
error: string;
|
||||||
|
validationErrors?: Array<{ field: string; message: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Union of success and error */
|
||||||
|
export type ActionResult<T = void> = ActionSuccess<T> | ActionError;
|
||||||
|
|
||||||
|
/** Standardized file download payload (used inside ActionSuccess.data) */
|
||||||
|
export interface FileDownload {
|
||||||
|
content: string;
|
||||||
|
filename: string;
|
||||||
|
mimeType: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper to create a success response */
|
||||||
|
export function actionSuccess(): { success: true };
|
||||||
|
export function actionSuccess<T>(data: T): { success: true; data: T };
|
||||||
|
export function actionSuccess<T>(data?: T) {
|
||||||
|
if (data === undefined) {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper to create an error response */
|
||||||
|
export function actionError(
|
||||||
|
error: string,
|
||||||
|
validationErrors?: Array<{ field: string; message: string }>,
|
||||||
|
): ActionError {
|
||||||
|
return validationErrors
|
||||||
|
? { success: false, error, validationErrors }
|
||||||
|
: { success: false, error };
|
||||||
|
}
|
||||||
@@ -98,7 +98,10 @@
|
|||||||
"./sidebar-navigation": "./src/makerkit/sidebar-navigation.tsx",
|
"./sidebar-navigation": "./src/makerkit/sidebar-navigation.tsx",
|
||||||
"./file-uploader": "./src/makerkit/file-uploader.tsx",
|
"./file-uploader": "./src/makerkit/file-uploader.tsx",
|
||||||
"./use-supabase-upload": "./src/hooks/use-supabase-upload.ts",
|
"./use-supabase-upload": "./src/hooks/use-supabase-upload.ts",
|
||||||
"./csp-provider": "./src/base-ui/csp-provider.tsx"
|
"./csp-provider": "./src/base-ui/csp-provider.tsx",
|
||||||
|
"./list-toolbar": "./src/makerkit/list-toolbar.tsx",
|
||||||
|
"./use-action-with-toast": "./src/hooks/use-action-with-toast.ts",
|
||||||
|
"./use-file-download-action": "./src/hooks/use-file-download-action.ts"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "git clean -xdf .turbo node_modules",
|
"clean": "git clean -xdf .turbo node_modules",
|
||||||
|
|||||||
67
packages/ui/src/hooks/use-action-with-toast.ts
Normal file
67
packages/ui/src/hooks/use-action-with-toast.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useAction } from 'next-safe-action/hooks';
|
||||||
|
import type { HookSafeActionFn } from 'next-safe-action/hooks';
|
||||||
|
|
||||||
|
import { toast } from '../shadcn/sonner';
|
||||||
|
|
||||||
|
const DEFAULT_ERROR = 'Ein Fehler ist aufgetreten';
|
||||||
|
|
||||||
|
interface UseActionWithToastOptions<TData> {
|
||||||
|
successMessage: string;
|
||||||
|
errorMessage?: string;
|
||||||
|
onSuccess?: (data: TData) => void;
|
||||||
|
onError?: (error: string, data?: TData) => void;
|
||||||
|
showSuccessToast?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps next-safe-action's `useAction` with unified toast notifications.
|
||||||
|
*
|
||||||
|
* Handles three cases:
|
||||||
|
* 1. Action succeeds with `{ success: true }` → toast.success
|
||||||
|
* 2. Action returns `{ success: false, error }` → toast.error
|
||||||
|
* 3. Action throws (serverError) → toast.error
|
||||||
|
*/
|
||||||
|
export function useActionWithToast<
|
||||||
|
TData extends { success: boolean; error?: string; [key: string]: unknown },
|
||||||
|
>(
|
||||||
|
action: HookSafeActionFn<any, any, any, TData>,
|
||||||
|
options: UseActionWithToastOptions<TData>,
|
||||||
|
) {
|
||||||
|
const {
|
||||||
|
successMessage,
|
||||||
|
errorMessage,
|
||||||
|
onSuccess,
|
||||||
|
onError,
|
||||||
|
showSuccessToast = true,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
return useAction(action, {
|
||||||
|
onSuccess: ({ data }) => {
|
||||||
|
if (!data) return;
|
||||||
|
|
||||||
|
// Application-level error: action returned { success: false }
|
||||||
|
if (!data.success) {
|
||||||
|
const msg = data.error ?? errorMessage ?? DEFAULT_ERROR;
|
||||||
|
toast.error(msg);
|
||||||
|
onError?.(msg, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showSuccessToast) {
|
||||||
|
toast.success(successMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSuccess?.(data);
|
||||||
|
},
|
||||||
|
onError: ({ error }) => {
|
||||||
|
const msg =
|
||||||
|
(error as { serverError?: string }).serverError ??
|
||||||
|
errorMessage ??
|
||||||
|
DEFAULT_ERROR;
|
||||||
|
toast.error(msg);
|
||||||
|
onError?.(msg);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
73
packages/ui/src/hooks/use-file-download-action.ts
Normal file
73
packages/ui/src/hooks/use-file-download-action.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { HookSafeActionFn } from 'next-safe-action/hooks';
|
||||||
|
|
||||||
|
import { useActionWithToast } from './use-action-with-toast';
|
||||||
|
|
||||||
|
interface FileDownloadData {
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
data?: {
|
||||||
|
content: string;
|
||||||
|
filename: string;
|
||||||
|
mimeType: string;
|
||||||
|
};
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UseFileDownloadOptions {
|
||||||
|
successMessage?: string;
|
||||||
|
errorMessage?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadBlob(blob: Blob, filename: string) {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = filename;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBase64(str: string): boolean {
|
||||||
|
// Text content (CSV, XML) won't start with common base64 patterns
|
||||||
|
// Base64 encoded binary content is typically longer and matches the pattern
|
||||||
|
return /^[A-Za-z0-9+/]+=*$/.test(str.slice(0, 100)) && str.length > 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps a server action that returns a file download payload.
|
||||||
|
* Automatically creates a blob and triggers download.
|
||||||
|
*
|
||||||
|
* Expects the action to return: { success: true, data: { content, filename, mimeType } }
|
||||||
|
*/
|
||||||
|
export function useFileDownloadAction(
|
||||||
|
action: HookSafeActionFn<any, any, any, FileDownloadData>,
|
||||||
|
options: UseFileDownloadOptions = {},
|
||||||
|
) {
|
||||||
|
return useActionWithToast<FileDownloadData>(action, {
|
||||||
|
successMessage: options.successMessage ?? 'Export heruntergeladen',
|
||||||
|
errorMessage: options.errorMessage ?? 'Export fehlgeschlagen',
|
||||||
|
onSuccess: (data) => {
|
||||||
|
const file = data.data;
|
||||||
|
if (!file?.content) return;
|
||||||
|
|
||||||
|
let blob: Blob;
|
||||||
|
|
||||||
|
if (isBase64(file.content)) {
|
||||||
|
// Binary content (Excel, PDF): decode base64
|
||||||
|
const byteChars = atob(file.content);
|
||||||
|
const byteNums = new Uint8Array(byteChars.length);
|
||||||
|
for (let i = 0; i < byteChars.length; i++) {
|
||||||
|
byteNums[i] = byteChars.charCodeAt(i);
|
||||||
|
}
|
||||||
|
blob = new Blob([byteNums], { type: file.mimeType });
|
||||||
|
} else {
|
||||||
|
// Text content (CSV, XML): use directly
|
||||||
|
blob = new Blob([file.content], { type: file.mimeType });
|
||||||
|
}
|
||||||
|
|
||||||
|
downloadBlob(blob, file.filename);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
119
packages/ui/src/makerkit/list-toolbar.tsx
Normal file
119
packages/ui/src/makerkit/list-toolbar.tsx
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
|
||||||
|
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
|
||||||
|
|
||||||
|
import { Search } from 'lucide-react';
|
||||||
|
|
||||||
|
import { Button } from '../shadcn/button';
|
||||||
|
import { Input } from '../shadcn/input';
|
||||||
|
|
||||||
|
interface FilterOption {
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FilterConfig {
|
||||||
|
/** URL param name (e.g. "status") */
|
||||||
|
param: string;
|
||||||
|
/** Display label (e.g. "Status") */
|
||||||
|
label: string;
|
||||||
|
/** Dropdown options including an "all" default */
|
||||||
|
options: FilterOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ListToolbarProps {
|
||||||
|
/** Placeholder text for search input */
|
||||||
|
searchPlaceholder?: string;
|
||||||
|
/** URL param name for search (default: "q") */
|
||||||
|
searchParam?: string;
|
||||||
|
/** Filter dropdowns */
|
||||||
|
filters?: FilterConfig[];
|
||||||
|
/** Whether to show search input (default: true) */
|
||||||
|
showSearch?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reusable toolbar for list pages with search and filter dropdowns.
|
||||||
|
* Syncs state with URL search params so server components can read them.
|
||||||
|
* Resets to page 1 on any filter/search change.
|
||||||
|
*/
|
||||||
|
export function ListToolbar({
|
||||||
|
searchPlaceholder = 'Suchen...',
|
||||||
|
searchParam = 'q',
|
||||||
|
filters = [],
|
||||||
|
showSearch = true,
|
||||||
|
}: ListToolbarProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
|
const updateParams = useCallback(
|
||||||
|
(updates: Record<string, string | null>) => {
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
params.delete('page');
|
||||||
|
for (const [key, value] of Object.entries(updates)) {
|
||||||
|
if (value === null || value === '') {
|
||||||
|
params.delete(key);
|
||||||
|
} else {
|
||||||
|
params.set(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const qs = params.toString();
|
||||||
|
router.push(qs ? `${pathname}?${qs}` : pathname);
|
||||||
|
},
|
||||||
|
[router, pathname, searchParams],
|
||||||
|
);
|
||||||
|
|
||||||
|
const currentSearch = searchParams.get(searchParam) ?? '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
{showSearch && (
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const value = (formData.get('search') as string) ?? '';
|
||||||
|
updateParams({ [searchParam]: value || null });
|
||||||
|
}}
|
||||||
|
className="flex gap-2"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
name="search"
|
||||||
|
type="search"
|
||||||
|
defaultValue={currentSearch}
|
||||||
|
placeholder={searchPlaceholder}
|
||||||
|
className="w-64"
|
||||||
|
/>
|
||||||
|
<Button type="submit" variant="outline" size="sm">
|
||||||
|
<Search className="mr-1 h-4 w-4" />
|
||||||
|
Suchen
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{filters.length > 0 && (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{filters.map((filter) => (
|
||||||
|
<select
|
||||||
|
key={filter.param}
|
||||||
|
value={searchParams.get(filter.param) ?? ''}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateParams({ [filter.param]: e.target.value || null })
|
||||||
|
}
|
||||||
|
className="border-input bg-background flex h-9 rounded-md border px-3 py-1 text-sm shadow-sm"
|
||||||
|
>
|
||||||
|
{filter.options.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user