Files
Investidor-V2/resources/js/pages/investment/business-wizard.tsx
T

1335 lines
65 KiB
TypeScript

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<string, string>;
when?: Record<string, string[]>;
}
>;
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<string, string | undefined>,
): 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 (
<div className="space-y-2">
<input
className={input}
type="search"
value={query}
maxLength={100}
placeholder="Pesquisar localização"
aria-label={`Pesquisar ${name}`}
onChange={(event) => setQuery(event.target.value)}
/>
<select
className={input}
value={value}
required={required}
aria-label={`Seleccionar ${name}`}
disabled={type !== 'province' && !parentId}
onChange={(event) => onChange(event.target.value)}
>
<option value="">Seleccionar</option>
{options.map((option) => (
<option key={option.id} value={option.id}>
{option.name}
</option>
))}
</select>
{error && (
<p role="alert" className="text-red-700">
{error}
</p>
)}
</div>
);
}
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<Business['payload']>(() => {
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<HTMLHeadingElement>(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<string, string[]> = {
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<typeof decodeBusinessLocations>,
) => {
update('locations_json', encodeBusinessLocations(rows));
};
const setLocation = (
index: number,
key: keyof ReturnType<typeof emptyBusinessLocation>,
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 (
<Frame
title={t(
'Preparar oportunidade de negócio',
'Prepare business opportunity',
)}
>
<div lang={english ? 'en' : 'pt'} className="space-y-5">
<p>
{t('Modalidade registada', 'Registered modality')}:{' '}
{businessModalities[record.modality] ?? record.modality}
</p>
{!modalityFormType && (
<p role="status">
{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.',
)}
</p>
)}
<a
className="underline"
href={`/investidor/negocios/${record.id}/classificacao`}
>
{t(
'Classificação multidimensional deste anúncio',
'Multidimensional classification of this listing',
)}
</a>
<button
type="button"
className="underline"
onClick={() => setEnglish(!english)}
>
{english ? 'Português' : 'English'}
</button>
<p>
{record.code} · {t('Versão', 'Version')} {version}
</p>
{[5, 7, 8].includes(step) && (
<BusinessPointSummary
payload={payload}
registered={registeredLocation}
available={pointPublicationAvailable}
/>
)}
<p>
{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.',
)}
</p>
<p>
{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.',
)}
</p>
<p className="text-sm">
{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.',
)}
</p>
<ol
className="flex flex-wrap gap-3"
aria-label={t('Etapas', 'Steps')}
>
{steps.map((labels, i) => (
<li key={labels[1]}>
<button
type="button"
className="rounded border px-3 py-2 focus-visible:outline-2"
aria-current={
step === i + 1 ? 'step' : undefined
}
disabled={busy}
onClick={() =>
update('wizard_step', String(i + 1))
}
>
{i + 1}. {labels[english ? 1 : 0]}
</button>
</li>
))}
</ol>
<progress
className="w-full"
max={8}
value={step}
aria-label={t('Progresso', 'Progress')}
/>
<h2 ref={heading} tabIndex={-1} className="text-xl font-bold">
{step}/8 — {steps[step - 1][english ? 1 : 0]}
</h2>
<form
className={`${card} space-y-4`}
onSubmit={(event) => {
event.preventDefault();
void save();
}}
>
<fieldset className="space-y-4">
<legend className="sr-only">
{steps[step - 1][english ? 1 : 0]}
</legend>
{step === 3 && (
<Field
label={t(
'Título público proposto',
'Proposed public title',
)}
>
<input
className={input}
value={publicTitle}
maxLength={180}
onChange={(event) =>
setPublicTitle(event.target.value)
}
aria-describedby="public-title-help"
/>
<span
id="public-title-help"
className="text-sm"
>
{t(
'Será revisto antes de qualquer publicação.',
'Reviewed before any publication.',
)}
</span>
</Field>
)}
{step === 3 && (
<Field
label={t(
'Sector de actividade *',
'Sector of activity *',
)}
>
<input
className={input}
type="search"
value={sectorSearch}
maxLength={100}
placeholder={t(
'Pesquisar sector',
'Search sector',
)}
aria-label={t(
'Pesquisar sector de actividade',
'Search sector of activity',
)}
onChange={(e) =>
setSectorSearch(e.target.value)
}
/>
<select
className={input}
value={sectorId ?? ''}
aria-label={t(
'Sector de actividade',
'Sector of activity',
)}
onChange={(e) =>
setSectorId(
e.target.value
? Number(e.target.value)
: null,
)
}
>
<option value="">
{t('Seleccionar', 'Select')}
</option>
{sectors
.filter(
(sector) =>
sector.id === sectorId ||
sector.name
.toLocaleLowerCase()
.includes(
sectorSearch
.trim()
.toLocaleLowerCase(),
),
)
.map((sector) => (
<option
key={sector.id}
value={sector.id}
>
{sector.name}
</option>
))}
</select>
</Field>
)}
{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
key={key}
label={
field.type === 'checkbox'
? ''
: `${english ? field.en : field.pt}${pointRequired.has(key) || requiredFields.has(key) || ((key === 'mandate_reference' || key === 'mandate_document_reference' || key === 'disclosure_scope') && payload.acting_capacity === 'representative') || (key === 'project_stage_other' && payload.project_stage === 'other') || (key === 'available_from' && payload.availability === 'from_date') || (key === 'province_id' && payload.geography_scope === 'specific') || (key === 'locations_json' && payload.geography_scope === 'multiple') || (['value_meaning', 'currency', 'asking_value'].includes(key) && ['defined', 'indicative'].includes(payload.value_status ?? '')) || (key === 'investment_total' && payload.opportunity_type === 'investment_project') || (key === 'asset_deal_kind' && ['company_sale', 'asset_sale'].includes(payload.opportunity_type ?? '')) || (key === 'partnership_contribution' && payload.opportunity_type === 'business_partnership') || (key === 'amount_sought' && payload.opportunity_type === 'financing_request') || (key === 'asset_modality' && payload.opportunity_type === 'asset_sale') || (['concession_entity', 'concession_reference'].includes(key) && payload.opportunity_type === 'concession_opportunity') || (key === 'supply_description' && payload.opportunity_type === 'supply_opportunity') ? ' *' : ''}`
}
>
{field.type === 'checkbox' ? (
<span className="flex items-start gap-3">
<input
type="checkbox"
checked={payload[key] === 'yes'}
onChange={(e) =>
update(
key,
e.target.checked
? 'yes'
: '',
)
}
className="mt-1"
/>
<span>
{english ? field.en : field.pt}{' '}
*
</span>
</span>
) : field.type === 'country' ? (
<CountrySelect
countries={countries}
value={payload[key] ?? ''}
allowLegacyValue={key === 'country'}
onChange={(value) =>
update(key, value)
}
label={
english ? field.en : field.pt
}
/>
) : field.type === 'territory' ? (
<TerritoryField
name={english ? field.en : field.pt}
type={
territoryField[
key as keyof typeof territoryField
].type
}
parentId={String(
payload[
territoryField[
key as keyof typeof territoryField
].parent
] ?? '',
)}
value={payload[key] ?? ''}
onChange={(value) =>
update(key, value)
}
/>
) : field.type === 'point_territory' ? (
<select
className={input}
value={payload[key] ?? ''}
onChange={(event) =>
update(key, event.target.value)
}
>
<option value="">
{t(
'Seleccionar uma localização declarada',
'Select a declared location',
)}
</option>
{payload[key] &&
!locationRows.some(
(row) =>
businessPointTerritoryKey(
row,
) === payload[key],
) && (
<option
value={payload[key]}
>
{t(
'Selecção guardada fora das localizações actuais; reconcilie antes de submeter',
'Saved selection is outside the current locations; reconcile before submitting',
)}
</option>
)}
{locationRows
.map((row, index) => ({
row,
index,
}))
.filter(
({ row }) =>
row.province_id,
)
.map(({ row, index }) => (
<option
key={businessPointTerritoryKey(
row,
)}
value={businessPointTerritoryKey(
row,
)}
>
{t(
'Localização',
'Location',
)}{' '}
{index + 1}
{payload.locations_json ===
resolvedLocationJson &&
territoryPaths[index]
?.length
? ` — ${territoryPaths[index].join(' / ')}`
: t(
' (declarada nesta etapa)',
' (declared in this step)',
)}
</option>
))}
</select>
) : field.type === 'select' ? (
<select
className={input}
value={payload[key] ?? ''}
onChange={(e) =>
update(key, e.target.value)
}
>
<option value="">
{t('Seleccionar', 'Select')}
</option>
{Object.entries(
field.options ?? {},
).map(([value, label]) => (
<option
key={value}
value={value}
>
{label}
</option>
))}
</select>
) : field.type === 'textarea' ? (
<textarea
className={input}
rows={4}
maxLength={field.max}
value={payload[key] ?? ''}
onChange={(e) =>
update(key, e.target.value)
}
/>
) : (
<input
className={input}
type={
field.type === 'decimal'
? 'text'
: field.type
}
inputMode={
field.type === 'decimal'
? 'decimal'
: undefined
}
maxLength={field.max}
value={payload[key] ?? ''}
onChange={(e) =>
update(key, e.target.value)
}
/>
)}
</Field>
))}
{step === 5 &&
payload.geography_scope === 'multiple' && (
<section
className="space-y-4"
aria-labelledby="multiple-locations-heading"
>
<h3
id="multiple-locations-heading"
className="font-medium"
>
{t(
'Localizações administrativas (várias) *',
'Administrative locations (multiple) *',
)}
</h3>
<p className="text-sm">
{t(
'Indique pelo menos duas localizações distintas. Se preparar um ponto exacto, escolha acima a localização a que pertence. Não é escolhido automaticamente o primeiro território.',
'Enter at least two distinct locations. If preparing an exact point, select its location above. The first territory is not selected automatically.',
)}
</p>
{locationRows.map((row, index) => (
<fieldset
key={index}
className="space-y-3 rounded border p-4"
>
<legend className="px-1 font-medium">
{t('Localização', 'Location')}{' '}
{index + 1}
</legend>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key) => {
const configuration =
territoryField[key];
const parentId =
configuration.parent
? row[
configuration.parent as keyof typeof row
]
: '';
const name = t(
key === 'province_id'
? 'Província ou Cidade de Maputo'
: key === 'district_id'
? 'Distrito'
: key ===
'admin_post_id'
? 'Posto administrativo'
: 'Localidade',
key === 'province_id'
? 'Province or Maputo City'
: key === 'district_id'
? 'District'
: key ===
'admin_post_id'
? 'Administrative post'
: 'Locality',
);
return (
<Field
key={key}
label={`${name}${key === 'province_id' ? ' *' : ''}`}
>
<TerritoryField
name={`${name}, ${t('localização', 'location')} ${index + 1}`}
type={
configuration.type
}
parentId={parentId}
value={row[key]}
required={
key ===
'province_id'
}
onChange={(value) =>
setLocation(
index,
key,
value,
)
}
/>
</Field>
);
})}
<button
type="button"
className="underline"
disabled={
locationRows.length <= 1
}
onClick={() =>
removeLocation(index)
}
>
{t(
'Remover esta localização',
'Remove this location',
)}
</button>
</fieldset>
))}
<button
type="button"
className={button}
disabled={locationRows.length >= 20}
onClick={addLocation}
>
{t(
'Adicionar localização',
'Add location',
)}
</button>
{locationRows.length < 2 && (
<p role="status">
{t(
'Adicione pelo menos mais uma localização antes de submeter.',
'Add at least one more location before submitting.',
)}
</p>
)}
{duplicateLocationPath && (
<p
role="alert"
className="text-red-700"
>
{t(
'Remova percursos administrativos repetidos ou sobrepostos.',
'Remove repeated or overlapping administrative paths.',
)}
</p>
)}
</section>
)}
{step === 7 && (
<p role="note">
{t(
'Este formulário regista referências. O envio de ficheiros com antivírus ainda não está disponível; não cole conteúdo reservado de documentos neste campo.',
'This form records references. File upload with antivirus is not available yet; do not paste confidential document content here.',
)}
</p>
)}
{step === 4 && fundingNeedsReconciliation && (
<p
role="status"
className="rounded border border-amber-600 p-3"
>
{t(
'Os montantes assegurado e procurado ainda não reconciliam com o investimento total. Complete os valores ou confirme-os durante a revisão.',
'The secured and sought amounts do not yet reconcile with total investment. Complete the values or confirm them during review.',
)}
</p>
)}
{step === 8 && (
<>
{fundingNeedsReconciliation && (
<p
role="status"
className="mb-4 rounded border border-amber-600 p-3"
>
{t(
'Aviso: o financiamento declarado não reconcilia com o investimento total; a revisão deverá confirmar os montantes.',
'Warning: the declared funding does not reconcile with total investment; review should confirm the amounts.',
)}
</p>
)}
<dl className="space-y-3 break-words">
<div>
<dt className="font-semibold">
{t(
'Título público proposto',
'Proposed public title',
)}
</dt>
<dd>{publicTitle || '—'}</dd>
</div>
<div>
<dt className="font-semibold">
{t(
'Tipo de oportunidade',
'Opportunity type',
)}
</dt>
<dd>
{businessModalities[modality] ??
modality.replaceAll('_', ' ')}
</dd>
</div>
{Object.entries(formSchema)
.filter(
([, field]) =>
field.type !==
'location_list' &&
Object.entries(
field.when ?? {},
).every(
([dependency, values]) =>
values.includes(
payload[
dependency
] ?? '',
),
),
)
.map(([key, field]) => (
<div key={key}>
<dt className="font-semibold">
{english
? field.en
: field.pt}
</dt>
<dd className="whitespace-pre-wrap">
{payload[key] || '—'}
</dd>
</div>
))}
{payload.geography_scope === 'multiple' && (
<div>
<dt className="font-semibold">
{t(
'Localizações administrativas',
'Administrative locations',
)}
</dt>
<dd>
{locationRows.length}{' '}
{t(
'localizações indicadas',
'locations entered',
)}
</dd>
</div>
)}
</dl>
{payload.geography_scope === 'multiple' && (
<ul className="list-disc space-y-1 pl-6">
{locationRows.map((_, index) => (
<li key={index}>
{payload.locations_json ===
resolvedLocationJson &&
territoryPaths[index]?.length
? territoryPaths[
index
].join(' → ')
: payload.locations_json !==
resolvedLocationJson
? t(
'Os nomes serão apresentados depois de guardar este rascunho.',
'Names will appear after this draft is saved.',
)
: t(
'Percurso territorial indisponível na referência pública actual.',
'Territorial path unavailable in the current public reference data.',
)}
</li>
))}
</ul>
)}
</>
)}
</fieldset>
<p role="status" aria-live="polite">
{busy
? t('A guardar…', 'Saving…')
: dirty
? t('Alterações por guardar', 'Unsaved changes')
: t(
'Rascunho guardado no servidor',
'Draft saved on server',
)}
</p>
{error && (
<p role="alert" className="text-red-700">
{error}
</p>
)}
<button className={button} disabled={busy}>
{t('Guardar rascunho', 'Save draft')}
</button>
</form>
{step === 6 && (
<BusinessObjects
businessId={record.id}
version={version}
editable={!dirty && !busy}
objects={objects}
objectKinds={objectKinds}
/>
)}
{step === 8 && (
<div className={`${card} space-y-4`}>
<label className="flex gap-3">
<input
type="checkbox"
checked={consent}
onChange={(e) => setConsent(e.target.checked)}
/>
{t(
'Confirmo a exactidão da declaração e autorizo a análise interna. Não autorizo publicação por esta acção.',
'I confirm this declaration and authorize internal review. This action does not authorize publication.',
)}
</label>
<p>
{t(
'A publicação só pode usar campos e conteúdos seleccionados após revisão editorial e verificação documental. Contactos pessoais permanecem ocultos por defeito.',
'Publication uses only selected content after editorial review and document verification. Personal contacts are hidden by default.',
)}
</p>
<Field
label={t(
'Digite o código acima para confirmar',
'Type the code above to confirm',
)}
>
<input
className={input}
autoComplete="off"
value={confirmation}
onChange={(e) =>
setConfirmation(e.target.value)
}
aria-describedby="business-submission-requirements"
/>
</Field>
<div
id="business-submission-requirements"
role="status"
aria-live="polite"
className="rounded border p-3"
>
{submissionBlockers.length > 0 ? (
<>
<p className="font-semibold">
{t(
'Para disponibilizar o botão de submissão:',
'To enable the submission button:',
)}
</p>
<ul className="list-disc pl-6">
{submissionBlockers.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
</>
) : (
<p>
{t(
'Confirmações preenchidas. Pode submeter para análise.',
'Confirmations completed. You can submit for review.',
)}
</p>
)}
</div>
<button
className={button}
aria-describedby="business-submission-requirements"
disabled={
busy ||
!consent ||
confirmation !== record.code ||
![
'confirm_information',
'confirm_disclosure_authority',
'confirm_no_publication_guarantee',
].every((field) => payload[field] === 'yes')
}
onClick={() => void submit()}
>
{t(
'Confirmar e submeter para análise',
'Confirm and submit for review',
)}
</button>
</div>
)}
<div className="flex flex-wrap gap-4">
<button
type="button"
className={button}
disabled={busy || step === 8}
onClick={async () => {
if (await save()) update('wizard_step', '8');
}}
>
{t('Pré-visualizar', 'Preview')}
</button>
<button
className={button}
disabled={busy || step === 1}
onClick={() => update('wizard_step', String(step - 1))}
>
{t('Anterior', 'Previous')}
</button>
<button
className={button}
disabled={busy || step === 8}
onClick={() => update('wizard_step', String(step + 1))}
>
{t('Seguinte', 'Next')}
</button>
<button
className="underline"
disabled={busy}
onClick={async () => {
if (await save())
router.visit('/investidor/negocios');
}}
>
{t('Guardar e sair', 'Save and exit')}
</button>
</div>
</div>
</Frame>
);
}