feat: add image handling to recipes
- Implemented image downloading and optimization in QuickImportService. - Added imageUrl field to CreateRecipeDto for recipe creation. - Created an endpoint in RecipesController to update recipe images. - Enhanced RecipesService to handle image URL updates and optimizations. - Updated Docker Compose to mount a volume for recipe images. - Refactored frontend to display images in recipe grids and detail views. - Added a new utility function for downloading and optimizing images. - Created a new API route for handling image uploads. - Introduced RecipeGrid component for better recipe display. - Updated RecipeDetailClient to manage image updates and display. - Added migration for new imageUrl column in the Recipe table.
This commit is contained in:
+1
-1
@@ -28,4 +28,4 @@ COPY --from=builder /app/prisma ./prisma
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["node", "dist/main"]
|
||||
CMD ["sh", "-c", "npx prisma migrate deploy && node dist/main"]
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
"pdf-parse": "^1.1.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"tesseract.js": "^6.0.1"
|
||||
"sharp": "^0.33.5",
|
||||
"tesseract.js": "^6.0.1",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.3.0",
|
||||
@@ -31,6 +33,7 @@
|
||||
"@types/multer": "^1.4.12",
|
||||
"@types/node": "^22.15.29",
|
||||
"@types/pdf-parse": "^1.1.5",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"prisma": "^6.12.0",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Migration: add imageUrl to Recipe
|
||||
ALTER TABLE `Recipe` ADD COLUMN `imageUrl` VARCHAR(191) NULL;
|
||||
@@ -60,12 +60,13 @@ model InventoryConsumption {
|
||||
}
|
||||
|
||||
model Recipe {
|
||||
id Int @id @default(autoincrement())
|
||||
name String
|
||||
description String?
|
||||
instructions String? @db.Text
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
id Int @id @default(autoincrement())
|
||||
name String
|
||||
description String?
|
||||
instructions String? @db.Text
|
||||
imageUrl String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
ingredients RecipeIngredient[]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as sharp from 'sharp';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
/** Privata IP-ranges som ska blockeras (SSRF-skydd) */
|
||||
const BLOCKED_HOSTNAMES = /^(localhost|127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.0\.0\.0|::1|fc00:|fe80:)/i;
|
||||
|
||||
/**
|
||||
* Laddar ner en bild från en extern URL, optimerar den med sharp och
|
||||
* sparar till destDir. Returnerar relativ URL för användning i DB (/images/{uuid}.jpg).
|
||||
*
|
||||
* SSRF-skydd:
|
||||
* - Kräver https://
|
||||
* - Blockar privata IP-adresser och localhost
|
||||
* - Timeout 10s, max 5 MB
|
||||
* - Validerar att content-type är image/*
|
||||
*/
|
||||
export async function downloadAndOptimizeImage(
|
||||
sourceUrl: string,
|
||||
destDir: string,
|
||||
): Promise<string> {
|
||||
// Protokollvalidering
|
||||
if (!sourceUrl.startsWith('https://')) {
|
||||
throw new Error('Bild-URL måste använda https://');
|
||||
}
|
||||
|
||||
// SSRF: blockera privata hostnames
|
||||
let hostname: string;
|
||||
try {
|
||||
hostname = new URL(sourceUrl).hostname;
|
||||
} catch {
|
||||
throw new Error('Ogiltig bild-URL');
|
||||
}
|
||||
|
||||
if (BLOCKED_HOSTNAMES.test(hostname)) {
|
||||
throw new Error('Bild-URL pekar på ett blockerat nätverk');
|
||||
}
|
||||
|
||||
// Ladda ner bilden
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 10_000);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(sourceUrl, {
|
||||
signal: controller.signal,
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; RecipeApp/1.0)' },
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status} vid nedladdning av bild`);
|
||||
}
|
||||
|
||||
// Validera content-type
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (!contentType.startsWith('image/')) {
|
||||
throw new Error(`Ogiltig content-type: ${contentType}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
if (arrayBuffer.byteLength > 5 * 1024 * 1024) {
|
||||
throw new Error('Bilden är för stor (max 5 MB)');
|
||||
}
|
||||
|
||||
const imageBuffer = Buffer.from(arrayBuffer);
|
||||
|
||||
// Skapa destDir om det inte finns
|
||||
if (!fs.existsSync(destDir)) {
|
||||
fs.mkdirSync(destDir, { recursive: true });
|
||||
}
|
||||
|
||||
const filename = `${uuidv4()}.jpg`;
|
||||
const outputPath = path.join(destDir, filename);
|
||||
|
||||
// Optimera med sharp
|
||||
await (sharp as unknown as (input: Buffer) => sharp.Sharp)(imageBuffer)
|
||||
.resize(1200, 800, {
|
||||
fit: 'inside',
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.jpeg({ quality: 80 })
|
||||
.toFile(outputPath);
|
||||
|
||||
// Returnera relativ sökväg för DB-lagring
|
||||
return `/images/${filename}`;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export interface ParsedRecipe {
|
||||
note?: string;
|
||||
}>;
|
||||
instructions?: string;
|
||||
imageUrl?: string;
|
||||
}
|
||||
|
||||
export abstract class RecipeParser {
|
||||
|
||||
@@ -14,6 +14,9 @@ export class GenericRecipeParser extends RecipeParser {
|
||||
parse(html: string): ParsedRecipe {
|
||||
console.log('[GenericParser] Parsing recipe from unknown site...');
|
||||
|
||||
// Extrahera og:image för bildurl-fallback
|
||||
const ogImage = this.extractOgImage(html);
|
||||
|
||||
// Försöka extrahera JSON-LD recipe data
|
||||
const jsonLdMatch = html.match(
|
||||
/<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/i
|
||||
@@ -29,7 +32,7 @@ export class GenericRecipeParser extends RecipeParser {
|
||||
|
||||
if (recipe) {
|
||||
console.log('[GenericParser] ✓ JSON-LD data found');
|
||||
return this.extractFromJsonLd(recipe);
|
||||
return this.extractFromJsonLd(recipe, ogImage);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('[GenericParser] JSON-LD parsing failed');
|
||||
@@ -37,13 +40,31 @@ export class GenericRecipeParser extends RecipeParser {
|
||||
}
|
||||
|
||||
console.log('[GenericParser] No JSON-LD found, using HTML parsing');
|
||||
return this.parseFromHtml(html);
|
||||
return this.parseFromHtml(html, ogImage);
|
||||
}
|
||||
|
||||
private extractFromJsonLd(recipe: any): ParsedRecipe {
|
||||
private extractOgImage(html: string): string | undefined {
|
||||
const match = html.match(/<meta[^>]+property="og:image"[^>]+content="([^"]+)"/i)
|
||||
|| html.match(/<meta[^>]+content="([^"]+)"[^>]+property="og:image"/i);
|
||||
return match ? match[1].trim() : undefined;
|
||||
}
|
||||
|
||||
private extractFromJsonLd(recipe: any, ogImage?: string): ParsedRecipe {
|
||||
const name = recipe.name || '';
|
||||
const description = recipe.description || '';
|
||||
|
||||
// Extrahera bildurl från JSON-LD
|
||||
let imageUrl: string | undefined = ogImage;
|
||||
if (recipe.image) {
|
||||
if (typeof recipe.image === 'string') {
|
||||
imageUrl = recipe.image;
|
||||
} else if (Array.isArray(recipe.image) && recipe.image.length > 0) {
|
||||
imageUrl = typeof recipe.image[0] === 'string' ? recipe.image[0] : recipe.image[0]?.url;
|
||||
} else if (recipe.image?.url) {
|
||||
imageUrl = recipe.image.url;
|
||||
}
|
||||
}
|
||||
|
||||
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
|
||||
if (recipe.recipeIngredient && Array.isArray(recipe.recipeIngredient)) {
|
||||
for (const ing of recipe.recipeIngredient) {
|
||||
@@ -75,10 +96,11 @@ export class GenericRecipeParser extends RecipeParser {
|
||||
description,
|
||||
ingredients,
|
||||
instructions,
|
||||
imageUrl,
|
||||
};
|
||||
}
|
||||
|
||||
private parseFromHtml(html: string): ParsedRecipe {
|
||||
private parseFromHtml(html: string, ogImage?: string): ParsedRecipe {
|
||||
// Försöka hitta titel
|
||||
let name = '';
|
||||
|
||||
@@ -143,6 +165,7 @@ export class GenericRecipeParser extends RecipeParser {
|
||||
description,
|
||||
ingredients,
|
||||
instructions,
|
||||
imageUrl: ogImage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ export class IcaRecipeParser extends RecipeParser {
|
||||
parse(html: string): ParsedRecipe {
|
||||
console.log('[IcaParser] Parsing ICA recipe...');
|
||||
|
||||
// Extrahera og:image för bildurl-fallback
|
||||
const ogImage = this.extractOgImage(html);
|
||||
|
||||
// Försöka extrahera JSON-LD recipe data (ICA använder detta)
|
||||
const jsonLdMatch = html.match(
|
||||
/<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/i
|
||||
@@ -29,7 +32,7 @@ export class IcaRecipeParser extends RecipeParser {
|
||||
|
||||
if (recipe) {
|
||||
console.log('[IcaParser] ✓ JSON-LD recipe found');
|
||||
return this.extractFromJsonLd(recipe);
|
||||
return this.extractFromJsonLd(recipe, ogImage);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('[IcaParser] JSON-LD parsing failed:', err);
|
||||
@@ -38,16 +41,34 @@ export class IcaRecipeParser extends RecipeParser {
|
||||
|
||||
// Fallback: HTML parsing (sällan nödvändigt för ICA)
|
||||
console.log('[IcaParser] Falling back to HTML parsing');
|
||||
return this.parseFromHtml(html);
|
||||
return this.parseFromHtml(html, ogImage);
|
||||
}
|
||||
|
||||
private extractFromJsonLd(recipe: any): ParsedRecipe {
|
||||
private extractOgImage(html: string): string | undefined {
|
||||
const match = html.match(/<meta[^>]+property="og:image"[^>]+content="([^"]+)"/i)
|
||||
|| html.match(/<meta[^>]+content="([^"]+)"[^>]+property="og:image"/i);
|
||||
return match ? match[1].trim() : undefined;
|
||||
}
|
||||
|
||||
private extractFromJsonLd(recipe: any, ogImage?: string): ParsedRecipe {
|
||||
// Extrahera titel
|
||||
const name = recipe.name || '';
|
||||
|
||||
// Extrahera beskrivning
|
||||
const description = recipe.description || '';
|
||||
|
||||
// Extrahera bildurl från JSON-LD (kan vara sträng eller array)
|
||||
let imageUrl: string | undefined = ogImage;
|
||||
if (recipe.image) {
|
||||
if (typeof recipe.image === 'string') {
|
||||
imageUrl = recipe.image;
|
||||
} else if (Array.isArray(recipe.image) && recipe.image.length > 0) {
|
||||
imageUrl = typeof recipe.image[0] === 'string' ? recipe.image[0] : recipe.image[0]?.url;
|
||||
} else if (recipe.image?.url) {
|
||||
imageUrl = recipe.image.url;
|
||||
}
|
||||
}
|
||||
|
||||
// Extrahera ingredienser
|
||||
const ingredients: Array<{ quantity: number; unit: string; name: string; note?: string }> = [];
|
||||
if (recipe.recipeIngredient && Array.isArray(recipe.recipeIngredient)) {
|
||||
@@ -81,10 +102,11 @@ export class IcaRecipeParser extends RecipeParser {
|
||||
description,
|
||||
ingredients,
|
||||
instructions,
|
||||
imageUrl,
|
||||
};
|
||||
}
|
||||
|
||||
private parseFromHtml(html: string): ParsedRecipe {
|
||||
private parseFromHtml(html: string, ogImage?: string): ParsedRecipe {
|
||||
let name = '';
|
||||
const titleMatch = html.match(/<h1[^>]*>([^<]+)<\/h1>/i);
|
||||
if (titleMatch) {
|
||||
@@ -133,6 +155,7 @@ export class IcaRecipeParser extends RecipeParser {
|
||||
description,
|
||||
ingredients,
|
||||
instructions,
|
||||
imageUrl: ogImage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,14 @@ import { createWorker } from 'tesseract.js';
|
||||
import { IcaRecipeParser } from './parsers/ica.parser';
|
||||
import { GenericRecipeParser } from './parsers/generic.parser';
|
||||
import { RecipeParser } from './parsers/base.parser';
|
||||
import { downloadAndOptimizeImage } from '../common/utils/download-image';
|
||||
|
||||
const IMAGE_DEST_DIR = process.env.IMAGE_DEST_DIR || '/app/recipe-images';
|
||||
|
||||
export interface QuickImportResult {
|
||||
markdown: string;
|
||||
source: 'ica' | 'pdf' | 'image' | 'other';
|
||||
imageUrl?: string;
|
||||
}
|
||||
|
||||
type UploadKind = 'pdf' | 'image';
|
||||
@@ -311,9 +315,21 @@ export class QuickImportService {
|
||||
source = 'ica';
|
||||
}
|
||||
|
||||
// Ladda ner och optimera bild om parser hittade en
|
||||
let imageUrl: string | undefined;
|
||||
if (recipe.imageUrl) {
|
||||
try {
|
||||
imageUrl = await downloadAndOptimizeImage(recipe.imageUrl, IMAGE_DEST_DIR);
|
||||
console.log('[QuickImport] Bild optimerad och sparad:', imageUrl);
|
||||
} catch (imgErr) {
|
||||
console.warn('[QuickImport] Kunde inte ladda ner bild:', imgErr);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
markdown,
|
||||
source,
|
||||
imageUrl,
|
||||
};
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Okänt fel vid scraping';
|
||||
|
||||
@@ -38,6 +38,10 @@ export class CreateRecipeDto {
|
||||
@IsString()
|
||||
instructions?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
imageUrl?: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Post, Patch } from '@nestjs/common';
|
||||
import { IsString } from 'class-validator';
|
||||
import { RecipesService } from './recipes.service';
|
||||
import { CreateRecipeDto } from './dto/create-recipe.dto';
|
||||
import { ParseMarkdownDto } from './dto/parse-markdown.dto';
|
||||
|
||||
class UpdateImageDto {
|
||||
@IsString()
|
||||
sourceUrl!: string;
|
||||
}
|
||||
|
||||
@Controller('recipes')
|
||||
export class RecipesController {
|
||||
constructor(private readonly recipesService: RecipesService) {}
|
||||
@@ -45,4 +51,12 @@ export class RecipesController {
|
||||
async remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.recipesService.remove(id);
|
||||
}
|
||||
|
||||
@Post(':id/image')
|
||||
async updateImage(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateImageDto,
|
||||
) {
|
||||
return this.recipesService.updateImage(id, dto.sourceUrl);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@ import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateRecipeDto } from './dto/create-recipe.dto';
|
||||
import { ParseMarkdownDto } from './dto/parse-markdown.dto';
|
||||
import { downloadAndOptimizeImage } from '../common/utils/download-image';
|
||||
|
||||
const IMAGE_DEST_DIR = process.env.IMAGE_DEST_DIR || '/app/recipe-images';
|
||||
|
||||
// Lokala typdefiniitioner (tidigare från recipe-document-converter)
|
||||
interface ParsedIngredient {
|
||||
@@ -340,6 +343,7 @@ export class RecipesService {
|
||||
name: updateRecipeDto.name,
|
||||
description: updateRecipeDto.description || null,
|
||||
instructions: updateRecipeDto.instructions || null,
|
||||
...(updateRecipeDto.imageUrl !== undefined && { imageUrl: updateRecipeDto.imageUrl || null }),
|
||||
ingredients: {
|
||||
create: updateRecipeDto.ingredients.map((ingredient) => ({
|
||||
productId: ingredient.productId,
|
||||
@@ -374,12 +378,39 @@ export class RecipesService {
|
||||
await this.prisma.recipe.delete({ where: { id } });
|
||||
}
|
||||
|
||||
async updateImage(id: number, sourceUrl: string) {
|
||||
const existingRecipe = await this.prisma.recipe.findUnique({ where: { id } });
|
||||
if (!existingRecipe) {
|
||||
throw new NotFoundException(`Recipe with id ${id} not found`);
|
||||
}
|
||||
|
||||
const imageUrl = await downloadAndOptimizeImage(sourceUrl, IMAGE_DEST_DIR);
|
||||
|
||||
return this.prisma.recipe.update({
|
||||
where: { id },
|
||||
data: { imageUrl },
|
||||
include: { ingredients: { include: { product: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
async create(createRecipeDto: CreateRecipeDto) {
|
||||
// Om imageUrl är en extern URL — ladda ner och optimera
|
||||
let imageUrl: string | null = createRecipeDto.imageUrl || null;
|
||||
if (imageUrl && imageUrl.startsWith('http')) {
|
||||
try {
|
||||
imageUrl = await downloadAndOptimizeImage(imageUrl, IMAGE_DEST_DIR);
|
||||
} catch (err) {
|
||||
console.warn('[RecipesService] Kunde inte ladda ner receptbild:', err);
|
||||
imageUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
const recipe = await this.prisma.recipe.create({
|
||||
data: {
|
||||
name: createRecipeDto.name,
|
||||
description: createRecipeDto.description || null,
|
||||
instructions: createRecipeDto.instructions || null,
|
||||
imageUrl,
|
||||
ingredients: {
|
||||
create: createRecipeDto.ingredients.map((ingredient) => ({
|
||||
productId: ingredient.productId,
|
||||
|
||||
@@ -8,6 +8,8 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
NEXT_PUBLIC_API_URL: "http://recipe-api:8080"
|
||||
volumes:
|
||||
- recipe_images:/app/public/images
|
||||
depends_on:
|
||||
recipe-api:
|
||||
condition: service_healthy
|
||||
@@ -30,6 +32,8 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
DATABASE_URL: "mysql://root:${MARIADB_ROOT_PASSWORD}@recipe-db:3306/${MARIADB_DATABASE}"
|
||||
volumes:
|
||||
- recipe_images:/app/recipe-images
|
||||
depends_on:
|
||||
recipe-db:
|
||||
condition: service_healthy
|
||||
@@ -68,6 +72,7 @@ services:
|
||||
|
||||
volumes:
|
||||
recipe_db_data:
|
||||
recipe_images:
|
||||
|
||||
networks:
|
||||
proxy:
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } },
|
||||
) {
|
||||
const { id } = await params;
|
||||
const body = await request.text();
|
||||
|
||||
const res = await fetch(`${API_BASE}/api/recipes/${id}/image`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
const text = await res.text();
|
||||
|
||||
return new NextResponse(text, {
|
||||
status: res.status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
'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 filtered = recipes.filter((r) =>
|
||||
r.name.toLowerCase().includes(search.toLowerCase()),
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: '1.25rem' }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Sök efter recept..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '0.6rem 1rem',
|
||||
fontSize: '1rem',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '24px',
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 && (
|
||||
<p style={{ color: '#868e96', textAlign: 'center', marginTop: '2rem' }}>
|
||||
{search ? 'Inga recept matchar sökningen.' : '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' }}>
|
||||
<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',
|
||||
fontSize: '0.85rem',
|
||||
color: '#868e96',
|
||||
overflow: 'hidden',
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: 2,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
} as React.CSSProperties}
|
||||
>
|
||||
{recipe.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type {
|
||||
Recipe,
|
||||
Product,
|
||||
RecipeInventoryPreview,
|
||||
} from '../../../features/inventory/types';
|
||||
import { fetchJson } from '../../../lib/api';
|
||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// 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>;
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
const UNIT_OPTIONS = [
|
||||
{ value: '', label: 'Välj enhet' },
|
||||
{ value: 'g', label: 'g (gram)' },
|
||||
{ value: 'kg', label: 'kg (kilogram)' },
|
||||
{ value: 'hg', label: 'hg (hektogram)' },
|
||||
{ value: 'ml', label: 'ml (milliliter)' },
|
||||
{ value: 'dl', label: 'dl (deciliter)' },
|
||||
{ value: 'l', label: 'l (liter)' },
|
||||
{ value: 'st', label: 'st (styck)' },
|
||||
{ value: 'tsk', label: 'tsk (tesked)' },
|
||||
{ value: 'msk', label: 'msk (matsked)' },
|
||||
{ value: 'port', label: 'port (portioner)' },
|
||||
{ value: 'efter smak', label: 'Efter smak' },
|
||||
{ value: 'förp', label: 'förp (förpackning)' },
|
||||
{ value: 'klyfta', label: 'klyfta' },
|
||||
];
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// Huvud-komponent
|
||||
// ──────────────────────────────────────────────
|
||||
|
||||
export default function RecipeDetailClient({ recipe: initialRecipe }: { recipe: Recipe }) {
|
||||
const router = useRouter();
|
||||
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);
|
||||
|
||||
// Redigeringsformulär-state
|
||||
const [form, setForm] = useState({
|
||||
name: initialRecipe.name,
|
||||
description: initialRecipe.description || '',
|
||||
instructions: initialRecipe.instructions || '',
|
||||
imageUrl: initialRecipe.imageUrl || '',
|
||||
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, startPreviewTransition] = useTransition();
|
||||
|
||||
// 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 = () => {
|
||||
setPreviewError(null);
|
||||
startPreviewTransition(async () => {
|
||||
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());
|
||||
} catch (err) {
|
||||
setPreviewError(err instanceof Error ? err.message : 'Fel vid hämtning av inventariedata');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// ── 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 fetch(`/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 fetch(`/api/recipes/${recipe.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
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 fetch(`/api/recipes/${recipe.id}/image`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
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...' : 'Inventariegranskning'}
|
||||
</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>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.4rem' }}>
|
||||
{recipe.ingredients.map((ing) => (
|
||||
<li key={ing.id} style={{ display: 'flex', gap: '0.5rem', alignItems: 'baseline' }}>
|
||||
<span style={{ fontWeight: 600, minWidth: '60px', textAlign: 'right' }}>
|
||||
{Number(ing.quantity)} {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>
|
||||
)}
|
||||
|
||||
{/* Inventarieförhandsgranskning */}
|
||||
{(preview || previewError) && (
|
||||
<section style={{ ...sectionStyle, marginTop: '1.5rem' }}>
|
||||
<h2 style={sectionTitle}>Inventariegranskning</h2>
|
||||
{previewError && <p style={errorStyle}>{previewError}</p>}
|
||||
{preview && (
|
||||
<>
|
||||
<div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap', marginBottom: '1rem', fontSize: '0.9rem' }}>
|
||||
<span>Totalt: <strong>{preview.summary.totalIngredients}</strong></span>
|
||||
<span style={{ color: '#1f5f2c' }}>Räcker: <strong>{preview.summary.enoughCount}</strong></span>
|
||||
<span style={{ color: '#8b0000' }}>Saknas: <strong>{preview.summary.missingCount}</strong></span>
|
||||
{preview.summary.unitMismatchCount > 0 && (
|
||||
<span style={{ color: '#8a4b00' }}>Enhetskonflikt: <strong>{preview.summary.unitMismatchCount}</strong></span>
|
||||
)}
|
||||
</div>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.5rem' }}>
|
||||
{preview.ingredients.map((ing) => (
|
||||
<li key={ing.ingredientId} style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
|
||||
padding: '0.5rem 0.75rem', borderRadius: '6px', border: '1px solid #eee',
|
||||
flexWrap: 'wrap', gap: '0.5rem',
|
||||
}}>
|
||||
<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>
|
||||
)}
|
||||
</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>
|
||||
|
||||
{/* 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,
|
||||
};
|
||||
@@ -1,11 +1,15 @@
|
||||
'use client';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter, useParams } from 'next/navigation';
|
||||
import { fetchJson } from '../../../../lib/api';
|
||||
import { parseErrorResponse } from '../../../../lib/error-handler';
|
||||
import type { Product, Recipe } from '../../../../features/inventory/types';
|
||||
import Navigation from '../../../Navigation';
|
||||
interface Props {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// Detaljsidan hanterar nu både visning och redigering.
|
||||
// Omdirigera från gammal /edit-URL till /recipes/[id]
|
||||
export default async function EditRecipeRedirect({ params }: Props) {
|
||||
const { id } = await params;
|
||||
redirect(`/recipes/${id}`);
|
||||
}
|
||||
|
||||
const MARKDOWN_HELP = `
|
||||
**Fetstil:** **text** eller __text__
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import Link from 'next/link';
|
||||
import { fetchJson } from '../../lib/api';
|
||||
import type { Recipe } from '../../features/inventory/types';
|
||||
import RecipePreview from './RecipePreview';
|
||||
import Navigation from '../Navigation';
|
||||
import RecipeGrid from './RecipeGrid';
|
||||
|
||||
export default async function RecipesPage() {
|
||||
const recipes = await fetchJson<Recipe[]>('/api/recipes');
|
||||
@@ -22,36 +22,12 @@ export default async function RecipesPage() {
|
||||
textDecoration: 'none',
|
||||
fontWeight: 500,
|
||||
fontSize: '1rem',
|
||||
transition: 'background 0.2s',
|
||||
}}
|
||||
>
|
||||
Lägg till nytt recept
|
||||
</Link>
|
||||
</div>
|
||||
<p>Här kan du jämföra recept mot nuvarande hemmavaror.</p>
|
||||
<RecipePreview recipes={recipes} />
|
||||
<RecipeGrid recipes={recipes} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function parseQuantityInput(input: string, defaultUnit: string) {
|
||||
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
|
||||
if (!match) return { quantity: NaN, unit: defaultUnit };
|
||||
let [, num, unit] = match;
|
||||
num = num.replace(',', '.');
|
||||
unit = unit.toLowerCase() || defaultUnit;
|
||||
const value = parseFloat(num);
|
||||
// Konvertera alltid till defaultUnit
|
||||
if (defaultUnit === 'kg') {
|
||||
if (unit === 'g' || unit === 'gram') return { quantity: value / 1000, unit: 'kg' };
|
||||
if (unit === 'hg' || unit === 'hektogram') return { quantity: value / 10, unit: 'kg' };
|
||||
if (unit === 'kg' || unit === 'kilogram' || unit === '') return { quantity: value, unit: 'kg' };
|
||||
}
|
||||
if (defaultUnit === 'g') {
|
||||
if (unit === 'kg' || unit === 'kilogram') return { quantity: value * 1000, unit: 'g' };
|
||||
if (unit === 'hg' || unit === 'hektogram') return { quantity: value * 100, unit: 'g' };
|
||||
if (unit === 'g' || unit === 'gram' || unit === '') return { quantity: value, unit: 'g' };
|
||||
}
|
||||
// Lägg till fler konverteringar vid behov
|
||||
return { quantity: value, unit: defaultUnit };
|
||||
}
|
||||
@@ -72,6 +72,7 @@ export type Recipe = {
|
||||
name: string;
|
||||
description: string | null;
|
||||
instructions: string | null;
|
||||
imageUrl: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
ingredients: RecipeIngredient[];
|
||||
|
||||
Reference in New Issue
Block a user