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; type Payload = Record; 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 = { 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 = { 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( 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, ) => ( ); 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 (
{returnDossier && ( Voltar ao dossier: {returnDossier.title} )} Terra e DUAT

Formulário de orientação e preparação

Modelo {modelVersion} {existing ? ` · Referência interna ${existing.reference} · versão ${existing.version}` : ''}

{disclaimer}

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.

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 }; }) } />
    {[ 'Pedido e requerente', 'Localização e situação', 'Plano e consulta', 'Rever', ].map((title, index) => (
  1. ))}
{step === 0 && (

A. Tipo de apoio e requerente

{form.errors['payload.support_kind'] && ( )} {text('request_description', 'Descrição do pedido', true)} {text( 'project_reference', 'Projecto/oportunidade já registado, se existir', )} {form.errors['payload.applicant_category'] && ( )} {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')} {form.errors['payload.preferred_contact'] && ( )}

País do requerente (opcional)

update('country', value)} label="País do requerente (opcional)" error={form.errors['payload.country']} allowLegacyValue />

País de origem declarado da solicitação (opcional)

update('declared_origin_country_code', value) } label="País de origem declarado da solicitação (opcional)" error={ form.errors[ 'payload.declared_origin_country_code' ] } />
{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', )}
)} {step === 1 && (

B. Localização, finalidade e situação conhecida

{form.errors['payload.area_status'] && ( )} {current.area_status !== 'seeking' && current.area_status !== 'unknown' && (current.parcels ?? []).map( (parcel: Parcel, index: number) => ( updateParcel(index, key, value) } onRemove={() => update( 'parcels', current.parcels.filter( (_: Parcel, i: number) => i !== index, ), ) } /> ), )} {areaStatus !== 'seeking' && ( )} {text('purpose', 'Uso pretendido *', true)} {text('activity', 'Actividade económica, se aplicável')} update('known_occupants', v)} /> {current.known_occupants === 'yes' && text( 'occupant_description', 'Descrição dos ocupantes/usos', )} update('known_improvements', v)} /> {current.known_improvements === 'yes' && text('improvements_description', 'Descrição')} update('prior_right_status', v)} /> {current.prior_right_status === 'yes' && text( 'prior_right_description', 'Descrição/referência dos antecedentes', )} 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' && (
Processo existente — informação comunicada pelo requerente {( [ 'official_reference', 'receiving_entity', 'presented_at', 'reported_status', 'pending_items', 'proof_available', ] as const ).map((key) => ( ))}
)}
)} {step === 2 && (

C. Plano de exploração e consulta comunitária (quando aplicável)

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.

{(current.exploration_plan?.activity_rows ?? []).map( (row: any, index: number) => (

Actividade {index + 1}

{( [ 'period', 'activity', 'area', 'area_unit', 'stage', 'targets', 'structures', 'investment', ] as const ).map((key) => ( ))}
), )} {(current.exploration_plan?.activity_rows?.length ?? 0) < 30 && ( )}