'use server'; import { revalidatePath } from 'next/cache'; import { Article, ArticleCreate, ArticleGroup, ArticleUpsert, } from '../types/catalog'; import { sites } from '../_config/sites'; import { endpoints } from '../_config/endpoints'; const api = endpoints.apiServer.url; async function mutate( url: string, method: string, data?: unknown, ): Promise { try { const response = await fetch(`${api}${url}`, { method, headers: { 'Content-Type': 'application/json' }, body: data === undefined ? undefined : JSON.stringify(data), }); const result = await response.json(); if (!response.ok) { return { success: false, errors: Array.isArray(result.message) ? result.message : [result.message ?? 'Speichern fehlgeschlagen'], }; } revalidatePath(sites.article.url); return { success: true, data: result }; } catch { return { success: false, errors: [ 'Der Artikelserver ist nicht erreichbar. Bitte erneut versuchen.', ], }; } } export async function articleCreate( data: ArticleCreate, ): Promise { return mutate('/articles', 'POST', data); } export async function articleUpdate( id: string, data: ArticleUpsert, ): Promise { const result = await mutate(`/articles/${id}`, 'PATCH', data); if (result.success) revalidatePath(`${sites.article.update.url}/${id}`); return result; } export async function articleFindAll(): Promise { const response = await fetch(`${api}/articles`, { cache: 'no-store' }); if (!response.ok) throw new Error('Artikel konnten nicht geladen werden'); return response.json(); } export async function articleFindById(id: string): Promise
{ const response = await fetch(`${api}/articles/${id}`, { cache: 'no-store' }); if (response.status === 404) return null; if (!response.ok) throw new Error('Artikel konnte nicht geladen werden'); return response.json(); } export async function articleDelete( id: string, revalidateUrl?: string, ): Promise { const result = await mutate(`/articles/${id}`, 'DELETE'); if (result.success && revalidateUrl) revalidatePath(revalidateUrl); return result; } export async function articleGroupsFindAll(): Promise { const response = await fetch(`${api}/article-groups`, { cache: 'no-store' }); if (!response.ok) throw new Error('Produktgruppen konnten nicht geladen werden'); return response.json(); } export async function articleGroupCreate(name: string): Promise { return mutate('/article-groups', 'POST', { name }); } export async function articleMigrationStatus(): Promise<{ pendingLegacyArticles: number; }> { const response = await fetch(`${api}/articles/migration-status`, { cache: 'no-store', }); if (!response.ok) throw new Error('Migrationsstatus konnte nicht geladen werden'); return response.json(); }