import { type FormEvent, useEffect, useState } from 'react' import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom' import { ApiHttpError } from '../../api/http' import { fetchInventoryCreateForm, fetchInventoryItem, postInventoryItem, putInventoryItem, } from '../../api/inventory' /** CI `inventory/kitchen/form.php` */ export function InventoryKitchenFormPage() { const { itemId } = useParams() const { pathname } = useLocation() const [searchParams] = useSearchParams() const isCreate = pathname.endsWith('/create') const [categories, setCategories] = useState[]>([]) const [name, setName] = useState('') const [categoryId, setCategoryId] = useState('') const [quantity, setQuantity] = useState('0') const [unit, setUnit] = useState('') const [sku, setSku] = useState('') const [description, setDescription] = useState('') const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) useEffect(() => { let c = false setLoading(true) const run = isCreate ? fetchInventoryCreateForm('kitchen', searchParams) : fetchInventoryItem(itemId ?? '') run .then((data) => { if (c) return if (data && typeof data === 'object') { const o = data as Record const cats = Array.isArray(o.categories) ? (o.categories as Record[]) : [] setCategories(cats) const item = (o.item ?? o) as Record if (!isCreate && item?.id != null) { setName(String(item.name ?? '')) setCategoryId(item.category_id != null ? String(item.category_id) : '') setQuantity(String(item.quantity ?? 0)) setUnit(String(item.unit ?? '')) setSku(String(item.sku ?? '')) setDescription(String(item.description ?? '')) } } setError(null) }) .catch((e: unknown) => { if (!c) setError(e instanceof ApiHttpError ? e.message : 'Unable to load form.') }) .finally(() => { if (!c) setLoading(false) }) return () => { c = true } }, [isCreate, itemId, searchParams]) async function onSubmit(e: FormEvent) { e.preventDefault() setSaving(true) setError(null) const body: Record = { type: 'kitchen', name, category_id: categoryId === '' ? null : Number(categoryId), quantity: quantity === '' ? 0 : Number(quantity), unit: unit || undefined, sku: sku || undefined, description: description || undefined, } try { if (isCreate) await postInventoryItem(body) else await putInventoryItem(itemId ?? '', body) window.location.href = '/app/administrator/inventory/kitchen' } catch (err: unknown) { setError(err instanceof ApiHttpError ? err.message : 'Save failed.') } finally { setSaving(false) } } return (

{isCreate ? 'Add' : 'Edit'} Kitchen Supply

{error ?
{error}
: null} {loading ?

Loading…

: null} {!loading ? (
void onSubmit(ev)}>
setName(e.target.value)} />
setQuantity(e.target.value)} />
setUnit(e.target.value)} />
setSku(e.target.value)} />