feat(api): add create and update product routes with authentication
refactor(admin): integrate router refresh after product updates in forms fix(imports): update fetch paths for product creation and update in ReceiptImportClient
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useEffect, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { Product, Category } from '../../../features/inventory/types';
|
||||
import EditProductForm from './EditProductForm';
|
||||
import { bulkSetCategory, suggestBulkCategories } from './actions';
|
||||
@@ -39,6 +40,7 @@ function flattenTree(nodes: CategoryNode[], depth = 0): { id: number; label: str
|
||||
}
|
||||
|
||||
export default function AdminProductList({ products }: Props) {
|
||||
const router = useRouter();
|
||||
const [search, setSearch] = useState('');
|
||||
const [sort, setSort] = useState('createdDesc');
|
||||
const [showUncategorizedOnly, setShowUncategorizedOnly] = useState(false);
|
||||
@@ -127,6 +129,7 @@ export default function AdminProductList({ products }: Props) {
|
||||
await bulkSetCategory(ids, categoryId);
|
||||
setSelectedIds(new Set());
|
||||
setBulkCategoryId('');
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setBulkError(err instanceof Error ? err.message : 'Fel vid uppdatering');
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useTransition, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { Product } from '../../../features/inventory/types';
|
||||
import { updateProductWithTags, deleteProduct, suggestProductCategory } from './actions';
|
||||
|
||||
@@ -33,6 +34,7 @@ const inputStyle: React.CSSProperties = {
|
||||
};
|
||||
|
||||
export default function EditProductForm({ product }: Props) {
|
||||
const router = useRouter();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -107,6 +109,7 @@ export default function EditProductForm({ product }: Props) {
|
||||
await updateProductWithTags(formData, rawTags);
|
||||
setSuccess(true);
|
||||
setIsOpen(false);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Okänt fel');
|
||||
}
|
||||
@@ -120,6 +123,7 @@ export default function EditProductForm({ product }: Props) {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await deleteProduct(product.id);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Okänt fel');
|
||||
}
|
||||
|
||||
@@ -108,8 +108,6 @@ export async function updateProductWithTags(formData: FormData, tags: string[])
|
||||
const text = await tagsRes.text();
|
||||
throw new Error(`Kunde inte uppdatera taggar: ${text}`);
|
||||
}
|
||||
|
||||
revalidatePath('/admin/products');
|
||||
}
|
||||
|
||||
export async function deleteProduct(id: number) {
|
||||
@@ -123,8 +121,6 @@ export async function deleteProduct(id: number) {
|
||||
const text = await res.text();
|
||||
throw new Error(`Kunde inte ta bort produkt: ${text}`);
|
||||
}
|
||||
|
||||
revalidatePath('/admin/products');
|
||||
}
|
||||
|
||||
export async function resetAllProducts() {
|
||||
@@ -155,8 +151,6 @@ export async function bulkSetCategory(ids: number[], categoryId: number | null)
|
||||
const text = await res.text();
|
||||
throw new Error(`Kunde inte uppdatera produkter: ${text}`);
|
||||
}
|
||||
|
||||
revalidatePath('/admin/products');
|
||||
}
|
||||
|
||||
export async function suggestProductCategory(productId: number) {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { auth } from '../../../../auth';
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
||||
|
||||
async function getAuthHeaders(): Promise<Record<string, string>> {
|
||||
const session = await auth();
|
||||
if (!session?.accessToken) {
|
||||
return {};
|
||||
}
|
||||
return { Authorization: `Bearer ${session.accessToken}` };
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { name } = body;
|
||||
|
||||
if (!name || typeof name !== 'string') {
|
||||
return Response.json({ error: 'Name is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const authHeaders = await getAuthHeaders();
|
||||
const res = await fetch(`${API_BASE}/api/products`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const e = await res.json().catch(() => ({}));
|
||||
return Response.json({ error: e.message ?? `HTTP ${res.status}` }, { status: res.status });
|
||||
}
|
||||
|
||||
const product = await res.json();
|
||||
return Response.json({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
canonicalName: product.canonicalName ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{ error: err instanceof Error ? err.message : 'Unknown error' },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { auth } from '../../../../../auth';
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
||||
|
||||
async function getAuthHeaders(): Promise<Record<string, string>> {
|
||||
const session = await auth();
|
||||
if (!session?.accessToken) {
|
||||
return {};
|
||||
}
|
||||
return { Authorization: `Bearer ${session.accessToken}` };
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const productId = parseInt(id, 10);
|
||||
const body = await req.json();
|
||||
const { categoryId } = body;
|
||||
|
||||
const authHeaders = await getAuthHeaders();
|
||||
const res = await fetch(`${API_BASE}/api/products/${productId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders },
|
||||
body: JSON.stringify({ categoryId }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const e = await res.json().catch(() => ({}));
|
||||
return Response.json({ error: e.message ?? `HTTP ${res.status}` }, { status: res.status });
|
||||
}
|
||||
|
||||
const product = await res.json();
|
||||
return Response.json({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
canonicalName: product.canonicalName ?? null,
|
||||
categoryId: product.categoryId ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{ error: err instanceof Error ? err.message : 'Unknown error' },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,7 @@ export default function ReceiptImportClient({ isAdmin }: { isAdmin: boolean }) {
|
||||
console.log('handleCreateProduct: isAdmin =', isAdmin, 'endpoint = /api/products-create');
|
||||
try {
|
||||
// Admin skapar aktiv produkt via API route
|
||||
const res = await fetch('/api/products-create', {
|
||||
const res = await fetch('/api/admin/create-product', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: row.rawName }),
|
||||
@@ -212,7 +212,7 @@ export default function ReceiptImportClient({ isAdmin }: { isAdmin: boolean }) {
|
||||
// Sätt kategori: AI-förslag har prioritet, annars manuellt val
|
||||
const categoryId = row.categorySuggestion?.categoryId ?? (row.selectedCategoryId !== '' ? row.selectedCategoryId : null);
|
||||
if (categoryId) {
|
||||
const patchRes = await fetch(`/api/products-update/${product.id}`, {
|
||||
const patchRes = await fetch(`/api/admin/update-product/${product.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ categoryId }),
|
||||
|
||||
Reference in New Issue
Block a user