Add update functionality for recipes and create edit page

This commit is contained in:
Nils-Johan Gynther
2026-04-10 17:45:24 +02:00
parent fb68f926b1
commit a1f8fe228c
4 changed files with 354 additions and 2 deletions
+9 -1
View File
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Param, ParseIntPipe, Post } from '@nestjs/common'; import { Body, Controller, Get, Param, ParseIntPipe, Post, Patch } from '@nestjs/common';
import { RecipesService } from './recipes.service'; import { RecipesService } from './recipes.service';
import { CreateRecipeDto } from './dto/create-recipe.dto'; import { CreateRecipeDto } from './dto/create-recipe.dto';
@@ -25,4 +25,12 @@ export class RecipesController {
async create(@Body() createRecipeDto: CreateRecipeDto) { async create(@Body() createRecipeDto: CreateRecipeDto) {
return this.recipesService.create(createRecipeDto); return this.recipesService.create(createRecipeDto);
} }
@Patch(':id')
async update(
@Param('id', ParseIntPipe) id: number,
@Body() createRecipeDto: CreateRecipeDto,
) {
return this.recipesService.update(id, createRecipeDto);
}
} }
+34
View File
@@ -302,6 +302,40 @@ export class RecipesService {
return recipe; return recipe;
} }
async update(id: number, updateRecipeDto: CreateRecipeDto) {
// Först, ta bort gamla ingredienser
await this.prisma.recipeIngredient.deleteMany({
where: { recipeId: id },
});
// Uppdatera receptet och lägg till nya ingredienser
const recipe = await this.prisma.recipe.update({
where: { id },
data: {
name: updateRecipeDto.name,
description: updateRecipeDto.description || null,
instructions: updateRecipeDto.instructions || null,
ingredients: {
create: updateRecipeDto.ingredients.map((ingredient) => ({
productId: ingredient.productId,
quantity: ingredient.quantity.toString(),
unit: ingredient.unit,
note: ingredient.note || null,
})),
},
},
include: {
ingredients: {
include: {
product: true,
},
},
},
});
return recipe;
}
async create(createRecipeDto: CreateRecipeDto) { async create(createRecipeDto: CreateRecipeDto) {
const recipe = await this.prisma.recipe.create({ const recipe = await this.prisma.recipe.create({
data: { data: {
+60 -1
View File
@@ -1,6 +1,7 @@
'use client'; 'use client';
import { useState, useTransition } from 'react'; import { useState, useTransition } from 'react';
import Link from 'next/link';
import type { import type {
Recipe, Recipe,
RecipeInventoryPreview, RecipeInventoryPreview,
@@ -115,7 +116,7 @@ export default function RecipePreview({ recipes }: Props) {
</select> </select>
</label> </label>
<div> <div style={{ display: 'flex', gap: '0.75rem' }}>
<button <button
type="button" type="button"
onClick={loadPreview} onClick={loadPreview}
@@ -124,6 +125,23 @@ export default function RecipePreview({ recipes }: Props) {
> >
{isPending ? 'Hämtar preview...' : 'Visa preview'} {isPending ? 'Hämtar preview...' : 'Visa preview'}
</button> </button>
{selectedRecipeId && (
<Link
href={`/recipes/${selectedRecipeId}/edit`}
style={{
padding: '0.6rem 1rem',
background: '#f0f0f0',
color: '#333',
border: '1px solid #ccc',
borderRadius: '4px',
textDecoration: 'none',
cursor: 'pointer',
display: 'inline-block',
}}
>
Redigera recept
</Link>
)}
</div> </div>
{error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null} {error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null}
@@ -154,6 +172,31 @@ export default function RecipePreview({ recipes }: Props) {
: 'Kan inte lagas exakt ännu'} : 'Kan inte lagas exakt ännu'}
</strong> </strong>
</div> </div>
{preview.summary.unitMismatchCount > 0 && (
<div
style={{
padding: '0.75rem',
background: '#fff4e5',
border: '1px solid #f0cf9b',
borderRadius: '4px',
color: '#8a4b00',
fontSize: '0.9rem',
marginTop: '0.5rem',
}}
>
<strong> Enhetskonflikt!</strong> {preview.summary.unitMismatchCount} ingrediens
{preview.summary.unitMismatchCount !== 1 ? 'er har' : ' har'} olika enheter än vad som finns i hemmavaror.
<br />
<span style={{ fontSize: '0.85rem', marginTop: '0.25rem', display: 'block' }}>
T.ex. receptet säger "0.5 st" men du har lagrat "1.3 kg". Du kan antingen:
<ul style={{ margin: '0.5rem 0 0 1rem', paddingLeft: '1rem' }}>
<li>Redigera receptet för att matcha dina enheter</li>
<li>Lagra ingrediensen med samma enhet som receptet använder</li>
</ul>
</span>
</div>
)}
</article> </article>
<div style={{ display: 'grid', gap: '0.75rem' }}> <div style={{ display: 'grid', gap: '0.75rem' }}>
@@ -215,6 +258,22 @@ export default function RecipePreview({ recipes }: Props) {
Saknas: {ingredient.missingQuantity} {ingredient.requiredUnit} Saknas: {ingredient.missingQuantity} {ingredient.requiredUnit}
</div> </div>
) : null} ) : null}
{ingredient.status === 'unit_mismatch' ? (
<div
style={{
padding: '0.5rem',
background: '#fff4e5',
border: '1px solid #f0cf9b',
borderRadius: '4px',
fontSize: '0.9rem',
marginTop: '0.25rem',
}}
>
<strong>Enhetsproblem:</strong> Receptet kräver {ingredient.requiredUnit} men hemmavaror lagras i andra enheter.
Uppdatera receptet eller lagra ingrediensen med rätt enhet.
</div>
) : null}
</div> </div>
{ingredient.matchingInventoryItems.length > 0 ? ( {ingredient.matchingInventoryItems.length > 0 ? (
+251
View File
@@ -0,0 +1,251 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { fetchJson } from '../../../../lib/api';
import type { Product, Recipe } from '../../../../features/inventory/types';
export default function EditRecipePage() {
const router = useRouter();
const params = useParams();
const recipeId = Array.isArray(params.id) ? params.id[0] : params.id;
const [recipe, setRecipe] = useState({
name: '',
description: '',
instructions: '',
ingredients: [{ productId: 0, quantity: '', unit: '', note: '', location: '' }],
});
const [products, setProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadData = async () => {
try {
// Ladda produkter
const productsData = await fetchJson<Product[]>('/api/products');
setProducts(productsData);
// Ladda receptet
const recipeData = await fetchJson<Recipe>(`/api/recipes/${recipeId}`);
setRecipe({
name: recipeData.name,
description: recipeData.description || '',
instructions: recipeData.instructions || '',
ingredients: recipeData.ingredients.map((ing: any) => ({
productId: ing.productId,
quantity: ing.quantity.toString(),
unit: ing.unit,
note: ing.note || '',
location: ing.location || '',
})),
});
} catch (err) {
setError((err as Error).message);
} finally {
setIsLoading(false);
}
};
loadData();
}, [recipeId]);
const handleIngredientChange = (index: number, field: string, value: string | number) => {
const newIngredients = [...recipe.ingredients];
newIngredients[index] = { ...newIngredients[index], [field]: value };
setRecipe({ ...recipe, ingredients: newIngredients });
};
const addIngredient = () => {
setRecipe({
...recipe,
ingredients: [...recipe.ingredients, { productId: 0, quantity: '', unit: '', note: '', location: '' }],
});
};
const removeIngredient = (index: number) => {
const newIngredients = [...recipe.ingredients];
newIngredients.splice(index, 1);
setRecipe({ ...recipe, ingredients: newIngredients });
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
setError(null);
// Konvertera quantity till number för varje ingrediens
const recipeToSend = {
...recipe,
ingredients: recipe.ingredients.map((ing) => ({
...ing,
quantity: Number(ing.quantity),
})),
};
try {
const response = await fetch(`/api/recipes/${recipeId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(recipeToSend),
});
if (!response.ok) {
throw new Error('Kunde inte uppdatera receptet');
}
router.push('/recipes');
} catch (err) {
setError((err as Error).message);
} finally {
setIsSaving(false);
}
};
const UNIT_OPTIONS = [
{ value: '', label: 'Välj enhet' },
{ value: 'g', label: 'g (gram)' },
{ value: 'kg', label: 'kg (kilogram)' },
{ value: 'hg', label: 'hg (hektogram)' },
{ value: 'ml', label: 'ml (milliliter)' },
{ value: 'dl', label: 'dl (deciliter)' },
{ value: 'l', label: 'l (liter)' },
{ value: 'st', label: 'st (styck)' },
{ value: 'tsk', label: 'tsk (tesked)' },
{ value: 'msk', label: 'msk (matsked)' },
];
const LOCATION_OPTIONS = [
{ value: '', label: 'Välj plats' },
{ value: 'Kyl', label: 'Kyl' },
{ value: 'Frys', label: 'Frys' },
{ value: 'Skafferi', label: 'Skafferi' },
{ value: 'Annat', label: 'Annat' },
];
if (isLoading) {
return (
<main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}>
<p>Laddar recept...</p>
</main>
);
}
return (
<main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}>
<h1>Redigera recept</h1>
{error && <p style={{ color: 'red' }}>{error}</p>}
<form onSubmit={handleSubmit} style={{ display: 'grid', gap: '1rem' }}>
<div style={{ display: 'grid', gap: '0.5rem' }}>
<label>
Receptnamn:
<input
type="text"
value={recipe.name}
onChange={(e) => setRecipe({ ...recipe, name: e.target.value })}
required
style={{ width: '100%', padding: '0.5rem' }}
/>
</label>
<label>
Beskrivning:
<textarea
value={recipe.description}
onChange={(e) => setRecipe({ ...recipe, description: e.target.value })}
style={{ width: '100%', padding: '0.5rem', minHeight: '100px' }}
/>
</label>
<label>
Instruktioner:
<textarea
value={recipe.instructions}
onChange={(e) => setRecipe({ ...recipe, instructions: e.target.value })}
style={{ width: '100%', padding: '0.5rem', minHeight: '100px' }}
/>
</label>
</div>
<h2>Ingredienser</h2>
{recipe.ingredients.map((ingredient, index) => (
<div key={index} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr auto', gap: '0.5rem', alignItems: 'center' }}>
<select
value={ingredient.productId}
onChange={(e) => handleIngredientChange(index, 'productId', Number(e.target.value))}
required
style={{ padding: '0.5rem' }}
>
<option value={0}>Välj produkt</option>
{products.length > 0 ? products.map((product) => (
<option key={product.id} value={product.id}>
{product.name}
</option>
)) : <option disabled>Kunde inte ladda produkter</option>}
</select>
<input
type="text"
placeholder="Mängd"
value={ingredient.quantity}
onChange={(e) => handleIngredientChange(index, 'quantity', e.target.value)}
required
style={{ padding: '0.5rem' }}
/>
<select
value={ingredient.unit}
onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)}
required
style={{ padding: '0.5rem' }}
>
{UNIT_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
<input
type="text"
placeholder="Notering (valfritt)"
value={ingredient.note || ''}
onChange={(e) => handleIngredientChange(index, 'note', e.target.value)}
style={{ padding: '0.5rem' }}
/>
<button type="button" onClick={() => removeIngredient(index)} style={{ padding: '0.5rem' }}>
Ta bort
</button>
</div>
))}
{products.length === 0 && (
<div style={{ color: 'red' }}>
Kunde inte ladda produkter. Kontrollera API:et.
</div>
)}
<div style={{ display: 'flex', gap: '1rem' }}>
<button type="button" onClick={addIngredient} style={{ padding: '0.5rem' }}>
Lägg till ingrediens
</button>
<button type="submit" disabled={isSaving} style={{ padding: '0.5rem' }}>
{isSaving ? 'Uppdaterar...' : 'Uppdatera recept'}
</button>
<button
type="button"
onClick={() => router.push('/recipes')}
style={{ padding: '0.5rem', background: '#f0f0f0', color: '#333', border: '1px solid #ccc', borderRadius: '4px', cursor: 'pointer' }}
>
Avbryt
</button>
</div>
</form>
</main>
);
}