/** * Resource create/edit drawer: the design system's CreateResourceDrawer with * name and quantity (the pool size), and on edit the services that use it, * read-only. Blocked dates are edited in RazorBooking. */ import { useEffect, useMemo, useState, type ReactNode } from 'react'; import { Button, CreateResourceDrawer, type ResourceDraft } from '../../ds'; import { ExternalLink } from '../../design-system/icons'; import { api } from '../../lib/api'; import { errorOf } from '../../lib/errorOf'; import { openHandoff } from '../../lib/handoff'; import type { ResourceRow } from './types'; export interface ResourceFormDrawerProps { open: boolean; onClose: () => void; /** Omit for create; pass the row for edit. */ resource?: ResourceRow | null; onSaved: () => void; } export function ResourceFormDrawer( { open, onClose, resource, onSaved }: ResourceFormDrawerProps ) { const isEdit = Boolean( resource?.id ); const [ name, setName ] = useState( '' ); const [ quantity, setQuantity ] = useState( 1 ); const [ busy, setBusy ] = useState( false ); const [ error, setError ] = useState< ReactNode >( null ); useEffect( () => { if ( ! open ) return; setName( resource?.name ?? '' ); setQuantity( resource?.quantity ?? 1 ); setError( null ); }, [ open, resource ] ); const serviceOptions = useMemo( () => ( resource?.services ?? [] ).map( ( s ) => ( { value: String( s.id ), label: s.name } ) ), [ resource ] ); const patch = ( p: Partial< ResourceDraft > ) => { if ( p.name !== undefined ) setName( p.name ); if ( p.quantity !== undefined ) setQuantity( Number( p.quantity ) || 0 ); }; const submit = async () => { if ( ! name.trim() || busy ) return; setBusy( true ); setError( null ); const body = { name: name.trim(), quantity, is_active: resource ? resource.is_active : true }; try { if ( resource ) { await api.put( `resources/${ resource.id }`, body ); } else { await api.post( 'resources', body ); } onSaved(); onClose(); } catch ( caught ) { setError( errorOf( caught, 'Couldn’t save the resource. Try again.' ) ); } finally { setBusy( false ); } }; return ( { error ? { error } : null } { isEdit ? ( ) : null } } /> ); }