feat: Implement quick import feature for recipes

- Added QuickImportController and QuickImportService to handle recipe imports from URLs and file paths.
- Created QuickImportModule to encapsulate the quick import functionality.
- Developed frontend ImportFilePage for users to upload files or enter URLs for recipe import.
- Integrated API proxy to communicate with the backend for quick import requests.
- Implemented WriteRecipePage for users to manually input recipes with Markdown support.
- Added page routing for the new import and write recipe functionalities.
This commit is contained in:
Nils-Johan Gynther
2026-04-12 07:41:18 +02:00
parent ea971c2f63
commit 4f183df711
12 changed files with 1379 additions and 61 deletions
@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const { input } = await request.json();
if (!input || typeof input !== 'string') {
return NextResponse.json(
{ error: 'Du måste ange en URL eller filsökväg' },
{ status: 400 }
);
}
// Anropa backend
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
const response = await fetch(`${backendUrl}/api/quick-import`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: input.trim() }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
return NextResponse.json(
{ error: errorData.message || 'Importen misslyckades' },
{ status: response.status }
);
}
const data = await response.json();
return NextResponse.json(data);
} catch (error) {
console.error('Quick import error:', error);
return NextResponse.json(
{ error: 'Serverfelet vid import. Försök igen senare.' },
{ status: 500 }
);
}
}
+221 -3
View File
@@ -1,5 +1,223 @@
import CreateRecipePage from './CreateRecipePage';
'use client';
export default function Page() {
return <CreateRecipePage />;
import Link from 'next/link';
import { useState } from 'react';
import Navigation from '../../Navigation';
import { parseErrorResponse } from '../../../lib/error-handler';
import { useRouter } from 'next/navigation';
export default function CreateRecipePage() {
const router = useRouter();
const [quickImportUrl, setQuickImportUrl] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleQuickImport = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsLoading(true);
try {
const input = quickImportUrl.trim();
if (!input) {
setError('Vänligen ange en URL eller filsökväg');
setIsLoading(false);
return;
}
// Försök importera från URL eller fil
const res = await fetch('/api/quick-import-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input }),
});
if (!res.ok) {
const errorMessage = await parseErrorResponse(res);
setError(errorMessage || 'Importen misslyckades. Kontrollera att länken eller filsökvägen är korrekt.');
setIsLoading(false);
return;
}
const data = await res.json();
if (data.markdown) {
// Omdirigera till /recipes/write med förifylld Markdown
// Vi använder sessionStorage för att passa data mellan sidor
sessionStorage.setItem('prefilled_markdown', data.markdown);
router.push('/recipes/write');
}
} catch (err) {
const message = err instanceof Error ? err.message : 'Något oväntad gick fel';
setError(`Fel: ${message}`);
} finally {
setIsLoading(false);
}
};
return (
<main style={{ padding: '1rem', maxWidth: '800px', margin: '0 auto' }}>
<Navigation />
<h1 style={{ marginBottom: '1.5rem' }}>Lägg till nytt recept</h1>
{/* SNABBIMPORT-SEKTION */}
<div
style={{
background: '#fef3c7',
border: '2px solid #f59e0b',
borderRadius: '8px',
padding: '1.5rem',
marginBottom: '2rem',
}}
>
<h2 style={{ margin: '0 0 0.5rem 0', fontSize: '1.1rem', color: '#92400e' }}>
Snabbimport
</h2>
<p style={{ margin: '0 0 1rem 0', color: '#92400e', fontSize: '0.9rem' }}>
Klistra in en ICA-receptlänk eller filsökväg för att importera direkt:
</p>
<form onSubmit={handleQuickImport} style={{ display: 'grid', gap: '0.75rem' }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '0.5rem' }}>
<input
type="text"
value={quickImportUrl}
onChange={(e) => setQuickImportUrl(e.target.value)}
placeholder="https://www.ica.se/recept/... eller C:\recepter\file.pdf"
style={{
padding: '0.75rem',
border: '1px solid #d97706',
borderRadius: '4px',
fontSize: '0.95rem',
boxSizing: 'border-box',
}}
disabled={isLoading}
/>
<button
type="submit"
disabled={isLoading || !quickImportUrl.trim()}
style={{
padding: '0.75rem 1.5rem',
background: '#f59e0b',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: isLoading || !quickImportUrl.trim() ? 'not-allowed' : 'pointer',
opacity: isLoading || !quickImportUrl.trim() ? 0.6 : 1,
fontSize: '0.95rem',
fontWeight: 600,
whiteSpace: 'nowrap',
}}
>
{isLoading ? 'Laddar...' : '→'}
</button>
</div>
{error && (
<p
style={{
margin: '0.5rem 0 0 0',
color: '#991b1b',
background: '#fee2e2',
padding: '0.75rem',
borderRadius: '4px',
fontSize: '0.85rem',
}}
>
{error}
</p>
)}
<p style={{ margin: '0.75rem 0 0 0', color: '#92400e', fontSize: '0.8rem' }}>
Stöds: ICA-recept, PDF-filer
</p>
</form>
</div>
{/* ELLER-SEPARATOR */}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '1rem',
margin: '2rem 0',
color: '#999',
}}
>
<div style={{ flex: 1, height: '1px', background: '#ddd' }} />
<span style={{ fontSize: '0.9rem', fontWeight: 500 }}>eller</span>
<div style={{ flex: 1, height: '1px', background: '#ddd' }} />
</div>
{/* KLASSISKA ALTERNATIV */}
<p style={{ marginBottom: '2rem', color: '#666' }}>
Välj ett sätt att lägga till ett recept:
</p>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: '1.5rem',
}}
>
{/* Skriv in recept */}
<Link
href="/recipes/write"
style={{
padding: '2rem',
border: '2px solid #0070f3',
borderRadius: '8px',
textDecoration: 'none',
background: 'linear-gradient(135deg, #e3f2fd 0%, #ffffff 100%)',
transition: 'all 0.2s',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
(e.currentTarget as HTMLElement).style.transform = 'translateY(-4px)';
(e.currentTarget as HTMLElement).style.boxShadow = '0 8px 16px rgba(0,112,243,0.2)';
}}
onMouseLeave={(e) => {
(e.currentTarget as HTMLElement).style.transform = 'translateY(0)';
(e.currentTarget as HTMLElement).style.boxShadow = 'none';
}}
>
<h2 style={{ margin: '0 0 0.5rem 0', color: '#0070f3', fontSize: '1.3rem' }}>
Skriv in recept
</h2>
<p style={{ margin: 0, color: '#666', fontSize: '0.9rem' }}>
Skriv in receptet med ingredienser och instruktioner
</p>
</Link>
{/* Importera från fil/länk */}
<Link
href="/recipes/import"
style={{
padding: '2rem',
border: '2px solid #10b981',
borderRadius: '8px',
textDecoration: 'none',
background: 'linear-gradient(135deg, #ecfdf5 0%, #ffffff 100%)',
transition: 'all 0.2s',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
(e.currentTarget as HTMLElement).style.transform = 'translateY(-4px)';
(e.currentTarget as HTMLElement).style.boxShadow = '0 8px 16px rgba(16,185,129,0.2)';
}}
onMouseLeave={(e) => {
(e.currentTarget as HTMLElement).style.transform = 'translateY(0)';
(e.currentTarget as HTMLElement).style.boxShadow = 'none';
}}
>
<h2 style={{ margin: '0 0 0.5rem 0', color: '#10b981', fontSize: '1.3rem' }}>
📥 Importera från fil
</h2>
<p style={{ margin: 0, color: '#666', fontSize: '0.9rem' }}>
Ladda upp PDF, länk eller annan filtyp
</p>
</Link>
</div>
</main>
);
}
@@ -0,0 +1,276 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import Navigation from '../../Navigation';
export default function ImportFilePage() {
const [selectedMethod, setSelectedMethod] = useState<'file' | 'url' | null>(null);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setError(null);
setUploadProgress(0);
// Placeholder för filuppladdning
// I framtiden kan detta hanteras med backend-endpoint för PDF-parsing
if (file.type === 'application/pdf') {
setError('PDF-import är under utveckling. Använd "Skriv in recept" för att mata in recept manuellt.');
} else {
setError('Endast PDF-filer stöds för närvarande.');
}
setUploadProgress(0);
};
const handleURLSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const url = formData.get('url') as string;
if (!url) {
setError('Vänligen ange en URL');
return;
}
setError('Länk-import är under utveckling. Använd "Skriv in recept" för att mata in recept manuellt.');
};
return (
<main style={{ padding: '1rem', maxWidth: '900px', margin: '0 auto' }}>
<Navigation />
<h1 style={{ marginBottom: '0.5rem' }}>Importera från fil eller länk</h1>
<p style={{ color: '#666', marginBottom: '1.5rem' }}>
Ladda upp en receptfil (PDF) eller ange en URL för att importera ett recept.
</p>
{error && (
<div
style={{
background: '#fef2f2',
border: '1px solid #fca5a5',
borderRadius: '6px',
padding: '1rem',
marginBottom: '1.5rem',
color: '#dc2626',
fontSize: '0.95rem',
}}
>
{error}
</div>
)}
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: '1.5rem',
marginBottom: '2rem',
}}
>
{/* Fil-upload */}
<div
onClick={() => setSelectedMethod('file')}
style={{
padding: '2rem',
border: selectedMethod === 'file' ? '2px solid #0070f3' : '2px solid #e5e7eb',
borderRadius: '8px',
background: selectedMethod === 'file' ? '#f0f9ff' : '#f9fafb',
cursor: 'pointer',
transition: 'all 0.2s',
}}
>
<h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#0070f3' }}>
📄 Ladda upp fil
</h2>
<p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}>
Ladda upp ett recept från en PDF eller textfil
</p>
{selectedMethod === 'file' && (
<div style={{ marginTop: '1rem' }}>
<label
style={{
display: 'block',
padding: '1rem',
background: 'white',
border: '2px dashed #0070f3',
borderRadius: '6px',
textAlign: 'center',
cursor: 'pointer',
transition: 'all 0.2s',
}}
onDragOver={(e) => {
e.preventDefault();
(e.currentTarget as HTMLElement).style.background = '#e3f2fd';
}}
onDragLeave={(e) => {
(e.currentTarget as HTMLElement).style.background = 'white';
}}
>
<input
type="file"
accept=".pdf,.txt,.docx"
onChange={handleFileUpload}
style={{ display: 'none' }}
/>
<p style={{ margin: '0', color: '#0070f3', fontWeight: 600 }}>
Dra och släpp fil här
</p>
<p style={{ margin: '0.5rem 0 0 0', color: '#999', fontSize: '0.85rem' }}>
eller klicka för att välja
</p>
<p style={{ margin: '0.5rem 0 0 0', color: '#999', fontSize: '0.8rem' }}>
PDF, TXT, DOCX stöds
</p>
</label>
{uploadProgress > 0 && uploadProgress < 100 && (
<div style={{ marginTop: '0.75rem' }}>
<div
style={{
width: '100%',
height: '6px',
background: '#e5e7eb',
borderRadius: '3px',
overflow: 'hidden',
}}
>
<div
style={{
height: '100%',
background: '#0070f3',
width: `${uploadProgress}%`,
transition: 'width 0.3s',
}}
/>
</div>
<p style={{ margin: '0.5rem 0 0 0', fontSize: '0.85rem', color: '#666' }}>
{uploadProgress}%
</p>
</div>
)}
</div>
)}
</div>
{/* URL-import */}
<div
onClick={() => setSelectedMethod('url')}
style={{
padding: '2rem',
border: selectedMethod === 'url' ? '2px solid #10b981' : '2px solid #e5e7eb',
borderRadius: '8px',
background: selectedMethod === 'url' ? '#f0fdf4' : '#f9fafb',
cursor: 'pointer',
transition: 'all 0.2s',
}}
>
<h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#10b981' }}>
🔗 Länk till recept
</h2>
<p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}>
Ange URL till en receptsida eller blogg
</p>
{selectedMethod === 'url' && (
<form onSubmit={handleURLSubmit} style={{ marginTop: '1rem' }}>
<input
type="url"
name="url"
placeholder="https://exempel.se/recept/..."
style={{
width: '100%',
padding: '0.75rem',
border: '1px solid #d1d5db',
borderRadius: '6px',
fontSize: '0.9rem',
boxSizing: 'border-box',
marginBottom: '0.75rem',
}}
/>
<button
type="submit"
style={{
width: '100%',
padding: '0.75rem',
background: '#10b981',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontWeight: 500,
fontSize: '0.95rem',
}}
>
Importera från länk
</button>
</form>
)}
</div>
</div>
{/* Info-box */}
<div
style={{
background: '#fef3c7',
border: '1px solid #fcd34d',
borderRadius: '6px',
padding: '1rem',
marginBottom: '1.5rem',
color: '#92400e',
fontSize: '0.9rem',
}}
>
<strong>💡 Tips:</strong> För närvarande är PDF och länk-import under utveckling. Du kan{' '}
<Link
href="/recipes/write"
style={{ color: '#0070f3', textDecoration: 'none', fontWeight: 600 }}
>
skriv in receptet manuellt
</Link>{' '}
eller prova att ladda upp en fil och se om det fungerar.
</div>
{/* Knapp för att gå tillbaka */}
<div style={{ display: 'flex', gap: '1rem' }}>
<Link
href="/recipes/create"
style={{
padding: '0.75rem 1.5rem',
background: 'transparent',
border: '1px solid #ddd',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '1rem',
textDecoration: 'none',
color: '#333',
fontWeight: 500,
}}
>
Tillbaka
</Link>
<Link
href="/recipes/write"
style={{
padding: '0.75rem 1.5rem',
background: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
textDecoration: 'none',
cursor: 'pointer',
fontSize: '1rem',
fontWeight: 500,
}}
>
Skriv in recept istället
</Link>
</div>
</main>
);
}
+2 -2
View File
@@ -1,5 +1,5 @@
import ImportRecipePage from './ImportRecipePage';
import ImportFilePage from './ImportFilePage';
export default function Page() {
return <ImportRecipePage />;
return <ImportFilePage />;
}
@@ -0,0 +1,460 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { fetchJson } from '../../../lib/api';
import { parseErrorResponse } from '../../../lib/error-handler';
import type { Product } from '../../../features/inventory/types';
import Navigation from '../../Navigation';
type ProductSuggestion = {
productId: number;
productName: string;
score: number;
};
type ParsedIngredientRow = {
rawName: string;
quantity: number;
unit: string;
note?: string;
suggestions: ProductSuggestion[];
selectedProductId: number;
editedQuantity: string;
editedUnit: string;
editedNote: string;
};
type ParseResult = {
name: string;
description?: string;
instructions?: string;
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)' },
];
type Step = 'input' | 'review' | 'saving';
export default function WriteRecipePage() {
const router = useRouter();
const [step, setStep] = useState<Step>('input');
const [markdown, setMarkdown] = useState('');
const [parsed, setParsed] = useState<ParseResult | null>(null);
const [editedName, setEditedName] = useState('');
const [editedDescription, setEditedDescription] = useState('');
const [editedInstructions, setEditedInstructions] = useState('');
const [ingredients, setIngredients] = useState<ParsedIngredientRow[]>([]);
const [allProducts, setAllProducts] = useState<Product[]>([]);
const [isParsing, setIsParsing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Hämta produkter från databas
fetchJson<Product[]>('/api/products')
.then(setAllProducts)
.catch(console.error);
// Kontrollera om det finns förifylld Markdown från snabbimport
const prefilledMarkdown = sessionStorage.getItem('prefilled_markdown');
if (prefilledMarkdown) {
setMarkdown(prefilledMarkdown);
sessionStorage.removeItem('prefilled_markdown');
// Auto-parse om Markdown finns
setTimeout(() => {
// Markeringen för auto-parse görs via en flag
sessionStorage.setItem('auto_parse_markdown', 'true');
}, 100);
}
}, []);
const handleParse = async () => {
if (!markdown.trim()) return;
setIsParsing(true);
setError(null);
try {
const res = await fetch('/api/parse-markdown-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ markdown }),
});
if (!res.ok) {
const errorMessage = await parseErrorResponse(res);
throw new Error(errorMessage);
}
const data = await res.json();
const rows: ParsedIngredientRow[] = data.ingredients.map(
(ing: Omit<ParsedIngredientRow, 'selectedProductId' | 'editedQuantity' | 'editedUnit' | 'editedNote'>) => ({
...ing,
selectedProductId: ing.suggestions[0]?.productId ?? 0,
editedQuantity: String(ing.quantity),
editedUnit: ing.unit,
editedNote: ing.note ?? '',
}),
);
setParsed(data);
setEditedName(data.name);
setEditedDescription(data.description ?? '');
setEditedInstructions(data.instructions ?? '');
setIngredients(rows);
setStep('review');
} catch (err) {
const message = err instanceof Error ? err.message : 'Något gick fel vid tolkning.';
setError(message);
} finally {
setIsParsing(false);
}
};
const updateIngredient = (index: number, field: keyof ParsedIngredientRow, value: string | number) => {
setIngredients((prev) => {
const updated = [...prev];
updated[index] = { ...updated[index], [field]: value };
return updated;
});
};
const removeIngredient = (index: number) => {
setIngredients((prev) => prev.filter((_, i) => i !== index));
};
const handleSave = async () => {
setIsSaving(true);
setError(null);
const validIngredients = ingredients.filter((ing) => ing.selectedProductId > 0);
if (validIngredients.length === 0) {
setError('Minst en ingrediens med vald produkt krävs.');
setIsSaving(false);
return;
}
const body = {
name: editedName,
description: editedDescription || undefined,
instructions: editedInstructions || undefined,
ingredients: validIngredients.map((ing) => ({
productId: ing.selectedProductId,
quantity: Number(ing.editedQuantity),
unit: ing.editedUnit,
note: ing.editedNote || undefined,
})),
};
try {
const res = await fetch('/api/recipes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
const errorMessage = await parseErrorResponse(res);
throw new Error(errorMessage);
}
router.push('/recipes');
} catch (err) {
const message = err instanceof Error ? err.message : 'Något gick fel vid sparning.';
setError(message);
} finally {
setIsSaving(false);
}
};
return (
<main style={{ padding: '1rem', maxWidth: '1000px', margin: '0 auto' }}>
<Navigation />
<h1 style={{ marginBottom: '0.5rem' }}>Skriv in recept</h1>
<p style={{ color: '#666', marginBottom: '1.5rem' }}>Skriv receptet i Markdown-format nama, ingredienser och instruktioner.</p>
{/* Steg-indikator */}
<div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.5rem', fontSize: '0.9rem', color: '#666' }}>
<span style={{ fontWeight: step === 'input' ? 700 : 400, color: step === 'input' ? '#0070f3' : '#666' }}>
1. Skriv
</span>
<span></span>
<span style={{ fontWeight: step === 'review' ? 700 : 400, color: step === 'review' ? '#0070f3' : '#666' }}>
2. Granska
</span>
<span></span>
<span style={{ color: '#999' }}>3. Spara</span>
</div>
{error && (
<p style={{ color: 'crimson', backgroundColor: '#ffe5e5', padding: '0.75rem', borderRadius: '4px', marginBottom: '1rem' }}>
{error}
</p>
)}
{/* STEG 1: Markdown-inmatning */}
{step === 'input' && (
<section style={{ display: 'grid', gap: '1rem' }}>
<div style={{ background: '#f9f9f9', border: '1px solid #ddd', borderRadius: '8px', padding: '1rem', fontSize: '0.875rem', color: '#555' }}>
<strong>Förväntat format:</strong>
<pre style={{ margin: '0.5rem 0 0', fontFamily: 'monospace', whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>{`# Receptnamn
Valfri beskrivning av receptet.
## Ingredienser
- 500 g köttfärs
- 1 st lök
- 2 msk tomatpuré
- 1 dl grädde (vispgrädde)
## Tillvägagångssätt
Stek löken i lite smör. Tillsätt köttfärsen...`}</pre>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
Skriv ditt recept i Markdown-format
</label>
<textarea
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
placeholder="# Mitt recept&#10;&#10;## Ingredienser&#10;- 500 g köttfärs"
style={{
width: '100%',
padding: '0.75rem',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '1rem',
minHeight: '300px',
fontFamily: 'monospace',
boxSizing: 'border-box',
}}
/>
</div>
<div style={{ display: 'flex', gap: '1rem' }}>
<button
onClick={handleParse}
disabled={isParsing || !markdown.trim()}
style={{
padding: '0.75rem 1.5rem',
background: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: isParsing || !markdown.trim() ? 'not-allowed' : 'pointer',
opacity: isParsing || !markdown.trim() ? 0.6 : 1,
fontSize: '1rem',
fontWeight: 500,
}}
>
{isParsing ? 'Tolkar...' : 'Tolka och granska'}
</button>
<button
onClick={() => router.push('/recipes')}
style={{ padding: '0.75rem 1rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '4px', cursor: 'pointer', fontSize: '1rem' }}
>
Avbryt
</button>
</div>
</section>
)}
{/* STEG 2: Granskning */}
{step === 'review' && parsed && (
<section style={{ display: 'grid', gap: '1.5rem' }}>
{/* Receptdetaljer */}
<div 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={editedName}
onChange={(e) => setEditedName(e.target.value)}
required
style={{ width: '100%', padding: '0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem', boxSizing: 'border-box' }}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Beskrivning</label>
<textarea
value={editedDescription}
onChange={(e) => setEditedDescription(e.target.value)}
style={{ width: '100%', padding: '0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem', minHeight: '80px', fontFamily: 'inherit', boxSizing: 'border-box' }}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Instruktioner</label>
<textarea
value={editedInstructions}
onChange={(e) => setEditedInstructions(e.target.value)}
style={{ width: '100%', padding: '0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem', minHeight: '150px', fontFamily: 'monospace', boxSizing: 'border-box' }}
/>
</div>
</div>
{/* Ingredienser */}
<div style={{ display: 'grid', gap: '0.75rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
<h2 style={{ margin: 0, fontSize: '1.1rem' }}>
Ingredienser{' '}
<span style={{ fontWeight: 400, fontSize: '0.875rem', color: '#666' }}>
välj produkt från databasen för varje rad
</span>
</h2>
{ingredients.map((ing, index) => (
<div
key={index}
style={{ display: 'grid', gap: '0.5rem', padding: '0.75rem', background: '#f9f9f9', borderRadius: '6px', border: '1px solid #eee' }}
>
{/* Rå text från Markdown */}
<div style={{ fontSize: '0.85rem', color: '#888', fontStyle: 'italic' }}>
Tolkad som: <strong style={{ color: '#555' }}>{ing.rawName}</strong>
{ing.suggestions.length > 0 && (
<span style={{ marginLeft: '0.5rem', color: '#0070f3' }}>
(bästa match: {ing.suggestions[0].productName}, {ing.suggestions[0].score}%)
</span>
)}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: '0.5rem', alignItems: 'end' }}>
{/* Produktval */}
<div>
<label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', fontWeight: 600 }}>Produkt *</label>
<select
value={ing.selectedProductId}
onChange={(e) => updateIngredient(index, 'selectedProductId', Number(e.target.value))}
style={{ width: '100%', padding: '0.5rem', border: ing.selectedProductId === 0 ? '1px solid #f59e0b' : '1px solid #ddd', borderRadius: '4px', fontSize: '0.9rem', background: ing.selectedProductId === 0 ? '#fffbeb' : 'white' }}
>
<option value={0}> Välj produkt </option>
{/* Förslag från backend (sorterade efter matchningspoäng) */}
{ing.suggestions.length > 0 && (
<optgroup label="Föreslagna matchningar">
{ing.suggestions.map((s) => (
<option key={s.productId} value={s.productId}>
{s.productName} ({s.score}%)
</option>
))}
</optgroup>
)}
<optgroup label="Alla produkter">
{allProducts.map((p) => (
<option key={p.id} value={p.id}>
{p.canonicalName || p.name}
</option>
))}
</optgroup>
</select>
</div>
{/* Mängd */}
<div>
<label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', fontWeight: 600 }}>Mängd</label>
<input
type="number"
value={ing.editedQuantity}
onChange={(e) => updateIngredient(index, 'editedQuantity', e.target.value)}
min="0.01"
step="0.01"
style={{ width: '100%', padding: '0.5rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '0.9rem', boxSizing: 'border-box' }}
/>
</div>
{/* Enhet */}
<div>
<label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', fontWeight: 600 }}>Enhet</label>
<select
value={ing.editedUnit}
onChange={(e) => updateIngredient(index, 'editedUnit', e.target.value)}
style={{ width: '100%', padding: '0.5rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '0.9rem' }}
>
{UNIT_OPTIONS.map((u) => (
<option key={u.value} value={u.value}>{u.label}</option>
))}
</select>
</div>
{/* Ta bort */}
<button
onClick={() => removeIngredient(index)}
title="Ta bort ingrediens"
style={{ padding: '0.5rem 0.75rem', background: '#fee2e2', color: '#dc2626', border: '1px solid #fca5a5', borderRadius: '4px', cursor: 'pointer', fontSize: '0.9rem', alignSelf: 'end' }}
>
</button>
</div>
{/* Anteckning */}
<div>
<label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', color: '#666' }}>Anteckning</label>
<input
type="text"
value={ing.editedNote}
onChange={(e) => updateIngredient(index, 'editedNote', e.target.value)}
placeholder="Valfri anteckning..."
style={{ width: '100%', padding: '0.5rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '0.85rem', boxSizing: 'border-box' }}
/>
</div>
</div>
))}
{ingredients.length === 0 && (
<p style={{ color: '#888', fontStyle: 'italic', margin: 0 }}>
Inga ingredienser tolkades från Markdown-texten.
</p>
)}
</div>
{/* Knappar */}
<div style={{ display: 'flex', gap: '1rem' }}>
<button
onClick={handleSave}
disabled={isSaving || !editedName.trim() || ingredients.filter((i) => i.selectedProductId > 0).length === 0}
style={{
padding: '0.75rem 1.5rem',
background: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: isSaving ? 'not-allowed' : 'pointer',
opacity: isSaving ? 0.6 : 1,
fontSize: '1rem',
fontWeight: 500,
}}
>
{isSaving ? 'Sparar...' : 'Spara recept'}
</button>
<button
onClick={() => setStep('input')}
style={{ padding: '0.75rem 1rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '4px', cursor: 'pointer', fontSize: '1rem' }}
>
Redigera
</button>
<button
onClick={() => router.push('/recipes')}
style={{ padding: '0.75rem 1rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '4px', cursor: 'pointer', fontSize: '1rem' }}
>
Avbryt
</button>
</div>
</section>
)}
</main>
);
}
+5
View File
@@ -0,0 +1,5 @@
import WriteRecipePage from './WriteRecipePage';
export default function Page() {
return <WriteRecipePage />;
}