Refactor logging in IcaRecipeParser and QuickImportService to use NestJS Logger

- Updated IcaRecipeParser to replace console.log statements with Logger for better logging practices.
- Enhanced QuickImportService with Logger for consistent logging and error handling.
- Changed quantity validation in CreateRecipeIngredientDto and CreateRecipeDto to allow zero.
- Removed CanonicalNameForm and NameForm components from the frontend.
- Updated EditProductForm to use a select dropdown for categories instead of a text input.
- Added validation for product name, canonical name, and category length in product update action.
- Refactored unit options into a separate file for better reusability across components.
- Removed unused API fetching functions and inventory types to clean up the codebase.
This commit is contained in:
Nils-Johan Gynther
2026-04-16 18:18:27 +02:00
parent 3f6d32ae44
commit d5b360fd62
19 changed files with 74 additions and 751 deletions
@@ -9,6 +9,7 @@ import type {
} from '../../../features/inventory/types';
import { fetchJson } from '../../../lib/api';
import { parseErrorResponse } from '../../../lib/error-handler';
import { UNIT_OPTIONS } from '../../../lib/units';
// ──────────────────────────────────────────────
// Hjälpfunktioner
@@ -50,23 +51,6 @@ function StatusBadge({ status }: { status: 'enough' | 'missing' | 'unit_mismatch
);
}
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)' },
{ value: 'port', label: 'port (portioner)' },
{ value: 'efter smak', label: 'Efter smak' },
{ value: 'förp', label: 'förp (förpackning)' },
{ value: 'klyfta', label: 'klyfta' },
];
// ──────────────────────────────────────────────
// Huvud-komponent
// ──────────────────────────────────────────────
@@ -1,476 +0,0 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { fetchJson } from '../../../lib/api';
import { parseErrorResponse } from '../../../lib/error-handler';
import type { Product } from '../../../features/inventory/types';
import Navigation from '../../Navigation';
const MARKDOWN_HELP = `
**Fetstil:** **text** eller __text__
*Kursiv:* *text* eller _text_
• Punktlista: - punkt eller * punkt
# Rubrik 1
## Rubrik 2
### Rubrik 3
`;
function SimpleMarkdownPreview({ text }: { text: string }) {
const lines = text.split('\n');
return (
<div style={{ whiteSpace: 'pre-wrap', lineHeight: 1.6, wordBreak: 'break-word' }}>
{lines.map((line, i) => {
if (line.startsWith('# ')) {
return <h3 key={i} style={{ margin: '0.5rem 0 0.25rem 0', fontSize: '1.3em', fontWeight: 700 }}>{line.slice(2)}</h3>;
}
if (line.startsWith('## ')) {
return <h4 key={i} style={{ margin: '0.5rem 0 0.25rem 0', fontSize: '1.1em', fontWeight: 700 }}>{line.slice(3)}</h4>;
}
if (line.startsWith('- ') || line.startsWith('* ')) {
return <div key={i} style={{ marginLeft: '1.5rem' }}> {line.slice(2)}</div>;
}
if (line.trim() === '') {
return <div key={i} style={{ height: '0.5rem' }} />;
}
return <div key={i}>{line}</div>;
})}
</div>
);
}
export default function CreateRecipePage() {
const router = useRouter();
const [recipe, setRecipe] = useState({
name: '',
description: '',
instructions: '',
ingredients: [{ productId: 0, quantity: '', unit: '', note: '', location: '' }],
});
const [products, setProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [showPreview, setShowPreview] = useState(false);
const [showMarkdownHelp, setShowMarkdownHelp] = useState(false);
useEffect(() => {
fetchJson<Product[]>('/api/products')
.then(setProducts)
.catch(console.error);
}, []);
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();
setIsLoading(true);
setError(null);
// Konvertera quantity till number för varje ingrediens
const recipeToSend = {
...recipe,
ingredients: recipe.ingredients.map(({ location: _loc, ...ing }) => ({
...ing,
quantity: Number(ing.quantity),
})),
};
try {
const response = await fetch('/api/recipes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(recipeToSend),
});
if (!response.ok) {
const errorMessage = await parseErrorResponse(response);
throw new Error(errorMessage);
}
router.push('/recipes');
} catch (err) {
const message = err instanceof Error ? err.message : 'Ett okänt fel inträffade. Försök igen.';
setError(message);
} finally {
setIsLoading(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)' },
{ value: 'krm', label: 'krm (kryddmått)' },
{ value: 'port', label: 'port (portioner)' },
{ value: 'efter smak', label: 'Efter smak' },
{ value: 'förp', label: 'förp (förpackning)' },
{ value: 'klyfta', label: 'klyfta' },
];
const LOCATION_OPTIONS = [
{ value: '', label: 'Välj plats' },
{ value: 'Kyl', label: 'Kyl' },
{ value: 'Frys', label: 'Frys' },
{ value: 'Skafferi', label: 'Skafferi' },
{ value: 'Annat', label: 'Annat' },
];
return (
<main style={{ padding: '1rem', maxWidth: '1000px', margin: '0 auto' }}>
<Navigation />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
<h1 style={{ margin: 0 }}>Lägg till nytt recept</h1>
<Link
href="/recipes/import"
style={{
padding: '0.5rem 1rem',
background: '#f0f0f0',
color: '#333',
borderRadius: '4px',
textDecoration: 'none',
fontWeight: 500,
fontSize: '0.9rem',
border: '1px solid #ddd',
}}
>
Importera från Markdown
</Link>
</div>
{error && <p style={{ color: 'crimson', backgroundColor: '#ffe5e5', padding: '0.75rem', borderRadius: '4px', marginBottom: '1rem' }}>{error}</p>}
<form onSubmit={handleSubmit} style={{ display: 'grid', gap: '1.5rem' }}>
{/* Receptdetaljer */}
<section style={{ display: 'grid', gap: '1rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2 style={{ margin: 0, fontSize: '1.1rem' }}>Receptdetaljer</h2>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
Receptnamn *
</label>
<input
type="text"
value={recipe.name}
onChange={(e) => setRecipe({ ...recipe, name: e.target.value })}
required
style={{
width: '100%',
padding: '0.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '44px',
boxSizing: 'border-box',
}}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
Beskrivning
</label>
<textarea
value={recipe.description}
onChange={(e) => setRecipe({ ...recipe, description: e.target.value })}
placeholder="Kort beskrivning av receptet..."
style={{
width: '100%',
padding: '0.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '100px',
fontFamily: 'inherit',
boxSizing: 'border-box',
}}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
Instruktioner
</label>
<button
type="button"
onClick={() => setShowMarkdownHelp(!showMarkdownHelp)}
style={{
marginBottom: '0.5rem',
padding: '0.4rem 0.75rem',
background: '#f9f9f9',
border: '1px solid #ddd',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '0.85rem',
color: '#666',
fontWeight: 500,
display: 'flex',
alignItems: 'center',
gap: '0.25rem',
}}
>
<span>{showMarkdownHelp ? '▼' : '▶'}</span>
<strong>Markdown-stöd</strong>
</button>
{showMarkdownHelp && (
<div style={{ marginBottom: '0.5rem', fontSize: '0.85rem', background: '#f9f9f9', padding: '0.5rem', borderRadius: '4px', color: '#666' }}>
<div style={{ whiteSpace: 'pre-wrap', marginTop: '0.25rem' }}>{MARKDOWN_HELP}</div>
</div>
)}
<textarea
value={recipe.instructions}
onChange={(e) => setRecipe({ ...recipe, instructions: e.target.value })}
placeholder="Skriv instruktioner här. Du kan använda Markdown för formatering."
style={{
width: '100%',
padding: '0.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '150px',
fontFamily: 'inherit',
boxSizing: 'border-box',
}}
/>
<button
type="button"
onClick={() => setShowPreview(!showPreview)}
style={{
marginTop: '0.5rem',
padding: '0.5rem 1rem',
background: '#f0f0f0',
border: '1px solid #ddd',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '0.9rem',
}}
>
{showPreview ? '✕ Dölj förhandsvisning' : '👁 Visa förhandsvisning'}
</button>
{showPreview && recipe.instructions && (
<div style={{
marginTop: '1rem',
padding: '1rem',
background: '#fafafa',
border: '1px solid #ddd',
borderRadius: '4px',
maxHeight: '300px',
overflowY: 'auto',
}}>
<strong>Förhandsvisning:</strong>
<SimpleMarkdownPreview text={recipe.instructions} />
</div>
)}
</div>
</section>
{/* Ingredienser */}
<section style={{ display: 'grid', gap: '1rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2 style={{ margin: 0, fontSize: '1.1rem' }}>Ingredienser</h2>
{recipe.ingredients.map((ingredient, index) => (
<div
key={index}
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
gap: '0.5rem',
alignItems: 'flex-end',
padding: '0.75rem',
background: '#f9f9f9',
borderRadius: '4px',
}}
>
<select
value={ingredient.productId}
onChange={(e) => handleIngredientChange(index, 'productId', Number(e.target.value))}
required
style={{
padding: '0.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '44px',
boxSizing: 'border-box',
width: '100%',
}}
>
<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.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '44px',
boxSizing: 'border-box',
width: '100%',
}}
/>
<select
value={ingredient.unit}
onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)}
required
style={{
padding: '0.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '44px',
boxSizing: 'border-box',
width: '100%',
}}
>
{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.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '44px',
boxSizing: 'border-box',
width: '100%',
}}
/>
<button
type="button"
onClick={() => removeIngredient(index)}
style={{
padding: '0.75rem 1rem',
background: '#fee',
color: '#c00',
border: '1px solid #faa',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '1rem',
minHeight: '44px',
fontWeight: 600,
}}
>
Ta bort
</button>
</div>
))}
{products.length === 0 && (
<div style={{ color: 'crimson', background: '#ffe5e5', padding: '0.75rem', borderRadius: '4px' }}>
Kunde inte ladda produkter. Kontrollera API:et.
</div>
)}
<button
type="button"
onClick={addIngredient}
style={{
padding: '0.75rem 1rem',
background: '#e8f5e9',
color: '#2e7d32',
border: '1px solid #81c784',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '1rem',
minHeight: '44px',
fontWeight: 600,
}}
>
+ Lägg till ingrediens
</button>
</section>
{/* Knappar */}
<div style={{
display: 'flex',
gap: '0.75rem',
flexWrap: 'wrap',
}}>
<button
type="submit"
disabled={isLoading}
style={{
padding: '0.75rem 1.5rem',
background: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '1rem',
minHeight: '44px',
fontWeight: 600,
}}
>
{isLoading ? '⏳ Sparar...' : '💾 Spara recept'}
</button>
<button
type="button"
onClick={() => router.push('/recipes')}
style={{
padding: '0.75rem 1.5rem',
background: '#f0f0f0',
color: '#333',
border: '1px solid #ccc',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '1rem',
minHeight: '44px',
}}
>
Avbryt
</button>
</div>
</form>
</main>
);
}
@@ -6,6 +6,7 @@ import { fetchJson } from '../../../lib/api';
import { parseErrorResponse } from '../../../lib/error-handler';
import type { Product } from '../../../features/inventory/types';
import Navigation from '../../Navigation';
import { UNIT_OPTIONS } from '../../../lib/units';
type ProductSuggestion = {
productId: number;
@@ -33,24 +34,6 @@ type ParseResult = {
ingredients: ParsedIngredientRow[];
};
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)' },
{ value: 'krm', label: 'krm (kryddmått)' },
{ value: 'port', label: 'port (portioner)' },
{ value: 'efter smak', label: 'Efter smak' },
{ value: 'förp', label: 'förp (förpackning)' },
{ value: 'klyfta', label: 'klyfta' },
];
type Step = 'input' | 'review' | 'saving';
export default function ImportRecipePage() {
+1 -18
View File
@@ -6,6 +6,7 @@ import { fetchJson } from '../../../lib/api';
import { parseErrorResponse } from '../../../lib/error-handler';
import type { Product } from '../../../features/inventory/types';
import Navigation from '../../Navigation';
import { UNIT_OPTIONS } from '../../../lib/units';
type ProductSuggestion = {
productId: number;
@@ -32,24 +33,6 @@ type ParseResult = {
ingredients: ParsedIngredientRow[];
};
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)' },
{ value: 'krm', label: 'krm (kryddmått)' },
{ value: 'port', label: 'port (portioner)' },
{ value: 'efter smak', label: 'Efter smak' },
{ value: 'förp', label: 'förp (förpackning)' },
{ value: 'klyfta', label: 'klyfta' },
];
type Step = 'input' | 'review' | 'saving';
export default function WriteRecipePage() {