feat: PantryItem (Baslager) - tabell, backend-modul och frontend-sida

This commit is contained in:
Nils-Johan Gynther
2026-04-15 22:06:40 +02:00
parent 65ec74ac7d
commit 47d1aafd9e
12 changed files with 373 additions and 1 deletions
+74
View File
@@ -0,0 +1,74 @@
'use client';
import { useState, useTransition } from 'react';
import type { Product } from '../../features/inventory/types';
import { addPantryItem } from './actions';
type Props = {
products: Product[];
pantryProductIds: Set<number>;
};
export default function AddToPantryForm({ products, pantryProductIds }: Props) {
const [selectedId, setSelectedId] = useState('');
const [isPending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
const available = products.filter((p) => !pantryProductIds.has(p.id));
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!selectedId) return;
setError(null);
startTransition(async () => {
try {
await addPantryItem(Number(selectedId));
setSelectedId('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Okänt fel');
}
});
}
return (
<form onSubmit={handleSubmit} style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
<select
value={selectedId}
onChange={(e) => setSelectedId(e.target.value)}
required
style={{
flex: '1 1 220px',
padding: '0.6rem 0.75rem',
border: '1px solid #ddd',
borderRadius: '6px',
fontSize: '1rem',
}}
>
<option value="">Välj produkt</option>
{available.map((p) => (
<option key={p.id} value={p.id}>
{p.canonicalName || p.name}
</option>
))}
</select>
<button
type="submit"
disabled={isPending || !selectedId}
style={{
padding: '0.6rem 1.25rem',
background: '#0070f3',
color: '#fff',
border: 'none',
borderRadius: '6px',
fontWeight: 600,
cursor: isPending || !selectedId ? 'not-allowed' : 'pointer',
opacity: isPending || !selectedId ? 0.6 : 1,
fontSize: '1rem',
}}
>
{isPending ? 'Lägger till…' : 'Lägg till'}
</button>
{error && <span style={{ color: 'crimson', fontSize: '0.9rem' }}>{error}</span>}
</form>
);
}
+96
View File
@@ -0,0 +1,96 @@
'use client';
import { useTransition } from 'react';
import { removePantryItem } from './actions';
type PantryItem = {
id: number;
product: { id: number; name: string; canonicalName: string | null; category: string | null };
};
type Props = {
items: PantryItem[];
};
export default function PantryList({ items }: Props) {
const [isPending, startTransition] = useTransition();
function handleRemove(id: number, name: string) {
if (!confirm(`Ta bort "${name}" från baslagret?`)) return;
startTransition(async () => {
await removePantryItem(id);
});
}
if (items.length === 0) {
return (
<p style={{ color: '#888', fontStyle: 'italic' }}>
Baslagret är tomt. Lägg till produkter ovan.
</p>
);
}
// Gruppera per kategori
const grouped = items.reduce<Record<string, PantryItem[]>>((acc, item) => {
const cat = item.product.category || 'Övrigt';
if (!acc[cat]) acc[cat] = [];
acc[cat].push(item);
return acc;
}, {});
const sortedCategories = Object.keys(grouped).sort((a, b) => {
if (a === 'Övrigt') return 1;
if (b === 'Övrigt') return -1;
return a.localeCompare(b, 'sv');
});
return (
<div style={{ display: 'grid', gap: '1.5rem' }}>
{sortedCategories.map((category) => (
<section key={category}>
<h3 style={{ margin: '0 0 0.5rem', fontSize: '1rem', color: '#555', fontWeight: 600 }}>
{category}
</h3>
<div style={{ display: 'grid', gap: '0.4rem' }}>
{grouped[category].map((item) => {
const displayName = item.product.canonicalName || item.product.name;
return (
<div
key={item.id}
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '0.6rem 0.75rem',
border: '1px solid #eee',
borderRadius: '6px',
background: '#fafafa',
}}
>
<span>{displayName}</span>
<button
type="button"
onClick={() => handleRemove(item.id, displayName)}
disabled={isPending}
style={{
background: 'none',
border: 'none',
color: '#c00',
cursor: isPending ? 'not-allowed' : 'pointer',
fontSize: '1.1rem',
padding: '0.2rem 0.5rem',
lineHeight: 1,
}}
title="Ta bort från baslagret"
>
×
</button>
</div>
);
})}
</div>
</section>
))}
</div>
);
}
+34
View File
@@ -0,0 +1,34 @@
'use server';
import { revalidatePath } from 'next/cache';
import { API_BASE } from '../../lib/api';
export async function addPantryItem(productId: number) {
const res = await fetch(`${API_BASE}/api/pantry`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId }),
cache: 'no-store',
});
if (!res.ok) {
const text = await res.text();
throw new Error(`Kunde inte lägga till i baslagret: ${text}`);
}
revalidatePath('/baslager');
}
export async function removePantryItem(id: number) {
const res = await fetch(`${API_BASE}/api/pantry/${id}`, {
method: 'DELETE',
cache: 'no-store',
});
if (!res.ok) {
const text = await res.text();
throw new Error(`Kunde inte ta bort från baslagret: ${text}`);
}
revalidatePath('/baslager');
}
+44
View File
@@ -0,0 +1,44 @@
import { fetchJson } from '../../lib/api';
import type { Product } from '../../features/inventory/types';
import Navigation from '../Navigation';
import AddToPantryForm from './AddToPantryForm';
import PantryList from './PantryList';
type PantryItem = {
id: number;
productId: number;
createdAt: string;
updatedAt: string;
product: Product;
};
export default async function BaslagerPage() {
const [pantryItems, products] = await Promise.all([
fetchJson<PantryItem[]>('/api/pantry'),
fetchJson<Product[]>('/api/products'),
]);
const pantryProductIds = new Set(pantryItems.map((i) => i.productId));
return (
<main style={{ padding: '1rem', maxWidth: '700px', margin: '0 auto' }}>
<Navigation />
<h1 style={{ marginBottom: '0.5rem' }}>Baslager</h1>
<p style={{ color: '#666', marginBottom: '1.5rem' }}>
Produkter du alltid räknar med att ha hemma.
</p>
<section style={{ marginBottom: '2rem' }}>
<h2 style={{ fontSize: '1.1rem', marginBottom: '0.75rem' }}>Lägg till produkt</h2>
<AddToPantryForm products={products} pantryProductIds={pantryProductIds} />
</section>
<section>
<h2 style={{ fontSize: '1.1rem', marginBottom: '0.75rem' }}>
{pantryItems.length} {pantryItems.length === 1 ? 'produkt' : 'produkter'} i baslagret
</h2>
<PantryList items={pantryItems} />
</section>
</main>
);
}