feat: enhance pantry management with new features and UI improvements
This commit is contained in:
@@ -17,6 +17,41 @@ En fullstack-applikation för hantering av hemmavaror och recept. Håll koll på
|
|||||||
- **Konsumtionshistorik** — spåra vad som använts när och i vilken mängd
|
- **Konsumtionshistorik** — spåra vad som använts när och i vilken mängd
|
||||||
- **Utförlig information** — stöd för varumärke, lagringsnot, tillkomsttid och mer
|
- **Utförlig information** — stöd för varumärke, lagringsnot, tillkomsttid och mer
|
||||||
|
|
||||||
|
### Baslager
|
||||||
|
- **Ständigt lager** — markera produkter du alltid räknar med att ha hemma
|
||||||
|
- **Grupperat per kategori** — produkterna i baslagret visas grupperade under kategorirubrik
|
||||||
|
- **Lägg till och ta bort** — välj från produktlistan via sökbar dropdown, ta bort med ett klick
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 📌 Så använder du Inventarie och Baslager
|
||||||
|
|
||||||
|
Dessa två funktioner fyller olika syften och kompletterar varandra:
|
||||||
|
|
||||||
|
#### Inventarie — ”vad du faktiskt har hemma”
|
||||||
|
Inventariet är en **aktiv förrådsbok** över varor du just nu har hemma. Här registrerar du:
|
||||||
|
- Exakt mängd (t.ex. 500 g pasta, 1,5 liter mjolk)
|
||||||
|
- Var varan förvaras (kyl, frys, skafferi)
|
||||||
|
- Bäst före-datum
|
||||||
|
- Om förpackningen är öppnad
|
||||||
|
|
||||||
|
När du lagar mat kan du registrera hur mycket du förbrukat, och inventariet uppdateras. **Inventariet är punkten i tid — det speglar verkligheten.**
|
||||||
|
|
||||||
|
#### Baslager — ”vad du alltid har hemma”
|
||||||
|
Baslagret är en **permanent lista** över varor du alltid räknar med att ha hemma, oavsett vad inventariet säger. Tänk salt, olja, socker, svartpeppar, mjolk, ägg — varor som nästan aldrig tar slut helt, eller som du alltid köper på direkt när de tar slut.
|
||||||
|
|
||||||
|
Baslagret **påverkar inköpslistan**: varor i baslagret markeras automatiskt som tillgängliga i matplanens inköpslista — du behöver inte föra in dem i inventariet för att det ska fungera.
|
||||||
|
|
||||||
|
#### Praktiskt flöde
|
||||||
|
| Situation | Använd |
|
||||||
|
|---|---|
|
||||||
|
| Du köpte 2 kg pasta idag | **Inventariet** — lägg till med mängd och bäst före |
|
||||||
|
| Salt ingår alltid i dina recept | **Baslager** — lägg till en gång, släpp sen |
|
||||||
|
| Du vill se vad du behöver köpa | **Matplanen** — inköpslistan jämför mot båda |
|
||||||
|
| Du tog slut på mjolk | Ta bort från inventariet (baslagret påverkas inte) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Recept
|
### Recept
|
||||||
- **Skapa och redigera recept** — med namn, beskrivning, portionsantal, ingredienser (kvantitet och enhet) och instruktioner i Markdown-format
|
- **Skapa och redigera recept** — med namn, beskrivning, portionsantal, ingredienser (kvantitet och enhet) och instruktioner i Markdown-format
|
||||||
- **Portionsjustering** — ange antal portioner vid skapandet; matplanen räknar automatiskt om ingrediensmängder om du lagar fler eller färre portioner
|
- **Portionsjustering** — ange antal portioner vid skapandet; matplanen räknar automatiskt om ingrediensmängder om du lagar fler eller färre portioner
|
||||||
@@ -39,11 +74,6 @@ En fullstack-applikation för hantering av hemmavaror och recept. Håll koll på
|
|||||||
- **Granska och lägg till** — se tolkningsresultatet, justera kvantitet och enhet, och lägg till direkt i inventariet
|
- **Granska och lägg till** — se tolkningsresultatet, justera kvantitet och enhet, och lägg till direkt i inventariet
|
||||||
- **AI-kategorisuggestion (premium)** — för varor som inte matchas mot befintliga produkter visas ett AI-förslag på kategori (t.ex. "✨ Mejeri och ägg > Kvarg och fil") som hjälp när användaren väljer produkt manuellt
|
- **AI-kategorisuggestion (premium)** — för varor som inte matchas mot befintliga produkter visas ett AI-förslag på kategori (t.ex. "✨ Mejeri och ägg > Kvarg och fil") som hjälp när användaren väljer produkt manuellt
|
||||||
|
|
||||||
### Baslager
|
|
||||||
- **Ständigt lager** — markera produkter du alltid räknar med att ha hemma
|
|
||||||
- **Grupperat per kategori** — produkterna i baslagret visas grupperade under kategorirubrik
|
|
||||||
- **Lägg till och ta bort** — välj från produktlistan via sökbar dropdown, ta bort med ett klick
|
|
||||||
|
|
||||||
### Admin: Produkter
|
### Admin: Produkter
|
||||||
> Obs: Destruktiva åtgärder (merge, ta bort, återställ, bulk-uppdatera, återställ all data) kräver admin-roll.
|
> Obs: Destruktiva åtgärder (merge, ta bort, återställ, bulk-uppdatera, återställ all data) kräver admin-roll.
|
||||||
**Admin: Produkter (fliken Databas i /profil)**
|
**Admin: Produkter (fliken Databas i /profil)**
|
||||||
@@ -76,6 +106,7 @@ Profilsidan `/profil` är en flikbaserad administrationsyta. Antalet flikar bero
|
|||||||
|
|
||||||
**Alla inloggade användare:**
|
**Alla inloggade användare:**
|
||||||
- **Min profil** — redigera förnamn, efternamn och e-postadress
|
- **Min profil** — redigera förnamn, efternamn och e-postadress
|
||||||
|
- **Databas** — hantera inventarie och baslager (se nedan)
|
||||||
|
|
||||||
**Enbart admin:**
|
**Enbart admin:**
|
||||||
- **Användare** — fullständig användarhantering:
|
- **Användare** — fullständig användarhantering:
|
||||||
|
|||||||
@@ -644,7 +644,11 @@ backend/src/
|
|||||||
- Om `entry.servings` och `recipe.servings` är satta beräknas en skala: `scale = entry.servings / recipe.servings`
|
- Om `entry.servings` och `recipe.servings` är satta beräknas en skala: `scale = entry.servings / recipe.servings`
|
||||||
- Ingrediensmängder multipliceras med skalan innan aggregering
|
- Ingrediensmängder multipliceras med skalan innan aggregering
|
||||||
- Returnerar lista av `{ productName, quantity, unit }`
|
- Returnerar lista av `{ productName, quantity, unit }`
|
||||||
- **`inventoryCompare(from, to)`** — Kör samma aggregering som `shoppingList` men jämför sedan varje ingrediens mot aktuellt inventarielager. Returnerar status per ingrediens: `räcker | saknas | enhetskonflikt`.
|
- **`inventoryCompare(from, to)`** — Kör samma aggregering som `shoppingList` men jämför sedan varje ingrediens mot:
|
||||||
|
1. **Pantry (baslager):** Om produkten finns i `PantryItem`-tabellen returneras `status: 'pantry'`, `missing: 0` — varan räknas alltid som tillgänglig oavsett inventariet.
|
||||||
|
2. **Inventariet:** Övriga ingredienser jämförs mot `InventoryItem`. Returnerar `status: 'enough' | 'missing'`.
|
||||||
|
- Sorteringsordning: `missing` → `enough` → `pantry`
|
||||||
|
- Frontend visar 📦-ikon och ”(baslager)” för pantry-varor; de visas aldrig som ”saknas” i inköpslistan.
|
||||||
|
|
||||||
**Kvittoimport-API:**
|
**Kvittoimport-API:**
|
||||||
- **`parseReceipt(file, isPremium)`** — Tar emot en bild eller PDF (max 15 MB), skickar den till Mistral AI för tolkning och returnerar en lista av kandidatprodukter med namn, kvantitet och enhet.
|
- **`parseReceipt(file, isPremium)`** — Tar emot en bild eller PDF (max 15 MB), skickar den till Mistral AI för tolkning och returnerar en lista av kandidatprodukter med namn, kvantitet och enhet.
|
||||||
|
|||||||
@@ -86,6 +86,10 @@ export class MealPlanService {
|
|||||||
async inventoryCompare(from: string, to: string) {
|
async inventoryCompare(from: string, to: string) {
|
||||||
const entries = await this.findByRange(from, to);
|
const entries = await this.findByRange(from, to);
|
||||||
|
|
||||||
|
// Hämta pantry-produkter — dessa anses alltid tillgängliga
|
||||||
|
const pantryItems = await this.prisma.pantryItem.findMany({ select: { productId: true } });
|
||||||
|
const pantryProductIds = new Set(pantryItems.map((p) => p.productId));
|
||||||
|
|
||||||
// Aggregera ingredienser per produkt+enhet (skalat per portionsantal)
|
// Aggregera ingredienser per produkt+enhet (skalat per portionsantal)
|
||||||
const map = new Map<string, { productId: number; name: string; required: number; unit: string }>();
|
const map = new Map<string, { productId: number; name: string; required: number; unit: string }>();
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
@@ -112,6 +116,19 @@ export class MealPlanService {
|
|||||||
// Kontrollera inventariet för varje ingrediens
|
// Kontrollera inventariet för varje ingrediens
|
||||||
const result = await Promise.all(
|
const result = await Promise.all(
|
||||||
Array.from(map.values()).map(async (item) => {
|
Array.from(map.values()).map(async (item) => {
|
||||||
|
// Pantry-varor anses alltid tillgängliga — visa inte i inköpslistan
|
||||||
|
if (pantryProductIds.has(item.productId)) {
|
||||||
|
return {
|
||||||
|
productId: item.productId,
|
||||||
|
name: item.name,
|
||||||
|
required: item.required,
|
||||||
|
unit: item.unit,
|
||||||
|
available: item.required,
|
||||||
|
missing: 0,
|
||||||
|
status: 'pantry' as const,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const inventoryItems = await this.prisma.inventoryItem.findMany({
|
const inventoryItems = await this.prisma.inventoryItem.findMany({
|
||||||
where: { productId: item.productId },
|
where: { productId: item.productId },
|
||||||
});
|
});
|
||||||
@@ -125,13 +142,15 @@ export class MealPlanService {
|
|||||||
unit: item.unit,
|
unit: item.unit,
|
||||||
available,
|
available,
|
||||||
missing: Math.max(0, item.required - available),
|
missing: Math.max(0, item.required - available),
|
||||||
status: (available >= item.required ? 'enough' : 'missing') as 'enough' | 'missing',
|
status: (available >= item.required ? 'enough' : 'missing') as 'enough' | 'missing' | 'pantry',
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const statusOrder = { missing: 0, enough: 1, pantry: 2 };
|
||||||
return result.sort((a, b) => {
|
return result.sort((a, b) => {
|
||||||
if (a.status !== b.status) return a.status === 'missing' ? -1 : 1;
|
const diff = statusOrder[a.status] - statusOrder[b.status];
|
||||||
|
if (diff !== 0) return diff;
|
||||||
return a.name.localeCompare(b.name, 'sv');
|
return a.name.localeCompare(b.name, 'sv');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,21 +7,99 @@ type PantryItem = {
|
|||||||
product: { id: number; name: string; canonicalName: string | null; category: string | null };
|
product: { id: number; name: string; canonicalName: string | null; category: string | null };
|
||||||
};
|
};
|
||||||
|
|
||||||
type InventoryItem = {
|
|
||||||
productId: number;
|
|
||||||
quantity: string;
|
|
||||||
unit: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
items: PantryItem[];
|
items: PantryItem[];
|
||||||
inventoryByProductId: Record<number, InventoryItem[]>;
|
|
||||||
onDeleted?: () => void;
|
onDeleted?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function PantryList({ items, inventoryByProductId, onDeleted }: Props) {
|
export default function PantryList({ items, onDeleted }: Props) {
|
||||||
const router = useRouter();
|
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) {
|
async function handleRemove(id: number, name: string) {
|
||||||
if (!confirm(`Ta bort "${name}" från baslagret?`)) return;
|
if (!confirm(`Ta bort "${name}" från baslagret?`)) return;
|
||||||
const res = await fetch(`/api/admin/pantry-item/${id}`, { method: 'DELETE' });
|
const res = await fetch(`/api/admin/pantry-item/${id}`, { method: 'DELETE' });
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { fetchJson } from '../../lib/api';
|
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 Navigation from '../Navigation';
|
||||||
import AddToPantryForm from './AddToPantryForm';
|
import AddToPantryForm from './AddToPantryForm';
|
||||||
import PantryList from './PantryList';
|
import PantryList from './PantryList';
|
||||||
@@ -13,20 +13,13 @@ type PantryItem = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default async function BaslagerPage() {
|
export default async function BaslagerPage() {
|
||||||
const [pantryItems, products, inventoryItems] = await Promise.all([
|
const [pantryItems, products] = await Promise.all([
|
||||||
fetchJson<PantryItem[]>('/api/pantry'),
|
fetchJson<PantryItem[]>('/api/pantry'),
|
||||||
fetchJson<Product[]>('/api/products'),
|
fetchJson<Product[]>('/api/products'),
|
||||||
fetchJson<InventoryItem[]>('/api/inventory').catch(() => [] as InventoryItem[]),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const pantryProductIds = new Set(pantryItems.map((i) => i.productId));
|
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 (
|
return (
|
||||||
<main style={{ padding: '1rem', maxWidth: '700px', margin: '0 auto' }}>
|
<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' }}>
|
<h2 style={{ fontSize: '1.1rem', marginBottom: '0.75rem' }}>
|
||||||
{pantryItems.length} {pantryItems.length === 1 ? 'produkt' : 'produkter'} i baslagret
|
{pantryItems.length} {pantryItems.length === 1 ? 'produkt' : 'produkter'} i baslagret
|
||||||
</h2>
|
</h2>
|
||||||
<PantryList items={pantryItems} inventoryByProductId={inventoryByProductId} />
|
<PantryList items={pantryItems} />
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ type InventoryCompareItem = {
|
|||||||
unit: string;
|
unit: string;
|
||||||
available: number;
|
available: number;
|
||||||
missing: number;
|
missing: number;
|
||||||
status: 'enough' | 'missing';
|
status: 'enough' | 'missing' | 'pantry';
|
||||||
};
|
};
|
||||||
|
|
||||||
function getWeekDates(offset = 0): string[] {
|
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>
|
<p style={{ color: '#888', margin: 0 }}>Laddar ingredienser...</p>
|
||||||
) : (() => {
|
) : (() => {
|
||||||
// Berika varje rad med inventariestatus
|
// Berika varje rad med inventariestatus
|
||||||
type DisplayStatus = 'enough' | 'partial' | 'missing';
|
type DisplayStatus = 'enough' | 'partial' | 'missing' | 'pantry';
|
||||||
const enriched = shopping.map((item) => {
|
const enriched = shopping.map((item) => {
|
||||||
const cmp = inventoryCompare.find(
|
const cmp = inventoryCompare.find(
|
||||||
(c) => c.productId === item.productId && c.unit === item.unit,
|
(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 displayStatus: DisplayStatus = 'missing';
|
||||||
let buyQty = item.quantity;
|
let buyQty = item.quantity;
|
||||||
if (cmp) {
|
if (cmp) {
|
||||||
if (cmp.available >= cmp.required) {
|
if (cmp.status === 'pantry') {
|
||||||
|
displayStatus = 'pantry';
|
||||||
|
buyQty = 0;
|
||||||
|
} else if (cmp.available >= cmp.required) {
|
||||||
displayStatus = 'enough';
|
displayStatus = 'enough';
|
||||||
buyQty = 0;
|
buyQty = 0;
|
||||||
} else if (cmp.available > 0) {
|
} else if (cmp.available > 0) {
|
||||||
@@ -247,12 +250,13 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
|
|||||||
return { ...item, cmp, displayStatus, buyQty };
|
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'));
|
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 missingCount = enriched.filter((e) => e.displayStatus === 'missing').length;
|
||||||
const partialCount = enriched.filter((e) => e.displayStatus === 'partial').length;
|
const partialCount = enriched.filter((e) => e.displayStatus === 'partial').length;
|
||||||
const enoughCount = enriched.filter((e) => e.displayStatus === 'enough').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 hasCompare = inventoryCompare.length > 0;
|
||||||
|
|
||||||
const fmtQty = (n: number) => (n % 1 === 0 ? String(n) : n.toFixed(1));
|
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>}
|
{missingCount > 0 && <span style={{ color: '#8b0000', fontWeight: 600 }}>❌ {missingCount} saknas</span>}
|
||||||
{partialCount > 0 && <span style={{ color: '#7a5000', fontWeight: 600 }}>⚠️ {partialCount} delvis hemma</span>}
|
{partialCount > 0 && <span style={{ color: '#7a5000', fontWeight: 600 }}>⚠️ {partialCount} delvis hemma</span>}
|
||||||
{enoughCount > 0 && <span style={{ color: '#1f5f2c', fontWeight: 600 }}>✅ {enoughCount} 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 && (
|
{missingCount === 0 && partialCount === 0 && (
|
||||||
<span style={{ color: '#1f5f2c', fontWeight: 600 }}>✅ Du har allt hemma!</span>
|
<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 isMissing = item.displayStatus === 'missing';
|
||||||
const isPartial = item.displayStatus === 'partial';
|
const isPartial = item.displayStatus === 'partial';
|
||||||
const isEnough = item.displayStatus === 'enough';
|
const isEnough = item.displayStatus === 'enough';
|
||||||
const bg = isMissing ? '#ffeaea' : isPartial ? '#fff8e6' : '#ecf8ee';
|
const isPantry = item.displayStatus === 'pantry';
|
||||||
const icon = isMissing ? '❌' : isPartial ? '⚠️' : '✅';
|
const bg = isMissing ? '#ffeaea' : isPartial ? '#fff8e6' : isPantry ? '#f5f5f5' : '#ecf8ee';
|
||||||
|
const icon = isMissing ? '❌' : isPartial ? '⚠️' : isPantry ? '📦' : '✅';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
@@ -293,8 +299,8 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
|
|||||||
fontSize: '0.88rem',
|
fontSize: '0.88rem',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{hasCompare && <span title={isEnough ? 'Finns hemma' : isPartial ? 'Delvis hemma' : 'Saknas'}>{icon}</span>}
|
{hasCompare && <span title={isEnough ? 'Finns hemma' : isPartial ? 'Delvis hemma' : isPantry ? 'Baslager — alltid hemma' : 'Saknas'}>{icon}</span>}
|
||||||
<span style={{ color: isEnough ? '#555' : '#111' }}>
|
<span style={{ color: (isEnough || isPantry) ? '#555' : '#111' }}>
|
||||||
<strong>{item.name}</strong>
|
<strong>{item.name}</strong>
|
||||||
{isPartial && item.cmp && (
|
{isPartial && item.cmp && (
|
||||||
<span style={{ color: '#7a5000', fontSize: '0.8rem', marginLeft: '0.4rem' }}>
|
<span style={{ color: '#7a5000', fontSize: '0.8rem', marginLeft: '0.4rem' }}>
|
||||||
@@ -306,9 +312,14 @@ export default function MealPlanClient({ recipes }: { recipes: Recipe[] }) {
|
|||||||
(finns hemma)
|
(finns hemma)
|
||||||
</span>
|
</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>
|
||||||
|
<span style={{ fontWeight: 600, whiteSpace: 'nowrap', color: (isEnough || isPantry) ? '#888' : '#111' }}>
|
||||||
|
{(isEnough || isPantry)
|
||||||
? '—'
|
? '—'
|
||||||
: `${fmtQty(item.buyQty)} ${item.unit}`}
|
: `${fmtQty(item.buyQty)} ${item.unit}`}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -14,20 +14,62 @@ type PantryItem = {
|
|||||||
product: Product;
|
product: Product;
|
||||||
};
|
};
|
||||||
|
|
||||||
type InventoryItem = {
|
|
||||||
productId: number;
|
|
||||||
quantity: string;
|
|
||||||
unit: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function PantryView() {
|
export default function PantryView() {
|
||||||
const [pantryItems, setPantryItems] = useState<PantryItem[]>([]);
|
const [pantryItems, setPantryItems] = useState<PantryItem[]>([]);
|
||||||
const [products, setProducts] = useState<Product[]>([]);
|
const [products, setProducts] = useState<Product[]>([]);
|
||||||
const [inventoryByProductId, setInventoryByProductId] = useState<Record<number, InventoryItem[]>>({});
|
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const authFetch = useAuthFetch();
|
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 () => {
|
const load = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|||||||
Reference in New Issue
Block a user