feat: enhance API response handling and add new components for module management
This commit is contained in:
@@ -64,7 +64,14 @@ export const generateSepaXml = authActionClient
|
||||
creditorId: input.creditorId,
|
||||
});
|
||||
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
|
||||
@@ -99,5 +106,5 @@ export const populateBatchFromMembers = authActionClient
|
||||
{ name: 'sepa.populate', count: result.addedCount },
|
||||
'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 {
|
||||
// --- SEPA Batches ---
|
||||
async listBatches(accountId: string) {
|
||||
const { data, error } = await client
|
||||
async listBatches(
|
||||
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')
|
||||
.select('*')
|
||||
.select('*', { count: 'exact' })
|
||||
.eq('account_id', accountId)
|
||||
.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;
|
||||
return data ?? [];
|
||||
|
||||
return {
|
||||
data: data ?? [],
|
||||
total: count ?? 0,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||
};
|
||||
},
|
||||
|
||||
async getBatch(batchId: string) {
|
||||
@@ -148,20 +177,48 @@ export function createFinanceApi(client: SupabaseClient<Database>) {
|
||||
},
|
||||
|
||||
// --- 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
|
||||
.from('invoices')
|
||||
.select('*')
|
||||
.select('*', { count: 'exact' })
|
||||
.eq('account_id', accountId)
|
||||
.order('issue_date', { ascending: false });
|
||||
if (opts?.status)
|
||||
|
||||
if (opts?.status) {
|
||||
query = query.eq(
|
||||
'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;
|
||||
return data ?? [];
|
||||
|
||||
return {
|
||||
data: data ?? [],
|
||||
total: count ?? 0,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||
};
|
||||
},
|
||||
|
||||
async createInvoice(input: CreateInvoiceInput, userId: string) {
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useAction } from 'next-safe-action/hooks';
|
||||
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 { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
|
||||
import {
|
||||
@@ -17,7 +28,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
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 { createMember } from '../server/actions/member-actions';
|
||||
@@ -28,12 +39,19 @@ interface Props {
|
||||
duesCategories: Array<{ id: string; name: string; amount: number }>;
|
||||
}
|
||||
|
||||
interface DuplicateEntry {
|
||||
field: string;
|
||||
message: string;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
export function CreateMemberForm({
|
||||
accountId,
|
||||
account,
|
||||
duesCategories,
|
||||
}: Props) {
|
||||
const router = useRouter();
|
||||
const [duplicates, setDuplicates] = useState<DuplicateEntry[]>([]);
|
||||
const form = useForm({
|
||||
resolver: zodResolver(CreateMemberSchema),
|
||||
defaultValues: {
|
||||
@@ -59,15 +77,16 @@ export function CreateMemberForm({
|
||||
},
|
||||
});
|
||||
|
||||
const { execute, isPending } = useAction(createMember, {
|
||||
onSuccess: ({ data }) => {
|
||||
if (data?.success) {
|
||||
toast.success('Mitglied erfolgreich erstellt');
|
||||
router.push(`/home/${account}/members-cms`);
|
||||
}
|
||||
const { execute, isPending } = useActionWithToast(createMember, {
|
||||
successMessage: 'Mitglied erfolgreich erstellt',
|
||||
errorMessage: 'Fehler beim Erstellen',
|
||||
onSuccess: () => {
|
||||
router.push(`/home/${account}/members-cms`);
|
||||
},
|
||||
onError: ({ error }) => {
|
||||
toast.error(error.serverError ?? 'Fehler beim Erstellen');
|
||||
onError: (_error, data) => {
|
||||
if (data?.validationErrors) {
|
||||
setDuplicates(data.validationErrors as DuplicateEntry[]);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -586,6 +605,37 @@ export function CreateMemberForm({
|
||||
</Button>
|
||||
</div>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,16 +4,20 @@ import { useCallback } from 'react';
|
||||
|
||||
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 { formatDate } from '@kit/shared/dates';
|
||||
import { Badge } from '@kit/ui/badge';
|
||||
import { Button } from '@kit/ui/button';
|
||||
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 {
|
||||
exportMembers,
|
||||
exportMembersExcel,
|
||||
} from '../server/actions/member-actions';
|
||||
|
||||
interface MembersDataTableProps {
|
||||
data: Array<Record<string, unknown>>;
|
||||
@@ -21,6 +25,7 @@ interface MembersDataTableProps {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
account: string;
|
||||
accountId: string;
|
||||
duesCategories: Array<{ id: string; name: string }>;
|
||||
}
|
||||
|
||||
@@ -38,6 +43,7 @@ export function MembersDataTable({
|
||||
page,
|
||||
pageSize,
|
||||
account,
|
||||
accountId,
|
||||
duesCategories,
|
||||
}: MembersDataTableProps) {
|
||||
const router = useRouter();
|
||||
@@ -102,6 +108,20 @@ export function MembersDataTable({
|
||||
[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 (
|
||||
<div className="space-y-4">
|
||||
{/* Toolbar */}
|
||||
@@ -137,6 +157,34 @@ export function MembersDataTable({
|
||||
))}
|
||||
</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
|
||||
size="sm"
|
||||
data-test="members-new-btn"
|
||||
|
||||
@@ -30,6 +30,26 @@ export const createMember = authActionClient
|
||||
const api = createMemberManagementApi(client);
|
||||
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...');
|
||||
const result = await api.createMember(input, userId);
|
||||
logger.info({ name: 'member.create' }, 'Member created');
|
||||
@@ -217,7 +237,14 @@ export const exportMembers = authActionClient
|
||||
const csv = await api.exportMembersCsv(input.accountId, {
|
||||
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
|
||||
@@ -248,11 +275,14 @@ export const exportMembersExcel = authActionClient
|
||||
const buffer = await api.exportMembersExcel(input.accountId, {
|
||||
status: input.status,
|
||||
});
|
||||
// Return base64 for client-side download
|
||||
return {
|
||||
success: true,
|
||||
base64: buffer.toString('base64'),
|
||||
filename: `mitglieder_${new Date().toISOString().split('T')[0]}.xlsx`,
|
||||
data: {
|
||||
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 {
|
||||
success: true,
|
||||
base64: buffer.toString('base64'),
|
||||
filename: `mitgliedsausweise_${new Date().toISOString().split('T')[0]}.pdf`,
|
||||
data: {
|
||||
content: buffer.toString('base64'),
|
||||
filename: `mitgliedsausweise_${new Date().toISOString().split('T')[0]}.pdf`,
|
||||
mimeType: 'application/pdf',
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"./schema/*": "./src/schema/*.ts",
|
||||
"./hooks/*": "./src/hooks/*.ts",
|
||||
"./components": "./src/components/index.ts",
|
||||
"./actions/*": "./src/server/actions/*.ts",
|
||||
"./services/*": "./src/server/services/*.ts"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -22,14 +22,14 @@ export const createModule = authActionClient
|
||||
'Creating module...',
|
||||
);
|
||||
|
||||
const module = await api.modules.createModule(input);
|
||||
const data = await api.modules.createModule(input);
|
||||
|
||||
logger.info(
|
||||
{ name: 'modules.create', moduleId: module.id },
|
||||
{ name: 'modules.create', moduleId: data.id },
|
||||
'Module created',
|
||||
);
|
||||
|
||||
return { success: true, module };
|
||||
return { success: true, data };
|
||||
});
|
||||
|
||||
export const updateModule = authActionClient
|
||||
@@ -44,14 +44,14 @@ export const updateModule = authActionClient
|
||||
'Updating module...',
|
||||
);
|
||||
|
||||
const module = await api.modules.updateModule(input);
|
||||
const data = await api.modules.updateModule(input);
|
||||
|
||||
logger.info(
|
||||
{ name: 'modules.update', moduleId: module.id },
|
||||
{ name: 'modules.update', moduleId: data.id },
|
||||
'Module updated',
|
||||
);
|
||||
|
||||
return { success: true, module };
|
||||
return { success: true, data };
|
||||
});
|
||||
|
||||
export const deleteModule = authActionClient
|
||||
|
||||
@@ -52,7 +52,11 @@ export const createRecord = authActionClient
|
||||
);
|
||||
|
||||
if (!validation.success) {
|
||||
return { success: false, errors: validation.errors };
|
||||
return {
|
||||
success: false,
|
||||
error: 'Validierungsfehler',
|
||||
validationErrors: validation.errors,
|
||||
};
|
||||
}
|
||||
|
||||
logger.info(
|
||||
@@ -72,7 +76,7 @@ export const createRecord = authActionClient
|
||||
newData: input.data as Record<string, unknown>,
|
||||
});
|
||||
|
||||
return { success: true, record };
|
||||
return { success: true, data: record };
|
||||
});
|
||||
|
||||
export const updateRecord = authActionClient
|
||||
@@ -86,6 +90,40 @@ export const updateRecord = authActionClient
|
||||
// Get existing record for audit
|
||||
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(
|
||||
{ name: 'records.update', recordId: input.recordId },
|
||||
'Updating record...',
|
||||
@@ -104,7 +142,7 @@ export const updateRecord = authActionClient
|
||||
newData: input.data as Record<string, unknown>,
|
||||
});
|
||||
|
||||
return { success: true, record };
|
||||
return { success: true, data: record };
|
||||
});
|
||||
|
||||
export const deleteRecord = authActionClient
|
||||
@@ -156,5 +194,5 @@ export const lockRecord = authActionClient
|
||||
newData: { locked: input.lock },
|
||||
});
|
||||
|
||||
return { success: true, record };
|
||||
return { success: true, data: record };
|
||||
});
|
||||
|
||||
@@ -26,14 +26,35 @@ export function createNewsletterApi(client: SupabaseClient<Database>) {
|
||||
|
||||
return {
|
||||
// --- Templates ---
|
||||
async listTemplates(accountId: string) {
|
||||
const { data, error } = await client
|
||||
async listTemplates(
|
||||
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')
|
||||
.select('*')
|
||||
.select('*', { count: 'exact' })
|
||||
.eq('account_id', accountId)
|
||||
.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;
|
||||
return data ?? [];
|
||||
|
||||
return {
|
||||
data: data ?? [],
|
||||
total: count ?? 0,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||
};
|
||||
},
|
||||
|
||||
async createTemplate(input: {
|
||||
@@ -61,14 +82,43 @@ export function createNewsletterApi(client: SupabaseClient<Database>) {
|
||||
},
|
||||
|
||||
// --- Newsletters ---
|
||||
async listNewsletters(accountId: string) {
|
||||
const { data, error } = await client
|
||||
async listNewsletters(
|
||||
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')
|
||||
.select('*')
|
||||
.select('*', { count: 'exact' })
|
||||
.eq('account_id', accountId)
|
||||
.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;
|
||||
return data ?? [];
|
||||
|
||||
return {
|
||||
data: data ?? [],
|
||||
total: count ?? 0,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil((count ?? 0) / pageSize),
|
||||
};
|
||||
},
|
||||
|
||||
async createNewsletter(input: CreateNewsletterInput, userId: string) {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useAction } from 'next-safe-action/hooks';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
@@ -17,7 +16,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
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 { createPage } from '../server/actions/site-builder-actions';
|
||||
@@ -51,15 +50,14 @@ export function CreatePageForm({ accountId, account }: Props) {
|
||||
.replace(/ß/g, 'ss')
|
||||
.replace(/^-|-$/g, '');
|
||||
|
||||
const { execute, isPending } = useAction(createPage, {
|
||||
onSuccess: ({ data }) => {
|
||||
if (data?.success && data.data) {
|
||||
toast.success('Seite erstellt — Editor wird geöffnet');
|
||||
const { execute, isPending } = useActionWithToast(createPage, {
|
||||
successMessage: 'Seite erstellt — Editor wird geöffnet',
|
||||
errorMessage: 'Fehler beim Erstellen',
|
||||
onSuccess: (data) => {
|
||||
if (data?.data) {
|
||||
router.push(`/home/${account}/site-builder/${data.data.id}/edit`);
|
||||
}
|
||||
},
|
||||
onError: ({ error }) =>
|
||||
toast.error(error.serverError ?? 'Fehler beim Erstellen'),
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useAction } from 'next-safe-action/hooks';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
@@ -17,7 +16,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
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 { createPost } from '../server/actions/site-builder-actions';
|
||||
@@ -53,12 +52,11 @@ export function CreatePostForm({ accountId, account }: Props) {
|
||||
.replace(/ü/g, 'ue')
|
||||
.replace(/ß/g, 'ss');
|
||||
|
||||
const { execute, isPending } = useAction(createPost, {
|
||||
const { execute, isPending } = useActionWithToast(createPost, {
|
||||
successMessage: 'Beitrag erstellt',
|
||||
onSuccess: () => {
|
||||
toast.success('Beitrag erstellt');
|
||||
router.push(`/home/${account}/site-builder/posts`);
|
||||
},
|
||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
import { Puck } from '@measured/puck';
|
||||
|
||||
import '@measured/puck/puck.css';
|
||||
import { useAction } from 'next-safe-action/hooks';
|
||||
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||
|
||||
import { clubPuckConfig } from '../config/puck-config';
|
||||
import { publishPage } from '../server/actions/site-builder-actions';
|
||||
@@ -17,9 +15,8 @@ interface Props {
|
||||
}
|
||||
|
||||
export function SiteEditor({ pageId, accountId, initialData }: Props) {
|
||||
const { execute: execPublish } = useAction(publishPage, {
|
||||
onSuccess: () => toast.success('Seite veröffentlicht'),
|
||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
||||
const { execute: execPublish } = useActionWithToast(publishPage, {
|
||||
successMessage: 'Seite veröffentlicht',
|
||||
});
|
||||
|
||||
const PuckAny = Puck as any;
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useAction } from 'next-safe-action/hooks';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
@@ -17,7 +16,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
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 { 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: () => {
|
||||
toast.success('Einstellungen gespeichert');
|
||||
router.refresh();
|
||||
},
|
||||
onError: ({ error }) => toast.error(error.serverError ?? 'Fehler'),
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,7 @@ import React from 'react';
|
||||
import type { Config } from '@measured/puck';
|
||||
|
||||
import { formatDate, formatMonthShort } from '@kit/shared/dates';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
|
||||
import { useSiteData } from '../context/site-data-context';
|
||||
|
||||
@@ -71,13 +72,13 @@ const ContactFormBlock = ({
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
alert('Nachricht erfolgreich gesendet!');
|
||||
toast.success('Nachricht erfolgreich gesendet!');
|
||||
form.reset();
|
||||
} else {
|
||||
alert(result.error || 'Fehler beim Senden');
|
||||
toast.error(result.error || 'Fehler beim Senden');
|
||||
}
|
||||
} catch {
|
||||
alert('Verbindungsfehler');
|
||||
toast.error('Verbindungsfehler');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -219,13 +220,15 @@ const NewsletterSignupBlock = ({
|
||||
});
|
||||
const result = await res.json();
|
||||
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();
|
||||
} else {
|
||||
alert(result.error || 'Fehler bei der Anmeldung');
|
||||
toast.error(result.error || 'Fehler bei der Anmeldung');
|
||||
}
|
||||
} catch {
|
||||
alert('Verbindungsfehler');
|
||||
toast.error('Verbindungsfehler');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -399,6 +402,8 @@ const EventListBlock = ({
|
||||
email: '',
|
||||
phone: '',
|
||||
dateOfBirth: '',
|
||||
parentName: '',
|
||||
parentPhone: '',
|
||||
});
|
||||
const [submitting, setSubmitting] = React.useState(false);
|
||||
const [successId, setSuccessId] = React.useState<string | null>(null);
|
||||
@@ -426,6 +431,8 @@ const EventListBlock = ({
|
||||
email: formData.email,
|
||||
phone: formData.phone || undefined,
|
||||
dateOfBirth: formData.dateOfBirth || undefined,
|
||||
parentName: formData.parentName || undefined,
|
||||
parentPhone: formData.parentPhone || undefined,
|
||||
}),
|
||||
});
|
||||
const result = await res.json();
|
||||
@@ -438,6 +445,8 @@ const EventListBlock = ({
|
||||
email: '',
|
||||
phone: '',
|
||||
dateOfBirth: '',
|
||||
parentName: '',
|
||||
parentPhone: '',
|
||||
});
|
||||
} else {
|
||||
setErrorMsg(result.error || 'Anmeldung fehlgeschlagen.');
|
||||
@@ -574,6 +583,29 @@ const EventListBlock = ({
|
||||
}
|
||||
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>
|
||||
{errorMsg && (
|
||||
<p className="mt-2 text-sm text-red-600">{errorMsg}</p>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useAction } from 'next-safe-action/hooks';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
@@ -17,7 +16,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
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 { createClub } from '../server/actions/verband-actions';
|
||||
@@ -62,15 +61,11 @@ export function CreateClubForm({
|
||||
},
|
||||
});
|
||||
|
||||
const { execute, isPending } = useAction(createClub, {
|
||||
onSuccess: ({ data }) => {
|
||||
if (data?.success) {
|
||||
toast.success(isEdit ? 'Verein aktualisiert' : 'Verein erstellt');
|
||||
router.push(`/home/${account}/verband/clubs`);
|
||||
}
|
||||
},
|
||||
onError: ({ error }) => {
|
||||
toast.error(error.serverError ?? 'Fehler beim Speichern');
|
||||
const { execute, isPending } = useActionWithToast(createClub, {
|
||||
successMessage: isEdit ? 'Verein aktualisiert' : 'Verein erstellt',
|
||||
errorMessage: 'Fehler beim Speichern',
|
||||
onSuccess: () => {
|
||||
router.push(`/home/${account}/verband/clubs`);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ import {
|
||||
DialogTitle,
|
||||
} from '@kit/ui/dialog';
|
||||
import { Input } from '@kit/ui/input';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { Textarea } from '@kit/ui/textarea';
|
||||
import { useActionWithToast } from '@kit/ui/use-action-with-toast';
|
||||
|
||||
import {
|
||||
getTransferPreview,
|
||||
@@ -90,7 +90,7 @@ export function CrossOrgMemberSearch({
|
||||
|
||||
const { execute: executePreview } = useAction(getTransferPreview, {
|
||||
onSuccess: ({ data }) => {
|
||||
if (data) setPreview(data);
|
||||
if (data?.data) setPreview(data.data);
|
||||
setPreviewLoading(false);
|
||||
},
|
||||
onError: () => {
|
||||
@@ -98,22 +98,18 @@ export function CrossOrgMemberSearch({
|
||||
},
|
||||
});
|
||||
|
||||
const { execute: executeTransfer, isPending: isTransferring } = useAction(
|
||||
transferMember,
|
||||
{
|
||||
const { execute: executeTransfer, isPending: isTransferring } =
|
||||
useActionWithToast(transferMember, {
|
||||
successMessage: 'Mitglied erfolgreich transferiert',
|
||||
errorMessage: 'Fehler beim Transfer',
|
||||
onSuccess: () => {
|
||||
toast.success('Mitglied erfolgreich transferiert');
|
||||
setTransferTarget(null);
|
||||
setTargetAccountId('');
|
||||
setTransferReason('');
|
||||
setKeepSepa(true);
|
||||
setPreview(null);
|
||||
},
|
||||
onError: ({ error }) => {
|
||||
toast.error(error.serverError ?? 'Fehler beim Transfer');
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const buildUrl = useCallback(
|
||||
(params: Record<string, string | number | null>) => {
|
||||
|
||||
@@ -135,7 +135,8 @@ export const getTransferPreview = authActionClient
|
||||
const client = getSupabaseServerClient();
|
||||
const api = createVerbandApi(client);
|
||||
|
||||
return api.getTransferPreview(input.memberId);
|
||||
const data = await api.getTransferPreview(input.memberId);
|
||||
return { success: true, data };
|
||||
});
|
||||
|
||||
export const transferMember = authActionClient
|
||||
@@ -169,7 +170,7 @@ export const transferMember = authActionClient
|
||||
);
|
||||
|
||||
revalidatePath(REVALIDATE_PATH, 'page');
|
||||
return { success: true, transferId };
|
||||
return { success: true, data: { transferId } };
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : 'Fehler beim Transfer';
|
||||
@@ -202,5 +203,5 @@ export const cloneTemplate = authActionClient
|
||||
);
|
||||
|
||||
revalidatePath(REVALIDATE_PATH, 'page');
|
||||
return { success: true, newTemplateId };
|
||||
return { success: true, data: { newTemplateId } };
|
||||
});
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
"exports": {
|
||||
"./actions": "./src/actions/index.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": {
|
||||
"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",
|
||||
"./env": "./src/env/index.ts",
|
||||
"./dates": "./src/dates/index.ts",
|
||||
"./formatters": "./src/dates/index.ts"
|
||||
"./formatters": "./src/dates/index.ts",
|
||||
"./api-response": "./src/api-response.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"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",
|
||||
"./file-uploader": "./src/makerkit/file-uploader.tsx",
|
||||
"./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": {
|
||||
"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