import { DossierPrefill } from '@/components/dossier-prefill'; import { contextApi } from '@/lib/investor-context'; import { valueText } from '@/lib/value-text'; import { Link, useForm } from '@inertiajs/react'; import { useState } from 'react'; import { Frame, Field, input, button, card } from './shared'; import type { References } from './shared'; import { Conversation } from './conversation'; import type { Message } from './conversation'; import CountrySelect, { type Country } from '@/components/country-select'; type Payload = { context_opportunity?: string; context_opportunity_snapshot?: string; simple_participation?: boolean; opportunity_title?: string; opportunity_reference?: string; full_name: string; email: string; phone: string; country: string; residence_country_code: string; incorporation_country_code: string; organization_country_snapshot?: { organization_id: string; organization_version: number; country: string; }; declared_origin_country_code: string; organisation: string; representative_role: string; experience: string; investment_capacity: string; other_details: string; profile_id: string; sector: string; objective: string; participation_id: string; partnership_id: string; estimated_amount: string; currency: string; horizon: string; location: string; cluster_ids: string[]; corridor_ids: string[]; project_ids: string[]; contact_consent: boolean; }; type Need = { category_id: string; option_id: string; unit_id: string; priority_id: string; quantity: string; deadline: string; details: { description: string; location: string; observations: string; qualification: string; specialty: string; experience: string; certifications: string; availability: string; institution: string; training_mode: string; duration: string; status: string; }; }; type Props = { contextDossierId?: string | null; contextChoices?: { id: string; title: string; version: number }[]; boundContextRevision?: number; countries: Country[]; zone_origin?: { zone_id: string; zone_version: number; intent: 'interest' | 'dossier' | 'meeting'; } | null; submission: { id: string; version: number; payload: Partial; opportunity_id?: number | null; dossier_id?: string | null; status: string; }; references: References; needs: Need[]; attachments: { id: string; file_name: string }[]; events: { action: string; version: number; created_at: string }[]; receipt: { reference: string; status: string; next_action?: string | null; next_action_due_at?: string | null; } | null; target: string | null; management: boolean; messages: Message[]; revisions: { version: number; created_at: string }[]; }; const emptyNeed = (): Need => ({ category_id: '', option_id: '', unit_id: '', priority_id: '', quantity: '', deadline: '', details: { description: '', location: '', observations: '', qualification: '', specialty: '', experience: '', certifications: '', availability: '', institution: '', training_mode: '', duration: '', status: '', }, }); export default function Submission(props: Props) { const [step, setStep] = useState(0); return ( ); } function Editor({ zone_origin, contextDossierId: initialContextId, contextChoices = [], boundContextRevision = 0, submission: s, references: r, needs, attachments, events, receipt, target, management, messages, revisions, step, setStep, countries, }: Props & { step: number; setStep: (step: number) => void }) { const [contextDossierId, setContextDossierId] = useState(initialContextId); const [chosenContext, setChosenContext] = useState(''); const [bindingBusy, setBindingBusy] = useState(false); const [bindingMessage, setBindingMessage] = useState(''); const initial: Payload = { full_name: '', email: '', phone: '', country: '', residence_country_code: '', incorporation_country_code: '', declared_origin_country_code: '', organisation: '', representative_role: '', experience: '', investment_capacity: '', other_details: '', profile_id: '', sector: '', objective: '', participation_id: '', partnership_id: '', estimated_amount: '', currency: '', horizon: '', location: '', cluster_ids: [], corridor_ids: [], project_ids: [], contact_consent: false, ...s.payload, }; const form = useForm({ version: s.version, context_revision: 0, context_reviewed: false, payload: initial, needs: needs.map((n) => ({ ...emptyNeed(), ...Object.fromEntries( Object.entries(n).filter(([k]) => [ 'category_id', 'option_id', 'unit_id', 'priority_id', 'quantity', 'deadline', 'details', ].includes(k), ), ), details: { ...emptyNeed().details, ...n.details }, })) as Need[], }); const upload = useForm<{ version: number; file: File | null }>({ version: s.version, file: null, }); const [note, setNote] = useState(''); const readonly = s.status !== 'draft' || management; const base = '/investidor/manifestacoes/' + s.id; const update = (key: K, value: Payload[K]) => form.setData('payload', { ...form.data.payload, [key]: value }); const text = ( key: keyof Payload, label: string, required = false, type = 'text', ) => ( { if (!e.target.validity.valid) setNote( `Verifique o campo ${label}: ${e.target.validationMessage}`, ); else setNote(''); }} value={valueText(form.data.payload[key] ?? '')} onChange={(e) => update(key, e.target.value as never)} maxLength={key === 'objective' ? 5000 : 2000} /> ); const option = ( key: 'profile_id' | 'participation_id' | 'partnership_id', group: string, label: string, ) => ( ); const updateNeed = (index: number, value: Need) => form.setData( 'needs', form.data.needs.map((n, i) => (i === index ? value : n)), ); const errorStep = (key: string) => key.startsWith('needs.') ? 2 : /payload\.(full_name|email|phone|country|profile_id|organisation|representative_role|sector|experience|investment_capacity)/.test( key, ) ? 0 : key === 'payload.contact_consent' ? 4 : 1; return (

{target ?? (zone_origin ? 'Pedido relativo a zona de investimento' : 'Interesse geral')}{' '} · Versão {s.version} ·{' '} {s.status === 'draft' ? 'Rascunho privado' : 'Submetido'}

Preparar apoio e acompanhamento deste projecto no Balcão Virtual {zone_origin && (

Consultar zona de origem {' '} · Versão da ficha {zone_origin.zone_version} ·{' '} { { interest: 'Manifestação de interesse', dossier: 'Pedido de dossier', meeting: 'Pedido de reunião', }[zone_origin.intent] } . Atendimento assistido, sem decisão administrativa automática.

)} {receipt && (

Protocolo: {receipt.reference} · Estado:{' '} {( { received: 'Recebido', in_review: 'Em análise', contacted: 'Contactado', closed: 'Encerrado', } as Record )[receipt.status] ?? receipt.status}

)} {receipt?.next_action && (

Próxima acção: {receipt.next_action}{' '} {receipt.next_action_due_at && new Date(receipt.next_action_due_at).toLocaleDateString( 'pt-MZ', )}

)} {s.status === 'submitted' && s.payload.simple_participation ? (

Dados da manifestação

{[ ['Nome', s.payload.full_name], ['Email', s.payload.email], ['Telefone', s.payload.phone], ['País declarado', s.payload.country], ['Sector', s.payload.sector], ['Oportunidade', target], ['Mensagem', s.payload.objective], ] .filter(([, value]) => value) .map(([label, value]) => (
{label}
{value}
))}
) : ( <>

Etapa {step + 1} de 5. Guarde antes de sair. A informação declarada não é publicada.

{!contextDossierId && !management && s.status === 'draft' && (

Reutilizar um dossier existente (opcional)

Pode continuar e submeter directamente sem criar um dossier. Associar reutiliza o contexto autorizado; campos já editados conservam-se.

{s.dossier_id && (

( `/investidor/manifestacoes/${s.id}/contexto`, { case_id: choice.id, case_version: choice.version, version: form.data.version, }, ); form.setData((d) => ({ ...d, version: result.version, })); setContextDossierId(result.case_id); setBindingMessage( 'Dossier associado. As suas edições foram preservadas; reveja os campos antes de submeter.', ); } catch (e) { setBindingMessage( e instanceof Error ? e.message : 'Não foi possível associar. Os campos foram preservados.', ); } finally { setBindingBusy(false); } }} > Associar este dossier e recuperar dados {bindingMessage && (

{bindingMessage}

)}
)} {contextDossierId && ( form.setData((d) => ({ ...d, context_revision: revision, context_reviewed: reviewed, })) } onApply={(patch, replace) => form.setData((d) => ({ ...d, payload: { ...d.payload, ...Object.fromEntries( Object.entries(patch) .filter( ([k]) => replace || !d.payload[ k as keyof Payload ], ) .map(([k, v]) => [ k, typeof v === 'string' ? v : '', ]), ), }, })) } /> )}
{ e.preventDefault(); form.put(base, { preserveScroll: true }); }} > {step === 0 && (
{text('full_name', 'Nome completo', true)} {text('email', 'Email', true, 'email')} {text('phone', 'Telefone')} {form.data.payload.country && (

País anteriormente registado:{' '} {form.data.payload.country}. Não foi convertido em residência, constituição ou origem.

)} {( [ 'residence_country_code', 'incorporation_country_code', 'declared_origin_country_code', ] as const ).map((key) => ( form.setData('payload', { ...form.data.payload, [key]: value, }) } /> ))} {s.payload.organization_country_snapshot && (

País copiado do{' '} cadastro mestre da organização , versão{' '} { s.payload .organization_country_snapshot .organization_version } :{' '} { s.payload .organization_country_snapshot .country } . Esta cópia conserva a origem; alterações posteriores do cadastro não alteram esta manifestação.

)}

Indique o país de onde apresenta este pedido, se desejar. Pode ser diferente do país de residência ou de constituição da entidade.

{option( 'profile_id', 'investor_profile', 'Perfil do investidor', )} {text('organisation', 'Organização / empresa')} {text( 'representative_role', 'Função do representante', )} {text('sector', 'Sector de interesse', true)} {text('experience', 'Experiência relevante')} {text( 'investment_capacity', 'Capacidade de investimento / especificação do perfil', )}
)} {step === 1 && (
{text( 'objective', 'Objectivo do investimento (mínimo 20 caracteres)', true, )}
{option( 'participation_id', 'participation', 'Modalidade de participação', )} {option( 'partnership_id', 'partnership', 'Modelo de parceria', )} {text( 'estimated_amount', 'Investimento estimado', false, 'number', )} {text( 'currency', 'Moeda (código de três letras)', )} {text('horizon', 'Prazo / horizonte', true)} {text('location', 'Localização pretendida')}
{( [ 'clusters', 'corridors', 'projects', ] as const ).map((group, i) => { const key = ( [ 'cluster_ids', 'corridor_ids', 'project_ids', ] as const )[i]; return (
{ [ 'Clusters', 'Corredores', 'Projectos âncora', ][i] } {r[group].map((entity) => ( ))}
); })}
)} {step === 2 && (

Mão de obra, infraestruturas, formação e apoios

Acrescente o que existe no local e o que necessita. As opções são mantidas pela gestão; use Outro para especificar casos adicionais.

{form.data.needs.map((need, index) => { const category = r.options.find( (o) => valueText(o.id) === valueText(need.category_id), )?.code ?? ''; const group = category.startsWith('labour') ? 'labour' : category.startsWith('infrastructure') ? 'infrastructure' : category === 'education' ? 'education' : 'support'; const needSelect = ( field: | 'category_id' | 'option_id' | 'unit_id' | 'priority_id', optionGroup: string, label: string, ) => ( ); return (
Necessidade {index + 1}
{needSelect( 'category_id', 'need_category', 'Categoria', )} {needSelect( 'option_id', group, 'Tipo', )} {needSelect( 'unit_id', 'unit', 'Unidade', )} {needSelect( 'priority_id', 'priority', 'Prioridade', )} updateNeed(index, { ...need, quantity: e.target .value, }) } /> updateNeed(index, { ...need, deadline: e.target .value, }) } />
{( [ 'description', 'location', 'observations', ...(group === 'labour' ? [ 'qualification', 'specialty', 'experience', 'certifications', 'availability', 'institution', ] : []), ...(group === 'education' ? [ 'qualification', 'institution', 'training_mode', 'duration', 'certifications', ] : []), ] as (keyof Need['details'])[] ).map((field) => (