102 lines
24 KiB
TypeScript
102 lines
24 KiB
TypeScript
import { Link, useForm } from '@inertiajs/react';
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
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 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: '', 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 }: { case: { id: string; reference: string; version: number; status: string; payload: Payload } | null; user: { name: string; email: string }; disclaimer: string; modelVersion: string }) {
|
|
const [step, setStep] = useState(0);
|
|
const initial = useMemo(() => existing?.payload ?? emptyPayload(user), [existing?.id]);
|
|
const form = useForm({ version: existing?.version ?? 1, payload: initial });
|
|
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 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}`])} />{help && <span className="block text-xs text-slate-600">{help}</span>}{form.errors[`payload.${key}`] && <span 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"><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>
|
|
<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="sm:col-span-2 text-xl font-semibold">A. Tipo de apoio e requerente</h2>
|
|
<label className="space-y-1"><span className="text-sm font-medium">Pretende apoio para *</span><select 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>
|
|
{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 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>
|
|
{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 ?? ''} 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>
|
|
{text('country', 'País, se aplicável')}{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 ?? ''} 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>
|
|
{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="sm:col-span-2 font-semibold">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" 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><label className="flex gap-2"><input type="checkbox" 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><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 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}>{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[]>([]);
|
|
useEffect(()=>{
|
|
const ids=['province_id','district_id','admin_post_id','locality_id'].map(k=>parcel[k]).filter(Boolean);
|
|
if (!ids.length) { setPath([]); return; }
|
|
const abort=new AbortController();
|
|
void (async()=>{const result:TerritoryOption[]=[];let parent='';for(let i=0;i<ids.length;i++){const type=['province','district','admin_post','locality'][i];const params=new URLSearchParams({type,id:ids[i],...(parent?{parent_id:parent}:{})});const response=await fetch(`/api/v1/investment/territory-options?${params}`,{signal:abort.signal,headers:{Accept:'application/json'}});if(!response.ok)break;const body=await response.json();const option=body.data?.[0] as TerritoryOption|undefined;if(!option)break;result.push(option);parent=option.id;}if(!abort.signal.aborted)setPath(result);})().catch(()=>{});
|
|
return ()=>abort.abort();
|
|
},[]);
|
|
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><div className="sm:col-span-2"><TerritoryFields 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>;
|
|
}
|