Refactor inventory forms to include unit and location options; update quantity input handling

This commit is contained in:
Nils-Johan Gynther
2026-04-09 23:25:52 +02:00
parent 50d79a348b
commit 03361f7b7d
9 changed files with 191 additions and 92 deletions
+1 -19
View File
@@ -2,31 +2,13 @@ import { fetchJson } from '../../../lib/api';
import type { Product } from '../../../features/inventory/types'; import type { Product } from '../../../features/inventory/types';
import CanonicalNameForm from './CanonicalNameForm'; import CanonicalNameForm from './CanonicalNameForm';
import MergePreviewForm from './MergePreviewForm'; import MergePreviewForm from './MergePreviewForm';
import Link from 'next/link';
export default async function AdminProductsPage() { export default async function AdminProductsPage() {
const products = await fetchJson<Product[]>('/api/products'); const products = await fetchJson<Product[]>('/api/products');
return ( return (
<main style={{ padding: '1.5rem', maxWidth: '1100px', margin: '0 auto' }}> <main style={{ padding: '1.5rem', maxWidth: '1100px', margin: '0 auto' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}> <h1 style={{ marginBottom: '1.5rem' }}>Admin: Produkter</h1>
<h1 style={{ margin: 0 }}>Admin: Produkter</h1>
<Link
href="/recipes/create"
style={{
padding: '0.5rem 1rem',
background: '#0070f3',
color: 'white',
borderRadius: '4px',
textDecoration: 'none',
fontWeight: 500,
fontSize: '1rem',
transition: 'background 0.2s',
}}
>
Lägg till nytt recept
</Link>
</div>
<p>Här kan du granska och standardisera produktnamn.</p> <p>Här kan du granska och standardisera produktnamn.</p>
<MergePreviewForm products={products} /> <MergePreviewForm products={products} />
+19
View File
@@ -0,0 +1,19 @@
import { NextRequest, NextResponse } from 'next/server';
const API_BASE = process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
export async function GET(request: NextRequest) {
const res = await fetch(`${API_BASE}/api/products`, {
method: 'GET',
cache: 'no-store',
});
const text = await res.text();
return new NextResponse(text, {
status: res.status,
headers: {
'Content-Type': 'application/json',
},
});
}
@@ -38,10 +38,12 @@ export default function InventoryConsumeForm({ id, unit }: Props) {
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
const form = e.currentTarget; const form = e.currentTarget;
const formData = new FormData(form); const formData = new FormData(form);
const raw = formData.get('amountUsed') as string;
const { quantity, unit: parsedUnit } = parseQuantityInput(raw, unit);
formData.set('amountUsed', String(quantity));
formData.set('unit', parsedUnit);
startTransition(async () => { startTransition(async () => {
try { try {
await consumeInventoryItem(formData); await consumeInventoryItem(formData);
@@ -67,9 +69,7 @@ export default function InventoryConsumeForm({ id, unit }: Props) {
<br /> <br />
<input <input
name="amountUsed" name="amountUsed"
type="number" type="text"
step="0.01"
min="0.01"
required required
style={{ width: '100%', padding: '0.5rem' }} style={{ width: '100%', padding: '0.5rem' }}
/> />
@@ -110,3 +110,14 @@ export default function InventoryConsumeForm({ id, unit }: Props) {
</div> </div>
); );
} }
function parseQuantityInput(input: string, defaultUnit: string) {
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
if (!match) return { quantity: NaN, unit: defaultUnit };
let [, num, unit] = match;
num = num.replace(',', '.');
unit = unit || defaultUnit;
if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
return { quantity: parseFloat(num), unit };
}
+55 -11
View File
@@ -13,6 +13,38 @@ function toDateInputValue(value: string | null) {
return value.slice(0, 10); return value.slice(0, 10);
} }
function parseQuantityInput(input: string, defaultUnit: string) {
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
if (!match) return { quantity: NaN, unit: defaultUnit };
let [, num, unit] = match;
num = num.replace(',', '.');
unit = unit || defaultUnit;
if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
return { quantity: parseFloat(num), unit };
}
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)' },
];
const LOCATION_OPTIONS = [
{ value: '', label: 'Välj plats' },
{ value: 'Kyl', label: 'Kyl' },
{ value: 'Frys', label: 'Frys' },
{ value: 'Skafferi', label: 'Skafferi' },
{ value: 'Annat', label: 'Annat' },
];
export default function InventoryEditForm({ item }: Props) { export default function InventoryEditForm({ item }: Props) {
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
@@ -43,10 +75,13 @@ export default function InventoryEditForm({ item }: Props) {
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
const form = e.currentTarget; const form = e.currentTarget;
const formData = new FormData(form); const formData = new FormData(form);
const raw = formData.get('quantity') as string;
const unit = formData.get('unit') as string;
const { quantity, unit: parsedUnit } = parseQuantityInput(raw, unit);
formData.set('quantity', String(quantity));
formData.set('unit', parsedUnit);
startTransition(async () => { startTransition(async () => {
try { try {
await updateInventoryItem(formData); await updateInventoryItem(formData);
@@ -79,9 +114,8 @@ export default function InventoryEditForm({ item }: Props) {
<br /> <br />
<input <input
name="quantity" name="quantity"
type="number" type="text"
step="0.01" required
min="0"
defaultValue={item.quantity} defaultValue={item.quantity}
style={{ width: '100%', padding: '0.5rem' }} style={{ width: '100%', padding: '0.5rem' }}
/> />
@@ -90,23 +124,33 @@ export default function InventoryEditForm({ item }: Props) {
<label> <label>
Enhet Enhet
<br /> <br />
<input <select
name="unit" name="unit"
type="text"
defaultValue={item.unit} defaultValue={item.unit}
style={{ width: '100%', padding: '0.5rem' }} style={{ width: '100%', padding: '0.5rem' }}
/> >
{UNIT_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</label> </label>
<label> <label>
Plats Plats
<br /> <br />
<input <select
name="location" name="location"
type="text"
defaultValue={item.location || ''} defaultValue={item.location || ''}
style={{ width: '100%', padding: '0.5rem' }} style={{ width: '100%', padding: '0.5rem' }}
/> >
{LOCATION_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</label> </label>
<label> <label>
+56 -15
View File
@@ -12,16 +12,51 @@ export default function InventoryForm({ products }: Props) {
const [isPending, setIsPending] = useState(false); const [isPending, setIsPending] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
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)' },
];
const LOCATION_OPTIONS = [
{ value: '', label: 'Välj plats' },
{ value: 'Kyl', label: 'Kyl' },
{ value: 'Frys', label: 'Frys' },
{ value: 'Skafferi', label: 'Skafferi' },
{ value: 'Annat', label: 'Annat' },
];
function parseQuantityInput(input: string, defaultUnit: string) {
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
if (!match) return { quantity: NaN, unit: defaultUnit };
let [, num, unit] = match;
num = num.replace(',', '.');
unit = unit || defaultUnit;
if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
return { quantity: parseFloat(num), unit };
}
return ( return (
<form <form
onSubmit={async (e) => { onSubmit={async (e) => {
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
setIsPending(true); setIsPending(true);
const form = e.currentTarget; const form = e.currentTarget;
const formData = new FormData(form); const formData = new FormData(form);
const raw = formData.get('quantity') as string;
const unit = formData.get('unit') as string;
const { quantity, unit: parsedUnit } = parseQuantityInput(raw, unit);
formData.set('quantity', String(quantity));
formData.set('unit', parsedUnit);
try { try {
await createInventoryItem(formData); await createInventoryItem(formData);
form.reset(); form.reset();
@@ -60,9 +95,7 @@ export default function InventoryForm({ products }: Props) {
<br /> <br />
<input <input
name="quantity" name="quantity"
type="number" type="text"
step="0.01"
min="0"
required required
style={{ width: '100%', padding: '0.5rem' }} style={{ width: '100%', padding: '0.5rem' }}
/> />
@@ -71,24 +104,32 @@ export default function InventoryForm({ products }: Props) {
<label> <label>
Enhet Enhet
<br /> <br />
<input <select
name="unit" name="unit"
type="text"
required required
placeholder="g, kg, st, dl..."
style={{ width: '100%', padding: '0.5rem' }} style={{ width: '100%', padding: '0.5rem' }}
/> >
{UNIT_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</label> </label>
<label> <label>
Plats Plats
<br /> <br />
<select name="location" required style={{ width: '100%', padding: '0.5rem' }}> <select
<option value="">Välj plats</option> name="location"
<option value="Kyl">Kyl</option> required
<option value="Frys">Frys</option> style={{ width: '100%', padding: '0.5rem' }}
<option value="Skafferi">Skafferi</option> >
<option value="Annat">Annat</option> {LOCATION_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select> </select>
</label> </label>
+1 -18
View File
@@ -106,24 +106,7 @@ export default async function InventoryPage({ searchParams }: InventoryPageProps
return ( return (
<main style={{ padding: '1.5rem', maxWidth: '1000px', margin: '0 auto' }}> <main style={{ padding: '1.5rem', maxWidth: '1000px', margin: '0 auto' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}> <h1 style={{ marginBottom: '1.5rem' }}>Varor hemma</h1>
<h1 style={{ margin: 0 }}>Varor hemma</h1>
<Link
href="/recipes/create"
style={{
padding: '0.5rem 1rem',
background: '#0070f3',
color: 'white',
borderRadius: '4px',
textDecoration: 'none',
fontWeight: 500,
fontSize: '1rem',
transition: 'background 0.2s',
}}
>
Lägg till nytt recept
</Link>
</div>
<ProductForm /> <ProductForm />
<InventoryForm products={products} /> <InventoryForm products={products} />
+1 -18
View File
@@ -3,24 +3,7 @@ import Link from 'next/link';
export default function HomePage() { export default function HomePage() {
return ( return (
<main style={{ padding: '2rem', maxWidth: '700px', margin: '0 auto' }}> <main style={{ padding: '2rem', maxWidth: '700px', margin: '0 auto' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}> <h1 style={{ marginBottom: '1.5rem' }}>Recipe App</h1>
<h1 style={{ margin: 0 }}>Recipe App</h1>
<Link
href="/recipes/create"
style={{
padding: '0.5rem 1rem',
background: '#0070f3',
color: 'white',
borderRadius: '4px',
textDecoration: 'none',
fontWeight: 500,
fontSize: '1rem',
transition: 'background 0.2s',
}}
>
Lägg till nytt recept
</Link>
</div>
<div style={{ display: 'grid', gap: '1rem' }}> <div style={{ display: 'grid', gap: '1rem' }}>
<Link href="/inventory" style={{ padding: '0.5rem', background: '#eee', borderRadius: '4px', textDecoration: 'none', color: '#222' }}> <Link href="/inventory" style={{ padding: '0.5rem', background: '#eee', borderRadius: '4px', textDecoration: 'none', color: '#222' }}>
till varor som finns hemma till varor som finns hemma
@@ -11,7 +11,7 @@ export default function CreateRecipePage() {
name: '', name: '',
description: '', description: '',
instructions: '', instructions: '',
ingredients: [{ productId: 0, quantity: '', unit: '', note: '' }], ingredients: [{ productId: 0, quantity: '', unit: '', note: '', location: '' }],
}); });
const [products, setProducts] = useState<Product[]>([]); const [products, setProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -32,7 +32,7 @@ export default function CreateRecipePage() {
const addIngredient = () => { const addIngredient = () => {
setRecipe({ setRecipe({
...recipe, ...recipe,
ingredients: [...recipe.ingredients, { productId: 0, quantity: '', unit: '', note: '' }], ingredients: [...recipe.ingredients, { productId: 0, quantity: '', unit: '', note: '', location: '' }],
}); });
}; };
@@ -75,6 +75,27 @@ export default function CreateRecipePage() {
} }
}; };
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)' },
];
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 ( return (
<main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}> <main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}>
<h1>Lägg till nytt recept</h1> <h1>Lägg till nytt recept</h1>
@@ -139,14 +160,18 @@ export default function CreateRecipePage() {
style={{ padding: '0.5rem' }} style={{ padding: '0.5rem' }}
/> />
<input <select
type="text"
placeholder="Enhet (t.ex. g, st, dl)"
value={ingredient.unit} value={ingredient.unit}
onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)} onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)}
required required
style={{ padding: '0.5rem' }} style={{ padding: '0.5rem' }}
/> >
{UNIT_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
<input <input
type="text" type="text"
+11
View File
@@ -31,3 +31,14 @@ export default async function RecipesPage() {
</main> </main>
); );
} }
function parseQuantityInput(input: string, defaultUnit: string) {
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
if (!match) return { quantity: NaN, unit: defaultUnit };
let [, num, unit] = match;
num = num.replace(',', '.');
unit = unit || defaultUnit;
if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
return { quantity: parseFloat(num), unit };
}