Files
Investidor-V2/resources/js/pages/land-assistance/form.tsx
T
nala cf003c8623
tests / ci (push) Canceled after 0s
versao nrgocios 4
2026-10-18 15:57:06 +02:00

1558 lines
73 KiB
TypeScript

import { DossierPrefill } from '@/components/dossier-prefill';
import { Link, useForm } from '@inertiajs/react';
import { useEffect, useMemo, useState } from 'react';
import CountrySelect, { type Country } from '@/components/country-select';
import {
TerritoryFields,
type TerritoryOption,
} from '@/components/investment-territory';
type Parcel = Record<string, string>;
type Payload = Record<string, any>;
const emptyParcel = (): Parcel => ({
province_id: '',
district_id: '',
admin_post_id: '',
locality_id: '',
place_description: '',
area: '',
area_unit: '',
cadastral_reference: '',
coordinates: '',
geometry_confidence: 'unknown',
});
const requiredLabels: Record<string, string> = {
support_kind: 'Pretende apoio para',
request_description: 'Descrição do pedido',
applicant_category: 'Categoria do requerente',
full_name: 'Nome ou denominação',
preferred_contact: 'Canal preferido',
area_status: 'Situação da localização',
purpose: 'Finalidade pretendida',
email: 'Email',
contact_person: 'Pessoa de contacto',
representative_role: 'Função da representação',
truth_declaration: 'Declaração de informação',
contact_consent: 'Autorização de contacto',
country: 'País do requerente',
declared_origin_country_code: 'Origem declarada da solicitação',
};
const emptyPayload = (user: { name: string; email: string }): Payload => ({
support_kind: '',
request_description: '',
project_reference: '',
applicant_category: '',
full_name: user.name ?? '',
contact_person: '',
email: user.email ?? '',
phone: '',
preferred_contact: '',
country: '',
declared_origin_country_code: '',
nationality: '',
representative_name: '',
representative_role: '',
representation_basis: '',
nuit: '',
constitution_or_residency_note: '',
area_status: '',
parcels: [emptyParcel()],
purpose: '',
activity: '',
known_occupants: 'unknown',
occupant_description: '',
known_improvements: 'unknown',
improvements_description: '',
prior_right_status: 'unknown',
prior_right_description: '',
conflict_status: 'unknown',
conflict_description: '',
official_process: {},
attachments_to_follow: [],
exploration_plan: { activity_rows: [], notes: '' },
consultation: { status: 'not_started', participants: [] },
additional_information: '',
truth_declaration: false,
contact_consent: false,
});
const supportKinds: Record<string, string> = {
investment: 'Terra para projecto de investimento',
home: 'Orientação para habitação',
family_exploitation: 'Exploração familiar',
recognition: 'Reconhecimento/titulação de área ocupada',
regularization: 'Regularização cadastral',
delimitation: 'Delimitação/demarcação',
change_of_use: 'Alteração de uso ou área',
transfer: 'Transmissão/herança',
existing_process: 'Acompanhamento de processo existente',
conflict_guidance: 'Esclarecimento sobre conflito/restrição',
other: 'Outro',
};
export default function LandForm({
case: existing,
user,
disclaimer,
modelVersion,
countries,
returnDossier,
boundContextRevision,
}: {
boundContextRevision?: number | null;
case: {
id: string;
reference: string;
version: number;
status: string;
payload: Payload;
} | null;
user: { name: string; email: string };
disclaimer: string;
modelVersion: string;
countries: Country[];
returnDossier?: { id: string; title: string; url: string } | null;
}) {
const [step, setStep] = useState(0);
const initial = useMemo(
() =>
existing?.payload ?? {
...emptyPayload(user),
...(returnDossier
? { investor_path_case_id: returnDossier.id }
: {}),
},
[existing?.id],
);
const form = useForm({
version: existing?.version ?? 1,
payload: initial,
context_revision: 0,
context_reviewed: false,
});
const [pendingErrorField, setPendingErrorField] = useState<string | null>(
null,
);
useEffect(() => {
const first = Object.keys(form.errors)[0];
if (!first) return;
const field = first.replace(/^payload\./, '').split('.')[0];
const errorStep = [
'truth_declaration',
'contact_consent',
'additional_information',
].includes(field)
? 3
: ['exploration_plan', 'consultation'].includes(field)
? 2
: [
'area_status',
'parcels',
'purpose',
'activity',
'known_occupants',
'known_improvements',
'prior_right_status',
'conflict_status',
'official_process',
].includes(field)
? 1
: 0;
setStep(errorStep);
setPendingErrorField(field);
}, [form.errors]);
useEffect(() => {
if (!pendingErrorField) return;
const timer = window.setTimeout(() => {
const target =
document.getElementById(`land-field-${pendingErrorField}`) ??
document.getElementById('land-error-summary');
target?.focus();
target?.scrollIntoView({ block: 'center' });
setPendingErrorField(null);
}, 0);
return () => window.clearTimeout(timer);
}, [pendingErrorField, step]);
const update = (field: string, value: unknown) =>
form.setData('payload', { ...form.data.payload, [field]: value });
const updateParcel = (index: number, key: string, value: unknown) => {
const parcels = [...(form.data.payload.parcels ?? [emptyParcel()])];
parcels[index] = { ...parcels[index], [key]: value };
update('parcels', parcels);
};
const text = (
key: string,
label: string,
required = false,
type = 'text',
help?: string,
) => (
<label className="block space-y-1" key={key}>
<span className="text-sm font-medium">
{label}
{required ? ' *' : ''}
</span>
<input
id={`land-field-${key}`}
className="w-full rounded border p-2"
type={type}
required={required}
value={form.data.payload[key] ?? ''}
onChange={(event) => update(key, event.target.value)}
aria-invalid={Boolean(form.errors[`payload.${key}`])}
aria-describedby={
form.errors[`payload.${key}`]
? `land-error-${key}`
: undefined
}
/>
{help && (
<span className="block text-xs text-slate-600">{help}</span>
)}
{form.errors[`payload.${key}`] && (
<span
id={`land-error-${key}`}
role="alert"
className="text-sm text-red-700"
>
{form.errors[`payload.${key}`]}
</span>
)}
</label>
);
const areaStatus = form.data.payload.area_status;
const category = form.data.payload.applicant_category;
const current = form.data.payload;
const saveUrl = existing
? `/investidor/terra-duat/${existing.id}`
: '/investidor/terra-duat';
const save = () =>
existing
? form.put(saveUrl, { preserveScroll: true })
: form.post(saveUrl, { preserveScroll: true });
const support = () =>
existing &&
form.post(`/investidor/terra-duat/${existing.id}/solicitar-apoio`, {
preserveScroll: true,
});
const canEdit =
!existing || ['draft', 'waiting_applicant'].includes(existing.status);
return (
<main className="mx-auto max-w-5xl space-y-6 p-6">
<header className="space-y-2">
{returnDossier && (
<Link className="underline" href={returnDossier.url}>
Voltar ao dossier: {returnDossier.title}
</Link>
)}
<Link href="/terra-duat" className="underline">
Terra e DUAT
</Link>
<h1 className="text-3xl font-bold">
Formulário de orientação e preparação
</h1>
<p className="text-sm">
Modelo {modelVersion}
{existing
? ` · Referência interna ${existing.reference} · versão ${existing.version}`
: ''}
</p>
<p className="rounded border border-amber-400 bg-amber-50 p-3">
{disclaimer}
</p>
<p className="text-sm">
A referência é interna do InvestMoz, não é número oficial de
processo. Preencha só o que sabe; documentos são opcionais
para pedir orientação.
</p>
</header>
<DossierPrefill
contextId={returnDossier?.id}
consumer="land"
values={form.data.payload}
boundRevision={boundContextRevision ?? 0}
onReview={(revision, reviewed) =>
form.setData((d) => ({
...d,
context_revision: revision,
context_reviewed: reviewed,
}))
}
onApply={(patch, replace) =>
form.setData((d) => {
const payload = { ...d.payload };
for (const [k, v] of Object.entries(patch)) {
if (k === 'parcels' && Array.isArray(v)) {
const current = payload.parcels?.[0] ?? {};
if (
replace ||
![
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].some((g) => current[g])
)
payload.parcels = [
{
...emptyParcel(),
...current,
...v[0],
},
...(payload.parcels?.slice(1) ?? []),
];
} else if (replace || !payload[k]) payload[k] = v;
}
return { ...d, payload };
})
}
/>
<ol
className="grid grid-cols-2 gap-2 sm:grid-cols-4"
aria-label="Etapas do formulário"
>
{[
'Pedido e requerente',
'Localização e situação',
'Plano e consulta',
'Rever',
].map((title, index) => (
<li key={title}>
<button
type="button"
onClick={() => setStep(index)}
aria-current={step === index ? 'step' : undefined}
className={`w-full rounded border p-2 text-sm ${step === index ? 'bg-emerald-800 text-white' : ''}`}
>
{index + 1}. {title}
</button>
</li>
))}
</ol>
{step === 0 && (
<section className="grid gap-4 rounded border p-4 sm:grid-cols-2">
<h2 className="text-xl font-semibold sm:col-span-2">
A. Tipo de apoio e requerente
</h2>
<label className="space-y-1">
<span className="text-sm font-medium">
Pretende apoio para *
</span>
<select
id="land-field-support_kind"
aria-invalid={Boolean(
form.errors['payload.support_kind'],
)}
aria-describedby={
form.errors['payload.support_kind']
? 'land-error-support_kind'
: undefined
}
className="w-full rounded border p-2"
required
value={current.support_kind ?? ''}
onChange={(event) =>
update('support_kind', event.target.value)
}
>
<option value="">Seleccione</option>
{Object.entries(supportKinds).map(
([value, label]) => (
<option key={value} value={value}>
{label}
</option>
),
)}
</select>
</label>
{form.errors['payload.support_kind'] && (
<p
id="land-error-support_kind"
role="alert"
className="text-red-700"
>
{form.errors['payload.support_kind']}
</p>
)}
{text('request_description', 'Descrição do pedido', true)}
{text(
'project_reference',
'Projecto/oportunidade já registado, se existir',
)}
<label className="space-y-1">
<span className="text-sm font-medium">
Categoria do requerente *
</span>
<select
className="w-full rounded border p-2"
required
id="land-field-applicant_category"
aria-invalid={Boolean(
form.errors['payload.applicant_category'],
)}
aria-describedby={
form.errors['payload.applicant_category']
? 'land-error-applicant_category'
: undefined
}
value={current.applicant_category ?? ''}
onChange={(event) =>
update('applicant_category', event.target.value)
}
>
<option value="">Seleccione</option>
<option value="individual">Pessoa singular</option>
<option value="entity">Pessoa colectiva</option>
<option value="community">Comunidade</option>
<option value="other">Outra</option>
</select>
</label>
{form.errors['payload.applicant_category'] && (
<p
id="land-error-applicant_category"
role="alert"
className="text-red-700"
>
{form.errors['payload.applicant_category']}
</p>
)}
{text('full_name', 'Nome ou denominação', true)}
{category === 'community' &&
text(
'contact_person',
'Pessoa de contacto da comunidade',
)}
{text('email', 'Email (facultativo)', false, 'email')}
{text('phone', 'Telefone (facultativo)', false, 'tel')}
<label className="space-y-1">
<span className="text-sm font-medium">
Canal preferido *
</span>
<select
className="w-full rounded border p-2"
required
value={current.preferred_contact ?? ''}
id="land-field-preferred_contact"
aria-invalid={Boolean(
form.errors['payload.preferred_contact'],
)}
aria-describedby={
form.errors['payload.preferred_contact']
? 'land-error-preferred_contact'
: undefined
}
onChange={(event) =>
update('preferred_contact', event.target.value)
}
>
<option value="">Seleccione</option>
<option value="email">Email</option>
<option value="phone">Telefone</option>
<option value="any">Qualquer um indicado</option>
</select>
</label>
{form.errors['payload.preferred_contact'] && (
<p
id="land-error-preferred_contact"
role="alert"
className="text-red-700"
>
{form.errors['payload.preferred_contact']}
</p>
)}
<div className="space-y-1">
<p className="text-sm font-medium">
País do requerente (opcional)
</p>
<CountrySelect
countries={countries}
value={current.country ?? ''}
onChange={(value) => update('country', value)}
label="País do requerente (opcional)"
error={form.errors['payload.country']}
allowLegacyValue
/>
</div>
<div className="space-y-1">
<p className="text-sm font-medium">
País de origem declarado da solicitação (opcional)
</p>
<CountrySelect
countries={countries}
value={current.declared_origin_country_code ?? ''}
onChange={(value) =>
update('declared_origin_country_code', value)
}
label="País de origem declarado da solicitação (opcional)"
error={
form.errors[
'payload.declared_origin_country_code'
]
}
/>
</div>
{text('nationality', 'Nacionalidade, se aplicável')}
{category === 'entity' && (
<>
{text('representative_name', 'Representante')}
{text(
'representative_role',
'Função/qualidade da representação',
)}
{text(
'representation_basis',
'Fundamento ou documento de representação (referência)',
)}
{text(
'constitution_or_residency_note',
'Constituição/residência — detalhe apenas se relevante',
)}
</>
)}
{text(
'nuit',
'NUIT/identificação — facultativo e apenas se necessário',
)}
</section>
)}
{step === 1 && (
<section className="space-y-5 rounded border p-4">
<h2 className="text-xl font-semibold">
B. Localização, finalidade e situação conhecida
</h2>
<label className="block space-y-1">
<span className="text-sm font-medium">
Situação da localização *
</span>
<select
className="w-full rounded border p-2"
required
value={current.area_status ?? ''}
id="land-field-area_status"
aria-invalid={Boolean(
form.errors['payload.area_status'],
)}
aria-describedby={
form.errors['payload.area_status']
? 'land-error-area_status'
: undefined
}
onChange={(event) =>
update('area_status', event.target.value)
}
>
<option value="">Seleccione</option>
<option value="identified">
Tenho uma área identificada
</option>
<option value="seeking">
Procuro uma localização
</option>
<option value="location_support">
Preciso de apoio para confirmar/localizar
</option>
<option value="unknown">Ainda não sei</option>
</select>
</label>
{form.errors['payload.area_status'] && (
<p
id="land-error-area_status"
role="alert"
className="text-red-700"
>
{form.errors['payload.area_status']}
</p>
)}
{current.area_status !== 'seeking' &&
current.area_status !== 'unknown' &&
(current.parcels ?? []).map(
(parcel: Parcel, index: number) => (
<ParcelEditor
key={index}
index={index}
parcel={parcel}
onChange={(key, value) =>
updateParcel(index, key, value)
}
onRemove={() =>
update(
'parcels',
current.parcels.filter(
(_: Parcel, i: number) =>
i !== index,
),
)
}
/>
),
)}
{areaStatus !== 'seeking' && (
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
update('parcels', [
...(current.parcels ?? []),
emptyParcel(),
])
}
>
Adicionar outra parcela (até 10)
</button>
)}
{text('purpose', 'Uso pretendido *', true)}
{text('activity', 'Actividade económica, se aplicável')}
<StatusField
label="Ocupantes ou utilizações conhecidas?"
value={current.known_occupants}
choices={['yes', 'no_as_far_as_known', 'unknown']}
labels={[
'Sim',
'Não, segundo a informação disponível',
'Não sei',
]}
onChange={(v) => update('known_occupants', v)}
/>
{current.known_occupants === 'yes' &&
text(
'occupant_description',
'Descrição dos ocupantes/usos',
)}
<StatusField
label="Construções, benfeitorias, machambas, servidões ou usos comunitários?"
value={current.known_improvements}
choices={['yes', 'unknown', 'none_identified']}
labels={[
'Sim',
'Não sei',
'Não identificados na informação disponível',
]}
onChange={(v) => update('known_improvements', v)}
/>
{current.known_improvements === 'yes' &&
text('improvements_description', 'Descrição')}
<StatusField
label="Título, autorização ou antecedentes?"
value={current.prior_right_status}
choices={['yes', 'unknown', 'no_documents']}
labels={[
'Sim',
'Não sei',
'Não disponho de documentos',
]}
onChange={(v) => update('prior_right_status', v)}
/>
{current.prior_right_status === 'yes' &&
text(
'prior_right_description',
'Descrição/referência dos antecedentes',
)}
<StatusField
label="Conflito, oposição ou possível sobreposição conhecida?"
value={current.conflict_status}
choices={['yes', 'unknown', 'no_knowledge']}
labels={['Sim', 'Não sei', 'Não tenho conhecimento']}
onChange={(v) => update('conflict_status', v)}
/>
{current.conflict_status === 'yes' &&
text(
'conflict_description',
'Descrição (não constitui resolução de litígio)',
)}
{current.support_kind === 'existing_process' && (
<fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2">
<legend className="font-medium">
Processo existente — informação comunicada pelo
requerente
</legend>
{(
[
'official_reference',
'receiving_entity',
'presented_at',
'reported_status',
'pending_items',
'proof_available',
] as const
).map((key) => (
<label key={key} className="space-y-1">
<span>
{
{
official_reference:
'Número oficial, se atribuído',
receiving_entity:
'Entidade receptora',
presented_at:
'Data de apresentação',
reported_status:
'Estado comunicado pela entidade',
pending_items:
'Pendências conhecidas',
proof_available:
'Comprovativo disponível',
}[key]
}
</span>
{key === 'proof_available' ? (
<select
className="w-full rounded border p-2"
value={
current.official_process?.[
key
] ?? ''
}
onChange={(e) =>
update('official_process', {
...current.official_process,
[key]: e.target.value,
})
}
>
<option value="">Não sei</option>
<option value="yes">Sim</option>
<option value="no">Não</option>
</select>
) : (
<input
className="w-full rounded border p-2"
type={
key === 'presented_at'
? 'date'
: 'text'
}
value={
current.official_process?.[
key
] ?? ''
}
onChange={(e) =>
update('official_process', {
...current.official_process,
[key]: e.target.value,
})
}
/>
)}
</label>
))}
</fieldset>
)}
</section>
)}
{step === 2 && (
<section className="space-y-5 rounded border p-4">
<h2 className="text-xl font-semibold">
C. Plano de exploração e consulta comunitária (quando
aplicável)
</h2>
<p>
As tabelas são facultativas. Os períodos são definidos
por si; o sistema não impõe cinco anos nem soma áreas
repetidas como novas parcelas.
</p>
{(current.exploration_plan?.activity_rows ?? []).map(
(row: any, index: number) => (
<div
key={index}
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
>
<h3 className="font-semibold sm:col-span-2">
Actividade {index + 1}
</h3>
{(
[
'period',
'activity',
'area',
'area_unit',
'stage',
'targets',
'structures',
'investment',
] as const
).map((key) => (
<label key={key} className="space-y-1">
<span>
{
{
period: 'Período',
activity: 'Actividade',
area: 'Área (não somada)',
area_unit: 'Unidade',
stage: 'Existente/planeado',
targets: 'Metas',
structures:
'Construções/vedações',
investment:
'Investimento previsto',
}[key]
}
</span>
{key === 'area_unit' ? (
<select
className="w-full rounded border p-2"
value={row[key] ?? ''}
onChange={(e) =>
update('exploration_plan', {
...current.exploration_plan,
activity_rows:
current.exploration_plan.activity_rows.map(
(
r: any,
i: number,
) =>
i === index
? {
...r,
[key]: e
.target
.value,
}
: r,
),
})
}
>
<option value="">
Por confirmar
</option>
<option value="m2">m²</option>
<option value="hectares">
Hectares
</option>
<option value="other">
Outra
</option>
</select>
) : key === 'stage' ? (
<select
className="w-full rounded border p-2"
value={row[key] ?? ''}
onChange={(e) =>
update('exploration_plan', {
...current.exploration_plan,
activity_rows:
current.exploration_plan.activity_rows.map(
(
r: any,
i: number,
) =>
i === index
? {
...r,
[key]: e
.target
.value,
}
: r,
),
})
}
>
<option value="">
Por confirmar
</option>
<option value="existing">
Existente
</option>
<option value="planned">
Planeado
</option>
<option value="unknown">
Não sei
</option>
</select>
) : (
<input
className="w-full rounded border p-2"
type={
[
'area',
'investment',
].includes(key)
? 'number'
: 'text'
}
min={
[
'area',
'investment',
].includes(key)
? 0
: undefined
}
value={row[key] ?? ''}
onChange={(e) =>
update('exploration_plan', {
...current.exploration_plan,
activity_rows:
current.exploration_plan.activity_rows.map(
(
r: any,
i: number,
) =>
i === index
? {
...r,
[key]: e
.target
.value,
}
: r,
),
})
}
/>
)}
</label>
))}
<button
type="button"
className="text-left text-sm underline"
onClick={() =>
update('exploration_plan', {
...current.exploration_plan,
activity_rows:
current.exploration_plan.activity_rows.filter(
(_: any, i: number) =>
i !== index,
),
})
}
>
Remover linha
</button>
</div>
),
)}
{(current.exploration_plan?.activity_rows?.length ?? 0) <
30 && (
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
update('exploration_plan', {
...current.exploration_plan,
activity_rows: [
...(current.exploration_plan
?.activity_rows ?? []),
{
period: '',
activity: '',
area: '',
area_unit: '',
stage: '',
targets: '',
structures: '',
investment: '',
},
],
})
}
>
Adicionar período/actividade
</button>
)}
<label className="block space-y-1">
<span>Notas do plano</span>
<textarea
className="w-full rounded border p-2"
value={current.exploration_plan?.notes ?? ''}
onChange={(e) =>
update('exploration_plan', {
...current.exploration_plan,
notes: e.target.value,
})
}
/>
</label>
<fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2">
<legend className="font-semibold">
Preparação/acompanhamento de consulta — não
preencher como realizada
</legend>
<label>
<span>Estado comunicado</span>
<select
className="w-full rounded border p-2"
value={
current.consultation?.status ??
'not_started'
}
onChange={(e) =>
update('consultation', {
...current.consultation,
status: e.target.value,
})
}
>
<option value="not_started">
Não iniciada
</option>
<option value="preparing">Em preparação</option>
<option value="reported_completed">
Requerente informa que ocorreu
</option>
<option value="unknown">Não sei</option>
</select>
</label>
{(
[
'community',
'location',
'date',
'facilitators',
'language',
'interventions',
'opposition',
'agreements',
'minutes_reference',
'opinions_received',
] as const
).map((key) => (
<label className="space-y-1" key={key}>
<span>
{
{
community: 'Comunidade',
location: 'Local',
date: 'Data',
facilitators:
'Responsáveis/facilitadores',
language: 'Língua/tradução',
interventions:
'Intervenções e divergências',
opposition: 'Oposição comunicada',
agreements:
'Acordos/compromissos comunicados',
minutes_reference:
'Referência de acta recebida',
opinions_received:
'Pareceres recebidos',
}[key]
}
</span>
{[
'interventions',
'opposition',
'agreements',
'opinions_received',
].includes(key) ? (
<textarea
className="w-full rounded border p-2"
value={
current.consultation?.[key] ?? ''
}
onChange={(e) =>
update('consultation', {
...current.consultation,
[key]: e.target.value,
})
}
/>
) : (
<input
className="w-full rounded border p-2"
type={key === 'date' ? 'date' : 'text'}
value={
current.consultation?.[key] ?? ''
}
onChange={(e) =>
update('consultation', {
...current.consultation,
[key]: e.target.value,
})
}
/>
)}
</label>
))}
{(current.consultation?.participants ?? []).map(
(person: any, index: number) => (
<div key={index} className="flex gap-2">
<input
className="w-full rounded border p-2"
aria-label="Nome de participante"
placeholder="Nome, se aplicável"
value={person.name ?? ''}
onChange={(e) =>
update('consultation', {
...current.consultation,
participants:
current.consultation.participants.map(
(p: any, i: number) =>
i === index
? {
...p,
name: e
.target
.value,
}
: p,
),
})
}
/>
<input
className="w-full rounded border p-2"
aria-label="Função de participante"
placeholder="Função"
value={person.role ?? ''}
onChange={(e) =>
update('consultation', {
...current.consultation,
participants:
current.consultation.participants.map(
(p: any, i: number) =>
i === index
? {
...p,
role: e
.target
.value,
}
: p,
),
})
}
/>
</div>
),
)}
{(current.consultation?.participants?.length ?? 0) <
200 && (
<button
type="button"
className="text-sm underline"
onClick={() =>
update('consultation', {
...current.consultation,
participants: [
...(current.consultation
?.participants ?? []),
{ name: '', role: '' },
],
})
}
>
Adicionar participante
</button>
)}
</fieldset>
</section>
)}
{step === 3 && (
<section className="space-y-4 rounded border p-4">
<h2 className="text-xl font-semibold">
D. Rever e pedir apoio
</h2>
<label className="block space-y-1">
<span>Informação complementar</span>
<textarea
className="w-full rounded border p-2"
value={current.additional_information ?? ''}
onChange={(e) =>
update('additional_information', e.target.value)
}
/>
</label>
<label className="flex gap-2">
<input
type="checkbox"
id="land-field-truth_declaration"
aria-invalid={Boolean(
form.errors['payload.truth_declaration'],
)}
aria-describedby={
form.errors['payload.truth_declaration']
? 'land-error-truth_declaration'
: undefined
}
checked={Boolean(current.truth_declaration)}
onChange={(e) =>
update('truth_declaration', e.target.checked)
}
/>
Confirmo que as respostas correspondem à informação de
que disponho e assinalei dúvidas conhecidas.
</label>
{form.errors['payload.truth_declaration'] && (
<p
id="land-error-truth_declaration"
role="alert"
className="text-red-700"
>
{form.errors['payload.truth_declaration']}
</p>
)}
<label className="flex gap-2">
<input
type="checkbox"
id="land-field-contact_consent"
aria-invalid={Boolean(
form.errors['payload.contact_consent'],
)}
aria-describedby={
form.errors['payload.contact_consent']
? 'land-error-contact_consent'
: undefined
}
checked={Boolean(current.contact_consent)}
onChange={(e) =>
update('contact_consent', e.target.checked)
}
/>
Autorizo o contacto para responder a este pedido. Esta
autorização não permite publicação dos documentos.
</label>
{form.errors['payload.contact_consent'] && (
<p
id="land-error-contact_consent"
role="alert"
className="text-red-700"
>
{form.errors['payload.contact_consent']}
</p>
)}
<p className="rounded bg-amber-50 p-3 text-sm">
Ainda não carregue actas, documentos de identidade ou
informações sensíveis que não sejam necessárias à
orientação. Os anexos são opcionais e ficam reservados
quando enviados.
</p>
<p className="text-sm">
O estado da consulta e dos processos externos será
sempre apresentado como informação comunicada, não como
confirmação oficial.
</p>
</section>
)}
<footer className="flex flex-wrap justify-between gap-3 border-t pt-4">
<button
type="button"
disabled={step === 0}
className="rounded border px-4 py-2 disabled:opacity-50"
onClick={() => setStep(step - 1)}
>
Anterior
</button>
<div className="flex flex-wrap gap-3">
<button
type="button"
disabled={!canEdit || form.processing}
className="rounded border px-4 py-2 disabled:opacity-50"
onClick={save}
>
Guardar rascunho
</button>
{step < 3 ? (
<button
type="button"
className="rounded bg-emerald-800 px-4 py-2 text-white"
onClick={() => setStep(step + 1)}
>
Continuar
</button>
) : existing ? (
<button
type="button"
disabled={!canEdit || form.processing}
className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50"
onClick={support}
>
Solicitar apoio
</button>
) : (
<button
type="button"
disabled={form.processing}
className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50"
onClick={save}
>
Guardar rascunho e continuar para solicitar apoio
</button>
)}
</div>
</footer>
{Object.keys(form.errors).length > 0 && (
<div
id="land-error-summary"
tabIndex={-1}
role="alert"
className="rounded border border-red-500 p-3"
>
<p>Revise os campos assinalados antes de continuar.</p>
<ul>
{Object.entries(form.errors).map(([key, value]) => (
<li key={key}>
{requiredLabels[
key.replace(/^payload\./, '')
] ?? 'Campo assinalado'}
: {String(value)}
</li>
))}
</ul>
</div>
)}
{existing && (
<Link
href={`/investidor/terra-duat/${existing.id}`}
className="underline"
>
Voltar ao acompanhamento
</Link>
)}
</main>
);
}
function StatusField({
label,
value,
choices,
labels,
onChange,
}: {
label: string;
value: string;
choices: string[];
labels: string[];
onChange: (value: string) => void;
}) {
return (
<label className="block space-y-1">
<span className="text-sm font-medium">{label}</span>
<select
className="w-full rounded border p-2"
value={value ?? 'unknown'}
onChange={(e) => onChange(e.target.value)}
>
{choices.map((choice, i) => (
<option key={choice} value={choice}>
{labels[i]}
</option>
))}
</select>
</label>
);
}
function ParcelEditor({
index,
parcel,
onChange,
onRemove,
}: {
index: number;
parcel: Parcel;
onChange: (key: string, value: string) => void;
onRemove: () => void;
}) {
const [path, setPath] = useState<TerritoryOption[]>([]);
const [recoveryError, setRecoveryError] = useState('');
const [recovering, setRecovering] = useState(false);
const [recoveryRetry, setRecoveryRetry] = useState(0);
const provinceId = parcel.province_id ?? '';
const districtId = parcel.district_id ?? '';
const postId = parcel.admin_post_id ?? '';
const localityId = parcel.locality_id ?? '';
useEffect(() => {
const ids = [provinceId, districtId, postId, localityId];
const types = ['province', 'district', 'admin_post', 'locality'];
const labels = [
'Província',
'Distrito',
'Posto administrativo',
'Localidade',
];
const abort = new AbortController();
setRecoveryError('');
if (!ids.some(Boolean)) {
setPath([]);
setRecovering(false);
return;
}
setRecovering(true);
let level = 0;
void (async () => {
const result: TerritoryOption[] = [];
let parent = '';
for (level = 0; level < ids.length; level++) {
const savedId = ids[level];
if (!savedId) {
if (ids.slice(level + 1).some(Boolean))
throw new Error(
'Falta um nível anterior na localização guardada.',
);
break;
}
const params = new URLSearchParams({
type: types[level],
id: savedId,
...(parent ? { parent_id: parent } : {}),
});
const response = await fetch(
`/api/v1/investment/territory-options?${params}`,
{
signal: abort.signal,
headers: { Accept: 'application/json' },
},
);
if (!response.ok)
throw new Error(
`A consulta devolveu HTTP ${response.status}.`,
);
const body = await response.json();
const option = (
body.data as TerritoryOption[] | undefined
)?.find(
(row) =>
row.id === savedId &&
row.location_type === types[level] &&
(!parent || row.parent_id === parent),
);
if (!option)
throw new Error(
'A opção guardada não foi encontrada no nível e hierarquia indicados.',
);
result.push(option);
parent = option.id;
}
if (!abort.signal.aborted) setPath(result);
})()
.catch((error: unknown) => {
if (!abort.signal.aborted)
setRecoveryError(
`Não foi possível recuperar ${labels[level] ?? 'a localização'}. ${error instanceof Error ? error.message : 'Erro de ligação.'} Os identificadores guardados foram preservados; não volte a selecionar para contornar a falha.`,
);
})
.finally(() => {
if (!abort.signal.aborted) setRecovering(false);
});
return () => abort.abort();
}, [provinceId, districtId, postId, localityId, recoveryRetry]);
const initial = useMemo(() => path, [path]);
return (
<fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2">
<legend className="px-1 font-semibold">
Parcela/área {index + 1}
</legend>
{recovering && (
<p role="status">A recuperar a localização guardada…</p>
)}
{recoveryError && (
<div role="alert" className="sm:col-span-2">
<p>{recoveryError}</p>
<button
type="button"
onClick={() => setRecoveryRetry((value) => value + 1)}
>
Tentar recuperar novamente
</button>
</div>
)}
<div className="sm:col-span-2">
<TerritoryFields
disabled={recovering || Boolean(recoveryError)}
initial={initial}
endpoint="/api/v1/investment/territory-options"
onChange={(next) => {
(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).forEach((field, i) =>
onChange(field, next[i]?.id ?? ''),
);
}}
/>
</div>
<label className="space-y-1">
<span>Área estimada (se conhecida)</span>
<input
type="number"
min="0"
className="w-full rounded border p-2"
value={parcel.area ?? ''}
onChange={(e) => onChange('area', e.target.value)}
/>
</label>
<label className="space-y-1">
<span>Unidade</span>
<select
className="w-full rounded border p-2"
value={parcel.area_unit ?? ''}
onChange={(e) => onChange('area_unit', e.target.value)}
>
<option value="">Por confirmar</option>
<option value="m2">m²</option>
<option value="hectares">Hectares</option>
<option value="other">Outra</option>
<option value="unknown">Não sei</option>
</select>
</label>
<label className="space-y-1">
<span>Referência cadastral, se existente</span>
<input
className="w-full rounded border p-2"
value={parcel.cadastral_reference ?? ''}
onChange={(e) =>
onChange('cadastral_reference', e.target.value)
}
/>
</label>
<label className="space-y-1">
<span>Coordenadas ou planta, se disponíveis</span>
<input
className="w-full rounded border p-2"
value={parcel.coordinates ?? ''}
onChange={(e) => onChange('coordinates', e.target.value)}
/>
</label>
<label className="space-y-1">
<span>Precisão indicada</span>
<select
className="w-full rounded border p-2"
value={parcel.geometry_confidence ?? 'unknown'}
onChange={(e) =>
onChange('geometry_confidence', e.target.value)
}
>
<option value="declared">Declarada pelo requerente</option>
<option value="approximate">Aproximada</option>
<option value="confirmed_by_authority">
Confirmada por entidade, segundo documento referido
</option>
<option value="unknown">Por confirmar</option>
</select>
</label>
<label className="space-y-1 sm:col-span-2">
<span>Descrição do local</span>
<textarea
className="w-full rounded border p-2"
value={parcel.place_description ?? ''}
onChange={(e) =>
onChange('place_description', e.target.value)
}
/>
</label>
<button
type="button"
className="text-left text-sm underline"
onClick={onRemove}
>
Remover parcela
</button>
<p className="text-xs text-slate-600">
A selecção territorial e qualquer intersecção cartográfica não
confirmam direitos, limites ou disponibilidade.
</p>
</fieldset>
);
}