feat(api): implement product creation and category update endpoints

This commit is contained in:
Nils-Johan Gynther
2026-04-19 17:32:55 +02:00
parent 81a8390bb7
commit 4bf5733c76
3 changed files with 120 additions and 5 deletions
+23 -5
View File
@@ -1,7 +1,6 @@
'use client';
import { useRef, useState, useEffect } from 'react';
import { createProductAction, updateProductCategoryAction } from './actions';
type CategorySuggestion = {
categoryId: number;
@@ -194,15 +193,34 @@ export default function ReceiptImportClient({ isAdmin }: { isAdmin: boolean }) {
setCreatingProduct(i);
setError(null);
// eslint-disable-next-line no-console
console.log('handleCreateProduct: isAdmin =', isAdmin, 'endpoint = /api/products');
console.log('handleCreateProduct: isAdmin =', isAdmin, 'endpoint = /api/products-create');
try {
// Admin skapar aktiv produkt direkt via Server Action
const product = await createProductAction(row.rawName);
// Admin skapar aktiv produkt via API route
const res = await fetch('/api/products-create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: row.rawName }),
});
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e.error ?? `HTTP ${res.status}`);
}
const product = await res.json();
// Sätt kategori: AI-förslag har prioritet, annars manuellt val
const categoryId = row.categorySuggestion?.categoryId ?? (row.selectedCategoryId !== '' ? row.selectedCategoryId : null);
if (categoryId) {
await updateProductCategoryAction(product.id, categoryId);
const patchRes = await fetch(`/api/products-update/${product.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ categoryId }),
});
if (!patchRes.ok) {
const e = await patchRes.json().catch(() => ({}));
throw new Error(e.error ?? `HTTP ${patchRes.status}`);
}
}
// Uppdatera produktlistan lokalt