varias alteracoes
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-06 14:50:12 +02:00
parent 4f35313d06
commit e65cb26901
333 changed files with 54656 additions and 2058 deletions
@@ -0,0 +1,23 @@
import type { ReactNode } from 'react';
export default function Blank({ disclaimer }: { disclaimer: string }) {
return <main className="mx-auto max-w-4xl space-y-6 p-8 print:max-w-none print:p-0">
<div className="flex justify-end print:hidden"><button className="rounded border px-4 py-2" onClick={() => window.print()}>Imprimir / guardar como PDF</button></div>
<header className="space-y-2 border-b pb-4"><p>InvestMoz · modelo de preparação · versão land-assistance-v1</p><h1 className="text-2xl font-bold">Formulário de orientação e preparação — Terra e DUAT</h1><p>{disclaimer}</p></header>
<p>Preencha apenas o que sabe. Use “Não sei” ou “Por confirmar”. Este modelo imprimível não é um PDF electrónico preenchível nem formulário oficial.</p>
<Section title="A. Tipo de apoio"><Lines items={['Terra para investimento', 'Habitação', 'Exploração familiar', 'Reconhecimento ou titulação de área ocupada', 'Regularização cadastral', 'Delimitação ou demarcação', 'Alteração de uso/área', 'Transmissão/herança', 'Acompanhamento de processo', 'Conflito/restrição', 'Outro']} /><Line label="Descrição do pedido" /><Line label="Modalidade invocada, se conhecida" /><Line label="Projecto ou oportunidade no InvestMoz" /></Section>
<Section title="B. Requerente"><Lines items={['Pessoa singular', 'Pessoa colectiva', 'Comunidade', 'Outra categoria']} /><Line label="Nome ou denominação" /><Line label="Pessoa de contacto" /><Line label="Email" /><Line label="Telefone" /><Line label="Canal preferido de resposta" /><Line label="País/nacionalidade (se aplicável)" /><Line label="Representante, qualidade e fundamento (se aplicável)" /><Line label="NUIT/identificação (apenas se necessário ao acto concreto)" /></Section>
<Section title="C. Localização"><Lines items={['Tenho área identificada', 'Procuro localização', 'Preciso de apoio para localizar']} />{['Província','Distrito/município','Posto administrativo','Localidade/bairro/comunidade','Descrição do local','Área e unidade','Referência cadastral (se existente)','Coordenadas/planta (se disponíveis)'].map((label) => <Line key={label} label={label} />)}</Section>
<Section title="D. Finalidade e situação conhecida"><Line label="Uso pretendido e actividade, se aplicável" />{['Ocupantes/utilizações conhecidas? Sim / Não segundo informação disponível / Não sei','Descrição','Construções, benfeitorias, machambas, servidões ou usos comunitários?','Título, autorização ou antecedentes?','Conflito, oposição ou possível sobreposição?','Descrição'].map((label) => <Line key={label} label={label} />)}<p>As respostas são declarações do requerente, não conclusões cadastrais.</p></Section>
<Section title="E. Processo existente"><Line label="Número oficial, se já atribuído" /><Line label="Entidade receptora e data apresentada" /><Line label="Estado comunicado pela entidade" /><Line label="Pendências e comprovativo disponível" /></Section>
<Section title="F. Plano de exploração, se aplicável"><p>Indique períodos livremente; não existe duração obrigatória presumida por este modelo.</p>{['Actividade e período','Área/unidade','Existente ou planeado','Metas e construções','Investimento previsto'].map((label) => <Line key={label} label={label} />)}</Section>
<Section title="G. Consulta comunitária e pareceres"><p>Esta secção serve apenas para preparar/registar informação. Não declarar consulta realizada sem evidência.</p>{['Comunidade/local/data','Participantes e funções','Língua/tradução','Intervenções e divergências','Oposição','Acordos e compromissos','Acta, assinaturas e pareceres recebidos'].map((label) => <Line key={label} label={label} />)}</Section>
<Section title="H. Documentos opcionais nesta fase"><Lines items={['Planta/esboço','Título ou antecedente','Plano de exploração','Recibo/comunicação oficial','Acta de consulta','Fotografias','Outros']} /><Line label="Informação complementar" /></Section>
<footer className="space-y-2 border-t pt-4"><p>Confirmo que os dados correspondem à informação de que disponho e que identifiquei as dúvidas conhecidas.</p><Line label="Data, nome do requerente/representante e assinatura (só na versão impressa, quando aplicável)"/><p className="font-semibold">{disclaimer}</p></footer>
<style>{'@media print { button { display: none } section { break-inside: avoid } }'}</style>
</main>;
}
function Section({ title, children }: { title: string; children: ReactNode }) { return <section className="space-y-3 rounded border p-4"><h2 className="text-lg font-bold">{title}</h2>{children}</section>; }
function Line({ label }: { label: string }) { return <div className="space-y-1"><span className="text-sm">{label}</span><div className="min-h-8 border-b border-dotted border-slate-500" /></div>; }
function Lines({ items }: { items: string[] }) { return <div className="grid gap-2 sm:grid-cols-2">{items.map((item) => <div key={item}>☐ {item}</div>)}</div>; }
@@ -0,0 +1,35 @@
import { Link, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
type Props = {
case: { id: string; reference: string; version: number; status: string; payload: Record<string, any>; updated_at: string };
documents: { id: string; category: string; file_name: string; status: 'active'|'quarantined' }[];
events: { action: string; version: number; metadata: Record<string, unknown>; created_at: string }[];
disclaimer: string;
management: boolean;
};
const statusLabels: Record<string,string> = { draft:'Rascunho privado', support_requested:'Apoio solicitado ao InvestMoz', internal_review:'Análise interna', waiting_applicant:'A aguardar informação do requerente', referral_prepared:'Encaminhamento preparado (não submetido)', closed:'Encerrado no InvestMoz' };
const actionLabels: Record<string,string> = { draft_created:'Rascunho criado', draft_updated:'Rascunho actualizado', support_requested:'Pedido de apoio registado', status_changed:'Estado interno actualizado', attachment_added:'Documento anexado', applicant_update_recorded:'Actualização comunicada pelo requerente' };
const categoryLabels: Record<string,string> = { sketch:'Planta/esboço', prior_right:'Antecedente de direito', exploration_plan:'Plano de exploração', official_receipt:'Recibo/comunicação oficial', consultation_minutes:'Acta/minuta', photo:'Fotografia', other:'Outro' };
export default function LandCase({case: record, documents, events, disclaimer, management}:Props) {
const [file,setFile]=useState<File|null>(null);
const [category,setCategory]=useState('other');
const [status,setStatus]=useState('internal_review');
const upload=useForm({version:record.version,category,file:null as File|null});
const report=useForm({version:record.version,reported_status:'',official_reference:'',receiving_entity:'',reported_at:''});
const change=useForm({version:record.version,status:'internal_review',evidence_reference:''});
const canEdit=['draft','waiting_applicant'].includes(record.status);
const payload=record.payload??{};
const supportKinds:Record<string,string>={investment:'Terra para investimento',home:'Habitação',family_exploitation:'Exploração familiar',recognition:'Reconhecimento/titulação',regularization:'Regularização cadastral',delimitation:'Delimitação/demarcação',change_of_use:'Alteração de uso/área',transfer:'Transmissão/herança',existing_process:'Processo existente',conflict_guidance:'Orientação sobre conflito/restrição',other:'Outro'};
return <main className="mx-auto max-w-5xl space-y-6 p-6">
<header className="space-y-2"><Link href="/investidor/terra-duat" className="underline">Os meus pedidos Terra e DUAT</Link><h1 className="text-3xl font-bold">Acompanhamento {record.reference}</h1><p>Referência interna InvestMoz · versão {record.version} · {statusLabels[record.status]??record.status}</p><p className="rounded border border-amber-400 bg-amber-50 p-3">{disclaimer}</p>{record.status==='referral_prepared'&&<p className="rounded bg-amber-50 p-3">O encaminhamento foi preparado internamente. Não há confirmação de submissão nem de recepção por entidade pública.</p>}</header>
{!management&&canEdit&&<Link className="inline-block rounded border px-4 py-2" href={`/investidor/terra-duat/${record.id}/editar`}>Continuar preenchimento</Link>}
{!management&&<Link className="ml-3 inline-block rounded border px-4 py-2" href={`/investidor/terra-duat/${record.id}/imprimir`}>Imprimir / guardar cópia preenchida como PDF</Link>}
<section className="grid gap-4 rounded border p-4 sm:grid-cols-2"><h2 className="sm:col-span-2 text-xl font-semibold">Resumo informado pelo requerente</h2><p><strong>Tipo:</strong> {supportKinds[payload.support_kind]??'Por indicar'}</p><p><strong>Requerente:</strong> {payload.full_name??'Por indicar'}</p><p><strong>Categoria:</strong> {payload.applicant_category??'Por indicar'}</p><p><strong>Contacto preferido:</strong> {payload.preferred_contact??'Por indicar'}</p><p className="sm:col-span-2"><strong>Descrição:</strong> {payload.request_description??'Por indicar'}</p><p className="sm:col-span-2"><strong>Uso pretendido:</strong> {payload.purpose??'Por indicar'}</p><p className="sm:col-span-2"><strong>Localização declarada:</strong> {(payload.parcels??[]).map((parcel:any)=>parcel.place_description).filter(Boolean).join('; ')||'Por localizar/confirmar'}</p><p className="sm:col-span-2 text-sm">Dados e situação geográfica aqui exibidos são declarações do requerente; não confirmam direitos ou disponibilidade cadastral.</p></section>
{!management&&<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Comunicar actualização</h2><p className="text-sm">A informação fica identificada como comunicada por si e não é confirmada automaticamente pelo InvestMoz.</p><label className="block space-y-1"><span>Actualização do estado *</span><textarea className="w-full rounded border p-2" value={report.data.reported_status} onChange={e=>report.setData('reported_status',e.target.value)} maxLength={1000}/></label><div className="grid gap-3 sm:grid-cols-3"><label>Referência oficial (se tiver)<input className="mt-1 w-full rounded border p-2" value={report.data.official_reference} onChange={e=>report.setData('official_reference',e.target.value)}/></label><label>Entidade indicada<input className="mt-1 w-full rounded border p-2" value={report.data.receiving_entity} onChange={e=>report.setData('receiving_entity',e.target.value)}/></label><label>Data indicada<input type="date" className="mt-1 w-full rounded border p-2" value={report.data.reported_at} onChange={e=>report.setData('reported_at',e.target.value)}/></label></div><button className="rounded border px-4 py-2" disabled={!report.data.reported_status||report.processing} onClick={()=>router.post(`/investidor/terra-duat/${record.id}/actualizacoes`,report.data,{preserveScroll:true})}>Registar informação comunicada</button></section>}
<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Documentos anexados</h2>{documents.map((document)=><p key={document.id}>{document.status==='active'?<a className="underline" href={`/investidor/terra-duat/${record.id}/documentos/${document.id}`}>{categoryLabels[document.category]??document.category}: {document.file_name}</a>:<span>{categoryLabels[document.category]??document.category}: {document.file_name} · em quarentena; leitura/descarga bloqueada até verificação</span>}</p>)}{!documents.length&&<p>Nenhum documento anexado. Anexos são opcionais nesta fase.</p>}{!management&&record.status!=='closed'&&<div className="grid gap-3 sm:grid-cols-3"><label>Categoria<select className="mt-1 w-full rounded border p-2" value={category} onChange={e=>setCategory(e.target.value)}>{Object.entries(categoryLabels).map(([key,label])=><option value={key} key={key}>{label}</option>)}</select></label><label className="sm:col-span-2">Ficheiro PDF/JPG/PNG (até 10 MB)<input className="mt-1 w-full rounded border p-2" type="file" accept=".pdf,.jpg,.jpeg,.png" onChange={e=>setFile(e.target.files?.[0]??null)}/></label><button className="rounded border px-4 py-2" disabled={!file||upload.processing} onClick={()=>router.post(`/investidor/terra-duat/${record.id}/documentos`,{version:record.version,category,file},{forceFormData:true,preserveScroll:true})}>Anexar em espaço privado</button></div>}<p className="text-sm">Os ficheiros são reservados; anexar não equivale a verificação, validação cadastral ou parecer oficial. O ambiente não tem antivírus configurado, por isso os uploads ficam em quarentena e não podem ser descarregados até verificação.</p></section>
<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Histórico no InvestMoz</h2>{events.map((event,index)=><div className="border-l-2 pl-3" key={`${event.version}-${index}`}><p className="font-medium">{actionLabels[event.action]??event.action}</p><p className="text-sm">{new Date(event.created_at).toLocaleString('pt-MZ')} · versão {event.version}</p>{event.action==='applicant_update_recorded'&&<p className="text-xs">Actualização comunicada pelo requerente; não verificada externamente.</p>}{event.action==='status_changed'&&event.metadata?.external_submission_confirmed===false&&<p className="text-xs">Transição de estado interno; submissão oficial não confirmada.</p>}</div>)}</section>
{management&&<section className="space-y-3 rounded border border-slate-400 p-4"><h2 className="text-xl font-semibold">Gestão interna</h2><label className="block">Estado interno<select className="mt-1 w-full rounded border p-2" value={change.data.status} onChange={e=>change.setData('status',e.target.value)}><option value="internal_review">Análise interna</option><option value="waiting_applicant">A aguardar requerente</option><option value="referral_prepared">Encaminhamento preparado (não enviado)</option><option value="closed">Encerrado no InvestMoz</option></select></label>{change.data.status==='referral_prepared'&&<label className="block">Referência interna da preparação<input className="mt-1 w-full rounded border p-2" value={change.data.evidence_reference} onChange={e=>change.setData('evidence_reference',e.target.value)}/></label>}<button className="rounded bg-slate-800 px-4 py-2 text-white" disabled={change.processing} onClick={()=>router.patch(`/management/terra-duat/${record.id}/estado`,{...change.data,version:record.version},{preserveScroll:true})}>Actualizar estado interno</button></section>}
</main>;
}
+101
View File
@@ -0,0 +1,101 @@
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>;
}
@@ -0,0 +1,24 @@
import { Link } from '@inertiajs/react';
export default function Guide({ disclaimer }: { disclaimer: string }) {
return <main className="mx-auto max-w-5xl space-y-8 p-6 print:p-0">
<header className="space-y-3">
<p className="text-sm font-semibold uppercase tracking-wide">InvestMoz · orientação informativa</p>
<h1 className="text-3xl font-bold">Terra e DUAT</h1>
<p>Prepare informação sobre uma área, um pedido ou um processo que já acompanha. Pode indicar dúvidas e dados por confirmar.</p>
<p className="rounded border border-amber-400 bg-amber-50 p-4 text-sm">{disclaimer}</p>
</header>
<section className="grid gap-4 md:grid-cols-3">
<article className="rounded border p-4"><h2 className="font-semibold">Preparar informação</h2><p>Identifique a finalidade, o requerente, a localização conhecida e os antecedentes que tiver.</p></article>
<article className="rounded border p-4"><h2 className="font-semibold">Organizar documentos</h2><p>Anexos são opcionais nesta fase. A lista não substitui os requisitos confirmados pela entidade competente.</p></article>
<article className="rounded border p-4"><h2 className="font-semibold">Acompanhar</h2><p>Guarde uma referência interna e registe separadamente informações comunicadas por si e diligências internas.</p></article>
</section>
<p className="rounded bg-slate-50 p-4">Não inferimos que uma área está livre, que não existem direitos ou conflitos, nem que um registo ou mapa confirma titularidade. O InvestMoz não atribui DUAT nem substitui a autoridade pública.</p>
<nav className="flex flex-wrap gap-4">
<Link className="rounded bg-emerald-800 px-4 py-3 text-white" href="/investidor/terra-duat/novo">Preencher no portal</Link>
<Link className="rounded border px-4 py-3" href="/terra-duat/formulario-em-branco">Descarregar formulário em branco (imprimir/guardar como PDF)</Link>
<Link className="rounded border px-4 py-3" href="/apoio">Solicitar apoio geral</Link>
</nav>
<details className="rounded border p-4"><summary className="cursor-pointer font-semibold">Estado das fontes e requisitos</summary><p className="mt-3">Os modelos digitalizados estão inventariados como referências reservadas. Conteúdo, actualidade e requisitos legais aguardam OCR, conferência oficial e revisão. Não use esta orientação como checklist oficial.</p></details>
</main>;
}
@@ -0,0 +1,4 @@
import { Link } from '@inertiajs/react';
type Row={id:string;reference:string;status:string;version:number;applicant:string|null;updated_at:string};
const labels:Record<string,string>={draft:'Rascunho',support_requested:'Apoio solicitado',internal_review:'Análise interna',waiting_applicant:'A aguardar requerente',referral_prepared:'Encaminhamento preparado (não enviado)',closed:'Encerrado'};
export default function Management({cases}:{cases:{data:Row[];prev_page_url:string|null;next_page_url:string|null}}){return <main className="mx-auto max-w-6xl space-y-6 p-6"><header><h1 className="text-3xl font-bold">Gestão — Terra e DUAT</h1><p>Fila interna. Não representa protocolo com autoridade pública.</p></header><div className="overflow-x-auto"><table className="w-full border-collapse text-left"><thead><tr><th className="border p-2">Referência interna</th><th className="border p-2">Requerente</th><th className="border p-2">Estado InvestMoz</th><th className="border p-2">Versão/actualização</th><th className="border p-2">Acção</th></tr></thead><tbody>{cases.data.map(row=><tr key={row.id}><td className="border p-2">{row.reference}</td><td className="border p-2">{row.applicant??'—'}</td><td className="border p-2">{labels[row.status]??row.status}</td><td className="border p-2">{row.version} · {new Date(row.updated_at).toLocaleString('pt-MZ')}</td><td className="border p-2"><Link className="underline" href={`/management/terra-duat/${row.id}`}>Abrir</Link></td></tr>)}</tbody></table></div>{!cases.data.length&&<p>Sem pedidos registados.</p>}<nav className="flex gap-4">{cases.prev_page_url&&<Link href={cases.prev_page_url}>Anterior</Link>}{cases.next_page_url&&<Link href={cases.next_page_url}>Seguinte</Link>}</nav></main>;}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
import { Link } from '@inertiajs/react';
type CaseRow={id:string;reference:string;status:string;version:number;updated_at:string};
const labels:Record<string,string>={draft:'Rascunho privado',support_requested:'Apoio solicitado ao InvestMoz',internal_review:'Análise interna',waiting_applicant:'A aguardar informação',referral_prepared:'Encaminhamento preparado (não enviado)',closed:'Encerrado no InvestMoz'};
export default function Workspace({cases}:{cases:{data:CaseRow[];prev_page_url:string|null;next_page_url:string|null}}){return <main className="mx-auto max-w-5xl space-y-6 p-6"><header><h1 className="text-3xl font-bold">Os meus pedidos — Terra e DUAT</h1><p>As referências e estados são internos do InvestMoz.</p></header><Link className="inline-block rounded bg-emerald-800 px-4 py-3 text-white" href="/terra-duat">Orientação Terra e DUAT</Link> <Link className="ml-2 inline-block rounded border px-4 py-3" href="/investidor/terra-duat/novo">Preparar novo pedido</Link><section className="space-y-3">{cases.data.map((record)=><article key={record.id} className="rounded border p-4"><Link href={`/investidor/terra-duat/${record.id}`} className="font-semibold underline">{record.reference}</Link><p>{labels[record.status]??record.status} · versão {record.version}</p><p className="text-sm">Actualizado {new Date(record.updated_at).toLocaleString('pt-MZ')}</p></article>)}{!cases.data.length&&<p>Ainda não tem rascunhos ou pedidos de apoio.</p>}</section><nav className="flex gap-4">{cases.prev_page_url&&<Link href={cases.prev_page_url}>Anterior</Link>}{cases.next_page_url&&<Link href={cases.next_page_url}>Seguinte</Link>}</nav></main>;}