Refactor logging in IcaRecipeParser and QuickImportService to use NestJS Logger
- Updated IcaRecipeParser to replace console.log statements with Logger for better logging practices. - Enhanced QuickImportService with Logger for consistent logging and error handling. - Changed quantity validation in CreateRecipeIngredientDto and CreateRecipeDto to allow zero. - Removed CanonicalNameForm and NameForm components from the frontend. - Updated EditProductForm to use a select dropdown for categories instead of a text input. - Added validation for product name, canonical name, and category length in product update action. - Refactored unit options into a separate file for better reusability across components. - Removed unused API fetching functions and inventory types to clean up the codebase.
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
import { RecipeParser, ParsedRecipe } from './base.parser';
|
import { RecipeParser, ParsedRecipe } from './base.parser';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -6,13 +7,14 @@ import { RecipeParser, ParsedRecipe } from './base.parser';
|
|||||||
* Denna är mer permissiv än site-specifika parsers
|
* Denna är mer permissiv än site-specifika parsers
|
||||||
*/
|
*/
|
||||||
export class GenericRecipeParser extends RecipeParser {
|
export class GenericRecipeParser extends RecipeParser {
|
||||||
|
private readonly logger = new Logger(GenericRecipeParser.name);
|
||||||
canHandle(url: string): boolean {
|
canHandle(url: string): boolean {
|
||||||
// Denna parser hanterar alltid (är fallback)
|
// Denna parser hanterar alltid (är fallback)
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
parse(html: string): ParsedRecipe {
|
parse(html: string): ParsedRecipe {
|
||||||
console.log('[GenericParser] Parsing recipe from unknown site...');
|
this.logger.log('Parsing recipe from unknown site...');
|
||||||
|
|
||||||
// Extrahera og:image för bildurl-fallback
|
// Extrahera og:image för bildurl-fallback
|
||||||
const ogImage = this.extractOgImage(html);
|
const ogImage = this.extractOgImage(html);
|
||||||
@@ -31,15 +33,15 @@ export class GenericRecipeParser extends RecipeParser {
|
|||||||
: jsonData['@graph']?.find((item: any) => item['@type'] === 'Recipe');
|
: jsonData['@graph']?.find((item: any) => item['@type'] === 'Recipe');
|
||||||
|
|
||||||
if (recipe) {
|
if (recipe) {
|
||||||
console.log('[GenericParser] ✓ JSON-LD data found');
|
this.logger.log('JSON-LD data found');
|
||||||
return this.extractFromJsonLd(recipe, ogImage);
|
return this.extractFromJsonLd(recipe, ogImage);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('[GenericParser] JSON-LD parsing failed');
|
this.logger.warn('JSON-LD parsing failed');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('[GenericParser] No JSON-LD found, using HTML parsing');
|
this.logger.log('No JSON-LD found, using HTML parsing');
|
||||||
return this.parseFromHtml(html, ogImage);
|
return this.parseFromHtml(html, ogImage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
import { RecipeParser, ParsedRecipe } from './base.parser';
|
import { RecipeParser, ParsedRecipe } from './base.parser';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -5,12 +6,13 @@ import { RecipeParser, ParsedRecipe } from './base.parser';
|
|||||||
* Använder JSON-LD structured data som primär källa
|
* Använder JSON-LD structured data som primär källa
|
||||||
*/
|
*/
|
||||||
export class IcaRecipeParser extends RecipeParser {
|
export class IcaRecipeParser extends RecipeParser {
|
||||||
|
private readonly logger = new Logger(IcaRecipeParser.name);
|
||||||
canHandle(url: string): boolean {
|
canHandle(url: string): boolean {
|
||||||
return /ica\.se\/recept/i.test(url);
|
return /ica\.se\/recept/i.test(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
parse(html: string): ParsedRecipe {
|
parse(html: string): ParsedRecipe {
|
||||||
console.log('[IcaParser] Parsing ICA recipe...');
|
this.logger.log('Parsing ICA recipe...');
|
||||||
|
|
||||||
// Extrahera og:image för bildurl-fallback
|
// Extrahera og:image för bildurl-fallback
|
||||||
const ogImage = this.extractOgImage(html);
|
const ogImage = this.extractOgImage(html);
|
||||||
@@ -31,16 +33,16 @@ export class IcaRecipeParser extends RecipeParser {
|
|||||||
: jsonData['@graph']?.find((item: any) => item['@type'] === 'Recipe');
|
: jsonData['@graph']?.find((item: any) => item['@type'] === 'Recipe');
|
||||||
|
|
||||||
if (recipe) {
|
if (recipe) {
|
||||||
console.log('[IcaParser] ✓ JSON-LD recipe found');
|
this.logger.log('JSON-LD recipe found');
|
||||||
return this.extractFromJsonLd(recipe, ogImage);
|
return this.extractFromJsonLd(recipe, ogImage);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('[IcaParser] JSON-LD parsing failed:', err);
|
this.logger.warn(`JSON-LD parsing failed: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: HTML parsing (sällan nödvändigt för ICA)
|
// Fallback: HTML parsing (sällan nödvändigt för ICA)
|
||||||
console.log('[IcaParser] Falling back to HTML parsing');
|
this.logger.log('Falling back to HTML parsing');
|
||||||
return this.parseFromHtml(html, ogImage);
|
return this.parseFromHtml(html, ogImage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
Injectable,
|
Injectable,
|
||||||
|
Logger,
|
||||||
ServiceUnavailableException,
|
ServiceUnavailableException,
|
||||||
UnsupportedMediaTypeException,
|
UnsupportedMediaTypeException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -25,24 +26,26 @@ type UploadKind = 'pdf' | 'image';
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class QuickImportService {
|
export class QuickImportService {
|
||||||
|
private readonly logger = new Logger(QuickImportService.name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Detekterar typ av input (URL eller filsökväg) och importerar från lämplig källa
|
* Detekterar typ av input (URL eller filsökväg) och importerar från lämplig källa
|
||||||
*/
|
*/
|
||||||
async importFromInput(input: string): Promise<QuickImportResult> {
|
async importFromInput(input: string): Promise<QuickImportResult> {
|
||||||
const trimmed = input.trim();
|
const trimmed = input.trim();
|
||||||
console.log('[QuickImport] Mottog input:', trimmed);
|
this.logger.log(`Mottog input: ${trimmed}`);
|
||||||
|
|
||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
throw new BadRequestException('Du måste ange en URL eller ladda upp en fil');
|
throw new BadRequestException('Du måste ange en URL eller ladda upp en fil');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.isUrl(trimmed)) {
|
if (this.isUrl(trimmed)) {
|
||||||
console.log('[QuickImport] Detekterade URL, försöker scrapa...');
|
this.logger.log('Detekterade URL, försöker scrapa...');
|
||||||
return this.scrapeRecipeFromUrl(trimmed);
|
return this.scrapeRecipeFromUrl(trimmed);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.looksLikeLocalFile(trimmed)) {
|
if (this.looksLikeLocalFile(trimmed)) {
|
||||||
console.log('[QuickImport] Försöker läsa lokal fil:', trimmed);
|
this.logger.log(`Försöker läsa lokal fil: ${trimmed}`);
|
||||||
try {
|
try {
|
||||||
const buffer = await fs.readFile(trimmed);
|
const buffer = await fs.readFile(trimmed);
|
||||||
return this.importFromUpload({
|
return this.importFromUpload({
|
||||||
@@ -51,7 +54,7 @@ export class QuickImportService {
|
|||||||
mimetype: this.getMimeTypeFromExtension(trimmed),
|
mimetype: this.getMimeTypeFromExtension(trimmed),
|
||||||
} as Express.Multer.File);
|
} as Express.Multer.File);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[QuickImport] Kunde inte läsa lokal fil:', error);
|
this.logger.error('Kunde inte läsa lokal fil:', error);
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'Kunde inte läsa filen. Använd filuppladdning i gränssnittet eller kontrollera sökvägen.',
|
'Kunde inte läsa filen. Använd filuppladdning i gränssnittet eller kontrollera sökvägen.',
|
||||||
);
|
);
|
||||||
@@ -68,7 +71,7 @@ export class QuickImportService {
|
|||||||
throw new BadRequestException('Ingen fil skickades med.');
|
throw new BadRequestException('Ingen fil skickades med.');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('[QuickImport] Mottog uppladdad fil:', file.originalname, file.mimetype);
|
this.logger.log(`Mottog uppladdad fil: ${file.originalname} (${file.mimetype})`);
|
||||||
const kind = this.getUploadKind(file);
|
const kind = this.getUploadKind(file);
|
||||||
|
|
||||||
if (kind === 'pdf') {
|
if (kind === 'pdf') {
|
||||||
@@ -154,7 +157,7 @@ export class QuickImportService {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error('[QuickImport] PDF ERROR:', error);
|
this.logger.error('PDF-import misslyckades', error);
|
||||||
throw new ServiceUnavailableException('PDF-importen misslyckades.');
|
throw new ServiceUnavailableException('PDF-importen misslyckades.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -176,7 +179,7 @@ export class QuickImportService {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error('[QuickImport] OCR ERROR:', error);
|
this.logger.error('OCR-import misslyckades', error);
|
||||||
throw new ServiceUnavailableException('OCR-importen misslyckades.');
|
throw new ServiceUnavailableException('OCR-importen misslyckades.');
|
||||||
} finally {
|
} finally {
|
||||||
await worker.terminate();
|
await worker.terminate();
|
||||||
@@ -262,7 +265,7 @@ export class QuickImportService {
|
|||||||
*/
|
*/
|
||||||
private async scrapeRecipeFromUrl(url: string): Promise<QuickImportResult> {
|
private async scrapeRecipeFromUrl(url: string): Promise<QuickImportResult> {
|
||||||
try {
|
try {
|
||||||
console.log('[QuickImport] Hämtar HTML från:', url);
|
this.logger.log(`Hämtar HTML från: ${url}`);
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -271,14 +274,14 @@ export class QuickImportService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('[QuickImport] HTTP status:', response.status);
|
this.logger.log(`HTTP status: ${response.status}`);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const html = await response.text();
|
const html = await response.text();
|
||||||
console.log('[QuickImport] HTML längd:', html.length, 'tecken');
|
this.logger.log(`HTML längd: ${html.length} tecken`);
|
||||||
|
|
||||||
const parsers: RecipeParser[] = [
|
const parsers: RecipeParser[] = [
|
||||||
new IcaRecipeParser(),
|
new IcaRecipeParser(),
|
||||||
@@ -288,7 +291,7 @@ export class QuickImportService {
|
|||||||
let recipe = null;
|
let recipe = null;
|
||||||
for (const parser of parsers) {
|
for (const parser of parsers) {
|
||||||
if (parser.canHandle(url)) {
|
if (parser.canHandle(url)) {
|
||||||
console.log('[QuickImport] Använder parser:', parser.constructor.name);
|
this.logger.log(`Använder parser: ${parser.constructor.name}`);
|
||||||
recipe = parser.parse(html);
|
recipe = parser.parse(html);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -298,17 +301,14 @@ export class QuickImportService {
|
|||||||
throw new Error('Ingen parserutrustning tillgänglig');
|
throw new Error('Ingen parserutrustning tillgänglig');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('[QuickImport] Parsad recept:', {
|
this.logger.log(`Parsad recept: ${recipe.name} (${recipe.ingredients.length} ingredienser)`);
|
||||||
name: recipe.name,
|
|
||||||
ingredienser: recipe.ingredients.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!recipe.name) {
|
if (!recipe.name) {
|
||||||
throw new Error('Kunde inte hitta receptnamn på sidan. Försök med en annan länk.');
|
throw new Error('Kunde inte hitta receptnamn på sidan. Försök med en annan länk.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const markdown = this.recipeToMarkdown(recipe, url);
|
const markdown = this.recipeToMarkdown(recipe, url);
|
||||||
console.log('[QuickImport] Markdown genererad, längd:', markdown.length);
|
this.logger.log(`Markdown genererad, längd: ${markdown.length}`);
|
||||||
|
|
||||||
let source: 'ica' | 'pdf' | 'image' | 'other' = 'other';
|
let source: 'ica' | 'pdf' | 'image' | 'other' = 'other';
|
||||||
if (/ica\.se/i.test(url)) {
|
if (/ica\.se/i.test(url)) {
|
||||||
@@ -320,9 +320,9 @@ export class QuickImportService {
|
|||||||
if (recipe.imageUrl) {
|
if (recipe.imageUrl) {
|
||||||
try {
|
try {
|
||||||
imageUrl = await downloadAndOptimizeImage(recipe.imageUrl, IMAGE_DEST_DIR);
|
imageUrl = await downloadAndOptimizeImage(recipe.imageUrl, IMAGE_DEST_DIR);
|
||||||
console.log('[QuickImport] Bild optimerad och sparad:', imageUrl);
|
this.logger.log(`Bild optimerad och sparad: ${imageUrl}`);
|
||||||
} catch (imgErr) {
|
} catch (imgErr) {
|
||||||
console.warn('[QuickImport] Kunde inte ladda ner bild:', imgErr);
|
this.logger.warn(`Kunde inte ladda ner bild: ${imgErr}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,7 +333,7 @@ export class QuickImportService {
|
|||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : 'Okänt fel vid scraping';
|
const message = err instanceof Error ? err.message : 'Okänt fel vid scraping';
|
||||||
console.error('[QuickImport] ERROR:', message);
|
this.logger.error(`Scraping misslyckades: ${message}`);
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`Kunde inte hämta recept: ${message}. Kontrollera att länken är korrekt och försök igen.`
|
`Kunde inte hämta recept: ${message}. Kontrollera att länken är korrekt och försök igen.`
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ export class CreateRecipeIngredientDto {
|
|||||||
productId!: number;
|
productId!: number;
|
||||||
|
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
@Min(0.01)
|
@Min(0)
|
||||||
quantity!: number;
|
quantity!: number;
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class CreateRecipeIngredientDto {
|
|||||||
productId!: number;
|
productId!: number;
|
||||||
|
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
@Min(0.01)
|
@Min(0)
|
||||||
quantity!: number;
|
quantity!: number;
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
|
|||||||
@@ -1,79 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useTransition } from 'react';
|
|
||||||
import { updateCanonicalName } from '../../inventory/actions';
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
id: number;
|
|
||||||
currentCanonicalName: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function CanonicalNameForm({
|
|
||||||
id,
|
|
||||||
currentCanonicalName,
|
|
||||||
}: Props) {
|
|
||||||
const [isPending, startTransition] = useTransition();
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form
|
|
||||||
onSubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
const form = e.currentTarget;
|
|
||||||
const formData = new FormData(form);
|
|
||||||
|
|
||||||
startTransition(async () => {
|
|
||||||
try {
|
|
||||||
await updateCanonicalName(formData);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'Okänt fel');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexWrap: 'wrap' }}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="hidden"
|
|
||||||
name="id"
|
|
||||||
value={id}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
name="canonicalName"
|
|
||||||
type="text"
|
|
||||||
defaultValue={currentCanonicalName || ''}
|
|
||||||
placeholder="Canonical name"
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
minHeight: '44px',
|
|
||||||
minWidth: '220px',
|
|
||||||
flex: '1 1 200px',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isPending}
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem 1.5rem',
|
|
||||||
background: '#0070f3',
|
|
||||||
color: 'white',
|
|
||||||
border: 'none',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
fontWeight: 600,
|
|
||||||
whiteSpace: 'nowrap',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isPending ? 'Sparar...' : 'Spara'}
|
|
||||||
</button>
|
|
||||||
{error ? <span style={{ color: 'crimson' }}>{error}</span> : null}
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -110,13 +110,23 @@ export default function EditProductForm({ product }: Props) {
|
|||||||
|
|
||||||
<label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
|
<label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
|
||||||
<span style={{ fontWeight: 600 }}>Kategori</span>
|
<span style={{ fontWeight: 600 }}>Kategori</span>
|
||||||
<input
|
<select
|
||||||
name="category"
|
name="category"
|
||||||
type="text"
|
|
||||||
defaultValue={product.category ?? ''}
|
defaultValue={product.category ?? ''}
|
||||||
style={inputStyle}
|
style={inputStyle}
|
||||||
placeholder="T.ex. Kött, Grönsaker, Mejeriprodukter"
|
>
|
||||||
/>
|
<option value="">— Ingen kategori —</option>
|
||||||
|
<option value="Kött & Fisk">Kött & Fisk</option>
|
||||||
|
<option value="Mejeri & Ägg">Mejeri & Ägg</option>
|
||||||
|
<option value="Grönsaker & Frukt">Grönsaker & Frukt</option>
|
||||||
|
<option value="Torrvaror & Skafferi">Torrvaror & Skafferi</option>
|
||||||
|
<option value="Bröd & Bakverk">Bröd & Bakverk</option>
|
||||||
|
<option value="Kryddor & Smaksättning">Kryddor & Smaksättning</option>
|
||||||
|
<option value="Dryck">Dryck</option>
|
||||||
|
<option value="Frysta varor">Frysta varor</option>
|
||||||
|
<option value="Konserver">Konserver</option>
|
||||||
|
<option value="Övrigt">Övrigt</option>
|
||||||
|
</select>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<div style={{ display: 'grid', gap: '0.25rem', fontSize: '0.85rem', color: '#888' }}>
|
<div style={{ display: 'grid', gap: '0.25rem', fontSize: '0.85rem', color: '#888' }}>
|
||||||
|
|||||||
@@ -9,6 +9,11 @@ export async function updateProduct(formData: FormData) {
|
|||||||
const canonicalName = String(formData.get('canonicalName') || '').trim();
|
const canonicalName = String(formData.get('canonicalName') || '').trim();
|
||||||
const category = String(formData.get('category') || '').trim();
|
const category = String(formData.get('category') || '').trim();
|
||||||
|
|
||||||
|
if (!name) throw new Error('Namn får inte vara tomt.');
|
||||||
|
if (name.length > 100) throw new Error('Namn får inte vara längre än 100 tecken.');
|
||||||
|
if (canonicalName.length > 100) throw new Error('Canonical name får inte vara längre än 100 tecken.');
|
||||||
|
if (category.length > 100) throw new Error('Kategori får inte vara längre än 100 tecken.');
|
||||||
|
|
||||||
const res = await fetch(`${API_BASE}/api/products/${id}`, {
|
const res = await fetch(`${API_BASE}/api/products/${id}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useState, useTransition } from 'react';
|
import { useState, useTransition } from 'react';
|
||||||
import { updateInventoryItem } from './actions';
|
import { updateInventoryItem } from './actions';
|
||||||
import type { InventoryItem } from '../../features/inventory/types';
|
import type { InventoryItem } from '../../features/inventory/types';
|
||||||
|
import { UNIT_OPTIONS } from '../../lib/units';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
item: InventoryItem;
|
item: InventoryItem;
|
||||||
@@ -35,23 +36,6 @@ function parseQuantityInput(input: string, defaultUnit: string) {
|
|||||||
return { quantity: value, unit: defaultUnit };
|
return { quantity: value, unit: defaultUnit };
|
||||||
}
|
}
|
||||||
|
|
||||||
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' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const LOCATION_OPTIONS = [
|
const LOCATION_OPTIONS = [
|
||||||
{ value: '', label: 'Välj plats' },
|
{ value: '', label: 'Välj plats' },
|
||||||
{ value: 'Kyl', label: 'Kyl' },
|
{ value: 'Kyl', label: 'Kyl' },
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { createInventoryItem } from './actions';
|
import { createInventoryItem } from './actions';
|
||||||
import type { Product } from '../../features/inventory/types';
|
import type { Product } from '../../features/inventory/types';
|
||||||
|
import { UNIT_OPTIONS } from '../../lib/units';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
products: Product[];
|
products: Product[];
|
||||||
@@ -13,23 +14,6 @@ export default function InventoryForm({ products }: Props) {
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
const UNIT_OPTIONS = [
|
|
||||||
{ value: '', label: 'Välj enhet' },
|
|
||||||
{ value: 'g', label: 'g (gram)' },
|
|
||||||
{ value: 'kg', label: 'kg (kilogram)' },
|
|
||||||
{ value: 'hg', label: 'hg (hektogram)' },
|
|
||||||
{ value: 'ml', label: 'ml (milliliter)' },
|
|
||||||
{ value: 'dl', label: 'dl (deciliter)' },
|
|
||||||
{ value: 'l', label: 'l (liter)' },
|
|
||||||
{ value: 'st', label: 'st (styck)' },
|
|
||||||
{ value: 'tsk', label: 'tsk (tesked)' },
|
|
||||||
{ value: 'msk', label: 'msk (matsked)' },
|
|
||||||
{ value: 'port', label: 'port (portioner)' },
|
|
||||||
{ value: 'efter smak', label: 'Efter smak' },
|
|
||||||
{ value: 'förp', label: 'förp (förpackning)' },
|
|
||||||
{ value: 'klyfta', label: 'klyfta' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const LOCATION_OPTIONS = [
|
const LOCATION_OPTIONS = [
|
||||||
{ value: '', label: 'Välj plats' },
|
{ value: '', label: 'Välj plats' },
|
||||||
{ value: 'Kyl', label: 'Kyl' },
|
{ value: 'Kyl', label: 'Kyl' },
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
} from '../../../features/inventory/types';
|
} from '../../../features/inventory/types';
|
||||||
import { fetchJson } from '../../../lib/api';
|
import { fetchJson } from '../../../lib/api';
|
||||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||||
|
import { UNIT_OPTIONS } from '../../../lib/units';
|
||||||
|
|
||||||
// ──────────────────────────────────────────────
|
// ──────────────────────────────────────────────
|
||||||
// Hjälpfunktioner
|
// Hjälpfunktioner
|
||||||
@@ -50,23 +51,6 @@ function StatusBadge({ status }: { status: 'enough' | 'missing' | 'unit_mismatch
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const UNIT_OPTIONS = [
|
|
||||||
{ value: '', label: 'Välj enhet' },
|
|
||||||
{ value: 'g', label: 'g (gram)' },
|
|
||||||
{ value: 'kg', label: 'kg (kilogram)' },
|
|
||||||
{ value: 'hg', label: 'hg (hektogram)' },
|
|
||||||
{ value: 'ml', label: 'ml (milliliter)' },
|
|
||||||
{ value: 'dl', label: 'dl (deciliter)' },
|
|
||||||
{ value: 'l', label: 'l (liter)' },
|
|
||||||
{ value: 'st', label: 'st (styck)' },
|
|
||||||
{ value: 'tsk', label: 'tsk (tesked)' },
|
|
||||||
{ value: 'msk', label: 'msk (matsked)' },
|
|
||||||
{ value: 'port', label: 'port (portioner)' },
|
|
||||||
{ value: 'efter smak', label: 'Efter smak' },
|
|
||||||
{ value: 'förp', label: 'förp (förpackning)' },
|
|
||||||
{ value: 'klyfta', label: 'klyfta' },
|
|
||||||
];
|
|
||||||
|
|
||||||
// ──────────────────────────────────────────────
|
// ──────────────────────────────────────────────
|
||||||
// Huvud-komponent
|
// Huvud-komponent
|
||||||
// ──────────────────────────────────────────────
|
// ──────────────────────────────────────────────
|
||||||
|
|||||||
@@ -1,476 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import Link from 'next/link';
|
|
||||||
import { fetchJson } from '../../../lib/api';
|
|
||||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
|
||||||
import type { Product } from '../../../features/inventory/types';
|
|
||||||
import Navigation from '../../Navigation';
|
|
||||||
|
|
||||||
const MARKDOWN_HELP = `
|
|
||||||
**Fetstil:** **text** eller __text__
|
|
||||||
*Kursiv:* *text* eller _text_
|
|
||||||
• Punktlista: - punkt eller * punkt
|
|
||||||
# Rubrik 1
|
|
||||||
## Rubrik 2
|
|
||||||
### Rubrik 3
|
|
||||||
`;
|
|
||||||
|
|
||||||
function SimpleMarkdownPreview({ text }: { text: string }) {
|
|
||||||
const lines = text.split('\n');
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div style={{ whiteSpace: 'pre-wrap', lineHeight: 1.6, wordBreak: 'break-word' }}>
|
|
||||||
{lines.map((line, i) => {
|
|
||||||
if (line.startsWith('# ')) {
|
|
||||||
return <h3 key={i} style={{ margin: '0.5rem 0 0.25rem 0', fontSize: '1.3em', fontWeight: 700 }}>{line.slice(2)}</h3>;
|
|
||||||
}
|
|
||||||
if (line.startsWith('## ')) {
|
|
||||||
return <h4 key={i} style={{ margin: '0.5rem 0 0.25rem 0', fontSize: '1.1em', fontWeight: 700 }}>{line.slice(3)}</h4>;
|
|
||||||
}
|
|
||||||
if (line.startsWith('- ') || line.startsWith('* ')) {
|
|
||||||
return <div key={i} style={{ marginLeft: '1.5rem' }}>• {line.slice(2)}</div>;
|
|
||||||
}
|
|
||||||
if (line.trim() === '') {
|
|
||||||
return <div key={i} style={{ height: '0.5rem' }} />;
|
|
||||||
}
|
|
||||||
return <div key={i}>{line}</div>;
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function CreateRecipePage() {
|
|
||||||
const router = useRouter();
|
|
||||||
const [recipe, setRecipe] = useState({
|
|
||||||
name: '',
|
|
||||||
description: '',
|
|
||||||
instructions: '',
|
|
||||||
ingredients: [{ productId: 0, quantity: '', unit: '', note: '', location: '' }],
|
|
||||||
});
|
|
||||||
const [products, setProducts] = useState<Product[]>([]);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [showPreview, setShowPreview] = useState(false);
|
|
||||||
const [showMarkdownHelp, setShowMarkdownHelp] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchJson<Product[]>('/api/products')
|
|
||||||
.then(setProducts)
|
|
||||||
.catch(console.error);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleIngredientChange = (index: number, field: string, value: string | number) => {
|
|
||||||
const newIngredients = [...recipe.ingredients];
|
|
||||||
newIngredients[index] = { ...newIngredients[index], [field]: value };
|
|
||||||
setRecipe({ ...recipe, ingredients: newIngredients });
|
|
||||||
};
|
|
||||||
|
|
||||||
const addIngredient = () => {
|
|
||||||
setRecipe({
|
|
||||||
...recipe,
|
|
||||||
ingredients: [...recipe.ingredients, { productId: 0, quantity: '', unit: '', note: '', location: '' }],
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const removeIngredient = (index: number) => {
|
|
||||||
const newIngredients = [...recipe.ingredients];
|
|
||||||
newIngredients.splice(index, 1);
|
|
||||||
setRecipe({ ...recipe, ingredients: newIngredients });
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
// Konvertera quantity till number för varje ingrediens
|
|
||||||
const recipeToSend = {
|
|
||||||
...recipe,
|
|
||||||
ingredients: recipe.ingredients.map(({ location: _loc, ...ing }) => ({
|
|
||||||
...ing,
|
|
||||||
quantity: Number(ing.quantity),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/recipes', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(recipeToSend),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorMessage = await parseErrorResponse(response);
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
router.push('/recipes');
|
|
||||||
} catch (err) {
|
|
||||||
const message = err instanceof Error ? err.message : 'Ett okänt fel inträffade. Försök igen.';
|
|
||||||
setError(message);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const UNIT_OPTIONS = [
|
|
||||||
{ value: '', label: 'Välj enhet' },
|
|
||||||
{ value: 'g', label: 'g (gram)' },
|
|
||||||
{ value: 'kg', label: 'kg (kilogram)' },
|
|
||||||
{ value: 'hg', label: 'hg (hektogram)' },
|
|
||||||
{ value: 'ml', label: 'ml (milliliter)' },
|
|
||||||
{ value: 'dl', label: 'dl (deciliter)' },
|
|
||||||
{ value: 'l', label: 'l (liter)' },
|
|
||||||
{ value: 'st', label: 'st (styck)' },
|
|
||||||
{ value: 'tsk', label: 'tsk (tesked)' },
|
|
||||||
{ value: 'msk', label: 'msk (matsked)' },
|
|
||||||
{ value: 'krm', label: 'krm (kryddmått)' },
|
|
||||||
{ value: 'port', label: 'port (portioner)' },
|
|
||||||
{ value: 'efter smak', label: 'Efter smak' },
|
|
||||||
{ value: 'förp', label: 'förp (förpackning)' },
|
|
||||||
{ value: 'klyfta', label: 'klyfta' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const LOCATION_OPTIONS = [
|
|
||||||
{ value: '', label: 'Välj plats' },
|
|
||||||
{ value: 'Kyl', label: 'Kyl' },
|
|
||||||
{ value: 'Frys', label: 'Frys' },
|
|
||||||
{ value: 'Skafferi', label: 'Skafferi' },
|
|
||||||
{ value: 'Annat', label: 'Annat' },
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main style={{ padding: '1rem', maxWidth: '1000px', margin: '0 auto' }}>
|
|
||||||
<Navigation />
|
|
||||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
|
|
||||||
<h1 style={{ margin: 0 }}>Lägg till nytt recept</h1>
|
|
||||||
<Link
|
|
||||||
href="/recipes/import"
|
|
||||||
style={{
|
|
||||||
padding: '0.5rem 1rem',
|
|
||||||
background: '#f0f0f0',
|
|
||||||
color: '#333',
|
|
||||||
borderRadius: '4px',
|
|
||||||
textDecoration: 'none',
|
|
||||||
fontWeight: 500,
|
|
||||||
fontSize: '0.9rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Importera från Markdown
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && <p style={{ color: 'crimson', backgroundColor: '#ffe5e5', padding: '0.75rem', borderRadius: '4px', marginBottom: '1rem' }}>{error}</p>}
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} style={{ display: 'grid', gap: '1.5rem' }}>
|
|
||||||
{/* Receptdetaljer */}
|
|
||||||
<section style={{ display: 'grid', gap: '1rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
|
|
||||||
<h2 style={{ margin: 0, fontSize: '1.1rem' }}>Receptdetaljer</h2>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
|
|
||||||
Receptnamn *
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={recipe.name}
|
|
||||||
onChange={(e) => setRecipe({ ...recipe, name: e.target.value })}
|
|
||||||
required
|
|
||||||
style={{
|
|
||||||
width: '100%',
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
|
|
||||||
Beskrivning
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
value={recipe.description}
|
|
||||||
onChange={(e) => setRecipe({ ...recipe, description: e.target.value })}
|
|
||||||
placeholder="Kort beskrivning av receptet..."
|
|
||||||
style={{
|
|
||||||
width: '100%',
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '100px',
|
|
||||||
fontFamily: 'inherit',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
|
|
||||||
Instruktioner
|
|
||||||
</label>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowMarkdownHelp(!showMarkdownHelp)}
|
|
||||||
style={{
|
|
||||||
marginBottom: '0.5rem',
|
|
||||||
padding: '0.4rem 0.75rem',
|
|
||||||
background: '#f9f9f9',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '0.85rem',
|
|
||||||
color: '#666',
|
|
||||||
fontWeight: 500,
|
|
||||||
display: 'flex',
|
|
||||||
alignItems: 'center',
|
|
||||||
gap: '0.25rem',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span>{showMarkdownHelp ? '▼' : '▶'}</span>
|
|
||||||
<strong>Markdown-stöd</strong>
|
|
||||||
</button>
|
|
||||||
{showMarkdownHelp && (
|
|
||||||
<div style={{ marginBottom: '0.5rem', fontSize: '0.85rem', background: '#f9f9f9', padding: '0.5rem', borderRadius: '4px', color: '#666' }}>
|
|
||||||
<div style={{ whiteSpace: 'pre-wrap', marginTop: '0.25rem' }}>{MARKDOWN_HELP}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<textarea
|
|
||||||
value={recipe.instructions}
|
|
||||||
onChange={(e) => setRecipe({ ...recipe, instructions: e.target.value })}
|
|
||||||
placeholder="Skriv instruktioner här. Du kan använda Markdown för formatering."
|
|
||||||
style={{
|
|
||||||
width: '100%',
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '150px',
|
|
||||||
fontFamily: 'inherit',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowPreview(!showPreview)}
|
|
||||||
style={{
|
|
||||||
marginTop: '0.5rem',
|
|
||||||
padding: '0.5rem 1rem',
|
|
||||||
background: '#f0f0f0',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '0.9rem',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{showPreview ? '✕ Dölj förhandsvisning' : '👁 Visa förhandsvisning'}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{showPreview && recipe.instructions && (
|
|
||||||
<div style={{
|
|
||||||
marginTop: '1rem',
|
|
||||||
padding: '1rem',
|
|
||||||
background: '#fafafa',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
maxHeight: '300px',
|
|
||||||
overflowY: 'auto',
|
|
||||||
}}>
|
|
||||||
<strong>Förhandsvisning:</strong>
|
|
||||||
<SimpleMarkdownPreview text={recipe.instructions} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Ingredienser */}
|
|
||||||
<section style={{ display: 'grid', gap: '1rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
|
|
||||||
<h2 style={{ margin: 0, fontSize: '1.1rem' }}>Ingredienser</h2>
|
|
||||||
|
|
||||||
{recipe.ingredients.map((ingredient, index) => (
|
|
||||||
<div
|
|
||||||
key={index}
|
|
||||||
style={{
|
|
||||||
display: 'grid',
|
|
||||||
gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
|
|
||||||
gap: '0.5rem',
|
|
||||||
alignItems: 'flex-end',
|
|
||||||
padding: '0.75rem',
|
|
||||||
background: '#f9f9f9',
|
|
||||||
borderRadius: '4px',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<select
|
|
||||||
value={ingredient.productId}
|
|
||||||
onChange={(e) => handleIngredientChange(index, 'productId', Number(e.target.value))}
|
|
||||||
required
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
width: '100%',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<option value={0}>Välj produkt</option>
|
|
||||||
{products.length > 0 ? products.map((product) => (
|
|
||||||
<option key={product.id} value={product.id}>
|
|
||||||
{product.name}
|
|
||||||
</option>
|
|
||||||
)) : <option disabled>Kunde inte ladda produkter</option>}
|
|
||||||
</select>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="Mängd"
|
|
||||||
value={ingredient.quantity}
|
|
||||||
onChange={(e) => handleIngredientChange(index, 'quantity', e.target.value)}
|
|
||||||
required
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
width: '100%',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<select
|
|
||||||
value={ingredient.unit}
|
|
||||||
onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)}
|
|
||||||
required
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
width: '100%',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{UNIT_OPTIONS.map((opt) => (
|
|
||||||
<option key={opt.value} value={opt.value}>
|
|
||||||
{opt.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="Notering (valfritt)"
|
|
||||||
value={ingredient.note || ''}
|
|
||||||
onChange={(e) => handleIngredientChange(index, 'note', e.target.value)}
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem',
|
|
||||||
border: '1px solid #ddd',
|
|
||||||
borderRadius: '4px',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
width: '100%',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => removeIngredient(index)}
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem 1rem',
|
|
||||||
background: '#fee',
|
|
||||||
color: '#c00',
|
|
||||||
border: '1px solid #faa',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
fontWeight: 600,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
✕ Ta bort
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{products.length === 0 && (
|
|
||||||
<div style={{ color: 'crimson', background: '#ffe5e5', padding: '0.75rem', borderRadius: '4px' }}>
|
|
||||||
Kunde inte ladda produkter. Kontrollera API:et.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={addIngredient}
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem 1rem',
|
|
||||||
background: '#e8f5e9',
|
|
||||||
color: '#2e7d32',
|
|
||||||
border: '1px solid #81c784',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
fontWeight: 600,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
+ Lägg till ingrediens
|
|
||||||
</button>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Knappar */}
|
|
||||||
<div style={{
|
|
||||||
display: 'flex',
|
|
||||||
gap: '0.75rem',
|
|
||||||
flexWrap: 'wrap',
|
|
||||||
}}>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isLoading}
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem 1.5rem',
|
|
||||||
background: '#0070f3',
|
|
||||||
color: 'white',
|
|
||||||
border: 'none',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
fontWeight: 600,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isLoading ? '⏳ Sparar...' : '💾 Spara recept'}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => router.push('/recipes')}
|
|
||||||
style={{
|
|
||||||
padding: '0.75rem 1.5rem',
|
|
||||||
background: '#f0f0f0',
|
|
||||||
color: '#333',
|
|
||||||
border: '1px solid #ccc',
|
|
||||||
borderRadius: '4px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '1rem',
|
|
||||||
minHeight: '44px',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Avbryt
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -6,6 +6,7 @@ import { fetchJson } from '../../../lib/api';
|
|||||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||||
import type { Product } from '../../../features/inventory/types';
|
import type { Product } from '../../../features/inventory/types';
|
||||||
import Navigation from '../../Navigation';
|
import Navigation from '../../Navigation';
|
||||||
|
import { UNIT_OPTIONS } from '../../../lib/units';
|
||||||
|
|
||||||
type ProductSuggestion = {
|
type ProductSuggestion = {
|
||||||
productId: number;
|
productId: number;
|
||||||
@@ -33,24 +34,6 @@ type ParseResult = {
|
|||||||
ingredients: ParsedIngredientRow[];
|
ingredients: ParsedIngredientRow[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const UNIT_OPTIONS = [
|
|
||||||
{ value: '', label: 'Välj enhet' },
|
|
||||||
{ value: 'g', label: 'g (gram)' },
|
|
||||||
{ value: 'kg', label: 'kg (kilogram)' },
|
|
||||||
{ value: 'hg', label: 'hg (hektogram)' },
|
|
||||||
{ value: 'ml', label: 'ml (milliliter)' },
|
|
||||||
{ value: 'dl', label: 'dl (deciliter)' },
|
|
||||||
{ value: 'l', label: 'l (liter)' },
|
|
||||||
{ value: 'st', label: 'st (styck)' },
|
|
||||||
{ value: 'tsk', label: 'tsk (tesked)' },
|
|
||||||
{ value: 'msk', label: 'msk (matsked)' },
|
|
||||||
{ value: 'krm', label: 'krm (kryddmått)' },
|
|
||||||
{ value: 'port', label: 'port (portioner)' },
|
|
||||||
{ value: 'efter smak', label: 'Efter smak' },
|
|
||||||
{ value: 'förp', label: 'förp (förpackning)' },
|
|
||||||
{ value: 'klyfta', label: 'klyfta' },
|
|
||||||
];
|
|
||||||
|
|
||||||
type Step = 'input' | 'review' | 'saving';
|
type Step = 'input' | 'review' | 'saving';
|
||||||
|
|
||||||
export default function ImportRecipePage() {
|
export default function ImportRecipePage() {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { fetchJson } from '../../../lib/api';
|
|||||||
import { parseErrorResponse } from '../../../lib/error-handler';
|
import { parseErrorResponse } from '../../../lib/error-handler';
|
||||||
import type { Product } from '../../../features/inventory/types';
|
import type { Product } from '../../../features/inventory/types';
|
||||||
import Navigation from '../../Navigation';
|
import Navigation from '../../Navigation';
|
||||||
|
import { UNIT_OPTIONS } from '../../../lib/units';
|
||||||
|
|
||||||
type ProductSuggestion = {
|
type ProductSuggestion = {
|
||||||
productId: number;
|
productId: number;
|
||||||
@@ -32,24 +33,6 @@ type ParseResult = {
|
|||||||
ingredients: ParsedIngredientRow[];
|
ingredients: ParsedIngredientRow[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const UNIT_OPTIONS = [
|
|
||||||
{ value: '', label: 'Välj enhet' },
|
|
||||||
{ value: 'g', label: 'g (gram)' },
|
|
||||||
{ value: 'kg', label: 'kg (kilogram)' },
|
|
||||||
{ value: 'hg', label: 'hg (hektogram)' },
|
|
||||||
{ value: 'ml', label: 'ml (milliliter)' },
|
|
||||||
{ value: 'dl', label: 'dl (deciliter)' },
|
|
||||||
{ value: 'l', label: 'l (liter)' },
|
|
||||||
{ value: 'st', label: 'st (styck)' },
|
|
||||||
{ value: 'tsk', label: 'tsk (tesked)' },
|
|
||||||
{ value: 'msk', label: 'msk (matsked)' },
|
|
||||||
{ value: 'krm', label: 'krm (kryddmått)' },
|
|
||||||
{ value: 'port', label: 'port (portioner)' },
|
|
||||||
{ value: 'efter smak', label: 'Efter smak' },
|
|
||||||
{ value: 'förp', label: 'förp (förpackning)' },
|
|
||||||
{ value: 'klyfta', label: 'klyfta' },
|
|
||||||
];
|
|
||||||
|
|
||||||
type Step = 'input' | 'review' | 'saving';
|
type Step = 'input' | 'review' | 'saving';
|
||||||
|
|
||||||
export default function WriteRecipePage() {
|
export default function WriteRecipePage() {
|
||||||
|
|||||||
@@ -43,27 +43,3 @@ export async function parseErrorResponse(response: Response): Promise<string> {
|
|||||||
|
|
||||||
return defaultMessages[status] || `Fel (${status}). Försök igen senare.`;
|
return defaultMessages[status] || `Fel (${status}). Försök igen senare.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Hämta data från API med bra felhantering
|
|
||||||
*/
|
|
||||||
export async function fetchWithErrorHandling(
|
|
||||||
url: string,
|
|
||||||
options?: RequestInit,
|
|
||||||
): Promise<any> {
|
|
||||||
try {
|
|
||||||
const response = await fetch(url, options);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorMessage = await parseErrorResponse(response);
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof Error) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
throw new Error('Ett okänt fel inträffade.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export const UNIT_OPTIONS = [
|
||||||
|
{ value: '', label: 'Välj enhet' },
|
||||||
|
{ value: 'g', label: 'g (gram)' },
|
||||||
|
{ value: 'kg', label: 'kg (kilogram)' },
|
||||||
|
{ value: 'hg', label: 'hg (hektogram)' },
|
||||||
|
{ value: 'ml', label: 'ml (milliliter)' },
|
||||||
|
{ value: 'dl', label: 'dl (deciliter)' },
|
||||||
|
{ value: 'l', label: 'l (liter)' },
|
||||||
|
{ value: 'st', label: 'st (styck)' },
|
||||||
|
{ value: 'tsk', label: 'tsk (tesked)' },
|
||||||
|
{ value: 'msk', label: 'msk (matsked)' },
|
||||||
|
{ value: 'krm', label: 'krm (kryddmått)' },
|
||||||
|
{ value: 'port', label: 'port (portioner)' },
|
||||||
|
{ value: 'efter smak', label: 'Efter smak' },
|
||||||
|
{ value: 'förp', label: 'förp (förpackning)' },
|
||||||
|
{ value: 'klyfta', label: 'klyfta' },
|
||||||
|
];
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
export type Product = {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
normalizedName: string;
|
|
||||||
category: string | null;
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InventoryItem = {
|
|
||||||
id: number;
|
|
||||||
productId: number;
|
|
||||||
quantity: string;
|
|
||||||
unit: string;
|
|
||||||
location: string | null;
|
|
||||||
priority: number | null;
|
|
||||||
purchaseDate: string | null;
|
|
||||||
opened: boolean | null;
|
|
||||||
shelfNote: string | null;
|
|
||||||
suitableFor: string | null;
|
|
||||||
isOnSale: boolean | null;
|
|
||||||
priceLevel: number | null;
|
|
||||||
weeksRemaining: number | null;
|
|
||||||
proteinType: string | null;
|
|
||||||
isLeftover: boolean | null;
|
|
||||||
comment: string | null;
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
product: Product;
|
|
||||||
};
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
const API_BASE =
|
|
||||||
process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
|
||||||
|
|
||||||
export async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
|
|
||||||
const res = await fetch(`${API_BASE}${path}`, {
|
|
||||||
...init,
|
|
||||||
cache: 'no-store',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...(init?.headers || {}),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text();
|
|
||||||
throw new Error(`API ${res.status}: ${text}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
export { API_BASE };
|
|
||||||
Reference in New Issue
Block a user