EditLocationPage.tsx
3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { useEffect, useState, type FormEvent } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { inventory } from '@/api/client'
import type { Location } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { Loading } from '@/components/Loading'
import { ErrorBox } from '@/components/ErrorBox'
import { DynamicExtFields } from '@/components/DynamicExtFields'
export function EditLocationPage() {
const { id = '' } = useParams<{ id: string }>()
const navigate = useNavigate()
const [location, setLocation] = useState<Location | null>(null)
const [name, setName] = useState('')
const [active, setActive] = useState(true)
const [loading, setLoading] = useState(true)
const [ext, setExt] = useState<Record<string, unknown>>({})
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
inventory.getLocation(id)
.then((loc) => {
setLocation(loc)
setName(loc.name)
setActive(loc.active)
setExt(loc.ext || {})
})
.catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
.finally(() => setLoading(false))
}, [id])
const onSubmit = async (e: FormEvent) => {
e.preventDefault()
setError(null)
setSubmitting(true)
try {
await inventory.updateLocation(id, {
name, active,
...(Object.keys(ext).length > 0 ? { ext } : {}),
})
navigate('/locations')
} catch (err: unknown) {
setError(err instanceof Error ? err : new Error(String(err)))
} finally {
setSubmitting(false)
}
}
if (loading) return <Loading />
if (!location) return <ErrorBox error={error ?? 'Location not found'} />
return (
<div>
<PageHeader
title={`Edit ${location.code}`}
subtitle={`Type: ${location.type} (read-only after creation)`}
actions={<button className="btn-secondary" onClick={() => navigate('/locations')}>Cancel</button>}
/>
<form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-2xl">
<div>
<label className="block text-sm font-medium text-slate-700">Name</label>
<input type="text" required value={name} onChange={(e) => setName(e.target.value)}
className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
</div>
<div className="flex items-center gap-2">
<input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)}
className="rounded border-slate-300" id="active" />
<label htmlFor="active" className="text-sm text-slate-700">Active</label>
</div>
<DynamicExtFields entityName="Location" values={ext} onChange={(k, v) => setExt(prev => ({ ...prev, [k]: v }))} />
{error && <ErrorBox error={error} />}
<button type="submit" className="btn-primary" disabled={submitting}>
{submitting ? 'Saving\u2026' : 'Save Changes'}
</button>
</form>
</div>
)
}