feat: add TypeScript definitions for next-auth session with accessToken and user details
Test Suite / test (24.15.0) (push) Has been cancelled
Test Suite / test (24.15.0) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import type { Recipe } from '../../features/inventory/types';
|
||||
|
||||
function RecipePlaceholder({ name }: { name: string }) {
|
||||
const initial = name.trim().charAt(0).toUpperCase() || '?';
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '160px',
|
||||
background: '#e9ecef',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: '2.5rem',
|
||||
fontWeight: 700,
|
||||
color: '#868e96',
|
||||
borderRadius: '8px 8px 0 0',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
>
|
||||
{initial}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RecipeGrid({ recipes }: { recipes: Recipe[] }) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [sort, setSort] = useState<'name' | 'newest' | 'oldest' | 'ingredients'>('newest');
|
||||
const [onlyWithImage, setOnlyWithImage] = useState(false);
|
||||
|
||||
const filtered = recipes
|
||||
.filter((r) => r.name.toLowerCase().includes(search.toLowerCase()))
|
||||
.filter((r) => !onlyWithImage || !!r.imageUrl)
|
||||
.sort((a, b) => {
|
||||
if (sort === 'name') return a.name.localeCompare(b.name, 'sv');
|
||||
if (sort === 'newest') return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
if (sort === 'oldest') return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
||||
if (sort === 'ingredients') return (b.ingredients?.length ?? 0) - (a.ingredients?.length ?? 0);
|
||||
return 0;
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ display: 'flex', gap: '0.75rem', marginBottom: '1rem', flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Sök efter recept..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
style={{
|
||||
flex: '1 1 200px',
|
||||
padding: '0.6rem 1rem',
|
||||
fontSize: '1rem',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '24px',
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<select
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value as typeof sort)}
|
||||
style={{
|
||||
padding: '0.55rem 0.75rem',
|
||||
fontSize: '0.9rem',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '8px',
|
||||
background: '#fff',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<option value="newest">Senast tillagda</option>
|
||||
<option value="oldest">Äldst först</option>
|
||||
<option value="name">Namn (A–Ö)</option>
|
||||
<option value="ingredients">Flest ingredienser</option>
|
||||
</select>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', fontSize: '0.9rem', cursor: 'pointer', userSelect: 'none' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyWithImage}
|
||||
onChange={(e) => setOnlyWithImage(e.target.checked)}
|
||||
/>
|
||||
Endast med bild
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 && (
|
||||
<p style={{ color: '#868e96', textAlign: 'center', marginTop: '2rem' }}>
|
||||
{search || onlyWithImage ? 'Inga recept matchar filtren.' : 'Inga recept tillagda ännu.'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
{filtered.map((recipe) => (
|
||||
<Link
|
||||
key={recipe.id}
|
||||
href={`/recipes/${recipe.id}`}
|
||||
style={{ textDecoration: 'none', color: 'inherit' }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
border: '1px solid #dee2e6',
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden',
|
||||
transition: 'box-shadow 0.15s',
|
||||
background: '#fff',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onMouseEnter={(e) =>
|
||||
((e.currentTarget as HTMLDivElement).style.boxShadow = '0 4px 12px rgba(0,0,0,0.12)')
|
||||
}
|
||||
onMouseLeave={(e) =>
|
||||
((e.currentTarget as HTMLDivElement).style.boxShadow = 'none')
|
||||
}
|
||||
>
|
||||
{recipe.imageUrl ? (
|
||||
<img
|
||||
src={recipe.imageUrl}
|
||||
alt={recipe.name}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '160px',
|
||||
objectFit: 'cover',
|
||||
display: 'block',
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<RecipePlaceholder name={recipe.name} />
|
||||
)}
|
||||
<div style={{ padding: '0.75rem 1rem 0.85rem' }}>
|
||||
<h3
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: '1rem',
|
||||
fontWeight: 600,
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
}}
|
||||
>
|
||||
{recipe.name}
|
||||
</h3>
|
||||
{recipe.description && (
|
||||
<p
|
||||
style={{
|
||||
margin: '0.25rem 0 0.5rem',
|
||||
fontSize: '0.85rem',
|
||||
color: '#868e96',
|
||||
overflow: 'hidden',
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: 2,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
} as React.CSSProperties}
|
||||
>
|
||||
{recipe.description}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: '0.75rem', marginTop: recipe.description ? 0 : '0.4rem', fontSize: '0.78rem', color: '#adb5bd' }}>
|
||||
{recipe.ingredients?.length > 0 && (
|
||||
<span>{recipe.ingredients.length} ingredienser</span>
|
||||
)}
|
||||
<span>{new Date(recipe.createdAt).toLocaleDateString('sv-SE')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useTransition } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { parseErrorResponse } from '../../lib/error-handler';
|
||||
import type {
|
||||
Recipe,
|
||||
RecipeInventoryPreview,
|
||||
} from '../../features/inventory/types';
|
||||
|
||||
type Props = {
|
||||
recipes: Recipe[];
|
||||
};
|
||||
|
||||
function getStatusStyle(status: 'enough' | 'missing' | 'unit_mismatch') {
|
||||
if (status === 'enough') {
|
||||
return {
|
||||
label: 'Räcker',
|
||||
color: '#1f5f2c',
|
||||
background: '#ecf8ee',
|
||||
border: '#b9e0bf',
|
||||
};
|
||||
}
|
||||
|
||||
if (status === 'missing') {
|
||||
return {
|
||||
label: 'Saknas',
|
||||
color: '#8b0000',
|
||||
background: '#ffeaea',
|
||||
border: '#f1b5b5',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
label: 'Enhetskonflikt',
|
||||
color: '#8a4b00',
|
||||
background: '#fff4e5',
|
||||
border: '#f0cf9b',
|
||||
};
|
||||
}
|
||||
|
||||
function formatDate(value: string | null) {
|
||||
if (!value) return null;
|
||||
return new Date(value).toLocaleDateString('sv-SE');
|
||||
}
|
||||
|
||||
function isWeightUnit(unit: string): boolean {
|
||||
return ['kg', 'g', 'mg', 'ml', 'l'].includes(unit.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function isPieceUnit(unit: string): boolean {
|
||||
return ['st', 'stycke'].includes(unit.trim().toLowerCase());
|
||||
}
|
||||
|
||||
export default function RecipePreview({ recipes }: Props) {
|
||||
const [selectedRecipeId, setSelectedRecipeId] = useState('');
|
||||
const [preview, setPreview] = useState<RecipeInventoryPreview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const selectAndLoad = (id: string) => {
|
||||
setSelectedRecipeId(id);
|
||||
setError(null);
|
||||
setPreview(null);
|
||||
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/recipe-preview-proxy?id=${id}`, {
|
||||
method: 'GET',
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorMessage = await parseErrorResponse(res);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const data: RecipeInventoryPreview = await res.json();
|
||||
setPreview(data);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Ett okänt fel inträffade.';
|
||||
setError(message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const loadPreview = () => {
|
||||
setError(null);
|
||||
setPreview(null);
|
||||
|
||||
if (!selectedRecipeId) {
|
||||
setError('Välj ett recept.');
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/recipe-preview-proxy?id=${selectedRecipeId}`, {
|
||||
method: 'GET',
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorMessage = await parseErrorResponse(res);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const data: RecipeInventoryPreview = await res.json();
|
||||
setPreview(data);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Ett okänt fel inträffade.';
|
||||
setError(message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const listedRecipes = recipes.slice(0, 10);
|
||||
|
||||
return (
|
||||
<section style={{ display: 'grid', gap: '1rem' }}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '1rem', alignItems: 'start' }}>
|
||||
<div
|
||||
style={{
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
display: 'grid',
|
||||
gap: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>Recept mot hemmavaror</h2>
|
||||
|
||||
<label>
|
||||
Recept
|
||||
<br />
|
||||
<select
|
||||
value={selectedRecipeId}
|
||||
onChange={(e) => setSelectedRecipeId(e.target.value)}
|
||||
style={{ width: '100%', padding: '0.5rem' }}
|
||||
>
|
||||
<option value="">Välj recept</option>
|
||||
{recipes.map((recipe) => (
|
||||
<option key={recipe.id} value={recipe.id}>
|
||||
{recipe.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.75rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={loadPreview}
|
||||
disabled={isPending}
|
||||
style={{ padding: '0.6rem 1rem' }}
|
||||
>
|
||||
{isPending ? 'Hämtar preview...' : 'Visa preview'}
|
||||
</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>
|
||||
|
||||
{error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null}
|
||||
</div>
|
||||
|
||||
{/* Receptlista till höger */}
|
||||
<div
|
||||
style={{
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
minWidth: '180px',
|
||||
maxWidth: '220px',
|
||||
}}
|
||||
>
|
||||
<h3 style={{ margin: '0 0 0.75rem 0', fontSize: '1rem' }}>Mina recept</h3>
|
||||
<ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'grid', gap: '0.4rem' }}>
|
||||
{listedRecipes.map((recipe) => (
|
||||
<li key={recipe.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={isPending}
|
||||
onClick={() => selectAndLoad(String(recipe.id))}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '0.4rem 0.6rem',
|
||||
background: String(recipe.id) === selectedRecipeId ? '#e8f0fe' : 'transparent',
|
||||
border: `1px solid ${String(recipe.id) === selectedRecipeId ? '#4285f4' : '#eee'}`,
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontWeight: String(recipe.id) === selectedRecipeId ? 600 : 400,
|
||||
color: String(recipe.id) === selectedRecipeId ? '#1a56db' : '#333',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
{recipe.name}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(() => {
|
||||
const selected = recipes.find((r) => String(r.id) === selectedRecipeId);
|
||||
if (!selected?.instructions) return null;
|
||||
return (
|
||||
<article
|
||||
style={{
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
display: 'grid',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<h3 style={{ margin: 0 }}>Instruktioner – {selected.name}</h3>
|
||||
<p style={{ margin: 0, whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>
|
||||
{selected.instructions}
|
||||
</p>
|
||||
</article>
|
||||
);
|
||||
})()}
|
||||
|
||||
{preview && preview.summary.missingCount > 0 && (
|
||||
<article
|
||||
style={{
|
||||
border: '1px solid #f1b5b5',
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
display: 'grid',
|
||||
gap: '0.5rem',
|
||||
background: '#ffeaea',
|
||||
}}
|
||||
>
|
||||
<h3 style={{ margin: 0, color: '#8b0000' }}>
|
||||
Saknade ingredienser ({preview.summary.missingCount})
|
||||
</h3>
|
||||
<ul style={{ margin: 0, paddingLeft: '1.25rem', display: 'grid', gap: '0.25rem' }}>
|
||||
{preview.ingredients
|
||||
.filter((ing) => ing.status === 'missing')
|
||||
.map((ing) => (
|
||||
<li key={ing.ingredientId}>
|
||||
<strong>{ing.productName}</strong> — saknas{' '}
|
||||
{ing.missingQuantity} {ing.requiredUnit}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</article>
|
||||
)}
|
||||
|
||||
{preview ? (
|
||||
<section style={{ display: 'grid', gap: '1rem' }}>
|
||||
<article
|
||||
style={{
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
display: 'grid',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<h3 style={{ margin: 0 }}>{preview.recipe.name}</h3>
|
||||
{preview.recipe.description ? <div>{preview.recipe.description}</div> : null}
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
|
||||
<span>Ingredienser: {preview.summary.totalIngredients}</span>
|
||||
<span>Räcker: {preview.summary.enoughCount}</span>
|
||||
<span>Saknas: {preview.summary.missingCount}</span>
|
||||
<span>Enhetskonflikter: {preview.summary.unitMismatchCount}</span>
|
||||
<strong>
|
||||
{preview.summary.canCookExactly
|
||||
? 'Kan lagas exakt'
|
||||
: 'Kan inte lagas exakt ännu'}
|
||||
</strong>
|
||||
</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>
|
||||
|
||||
<div style={{ display: 'grid', gap: '0.75rem' }}>
|
||||
{preview.ingredients.map((ingredient) => {
|
||||
const statusStyle = getStatusStyle(ingredient.status);
|
||||
|
||||
return (
|
||||
<article
|
||||
key={ingredient.ingredientId}
|
||||
style={{
|
||||
border: `1px solid ${statusStyle.border}`,
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
display: 'grid',
|
||||
gap: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
gap: '1rem',
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong>{ingredient.productName}</strong>
|
||||
<div>
|
||||
Krävs: {ingredient.requiredQuantity} {ingredient.requiredUnit}
|
||||
</div>
|
||||
{ingredient.note ? <div>Notering: {ingredient.note}</div> : null}
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
padding: '0.3rem 0.6rem',
|
||||
borderRadius: '999px',
|
||||
background: statusStyle.background,
|
||||
color: statusStyle.color,
|
||||
border: `1px solid ${statusStyle.border}`,
|
||||
fontSize: '0.85rem',
|
||||
fontWeight: 600,
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{statusStyle.label}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gap: '0.35rem' }}>
|
||||
<div>
|
||||
Tillgängligt i jämförbar enhet: {ingredient.availableQuantity}{' '}
|
||||
{ingredient.availableUnit || ''}
|
||||
</div>
|
||||
|
||||
{ingredient.status === 'missing' ? (
|
||||
<div>
|
||||
Saknas: {ingredient.missingQuantity} {ingredient.requiredUnit}
|
||||
</div>
|
||||
) : 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>
|
||||
|
||||
{ingredient.matchingInventoryItems.length > 0 ? (
|
||||
<div style={{ display: 'grid', gap: '0.35rem' }}>
|
||||
<strong>Matchande inventory</strong>
|
||||
{ingredient.matchingInventoryItems.map((item) => (
|
||||
<div key={item.id}>
|
||||
#{item.id}: {item.quantity} {item.unit}
|
||||
{item.brand ? `, ${item.brand}` : ''}
|
||||
{item.location ? `, ${item.location}` : ''}
|
||||
{item.bestBeforeDate ? `, bäst före ${formatDate(item.bestBeforeDate)}` : ''}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{ingredient.otherInventoryItems && ingredient.otherInventoryItems.length > 0 ? (
|
||||
<div style={{ display: 'grid', gap: '0.35rem' }}>
|
||||
<strong>Andra enheter:</strong>
|
||||
{ingredient.otherInventoryItems.map((item) => {
|
||||
const weight = isWeightUnit(item.unit);
|
||||
const pieces = isPieceUnit(ingredient.requiredUnit);
|
||||
const pieces2 = isPieceUnit(item.unit);
|
||||
const weight2 = isWeightUnit(ingredient.requiredUnit);
|
||||
|
||||
return (
|
||||
<div key={item.id}>
|
||||
#{item.id}: {item.quantity} {item.unit}
|
||||
{item.canConvert ? (
|
||||
<span> ≈ {(item.convertedQuantity || 0).toFixed(2)} {ingredient.requiredUnit}</span>
|
||||
) : (
|
||||
<span>
|
||||
{weight && pieces
|
||||
? ' (kan inte konvertera vikt till stycken)'
|
||||
: pieces2 && weight2
|
||||
? ' (kan inte konvertera stycken till vikt)'
|
||||
: ' (kan inte konvertera)'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuthFetch } from '../../../lib/use-auth-fetch';
|
||||
import type {
|
||||
Recipe,
|
||||
Product,
|
||||
RecipeInventoryPreview,
|
||||
} from '../../../features/inventory/types';
|
||||
import { fetchJson } from '../../../lib/api';
|
||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||
import { UNIT_OPTIONS } from '../../../lib/units';
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// Hjälpfunktioner
|
||||
// ──────────────────────────────────────────────
|
||||
|
||||
function SimpleMarkdownPreview({ text }: { text: string }) {
|
||||
return (
|
||||
<div style={{ whiteSpace: 'pre-wrap', lineHeight: 1.7 }}>
|
||||
{text.split('\n').map((line, i) => {
|
||||
if (line.startsWith('# ')) return <h3 key={i} style={{ margin: '0.5rem 0 0.25rem', fontSize: '1.3em', fontWeight: 700 }}>{line.slice(2)}</h3>;
|
||||
if (line.startsWith('## ')) return <h4 key={i} style={{ margin: '0.5rem 0 0.25rem', 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>;
|
||||
const numberedMatch = line.match(/^(\d+)\.\s+(.*)/);
|
||||
if (numberedMatch) return (
|
||||
<div key={i} style={{ display: 'flex', gap: '0.6rem', marginBottom: '0.35rem' }}>
|
||||
<span style={{ fontWeight: 700, minWidth: '1.5rem', textAlign: 'right', flexShrink: 0 }}>{numberedMatch[1]}.</span>
|
||||
<span>{numberedMatch[2]}</span>
|
||||
</div>
|
||||
);
|
||||
if (line.trim() === '') return <div key={i} style={{ height: '0.5rem' }} />;
|
||||
return <div key={i}>{line}</div>;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: 'enough' | 'missing' | 'unit_mismatch' }) {
|
||||
const styles = {
|
||||
enough: { label: 'Räcker', color: '#1f5f2c', background: '#ecf8ee', border: '#b9e0bf' },
|
||||
missing: { label: 'Saknas', color: '#8b0000', background: '#ffeaea', border: '#f1b5b5' },
|
||||
unit_mismatch: { label: 'Enhetskonflikt', color: '#8a4b00', background: '#fff4e5', border: '#f0cf9b' },
|
||||
}[status];
|
||||
|
||||
return (
|
||||
<span style={{
|
||||
padding: '0.15rem 0.5rem',
|
||||
fontSize: '0.8rem',
|
||||
fontWeight: 600,
|
||||
borderRadius: '4px',
|
||||
color: styles.color,
|
||||
background: styles.background,
|
||||
border: `1px solid ${styles.border}`,
|
||||
}}>
|
||||
{styles.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// Huvud-komponent
|
||||
// ──────────────────────────────────────────────
|
||||
|
||||
export default function RecipeDetailClient({ recipe: initialRecipe }: { recipe: Recipe }) {
|
||||
const router = useRouter();
|
||||
const authFetch = useAuthFetch();
|
||||
const [recipe, setRecipe] = useState(initialRecipe);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isLiked, setIsLiked] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [servings, setServings] = useState<number>(initialRecipe.servings ?? 1);
|
||||
|
||||
// Redigeringsformulär-state
|
||||
const [form, setForm] = useState({
|
||||
name: initialRecipe.name,
|
||||
description: initialRecipe.description || '',
|
||||
instructions: initialRecipe.instructions || '',
|
||||
imageUrl: initialRecipe.imageUrl || '',
|
||||
servings: initialRecipe.servings as number | null,
|
||||
isPublic: initialRecipe.isPublic,
|
||||
ingredients: initialRecipe.ingredients.map((ing) => ({
|
||||
productId: ing.productId,
|
||||
quantity: String(ing.quantity),
|
||||
unit: ing.unit,
|
||||
note: ing.note || '',
|
||||
})),
|
||||
});
|
||||
|
||||
// Produktlista för ingrediens-väljare
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
|
||||
// Inventarieförhandsgranskning
|
||||
const [preview, setPreview] = useState<RecipeInventoryPreview | null>(null);
|
||||
const [previewError, setPreviewError] = useState<string | null>(null);
|
||||
const [isPreviewing, setIsPreviewing] = useState(false);
|
||||
const previewSectionRef = useRef<HTMLElement>(null);
|
||||
|
||||
// Bilduppdatering
|
||||
const [imageUrlInput, setImageUrlInput] = useState('');
|
||||
const [imageError, setImageError] = useState<string | null>(null);
|
||||
const [isUploadingImage, setIsUploadingImage] = useState(false);
|
||||
|
||||
// localStorage: gilla
|
||||
useEffect(() => {
|
||||
const liked = localStorage.getItem(`recipe-liked-${recipe.id}`) === 'true';
|
||||
setIsLiked(liked);
|
||||
}, [recipe.id]);
|
||||
|
||||
// Ladda produkter för redigera-läge
|
||||
useEffect(() => {
|
||||
if (isEditing && products.length === 0) {
|
||||
fetchJson<Product[]>('/api/products').then(setProducts).catch(console.error);
|
||||
}
|
||||
}, [isEditing, products.length]);
|
||||
|
||||
// ── Gilla ──
|
||||
const toggleLike = () => {
|
||||
const next = !isLiked;
|
||||
setIsLiked(next);
|
||||
localStorage.setItem(`recipe-liked-${recipe.id}`, String(next));
|
||||
};
|
||||
|
||||
// ── Inventarieförhandsgranskning ──
|
||||
const loadPreview = async () => {
|
||||
if (preview) {
|
||||
previewSectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
return;
|
||||
}
|
||||
setPreviewError(null);
|
||||
setIsPreviewing(true);
|
||||
try {
|
||||
const res = await fetch(`/api/recipe-preview-proxy?id=${recipe.id}`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error(await parseErrorResponse(res));
|
||||
setPreview(await res.json());
|
||||
setTimeout(() => previewSectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 50);
|
||||
} catch (err) {
|
||||
setPreviewError(err instanceof Error ? err.message : 'Fel vid hämtning av inventariedata');
|
||||
} finally {
|
||||
setIsPreviewing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Ta bort recept ──
|
||||
const handleDelete = async () => {
|
||||
if (!confirm(`Ta bort receptet "${recipe.name}"? Det går inte att ångra.`)) return;
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
const res = await authFetch(`/api/recipes/${recipe.id}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error(await parseErrorResponse(res));
|
||||
router.push('/recipes');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Kunde inte ta bort receptet.');
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Spara redigering ──
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const body = {
|
||||
...form,
|
||||
ingredients: form.ingredients.map((ing) => ({
|
||||
...ing,
|
||||
quantity: Number(ing.quantity),
|
||||
})),
|
||||
};
|
||||
const res = await authFetch(`/api/recipes/${recipe.id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) throw new Error(await parseErrorResponse(res));
|
||||
const updated: Recipe = await res.json();
|
||||
setRecipe(updated);
|
||||
setIsEditing(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Kunde inte spara receptet.');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Uppdatera bild ──
|
||||
const handleImageUpdate = async () => {
|
||||
if (!imageUrlInput.trim()) return;
|
||||
setIsUploadingImage(true);
|
||||
setImageError(null);
|
||||
try {
|
||||
const res = await authFetch(`/api/recipes/${recipe.id}/image`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ sourceUrl: imageUrlInput.trim() }),
|
||||
});
|
||||
if (!res.ok) throw new Error(await parseErrorResponse(res));
|
||||
const updated: Recipe = await res.json();
|
||||
setRecipe(updated);
|
||||
setForm((f) => ({ ...f, imageUrl: updated.imageUrl || '' }));
|
||||
setImageUrlInput('');
|
||||
} catch (err) {
|
||||
setImageError(err instanceof Error ? err.message : 'Kunde inte hämta bilden.');
|
||||
} finally {
|
||||
setIsUploadingImage(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Ingrediens-hjälpfunktioner (redigera-läge) ──
|
||||
const setIngredientField = (idx: number, field: string, value: string | number) => {
|
||||
setForm((f) => {
|
||||
const ings = [...f.ingredients];
|
||||
ings[idx] = { ...ings[idx], [field]: value };
|
||||
return { ...f, ingredients: ings };
|
||||
});
|
||||
};
|
||||
|
||||
const addIngredient = () =>
|
||||
setForm((f) => ({
|
||||
...f,
|
||||
ingredients: [...f.ingredients, { productId: 0, quantity: '', unit: '', note: '' }],
|
||||
}));
|
||||
|
||||
const removeIngredient = (idx: number) =>
|
||||
setForm((f) => {
|
||||
const ings = [...f.ingredients];
|
||||
ings.splice(idx, 1);
|
||||
return { ...f, ingredients: ings };
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// VY-LÄGE
|
||||
// ──────────────────────────────────────────────
|
||||
if (!isEditing) {
|
||||
return (
|
||||
<div>
|
||||
{/* Bild */}
|
||||
{recipe.imageUrl ? (
|
||||
<img
|
||||
src={recipe.imageUrl}
|
||||
alt={recipe.name}
|
||||
style={{ width: '100%', maxHeight: '400px', objectFit: 'cover', borderRadius: '8px', marginBottom: '1.25rem', display: 'block' }}
|
||||
/>
|
||||
) : (
|
||||
<div style={{
|
||||
width: '100%', height: '200px', background: '#e9ecef', borderRadius: '8px',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: '4rem', fontWeight: 700, color: '#868e96', marginBottom: '1.25rem',
|
||||
}}>
|
||||
{recipe.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Titel + knappar */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: '0.75rem', marginBottom: '1rem' }}>
|
||||
<h1 style={{ margin: 0, fontSize: '1.75rem' }}>{recipe.name}</h1>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
|
||||
<button onClick={toggleLike} style={btnStyle(isLiked ? '#e53e3e' : undefined)}>
|
||||
{isLiked ? '♥ Gillad' : '♡ Gilla'}
|
||||
</button>
|
||||
<button onClick={loadPreview} disabled={isPreviewing} style={btnStyle()}>
|
||||
{isPreviewing ? 'Hämtar...' : '🛒 Vad behöver jag köpa?'}
|
||||
</button>
|
||||
<button onClick={() => setIsEditing(true)} style={btnStyle()}>Redigera</button>
|
||||
<button onClick={handleDelete} disabled={isDeleting} style={btnStyle('#e53e3e')}>
|
||||
{isDeleting ? 'Tar bort...' : 'Ta bort'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p style={errorStyle}>{error}</p>}
|
||||
|
||||
{recipe.description && (
|
||||
<p style={{ color: '#555', marginBottom: '1.25rem', fontSize: '1.05rem' }}>{recipe.description}</p>
|
||||
)}
|
||||
|
||||
{/* Ingredienser */}
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Ingredienser</h2>
|
||||
{recipe.servings && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '1rem', fontSize: '0.9rem', flexWrap: 'wrap' }}>
|
||||
<span style={{ color: '#555' }}>Portioner:</span>
|
||||
<button type="button" onClick={() => setServings((s) => Math.max(1, s - 1))} style={btnStyle()}>−</button>
|
||||
<span style={{ fontWeight: 700, minWidth: '2rem', textAlign: 'center' }}>{servings}</span>
|
||||
<button type="button" onClick={() => setServings((s) => s + 1)} style={btnStyle()}>+</button>
|
||||
{servings !== recipe.servings && (
|
||||
<button type="button" onClick={() => setServings(recipe.servings!)} style={{ ...btnStyle(), fontSize: '0.8rem', padding: '0.3rem 0.6rem' }}>
|
||||
Återställ ({recipe.servings})
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.4rem' }}>
|
||||
{recipe.ingredients.map((ing) => {
|
||||
const scale = recipe.servings ? servings / recipe.servings : 1;
|
||||
const qty = Number(ing.quantity) * scale;
|
||||
const displayQty = qty % 1 === 0 ? qty : parseFloat(qty.toFixed(2));
|
||||
return (
|
||||
<li key={ing.id} style={{ display: 'flex', gap: '0.5rem', alignItems: 'baseline' }}>
|
||||
<span style={{ fontWeight: 600, minWidth: '60px', textAlign: 'right' }}>
|
||||
{displayQty} {ing.unit}
|
||||
</span>
|
||||
<span>{ing.product.canonicalName || ing.product.name}</span>
|
||||
{ing.note && <span style={{ color: '#868e96', fontSize: '0.875rem' }}>({ing.note})</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{/* Instruktioner */}
|
||||
{recipe.instructions && (
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Instruktioner</h2>
|
||||
<SimpleMarkdownPreview text={recipe.instructions} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Lagergranskning */}
|
||||
{(preview || previewError) && (
|
||||
<section ref={previewSectionRef} style={{ ...sectionStyle, marginTop: '1.5rem' }}>
|
||||
<h2 style={sectionTitle}>🛒 Vad behöver jag köpa?</h2>
|
||||
{previewError && <p style={errorStyle}>{previewError}</p>}
|
||||
{preview && (
|
||||
<>
|
||||
{/* Summerbanner */}
|
||||
{preview.summary.canCookExactly ? (
|
||||
<div style={{ background: '#f0fdf4', border: '1px solid #86efac', borderRadius: '8px', padding: '0.875rem 1rem', marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.6rem', color: '#166534', fontWeight: 600 }}>
|
||||
<span style={{ fontSize: '1.3rem' }}>✅</span>
|
||||
<span>Du har allt hemma! Du kan laga det här receptet direkt.</span>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ background: '#fef2f2', border: '1px solid #fca5a5', borderRadius: '8px', padding: '0.875rem 1rem', marginBottom: '1rem', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.75rem' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', color: '#991b1b', fontWeight: 600 }}>
|
||||
<span style={{ fontSize: '1.3rem' }}>🛒</span>
|
||||
<span>
|
||||
Du saknar {preview.summary.missingCount + preview.summary.unitMismatchCount} av {preview.summary.totalIngredients} ingredienser
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
disabled
|
||||
title="Inköpslista kommer snart"
|
||||
style={{ padding: '0.45rem 1rem', background: '#e5e7eb', color: '#9ca3af', border: '1px solid #d1d5db', borderRadius: '6px', cursor: 'not-allowed', fontSize: '0.9rem', fontWeight: 500 }}
|
||||
>
|
||||
+ Lägg till i inköpslista (kommer snart)
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Ingredienslista med status */}
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.4rem' }}>
|
||||
{preview.ingredients.map((ing) => {
|
||||
const rowBg = ing.status === 'enough' ? '#f0fdf4' : ing.status === 'missing' ? '#fef2f2' : '#fffbeb';
|
||||
const rowBorder = ing.status === 'enough' ? '#bbf7d0' : ing.status === 'missing' ? '#fca5a5' : '#fde68a';
|
||||
const icon = ing.status === 'enough' ? '✅' : ing.status === 'missing' ? '❌' : '⚠️';
|
||||
return (
|
||||
<li key={ing.ingredientId} style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
|
||||
padding: '0.5rem 0.75rem', borderRadius: '6px',
|
||||
border: `1px solid ${rowBorder}`, background: rowBg,
|
||||
flexWrap: 'wrap', gap: '0.5rem',
|
||||
}}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<span>{icon}</span>
|
||||
<strong>{ing.productName}</strong>
|
||||
<span style={{ color: '#555', fontSize: '0.875rem' }}>
|
||||
{ing.requiredQuantity} {ing.requiredUnit}
|
||||
{ing.status !== 'enough' && ing.missingQuantity > 0 && (
|
||||
<> — saknar <strong>{ing.missingQuantity} {ing.requiredUnit}</strong></>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<StatusBadge status={ing.status} />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Näringsvärden */}
|
||||
{(() => {
|
||||
const scale = recipe.servings ? servings / recipe.servings : 1;
|
||||
const totals = recipe.ingredients.reduce(
|
||||
(acc, ing) => {
|
||||
const n = ing.product.nutrition;
|
||||
if (!n) return acc;
|
||||
const qty = Number(ing.quantity) * scale;
|
||||
const qtyInGrams = ing.unit === 'g' ? qty : ing.unit === 'kg' ? qty * 1000 : null;
|
||||
if (qtyInGrams === null) return acc;
|
||||
const f = qtyInGrams / 100;
|
||||
return {
|
||||
calories: acc.calories + (n.calories ?? 0) * f,
|
||||
protein: acc.protein + (n.protein ?? 0) * f,
|
||||
fat: acc.fat + (n.fat ?? 0) * f,
|
||||
carbohydrates: acc.carbohydrates + (n.carbohydrates ?? 0) * f,
|
||||
};
|
||||
},
|
||||
{ calories: 0, protein: 0, fat: 0, carbohydrates: 0 },
|
||||
);
|
||||
const hasAny = recipe.ingredients.some(
|
||||
(i) => i.product.nutrition && (i.unit === 'g' || i.unit === 'kg'),
|
||||
);
|
||||
if (!hasAny) return null;
|
||||
const portionLabel = recipe.servings
|
||||
? `${servings} ${servings === 1 ? 'portion' : 'portioner'}`
|
||||
: 'hela receptet';
|
||||
return (
|
||||
<section style={{ ...sectionStyle, marginTop: '1.5rem' }}>
|
||||
<h2 style={sectionTitle}>Näringsvärden ({portionLabel})</h2>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(110px, 1fr))', gap: '0.75rem' }}>
|
||||
{[
|
||||
{ label: 'Energi', value: totals.calories, unit: 'kcal' },
|
||||
{ label: 'Protein', value: totals.protein, unit: 'g' },
|
||||
{ label: 'Fett', value: totals.fat, unit: 'g' },
|
||||
{ label: 'Kolhydrater', value: totals.carbohydrates, unit: 'g' },
|
||||
].map(({ label, value, unit }) => (
|
||||
<div key={label} style={{ padding: '0.75rem', background: '#f8f9fa', borderRadius: '6px', textAlign: 'center' }}>
|
||||
<div style={{ fontSize: '1.2rem', fontWeight: 700 }}>
|
||||
{value < 1 ? value.toFixed(1) : Math.round(value)}{unit}
|
||||
</div>
|
||||
<div style={{ fontSize: '0.8rem', color: '#666' }}>{label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p style={{ fontSize: '0.8rem', color: '#888', marginTop: '0.5rem', marginBottom: 0 }}>
|
||||
* Endast ingredienser med viktenhet (g/kg) och registrerade näringsvärden inkluderas.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// REDIGERA-LÄGE
|
||||
// ──────────────────────────────────────────────
|
||||
return (
|
||||
<div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
|
||||
<h1 style={{ margin: 0 }}>Redigera recept</h1>
|
||||
<button onClick={() => setIsEditing(false)} style={btnStyle()}>Avbryt</button>
|
||||
</div>
|
||||
|
||||
{error && <p style={errorStyle}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSave} style={{ display: 'grid', gap: '1.25rem' }}>
|
||||
{/* Bild-uppdatering */}
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Bild</h2>
|
||||
{recipe.imageUrl && (
|
||||
<img src={recipe.imageUrl} alt="" style={{ width: '100%', maxHeight: '200px', objectFit: 'cover', borderRadius: '6px', marginBottom: '0.75rem' }} />
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: '0.5rem' }}>
|
||||
<input
|
||||
type="url"
|
||||
placeholder="https://... (bild-URL)"
|
||||
value={imageUrlInput}
|
||||
onChange={(e) => setImageUrlInput(e.target.value)}
|
||||
style={inputStyle}
|
||||
/>
|
||||
<button type="button" onClick={handleImageUpdate} disabled={isUploadingImage || !imageUrlInput.trim()} style={btnStyle()}>
|
||||
{isUploadingImage ? 'Hämtar...' : 'Uppdatera bild'}
|
||||
</button>
|
||||
</div>
|
||||
{imageError && <p style={{ ...errorStyle, marginTop: '0.5rem' }}>{imageError}</p>}
|
||||
</section>
|
||||
|
||||
{/* Grundinfo */}
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Receptdetaljer</h2>
|
||||
<label style={labelStyle}>Receptnamn *</label>
|
||||
<input type="text" required value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} style={{ ...inputStyle, marginBottom: '1rem' }} />
|
||||
|
||||
<label style={labelStyle}>Beskrivning</label>
|
||||
<textarea value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} rows={3} style={{ ...inputStyle, fontFamily: 'inherit', resize: 'vertical', marginBottom: '1rem' }} />
|
||||
|
||||
<label style={labelStyle}>Instruktioner</label>
|
||||
<textarea value={form.instructions} onChange={(e) => setForm((f) => ({ ...f, instructions: e.target.value }))} rows={8} style={{ ...inputStyle, fontFamily: 'inherit', resize: 'vertical' }} />
|
||||
</section>
|
||||
|
||||
{/* Portioner */}
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Portioner</h2>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
step={1}
|
||||
value={form.servings ?? ''}
|
||||
onChange={(e) => setForm((f) => ({ ...f, servings: e.target.value ? Number(e.target.value) : null }))}
|
||||
style={{ ...inputStyle, width: '120px' }}
|
||||
placeholder="t.ex. 4"
|
||||
/>
|
||||
<p style={{ fontSize: '0.85rem', color: '#666', marginTop: '0.4rem', marginBottom: 0 }}>
|
||||
Anges portioner kan mängderna skalas på receptsidan.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{/* Synlighet */}
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Synlighet</h2>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.isPublic}
|
||||
onChange={(e) => setForm((f) => ({ ...f, isPublic: e.target.checked }))}
|
||||
style={{ width: 16, height: 16 }}
|
||||
/>
|
||||
<span>Publikt recept (synligt för alla inloggade)</span>
|
||||
</label>
|
||||
<p style={{ fontSize: '0.85rem', color: '#666', marginTop: '0.4rem', marginBottom: 0 }}>
|
||||
Privata recept syns bara för dig och de du delar med.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{/* Ingredienser */}
|
||||
<section style={sectionStyle}>
|
||||
<h2 style={sectionTitle}>Ingredienser</h2>
|
||||
{form.ingredients.map((ing, idx) => (
|
||||
<div key={idx} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto auto auto', gap: '0.5rem', marginBottom: '0.75rem', alignItems: 'center' }}>
|
||||
<select
|
||||
value={ing.productId}
|
||||
onChange={(e) => setIngredientField(idx, 'productId', Number(e.target.value))}
|
||||
style={inputStyle}
|
||||
>
|
||||
<option value={0}>Välj produkt...</option>
|
||||
{products.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.canonicalName || p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="Mängd"
|
||||
value={ing.quantity}
|
||||
min={0}
|
||||
step="any"
|
||||
onChange={(e) => setIngredientField(idx, 'quantity', e.target.value)}
|
||||
style={{ ...inputStyle, width: '80px' }}
|
||||
/>
|
||||
<select
|
||||
value={ing.unit}
|
||||
onChange={(e) => setIngredientField(idx, 'unit', e.target.value)}
|
||||
style={{ ...inputStyle, width: '120px' }}
|
||||
>
|
||||
{UNIT_OPTIONS.map((u) => <option key={u.value} value={u.value}>{u.label}</option>)}
|
||||
</select>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Not (valfri)"
|
||||
value={ing.note}
|
||||
onChange={(e) => setIngredientField(idx, 'note', e.target.value)}
|
||||
style={{ ...inputStyle, width: '110px' }}
|
||||
/>
|
||||
<button type="button" onClick={() => removeIngredient(idx)} style={{ ...btnStyle('#e53e3e'), whiteSpace: 'nowrap' }}>Ta bort</button>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={addIngredient} style={btnStyle()}>+ Lägg till ingrediens</button>
|
||||
</section>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.75rem' }}>
|
||||
<button type="submit" disabled={isSaving} style={btnStyle('#0070f3')}>
|
||||
{isSaving ? 'Sparar...' : 'Spara ändringar'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setIsEditing(false)} style={btnStyle()}>Avbryt</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// Stilkonstanter
|
||||
// ──────────────────────────────────────────────
|
||||
|
||||
function btnStyle(bg?: string): React.CSSProperties {
|
||||
return {
|
||||
padding: '0.45rem 0.9rem',
|
||||
background: bg || '#f0f0f0',
|
||||
color: bg ? '#fff' : '#333',
|
||||
border: '1px solid ' + (bg || '#ccc'),
|
||||
borderRadius: '6px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.9rem',
|
||||
fontWeight: 500,
|
||||
whiteSpace: 'nowrap',
|
||||
};
|
||||
}
|
||||
|
||||
const sectionStyle: React.CSSProperties = {
|
||||
border: '1px solid #dee2e6',
|
||||
borderRadius: '8px',
|
||||
padding: '1rem',
|
||||
};
|
||||
|
||||
const sectionTitle: React.CSSProperties = {
|
||||
margin: '0 0 0.75rem',
|
||||
fontSize: '1.1rem',
|
||||
fontWeight: 700,
|
||||
};
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
width: '100%',
|
||||
padding: '0.6rem 0.75rem',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '6px',
|
||||
fontSize: '0.95rem',
|
||||
boxSizing: 'border-box',
|
||||
};
|
||||
|
||||
const labelStyle: React.CSSProperties = {
|
||||
display: 'block',
|
||||
fontWeight: 600,
|
||||
marginBottom: '0.35rem',
|
||||
};
|
||||
|
||||
const errorStyle: React.CSSProperties = {
|
||||
color: 'crimson',
|
||||
background: '#ffe5e5',
|
||||
padding: '0.6rem 0.75rem',
|
||||
borderRadius: '6px',
|
||||
margin: 0,
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
interface Props {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export default async function EditRecipeRedirect({ params }: Props) {
|
||||
const { id } = await params;
|
||||
redirect(`/recipes/${id}`);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { fetchJson } from '../../../lib/api';
|
||||
import type { Recipe } from '../../../features/inventory/types';
|
||||
import Navigation from '../../Navigation';
|
||||
import RecipeDetailClient from './RecipeDetailClient';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
interface Props {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export default async function RecipeDetailPage({ params }: Props) {
|
||||
const { id } = await params;
|
||||
let recipe: Recipe;
|
||||
|
||||
try {
|
||||
recipe = await fetchJson<Recipe>(`/api/recipes/${id}`);
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<main style={{ padding: '1rem', maxWidth: '900px', margin: '0 auto' }}>
|
||||
<Navigation />
|
||||
<RecipeDetailClient recipe={recipe} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useState } from 'react';
|
||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function CreateRecipeClient() {
|
||||
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) {
|
||||
sessionStorage.setItem('prefilled_markdown', data.markdown);
|
||||
if (data.imageUrl) {
|
||||
sessionStorage.setItem('prefilled_image_url', data.imageUrl);
|
||||
}
|
||||
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' }}>
|
||||
<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: 'repeat(auto-fit, minmax(350px, 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,11 @@
|
||||
import Navigation from '../../Navigation';
|
||||
import CreateRecipeClient from './CreateRecipeClient';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<>
|
||||
<Navigation />
|
||||
<CreateRecipeClient />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||
|
||||
export default function ImportFilePage() {
|
||||
const router = useRouter();
|
||||
const [selectedMethod, setSelectedMethod] = useState<'file' | 'url' | null>('file');
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [url, setUrl] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleFileSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!selectedFile) {
|
||||
setError('Välj en PDF eller bildfil först.');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', selectedFile);
|
||||
|
||||
const res = await fetch('/api/quick-import-proxy', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorMessage = await parseErrorResponse(res);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
// ...existing code...
|
||||
sessionStorage.setItem('prefilled_markdown', data.markdown ?? '');
|
||||
if (data.imageUrl) {
|
||||
sessionStorage.setItem('prefilled_image_url', data.imageUrl);
|
||||
} else {
|
||||
sessionStorage.removeItem('prefilled_image_url');
|
||||
}
|
||||
router.push('/recipes/write');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Importen misslyckades.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUrlSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!url.trim()) {
|
||||
setError('Vänligen ange en URL.');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/quick-import-proxy', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ input: url.trim() }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorMessage = await parseErrorResponse(res);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
// ...existing code...
|
||||
sessionStorage.setItem('prefilled_markdown', data.markdown ?? '');
|
||||
if (data.imageUrl) {
|
||||
sessionStorage.setItem('prefilled_image_url', data.imageUrl);
|
||||
} else {
|
||||
sessionStorage.removeItem('prefilled_image_url');
|
||||
}
|
||||
router.push('/recipes/write');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Importen misslyckades.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main style={{ padding: '1rem', maxWidth: '900px', margin: '0 auto' }}>
|
||||
<h1 style={{ marginBottom: '0.5rem' }}>Importera från fil eller länk</h1>
|
||||
<p style={{ color: '#666', marginBottom: '1.5rem' }}>
|
||||
Ladda upp en PDF eller bild för OCR, eller ange en receptlänk.
|
||||
</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: 'repeat(auto-fit, minmax(350px, 1fr))',
|
||||
gap: '1.5rem',
|
||||
marginBottom: '2rem',
|
||||
}}
|
||||
>
|
||||
<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',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: '0 0 1rem 0', fontSize: '1.2rem', color: '#0070f3' }}>
|
||||
Ladda upp PDF eller bild
|
||||
</h2>
|
||||
<p style={{ color: '#666', margin: '0 0 1rem 0', fontSize: '0.95rem' }}>
|
||||
Stöd för PDF, PNG, JPG, JPEG, WEBP och BMP.
|
||||
</p>
|
||||
|
||||
{selectedMethod === 'file' && (
|
||||
<form onSubmit={handleFileSubmit} style={{ display: 'grid', gap: '0.75rem' }}>
|
||||
<input
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg,.webp,.bmp"
|
||||
onChange={(e) => setSelectedFile(e.target.files?.[0] ?? null)}
|
||||
style={{
|
||||
padding: '0.75rem',
|
||||
background: 'white',
|
||||
border: '1px solid #cbd5e1',
|
||||
borderRadius: '6px',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!selectedFile || isLoading}
|
||||
style={{
|
||||
padding: '0.75rem',
|
||||
background: '#0070f3',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
cursor: !selectedFile || isLoading ? 'not-allowed' : 'pointer',
|
||||
opacity: !selectedFile || isLoading ? 0.6 : 1,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{isLoading ? 'Importerar...' : 'Importera fil'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<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',
|
||||
}}
|
||||
>
|
||||
<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 exempelvis ICA eller en annan receptsida.
|
||||
</p>
|
||||
|
||||
{selectedMethod === 'url' && (
|
||||
<form onSubmit={handleUrlSubmit} style={{ display: 'grid', gap: '0.75rem' }}>
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="https://exempel.se/recept/..."
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '0.75rem',
|
||||
border: '1px solid #d1d5db',
|
||||
borderRadius: '6px',
|
||||
fontSize: '0.9rem',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!url.trim() || isLoading}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '0.75rem',
|
||||
background: '#10b981',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
cursor: !url.trim() || isLoading ? 'not-allowed' : 'pointer',
|
||||
opacity: !url.trim() || isLoading ? 0.6 : 1,
|
||||
fontWeight: 600,
|
||||
fontSize: '0.95rem',
|
||||
}}
|
||||
>
|
||||
{isLoading ? 'Importerar...' : 'Importera från länk'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
background: '#f0fdf4',
|
||||
border: '1px solid #86efac',
|
||||
borderRadius: '6px',
|
||||
padding: '1rem',
|
||||
marginBottom: '1.5rem',
|
||||
color: '#166534',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
Efter import öppnas receptet automatiskt i redigeringsläget.
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '1rem' }}>
|
||||
<Link
|
||||
href="/recipes/create"
|
||||
style={{
|
||||
padding: '0.75rem 1.5rem',
|
||||
background: 'transparent',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
textDecoration: 'none',
|
||||
color: '#333',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
Tillbaka
|
||||
</Link>
|
||||
<Link
|
||||
href="/recipes/write"
|
||||
style={{
|
||||
padding: '0.75rem 1.5rem',
|
||||
background: '#0070f3',
|
||||
color: 'white',
|
||||
borderRadius: '4px',
|
||||
textDecoration: 'none',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
Skriv in recept istället
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuthFetch } from '../../../lib/use-auth-fetch';
|
||||
import { fetchJson } from '../../../lib/api';
|
||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||
import type { Product } from '../../../features/inventory/types';
|
||||
import { UNIT_OPTIONS } from '../../../lib/units';
|
||||
|
||||
type ProductSuggestion = {
|
||||
productId: number;
|
||||
productName: string;
|
||||
score: number;
|
||||
};
|
||||
|
||||
type ParsedIngredientRow = {
|
||||
rawName: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
note?: string;
|
||||
suggestions: ProductSuggestion[];
|
||||
// Valda värden (redigerbara i steg 2)
|
||||
selectedProductId: number;
|
||||
editedQuantity: string;
|
||||
editedUnit: string;
|
||||
editedNote: string;
|
||||
};
|
||||
|
||||
type ParseResult = {
|
||||
name: string;
|
||||
description?: string;
|
||||
instructions?: string;
|
||||
ingredients: ParsedIngredientRow[];
|
||||
};
|
||||
|
||||
type Step = 'input' | 'review' | 'saving';
|
||||
|
||||
export default function ImportRecipePage() {
|
||||
const router = useRouter();
|
||||
const authFetch = useAuthFetch();
|
||||
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(() => {
|
||||
fetchJson<Product[]>('/api/products')
|
||||
.then(setAllProducts)
|
||||
.catch(console.error);
|
||||
}, []);
|
||||
|
||||
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 authFetch('/api/recipes', {
|
||||
method: 'POST',
|
||||
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' }}>
|
||||
<h1 style={{ marginBottom: '0.5rem' }}>Importera recept från Markdown</h1>
|
||||
|
||||
{/* 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. Klistra in
|
||||
</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 }}>
|
||||
Klistra in ditt recept i Markdown-format
|
||||
</label>
|
||||
<textarea
|
||||
value={markdown}
|
||||
onChange={(e) => setMarkdown(e.target.value)}
|
||||
placeholder="# Mitt recept ## Ingredienser - 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 recept'}
|
||||
</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 Markdown
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import Link from 'next/link';
|
||||
import { fetchJson } from '../../lib/api';
|
||||
import type { Recipe } from '../../features/inventory/types';
|
||||
import Navigation from '../Navigation';
|
||||
import RecipeGrid from './RecipeGrid';
|
||||
|
||||
export default async function RecipesPage() {
|
||||
const recipes = await fetchJson<Recipe[]>('/api/recipes');
|
||||
|
||||
return (
|
||||
<main style={{ padding: '1rem', maxWidth: '1000px', margin: '0 auto' }}>
|
||||
<Navigation />
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
|
||||
<h1 style={{ margin: 0 }}>Recept</h1>
|
||||
<Link
|
||||
href="/recipes/create"
|
||||
style={{
|
||||
padding: '0.5rem 1rem',
|
||||
background: '#0070f3',
|
||||
color: 'white',
|
||||
borderRadius: '4px',
|
||||
textDecoration: 'none',
|
||||
fontWeight: 500,
|
||||
fontSize: '1rem',
|
||||
}}
|
||||
>
|
||||
Lägg till nytt recept
|
||||
</Link>
|
||||
</div>
|
||||
<RecipeGrid recipes={recipes} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,636 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuthFetch } from '../../../lib/use-auth-fetch';
|
||||
import { fetchJson } from '../../../lib/api';
|
||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||
import type { Product } from '../../../features/inventory/types';
|
||||
import { UNIT_OPTIONS } from '../../../lib/units';
|
||||
|
||||
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[];
|
||||
};
|
||||
|
||||
type Step = 'input' | 'review' | 'saving' | 'saved';
|
||||
|
||||
export default function WriteRecipePage() {
|
||||
const router = useRouter();
|
||||
const authFetch = useAuthFetch();
|
||||
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 [editedServings, setEditedServings] = useState<number | null>(null);
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(null);
|
||||
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);
|
||||
const [showDebugPanel, setShowDebugPanel] = useState(false);
|
||||
|
||||
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');
|
||||
const prefilledImageUrl = sessionStorage.getItem('prefilled_image_url');
|
||||
// ...existing code...
|
||||
if (prefilledImageUrl) {
|
||||
setImageUrl(prefilledImageUrl);
|
||||
sessionStorage.removeItem('prefilled_image_url');
|
||||
}
|
||||
if (prefilledMarkdown) {
|
||||
setMarkdown(prefilledMarkdown);
|
||||
sessionStorage.removeItem('prefilled_markdown');
|
||||
// Auto-parse markdown från snabbimport
|
||||
setIsParsing(true);
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/parse-markdown-proxy', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ markdown: prefilledMarkdown }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(errorText || 'Kunde inte tolka recept');
|
||||
}
|
||||
|
||||
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 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,
|
||||
imageUrl: imageUrl || undefined,
|
||||
servings: editedServings ?? undefined,
|
||||
ingredients: validIngredients.map((ing) => ({
|
||||
productId: ing.selectedProductId,
|
||||
quantity: Number(ing.editedQuantity),
|
||||
unit: ing.editedUnit,
|
||||
note: ing.editedNote || undefined,
|
||||
})),
|
||||
};
|
||||
// ...existing code...
|
||||
|
||||
try {
|
||||
const res = await authFetch('/api/recipes', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorMessage = await parseErrorResponse(res);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
// ...existing code...
|
||||
|
||||
setStep('saved');
|
||||
router.refresh();
|
||||
setTimeout(() => router.push('/recipes'), 2000);
|
||||
} 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' }}>
|
||||
<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 ## Ingredienser - 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', gridTemplateColumns: '7fr 3fr', gap: '1.5rem' }}>
|
||||
{/* Vänster: Receptdetaljer + Ingredienser */}
|
||||
<div 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>
|
||||
|
||||
{imageUrl && (
|
||||
<div>
|
||||
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Bild</label>
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="Receptbild"
|
||||
style={{ width: '100%', maxHeight: '220px', objectFit: 'cover', borderRadius: '6px', border: '1px solid #ddd' }}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setImageUrl(null)}
|
||||
style={{ marginTop: '0.4rem', fontSize: '0.8rem', color: '#dc2626', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
|
||||
>
|
||||
Ta bort bild
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<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>
|
||||
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Portioner</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
step={1}
|
||||
value={editedServings ?? ''}
|
||||
onChange={(e) => setEditedServings(e.target.value ? Number(e.target.value) : null)}
|
||||
placeholder="t.ex. 4"
|
||||
style={{ width: '120px', padding: '0.5rem 0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem' }}
|
||||
/>
|
||||
<p style={{ fontSize: '0.82rem', color: '#888', margin: '0.3rem 0 0' }}>Anges portioner kan mängderna skalas på receptsidan.</p>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
{/* Höger: Debug Panel (Sticky) */}
|
||||
<div style={{ position: 'sticky', top: '1rem', height: 'fit-content' }}>
|
||||
<details
|
||||
open={showDebugPanel}
|
||||
onChange={(e) => setShowDebugPanel((e.target as HTMLDetailsElement).open)}
|
||||
style={{
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '8px',
|
||||
padding: '0.75rem',
|
||||
background: '#f9f9f9',
|
||||
}}
|
||||
>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 600, fontSize: '0.9rem', color: '#666', userSelect: 'none' }}>
|
||||
🔍 Import Debug {showDebugPanel ? '▼' : '▶'}
|
||||
</summary>
|
||||
|
||||
{/* Raw Markdown */}
|
||||
<details
|
||||
style={{
|
||||
marginTop: '0.75rem',
|
||||
paddingTop: '0.75rem',
|
||||
borderTop: '1px solid #ddd',
|
||||
}}
|
||||
>
|
||||
<summary style={{ cursor: 'pointer', fontSize: '0.8rem', fontWeight: 500, color: '#555', userSelect: 'none' }}>
|
||||
Raw Markdown
|
||||
</summary>
|
||||
<pre
|
||||
style={{
|
||||
background: 'white',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
padding: '0.5rem',
|
||||
fontSize: '0.7rem',
|
||||
overflow: 'auto',
|
||||
maxHeight: '250px',
|
||||
margin: '0.5rem 0 0',
|
||||
fontFamily: 'monospace',
|
||||
color: '#333',
|
||||
wordBreak: 'break-word',
|
||||
whiteSpace: 'pre-wrap',
|
||||
overflowWrap: 'break-word',
|
||||
}}
|
||||
>
|
||||
{markdown}
|
||||
</pre>
|
||||
</details>
|
||||
|
||||
{/* Parse Result */}
|
||||
<details
|
||||
style={{
|
||||
marginTop: '0.5rem',
|
||||
paddingTop: '0.5rem',
|
||||
borderTop: '1px solid #ddd',
|
||||
}}
|
||||
>
|
||||
<summary style={{ cursor: 'pointer', fontSize: '0.8rem', fontWeight: 500, color: '#555', userSelect: 'none' }}>
|
||||
Parse Result
|
||||
</summary>
|
||||
<pre
|
||||
style={{
|
||||
background: 'white',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
padding: '0.5rem',
|
||||
fontSize: '0.65rem',
|
||||
overflow: 'auto',
|
||||
maxHeight: '250px',
|
||||
margin: '0.5rem 0 0',
|
||||
fontFamily: 'monospace',
|
||||
color: '#333',
|
||||
wordBreak: 'break-word',
|
||||
whiteSpace: 'pre-wrap',
|
||||
overflowWrap: 'break-word',
|
||||
}}
|
||||
>
|
||||
{JSON.stringify(parsed, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* SPARAT */}
|
||||
{step === 'saved' && (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
padding: '3rem',
|
||||
gap: '1rem',
|
||||
background: '#f0fdf4',
|
||||
border: '1px solid #86efac',
|
||||
borderRadius: '8px',
|
||||
textAlign: 'center',
|
||||
}}>
|
||||
<div style={{ fontSize: '3rem' }}>✓</div>
|
||||
<h2 style={{ margin: 0, color: '#166534' }}>Receptet sparades!</h2>
|
||||
<p style={{ margin: 0, color: '#15803d' }}>Du skickas strax till receptlistan...</p>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import Navigation from '../../Navigation';
|
||||
import WriteRecipePage from './WriteRecipePage';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<>
|
||||
<Navigation />
|
||||
<WriteRecipePage />
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user