291 lines
11 KiB
TypeScript
291 lines
11 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { useForm } from '@inertiajs/react';
|
|
import { portalRequest } from '@/lib/portal-api';
|
|
import { Field, button, control } from './shared';
|
|
|
|
export type SubjectField = {
|
|
name: string;
|
|
label: string;
|
|
type: string;
|
|
options: string[];
|
|
};
|
|
type Value = string | number | boolean | null;
|
|
const names: Record<string, string> = {
|
|
draft: 'Rascunho',
|
|
planned: 'Planeado',
|
|
active: 'Activo',
|
|
suspended: 'Suspenso',
|
|
completed: 'Concluído',
|
|
cancelled: 'Cancelado',
|
|
inactive: 'Inactivo',
|
|
proposed: 'Proposto',
|
|
closed: 'Encerrado',
|
|
input: 'Insumos',
|
|
production: 'Produção',
|
|
processing: 'Transformação',
|
|
logistics: 'Logística',
|
|
market: 'Mercado',
|
|
supplies: 'Fornece',
|
|
processes: 'Transforma',
|
|
distributes: 'Distribui',
|
|
supports: 'Apoia',
|
|
official: 'Oficial',
|
|
influence: 'Influência',
|
|
proximity: 'Proximidade',
|
|
potential: 'Potencial',
|
|
historical: 'Histórica',
|
|
anchor: 'Âncora',
|
|
complementary: 'Complementar',
|
|
supporting: 'Apoio',
|
|
primary: 'Principal',
|
|
beneficiary: 'Beneficiária',
|
|
served: 'Servida',
|
|
enabled: 'Viabilizada',
|
|
dependent: 'Dependente',
|
|
related: 'Relacionada',
|
|
identified: 'Identificada',
|
|
in_review: 'Em análise',
|
|
resolved: 'Resolvida',
|
|
withdrawn: 'Retirada',
|
|
};
|
|
|
|
function Reference({
|
|
base,
|
|
field,
|
|
value,
|
|
onChange,
|
|
}: {
|
|
base: string;
|
|
field: SubjectField;
|
|
value: Value;
|
|
onChange: (value: Value) => void;
|
|
}) {
|
|
const [query, setQuery] = useState('');
|
|
const [items, setItems] = useState<{ id: string; name: string }[]>([]);
|
|
const [message, setMessage] = useState('');
|
|
useEffect(() => {
|
|
const abort = new AbortController();
|
|
const timer = setTimeout(() => {
|
|
void portalRequest<{ data: { id: string; name: string }[] }>(
|
|
`${base}/choices?${new URLSearchParams({ field: field.name, q: query })}`,
|
|
{ signal: abort.signal },
|
|
)
|
|
.then((data) => {
|
|
setItems(data.data);
|
|
setMessage('');
|
|
})
|
|
.catch((error) => {
|
|
if (!abort.signal.aborted)
|
|
setMessage(
|
|
error instanceof Error
|
|
? error.message
|
|
: 'Não foi possível consultar o catálogo.',
|
|
);
|
|
});
|
|
}, 250);
|
|
return () => {
|
|
clearTimeout(timer);
|
|
abort.abort();
|
|
};
|
|
}, [base, field.name, query]);
|
|
return (
|
|
<div className="space-y-2">
|
|
<input
|
|
className={control}
|
|
aria-label={`Pesquisar ${field.label.toLowerCase()}`}
|
|
placeholder="Pesquisar no catálogo existente"
|
|
value={query}
|
|
onChange={(event) => setQuery(event.target.value)}
|
|
/>
|
|
<select
|
|
className={control}
|
|
aria-label={field.label}
|
|
value={String(value ?? '')}
|
|
onChange={(event) => onChange(event.target.value || null)}
|
|
>
|
|
<option value="">Sem selecção</option>
|
|
{value && !items.some((item) => item.id === value) && (
|
|
<option value={String(value)}>
|
|
Selecção actual preservada
|
|
</option>
|
|
)}
|
|
{items.map((item) => (
|
|
<option key={item.id} value={item.id}>
|
|
{item.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
{items.length === 100 && (
|
|
<p className="text-sm">
|
|
Refine a pesquisa para consultar outros resultados.
|
|
</p>
|
|
)}
|
|
{message && <p role="status">{message}</p>}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function SubjectForm({
|
|
base,
|
|
revision,
|
|
fields,
|
|
initial,
|
|
withdraw = false,
|
|
}: {
|
|
base: string;
|
|
revision: number;
|
|
fields: SubjectField[];
|
|
initial: Record<string, Value>;
|
|
withdraw?: boolean;
|
|
}) {
|
|
const [open, setOpen] = useState(false);
|
|
const form = useForm({
|
|
expected_revision: revision,
|
|
withdraw,
|
|
fields: Object.fromEntries(
|
|
fields.map((field) => [field.name, initial[field.name] ?? null]),
|
|
) as Record<string, Value>,
|
|
});
|
|
const set = (field: string, value: Value) =>
|
|
form.setData('fields', { ...form.data.fields, [field]: value });
|
|
return (
|
|
<details
|
|
className="rounded border p-4"
|
|
onToggle={(event) => setOpen(event.currentTarget.open)}
|
|
>
|
|
<summary className="cursor-pointer font-medium underline">
|
|
Alterar proposta
|
|
</summary>
|
|
{open && (
|
|
<form
|
|
className="mt-4 space-y-4"
|
|
onSubmit={(event) => {
|
|
event.preventDefault();
|
|
form.post(`${base}/drafts`, { preserveScroll: true });
|
|
}}
|
|
>
|
|
<p>
|
|
Guarde uma nova edição. As decisões anteriores mantêm-se
|
|
no histórico e não aprovam automaticamente esta
|
|
alteração.
|
|
</p>
|
|
<label className="flex gap-2">
|
|
<input
|
|
type="checkbox"
|
|
checked={form.data.withdraw}
|
|
onChange={(event) =>
|
|
form.setData('withdraw', event.target.checked)
|
|
}
|
|
/>
|
|
Propor a retirada deste registo. A situação actual
|
|
mantém-se até à publicação expressa da decisão.
|
|
</label>
|
|
<div className="grid gap-4 sm:grid-cols-2">
|
|
{fields.map((field) => (
|
|
<Field
|
|
key={field.name}
|
|
label={field.label}
|
|
error={
|
|
(form.errors as Record<string, string>)[
|
|
`fields.${field.name}`
|
|
] ??
|
|
(form.errors as Record<string, string>)[
|
|
field.name
|
|
]
|
|
}
|
|
>
|
|
{field.type === 'reference' ? (
|
|
<Reference
|
|
base={base}
|
|
field={field}
|
|
value={form.data.fields[field.name]}
|
|
onChange={(value) =>
|
|
set(field.name, value)
|
|
}
|
|
/>
|
|
) : field.type === 'enum' ? (
|
|
<select
|
|
className={control}
|
|
value={String(
|
|
form.data.fields[field.name] ?? '',
|
|
)}
|
|
onChange={(event) =>
|
|
set(field.name, event.target.value)
|
|
}
|
|
>
|
|
<option value="">Seleccionar</option>
|
|
{field.options.map((option) => (
|
|
<option key={option} value={option}>
|
|
{names[option] ?? option}
|
|
</option>
|
|
))}
|
|
</select>
|
|
) : field.type === 'boolean' ? (
|
|
<input
|
|
type="checkbox"
|
|
checked={Boolean(
|
|
form.data.fields[field.name],
|
|
)}
|
|
onChange={(event) =>
|
|
set(
|
|
field.name,
|
|
event.target.checked,
|
|
)
|
|
}
|
|
/>
|
|
) : field.type === 'date' ? (
|
|
<input
|
|
className={control}
|
|
type="date"
|
|
value={String(
|
|
form.data.fields[field.name] ?? '',
|
|
).slice(0, 10)}
|
|
onChange={(event) =>
|
|
set(
|
|
field.name,
|
|
event.target.value || null,
|
|
)
|
|
}
|
|
/>
|
|
) : (
|
|
<textarea
|
|
className={control}
|
|
rows={
|
|
field.name === 'description' ||
|
|
field.name === 'rationale'
|
|
? 4
|
|
: 2
|
|
}
|
|
value={String(
|
|
form.data.fields[field.name] ?? '',
|
|
)}
|
|
onChange={(event) =>
|
|
set(
|
|
field.name,
|
|
event.target.value || null,
|
|
)
|
|
}
|
|
/>
|
|
)}
|
|
</Field>
|
|
))}
|
|
</div>
|
|
{Object.entries(form.errors)
|
|
.filter(
|
|
([key]) =>
|
|
key === 'expected_revision' || key === 'fields',
|
|
)
|
|
.map(([key, message]) => (
|
|
<p role="alert" key={key}>
|
|
{message}
|
|
</p>
|
|
))}
|
|
<button className={button} disabled={form.processing}>
|
|
Guardar nova edição privada
|
|
</button>
|
|
</form>
|
|
)}
|
|
</details>
|
|
);
|
|
}
|