import { useCallback, useEffect, useRef, useState } from 'react'; import { router } from '@inertiajs/react'; import CountrySelect, { type Country } from '@/components/country-select'; import { Frame, Field, input, button, card, api } from './shared'; import type { Business } from './business-types'; import { businessModalities } from './business-types'; import BusinessObjects from './business-objects'; import type { BusinessObject } from './business-objects'; import BusinessPointSummary, { type RegisteredBusinessLocation, } from '@/components/business-point-summary'; import { decodeBusinessLocations, emptyBusinessLocation, encodeBusinessLocations, hasDuplicateBusinessLocationPath, locationPathFromPayload, updateBusinessLocation, businessPointTerritoryKey, businessPointRequiredFields, } from '../../lib/business-locations'; export type FormSchema = Record< string, { step: number; pt: string; en: string; type: string; max: number; options?: Record; when?: Record; } >; type Props = { countries: Country[]; record: Business; modalities: string[]; formSchema: FormSchema; modalityFormType?: string | null; objects: BusinessObject[]; objectKinds: string[]; sectors: { id: number; name: string }[]; registeredLocation?: RegisteredBusinessLocation | null; pointPublicationAvailable?: boolean; }; const steps = [ ['Proponente', 'Applicant'], ['Representação', 'Representation'], ['Oportunidade', 'Opportunity'], ['Valor', 'Value'], ['Localização', 'Location'], ['Activos e direitos', 'Assets and rights'], ['Fontes', 'Sources'], ['Resumo e confirmação', 'Summary and confirmation'], ]; const requiredFields = new Set([ 'proponent_type', 'proponent_name', 'contact_name', 'country', 'acting_capacity', 'title', 'opportunity_type', 'description', 'project_stage', 'availability', 'value_status', 'geography_scope', 'source_reference', 'source_provider', 'source_date', 'confirm_information', 'confirm_disclosure_authority', 'confirm_no_publication_guarantee', ]); function toScaledAmount(value: string | undefined): bigint | null { if (!value) return null; const match = /^(\d{1,15})(?:\.(\d{1,4}))?$/.exec(value); if (!match) return null; return BigInt(match[1]) * 10_000n + BigInt((match[2] ?? '').padEnd(4, '0')); } function fundingReconciliationWarning( payload: Record, ): boolean { if (payload.opportunity_type !== 'investment_project') return false; const total = toScaledAmount(payload.investment_total); const secured = toScaledAmount(payload.amount_secured); const sought = toScaledAmount(payload.amount_sought); const hasFundingInput = Boolean( payload.amount_secured || payload.amount_sought, ); if (total === null || !hasFundingInput) return false; return secured === null || sought === null || secured + sought !== total; } const territoryField = { province_id: { type: 'province', parent: '' }, district_id: { type: 'district', parent: 'province_id' }, admin_post_id: { type: 'admin_post', parent: 'district_id' }, locality_id: { type: 'locality', parent: 'admin_post_id' }, } as const; function TerritoryField({ name, type, parentId, value, onChange, required = false, }: { name: string; type: string; parentId: string; value: string; onChange: (value: string) => void; required?: boolean; }) { const [query, setQuery] = useState(''); const [options, setOptions] = useState<{ id: string; name: string }[]>([]); const [error, setError] = useState(''); useEffect(() => { let active = true; if (type !== 'province' && !parentId) { setOptions([]); return () => { active = false; }; } const parameters = new URLSearchParams({ type }); if (parentId) parameters.set('parent_id', parentId); if (query.trim()) parameters.set('q', query.trim()); if (value) parameters.set('id', value); void api(`/api/v1/investment/territory-options?${parameters}`) .then((result: { data: { id: string; name: string }[] }) => { if (active) { setOptions(result.data ?? []); setError(''); } }) .catch((cause) => { if (active) setError( cause instanceof Error ? cause.message : 'Falha ao carregar localizações.', ); }); return () => { active = false; }; }, [type, parentId, query, value]); return (
setQuery(event.target.value)} /> {error && (

{error}

)}
); } export default function BusinessWizard({ countries, record, formSchema, modalityFormType, objects, objectKinds, sectors, registeredLocation, pointPublicationAvailable, }: Props) { const [english, setEnglish] = useState(false); const t = (pt: string, en: string) => (english ? en : pt); const [payload, setPayload] = useState(() => { const initial: Business['payload'] = { ...record.payload, opportunity_type: record.payload.opportunity_type ?? modalityFormType ?? '', wizard_version: '2', }; if ( initial.geography_scope === 'multiple' && decodeBusinessLocations(initial.locations_json).length === 0 ) { initial.locations_json = encodeBusinessLocations([ locationPathFromPayload(initial), ]); } return initial; }); const modality = record.modality; const pointRequired = businessPointRequiredFields(payload); const [sectorId, setSectorId] = useState(record.sector_id ?? null); const [sectorSearch, setSectorSearch] = useState(''); const [publicTitle, setPublicTitle] = useState(record.public_title ?? ''); const [territoryPaths, setTerritoryPaths] = useState( record.territory_paths ?? [], ); const [resolvedLocationJson, setResolvedLocationJson] = useState( record.payload.locations_json ?? '', ); const [version, setVersion] = useState(record.version_no); const versionRef = useRef(record.version_no); const saved = useRef( JSON.stringify({ payload: record.payload, modality: record.modality, sectorId: record.sector_id ?? null, publicTitle: record.public_title ?? '', }), ); const inFlight = useRef(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [consent, setConsent] = useState(false); const [confirmation, setConfirmation] = useState(''); const heading = useRef(null); const step = Math.max(1, Math.min(8, Number(payload.wizard_step ?? 1))); const serialized = JSON.stringify({ payload, modality, sectorId, publicTitle, }); const dirty = serialized !== saved.current; const submissionBlockers: string[] = []; if (busy) submissionBlockers.push( t('Aguarde que a gravação termine.', 'Wait for saving to finish.'), ); if (!consent) submissionBlockers.push( t( 'Marque a confirmação de exactidão e autorização de análise interna, junto ao código.', 'Check the accuracy and internal review consent box beside the code.', ), ); if (confirmation !== record.code) submissionBlockers.push( confirmation.trim() === record.code ? t( 'Retire os espaços antes ou depois do código MNE.', 'Remove spaces before or after the MNE code.', ) : t( 'Introduza o código MNE completo mostrado no topo desta página, incluindo MNE- e os hífenes.', 'Enter the full MNE code shown at the top of this page, including MNE- and the hyphens.', ), ); for (const [key, pt, en] of [ [ 'confirm_information', 'Confirme que a informação corresponde ao que conhece.', 'Confirm that the information reflects your knowledge.', ], [ 'confirm_disclosure_authority', 'Confirme que tem autorização para apresentar a oportunidade e divulgar os conteúdos seleccionados.', 'Confirm your authority to present the opportunity and disclose the selected content.', ], [ 'confirm_no_publication_guarantee', 'Confirme que compreende que a submissão não constitui publicação, aprovação oficial ou garantia de investimento.', 'Confirm that submission does not constitute publication, official approval or an investment guarantee.', ], ]) { if (payload[key] !== 'yes') submissionBlockers.push(t(pt, en)); } const save = useCallback(async () => { if (inFlight.current) return false; if (serialized === saved.current) return true; inFlight.current = true; setBusy(true); setError(''); try { const result: Business = await api( `/api/v1/existing-business/listings/${record.id}`, { _method: 'PUT', payload, modality, sector_id: sectorId, public_title: publicTitle || null, classification: record.classification, reason: 'Gravação do formulário privado por etapas', version_no: versionRef.current, }, ); versionRef.current = result.version_no; setTerritoryPaths(result.territory_paths ?? []); setResolvedLocationJson(result.payload.locations_json ?? ''); saved.current = serialized; setVersion(result.version_no); return true; } catch (e) { setError( e instanceof Error ? e.message : 'Não foi possível guardar / Save failed', ); return false; } finally { inFlight.current = false; setBusy(false); } }, [ serialized, payload, modality, sectorId, publicTitle, record.id, record.classification, ]); useEffect(() => { if (!dirty || busy || error) return; const timer = setTimeout(() => { void save(); }, 3000); return () => clearTimeout(timer); }, [dirty, busy, error, save]); useEffect(() => { const protect = (event: BeforeUnloadEvent) => { if (dirty || busy) { event.preventDefault(); event.returnValue = ''; } }; window.addEventListener('beforeunload', protect); return () => window.removeEventListener('beforeunload', protect); }, [dirty, busy]); useEffect(() => { heading.current?.focus(); }, [step]); useEffect( () => router.on('before', (event) => { if ( serialized !== saved.current && !window.confirm( 'Existem alterações por guardar. Sair? / Unsaved changes. Leave?', ) ) event.preventDefault(); }), [serialized], ); const update = (key: string, value: string) => { setError(''); setPayload((current) => { const next = { ...current, [key]: value }; if (key === 'geography_scope' && value === 'multiple') { const rows = decodeBusinessLocations(current.locations_json); if (!rows.length) { rows.push(locationPathFromPayload(current)); } next.locations_json = encodeBusinessLocations(rows); } if (key === 'geography_scope' && value === 'specific') { const first = decodeBusinessLocations( current.locations_json, )[0]; if (first?.province_id) { next.province_id = first.province_id; next.district_id = first.district_id; next.admin_post_id = first.admin_post_id; next.locality_id = first.locality_id; } } const dependencies: Record = { province_id: ['district_id', 'admin_post_id', 'locality_id'], district_id: ['admin_post_id', 'locality_id'], admin_post_id: ['locality_id'], }; for (const child of dependencies[key] ?? []) delete next[child]; if (key === 'opportunity_type') { const conditional = [ 'asking_value', 'value_status', 'value_meaning', 'value_nature', 'currency', 'amount_secured', 'investment_total', 'amount_sought', 'equity_percentage', 'asset_deal_kind', 'partnership_contribution', 'asset_modality', 'concession_entity', 'concession_reference', 'supply_description', ]; for (const field of conditional) delete next[field]; } return next; }); }; const locationRows = decodeBusinessLocations(payload.locations_json); const saveLocationRows = ( rows: ReturnType, ) => { update('locations_json', encodeBusinessLocations(rows)); }; const setLocation = ( index: number, key: keyof ReturnType, value: string, ) => saveLocationRows( updateBusinessLocation(locationRows, index, key, value), ); const addLocation = () => { if (locationRows.length >= 20) return; saveLocationRows([...locationRows, emptyBusinessLocation()]); }; const removeLocation = (index: number) => { const remaining = locationRows.filter( (_, rowIndex) => rowIndex !== index, ); saveLocationRows( remaining.length ? remaining : [emptyBusinessLocation()], ); }; const duplicateLocationPath = hasDuplicateBusinessLocationPath(locationRows); const fundingNeedsReconciliation = fundingReconciliationWarning(payload); const submit = async () => { if ( payload.geography_scope === 'multiple' && (locationRows.length < 2 || locationRows.some((location) => !location.province_id) || duplicateLocationPath) ) { update('wizard_step', '5'); setError( t( 'Indique pelo menos duas localizações distintas com província seleccionada.', 'Enter at least two distinct locations with a province selected.', ), ); return; } if ( !consent || confirmation !== record.code || ![ 'confirm_information', 'confirm_disclosure_authority', 'confirm_no_publication_guarantee', ].every((field) => payload[field] === 'yes') || !(await save()) ) return; setBusy(true); try { await api( `/api/v1/existing-business/listings/${record.id}/transitions`, { action: 'submitted', version_no: versionRef.current, review_consent: true, confirmation_code: confirmation, note: 'Submissão confirmada do formulário privado por etapas', }, ); router.reload(); } catch (e) { setError( e instanceof Error ? e.message : 'Falha na submissão / Submission failed', ); setBusy(false); } }; return (

{t('Modalidade registada', 'Registered modality')}:{' '} {businessModalities[record.modality] ?? record.modality}

{!modalityFormType && (

{t( 'Pode guardar e recuperar esta preparação. O formulário específico de submissão desta modalidade ainda não está disponível; os dados e a modalidade original serão preservados.', 'You can save and recover this draft. Its specific submission form is not available yet; the original modality and data are preserved.', )}

)} {t( 'Classificação multidimensional deste anúncio', 'Multidimensional classification of this listing', )}

{record.code} · {t('Versão', 'Version')} {version}

{[5, 7, 8].includes(step) && ( )}

{t( 'Área privada. Guardar ou submeter não publica a oportunidade nem confirma a titularidade ou a transmissibilidade.', 'Private area. Saving or submitting does not publish the opportunity or verify ownership or transferability.', )}

{t( 'Divulgue uma oportunidade de venda, parceria, financiamento, fornecimento ou desenvolvimento de projecto. Preencha os dados disponíveis e guarde para continuar mais tarde. A publicação está sujeita a revisão.', 'Share an opportunity for sale, partnership, financing, supply or project development. Enter the information available and save to continue later. Publication is subject to review.', )}

{t( 'Os campos com * são necessários para submeter. Os restantes podem ser completados durante a revisão.', 'Fields marked * are required for submission. Other fields can be completed during review.', )}

    {steps.map((labels, i) => (
  1. ))}

{step}/8 — {steps[step - 1][english ? 1 : 0]}

{ event.preventDefault(); void save(); }} >
{steps[step - 1][english ? 1 : 0]} {step === 3 && ( setPublicTitle(event.target.value) } aria-describedby="public-title-help" /> {t( 'Será revisto antes de qualquer publicação.', 'Reviewed before any publication.', )} )} {step === 3 && ( setSectorSearch(e.target.value) } /> )} {Object.entries(formSchema) .filter( ([key, field]) => field.step === step && key !== 'locations_json' && !( payload.geography_scope === 'multiple' && [ 'province_id', 'district_id', 'admin_post_id', 'locality_id', ].includes(key) ) && Object.entries(field.when ?? {}).every( ([dependency, values]) => values.includes( payload[dependency] ?? '', ), ) && (!( key === 'mandate_reference' || key === 'mandate_valid_until' ) || payload.acting_capacity === 'representative') && ((key !== 'mandate_document_reference' && key !== 'disclosure_scope') || payload.acting_capacity === 'representative'), ) .map(([key, field]) => ( {field.type === 'checkbox' ? ( update( key, e.target.checked ? 'yes' : '', ) } className="mt-1" /> {english ? field.en : field.pt}{' '} * ) : field.type === 'country' ? ( update(key, value) } label={ english ? field.en : field.pt } /> ) : field.type === 'territory' ? ( update(key, value) } /> ) : field.type === 'point_territory' ? ( ) : field.type === 'select' ? ( ) : field.type === 'textarea' ? (