feat: enhance pantry management with new features and UI improvements

This commit is contained in:
Nils-Johan Gynther
2026-04-21 16:09:33 +02:00
parent 69f05e6b43
commit 2acf66e4c4
7 changed files with 221 additions and 43 deletions
+86 -8
View File
@@ -7,21 +7,99 @@ type PantryItem = {
product: { id: number; name: string; canonicalName: string | null; category: string | null };
};
type InventoryItem = {
productId: number;
quantity: string;
unit: string;
};
type Props = {
items: PantryItem[];
inventoryByProductId: Record<number, InventoryItem[]>;
onDeleted?: () => void;
};
export default function PantryList({ items, inventoryByProductId, onDeleted }: Props) {
export default function PantryList({ items, onDeleted }: Props) {
const router = useRouter();
async function handleRemove(id: number, name: string) {
if (!confirm(`Ta bort "${name}" från baslagret?`)) return;
const res = await fetch(`/api/admin/pantry-item/${id}`, { method: 'DELETE' });
if (res.ok) {
if (onDeleted) onDeleted();
else router.refresh();
}
}
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 style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{displayName}
</span>
<button
type="button"
onClick={() => handleRemove(item.id, displayName)}
style={{
background: 'none',
border: 'none',
color: '#c00',
cursor: 'pointer',
fontSize: '1.1rem',
padding: '0.2rem 0.5rem',
lineHeight: 1,
flexShrink: 0,
}}
title="Ta bort från baslagret"
>
×
</button>
</div>
);
})}
</div>
</section>
))}
</div>
);
}
async function handleRemove(id: number, name: string) {
if (!confirm(`Ta bort "${name}" från baslagret?`)) return;
const res = await fetch(`/api/admin/pantry-item/${id}`, { method: 'DELETE' });
+3 -10
View File
@@ -1,5 +1,5 @@
import { fetchJson } from '../../lib/api';
import type { Product, InventoryItem } from '../../features/inventory/types';
import type { Product } from '../../features/inventory/types';
import Navigation from '../Navigation';
import AddToPantryForm from './AddToPantryForm';
import PantryList from './PantryList';
@@ -13,20 +13,13 @@ type PantryItem = {
};
export default async function BaslagerPage() {
const [pantryItems, products, inventoryItems] = await Promise.all([
const [pantryItems, products] = await Promise.all([
fetchJson<PantryItem[]>('/api/pantry'),
fetchJson<Product[]>('/api/products'),
fetchJson<InventoryItem[]>('/api/inventory').catch(() => [] as InventoryItem[]),
]);
const pantryProductIds = new Set(pantryItems.map((i) => i.productId));
// Bygg upp en map productId → inventarieposter
const inventoryByProductId = inventoryItems.reduce<Record<number, InventoryItem[]>>((acc, item) => {
if (!acc[item.productId]) acc[item.productId] = [];
acc[item.productId].push(item);
return acc;
}, {});
return (
<main style={{ padding: '1rem', maxWidth: '700px', margin: '0 auto' }}>
@@ -45,7 +38,7 @@ export default async function BaslagerPage() {
<h2 style={{ fontSize: '1.1rem', marginBottom: '0.75rem' }}>
{pantryItems.length} {pantryItems.length === 1 ? 'produkt' : 'produkter'} i baslagret
</h2>
<PantryList items={pantryItems} inventoryByProductId={inventoryByProductId} />
<PantryList items={pantryItems} />
</section>
</main>
);
+21 -10
View File
@@ -25,7 +25,7 @@ type InventoryCompareItem = {
unit: string;
available: number;
missing: number;
status: 'enough' | 'missing';
status: 'enough' | 'missing' | 'pantry';
};
function getWeekDates(offset = 0): string[] {
@@ -228,7 +228,7 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
<p style={{ color: '#888', margin: 0 }}>Laddar ingredienser...</p>
) : (() => {
// Berika varje rad med inventariestatus
type DisplayStatus = 'enough' | 'partial' | 'missing';
type DisplayStatus = 'enough' | 'partial' | 'missing' | 'pantry';
const enriched = shopping.map((item) => {
const cmp = inventoryCompare.find(
(c) => c.productId === item.productId && c.unit === item.unit,
@@ -236,7 +236,10 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
let displayStatus: DisplayStatus = 'missing';
let buyQty = item.quantity;
if (cmp) {
if (cmp.available >= cmp.required) {
if (cmp.status === 'pantry') {
displayStatus = 'pantry';
buyQty = 0;
} else if (cmp.available >= cmp.required) {
displayStatus = 'enough';
buyQty = 0;
} else if (cmp.available > 0) {
@@ -247,12 +250,13 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
return { ...item, cmp, displayStatus, buyQty };
});
const order: Record<DisplayStatus, number> = { missing: 0, partial: 1, enough: 2 };
const order: Record<DisplayStatus, number> = { missing: 0, partial: 1, enough: 2, pantry: 3 };
enriched.sort((a, b) => order[a.displayStatus] - order[b.displayStatus] || a.name.localeCompare(b.name, 'sv'));
const missingCount = enriched.filter((e) => e.displayStatus === 'missing').length;
const partialCount = enriched.filter((e) => e.displayStatus === 'partial').length;
const enoughCount = enriched.filter((e) => e.displayStatus === 'enough').length;
const pantryCount = enriched.filter((e) => e.displayStatus === 'pantry').length;
const hasCompare = inventoryCompare.length > 0;
const fmtQty = (n: number) => (n % 1 === 0 ? String(n) : n.toFixed(1));
@@ -265,6 +269,7 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
{missingCount > 0 && <span style={{ color: '#8b0000', fontWeight: 600 }}> {missingCount} saknas</span>}
{partialCount > 0 && <span style={{ color: '#7a5000', fontWeight: 600 }}> {partialCount} delvis hemma</span>}
{enoughCount > 0 && <span style={{ color: '#1f5f2c', fontWeight: 600 }}> {enoughCount} hemma</span>}
{pantryCount > 0 && <span style={{ color: '#555', fontWeight: 600 }}>📦 {pantryCount} baslager</span>}
{missingCount === 0 && partialCount === 0 && (
<span style={{ color: '#1f5f2c', fontWeight: 600 }}> Du har allt hemma!</span>
)}
@@ -276,8 +281,9 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
const isMissing = item.displayStatus === 'missing';
const isPartial = item.displayStatus === 'partial';
const isEnough = item.displayStatus === 'enough';
const bg = isMissing ? '#ffeaea' : isPartial ? '#fff8e6' : '#ecf8ee';
const icon = isMissing ? '' : isPartial ? '⚠️' : '';
const isPantry = item.displayStatus === 'pantry';
const bg = isMissing ? '#ffeaea' : isPartial ? '#fff8e6' : isPantry ? '#f5f5f5' : '#ecf8ee';
const icon = isMissing ? '❌' : isPartial ? '⚠️' : isPantry ? '📦' : '✅';
return (
<li
@@ -293,8 +299,8 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
fontSize: '0.88rem',
}}
>
{hasCompare && <span title={isEnough ? 'Finns hemma' : isPartial ? 'Delvis hemma' : 'Saknas'}>{icon}</span>}
<span style={{ color: isEnough ? '#555' : '#111' }}>
{hasCompare && <span title={isEnough ? 'Finns hemma' : isPartial ? 'Delvis hemma' : isPantry ? 'Baslager — alltid hemma' : 'Saknas'}>{icon}</span>}
<span style={{ color: (isEnough || isPantry) ? '#555' : '#111' }}>
<strong>{item.name}</strong>
{isPartial && item.cmp && (
<span style={{ color: '#7a5000', fontSize: '0.8rem', marginLeft: '0.4rem' }}>
@@ -306,9 +312,14 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
(finns hemma)
</span>
)}
{isPantry && (
<span style={{ color: '#888', fontSize: '0.8rem', marginLeft: '0.4rem' }}>
(baslager)
</span>
)}
</span>
<span style={{ fontWeight: 600, whiteSpace: 'nowrap', color: isEnough ? '#888' : '#111' }}>
{isEnough
<span style={{ fontWeight: 600, whiteSpace: 'nowrap', color: (isEnough || isPantry) ? '#888' : '#111' }}>
{(isEnough || isPantry)
? '—'
: `${fmtQty(item.buyQty)} ${item.unit}`}
</span>
+49 -7
View File
@@ -14,20 +14,62 @@ type PantryItem = {
product: Product;
};
type InventoryItem = {
productId: number;
quantity: string;
unit: string;
};
export default function PantryView() {
const [pantryItems, setPantryItems] = useState<PantryItem[]>([]);
const [products, setProducts] = useState<Product[]>([]);
const [inventoryByProductId, setInventoryByProductId] = useState<Record<number, InventoryItem[]>>({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const authFetch = useAuthFetch();
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const [pantryRes, prodRes] = await Promise.all([
authFetch('/api/pantry'),
fetch('/api/products'),
]);
if (!pantryRes.ok) throw new Error('Kunde inte hämta baslager');
if (!prodRes.ok) throw new Error('Kunde inte hämta produkter');
const [pantry, prods] = await Promise.all([pantryRes.json(), prodRes.json()]);
setPantryItems(pantry);
setProducts(prods);
} catch (e) {
setError(e instanceof Error ? e.message : 'Okänt fel');
} finally {
setLoading(false);
}
}, [authFetch]);
useEffect(() => { load(); }, [load]);
if (loading) return <p style={{ color: '#888' }}>Laddar baslager</p>;
if (error) return <p style={{ color: '#c00' }}>{error}</p>;
const pantryProductIds = new Set(pantryItems.map((i) => i.productId));
return (
<div>
<p style={{ color: '#555', marginBottom: '1rem' }}>
Produkter du alltid räknar med att ha hemma. Lägg till och ta bort varor i ditt baslager.
</p>
<section style={{ marginBottom: '2rem' }}>
<h2 style={{ fontSize: '1.1rem', marginBottom: '0.75rem' }}>Lägg till produkt</h2>
<AddToPantryForm products={products} pantryProductIds={pantryProductIds} onCreated={load} />
</section>
<section>
<h2 style={{ fontSize: '1.1rem', marginBottom: '0.75rem' }}>
{pantryItems.length} {pantryItems.length === 1 ? 'produkt' : 'produkter'} i baslagret
</h2>
<PantryList items={pantryItems} onDeleted={load} />
</section>
</div>
);
}
const load = useCallback(async () => {
setLoading(true);
setError(null);