Files
Investidor-V2/resources/js/pages/investment/profile.tsx
T
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

405 lines
16 KiB
TypeScript

import { Link, router, useForm } from '@inertiajs/react';
import { Frame, Field, input, button, card } from './shared';
import PartnershipSourceLinks from '@/components/partnership-source-links';
import CountrySelect, { type Country } from '@/components/country-select';
import { useEffect, useId } from 'react';
type RecordData = { version: number; payload: Record<string, string> };
type Company = RecordData & {
id: string;
countrySource?: {
organization_id: string;
organization_version: number;
country: string;
} | null;
};
type Organization = {
id: string;
name: string;
version: number;
country: string | null;
canEdit: boolean;
provenance: { reference: string; kind: string } | null;
};
const labels: Record<string, string> = {
phone: 'Telefone',
country: 'País anteriormente registado',
residence_country_code: 'País de residência do investidor',
incorporation_country_code: 'País de constituição da entidade',
sector: 'Sector de interesse',
experience: 'Experiência relevante',
investment_capacity: 'Capacidade de investimento declarada',
name: 'Nome da empresa',
registration: 'Referência de registo / NUIT',
role: 'Função ou relação com a empresa',
description: 'Actividade e observações',
};
export default function Profile({
account,
companies,
countries,
organizations = [],
organizationCountryAvailable = false,
}: {
account: RecordData;
companies: Company[];
countries: Country[];
organizations?: Organization[];
organizationCountryAvailable?: boolean;
}) {
return (
<Frame title="Perfil de investimento e empresas">
<Link href="/investidor/manifestacoes" className="underline">
Voltar à área do investidor
</Link>
<p>
Estes dados são privados e servem para preencher novas
manifestações. Nome e email são mantidos nas{' '}
<Link className="underline" href="/settings/profile">
definições da conta
</Link>
.
</p>
<Editor
key={'account-' + account.version}
record={account}
countries={countries}
fields={[
'phone',
'residence_country_code',
'sector',
'experience',
'investment_capacity',
]}
/>
<h2 className="text-2xl font-bold">Empresas declaradas</h2>
<p>
Declarar uma empresa não comprova representação legal nem
concede acesso aos registos de outras pessoas. A equipa pode
pedir evidência durante o atendimento.
</p>
{companies.map((company) => (
<section key={company.id} className={card}>
<PartnershipSourceLinks type="company" id={company.id} />
<h3 className="text-xl font-bold">
{company.payload.name}
</h3>
{company.countrySource && (
<p>
País reutilizado: {company.countrySource.country};
organização{' '}
{organizations.find(
(o) =>
o.id ===
company.countrySource?.organization_id,
)?.name ?? company.countrySource.organization_id}
, versão{' '}
{company.countrySource.organization_version}. O
valor é uma cópia identificada; não é atualizado
automaticamente quando o cadastro mestre muda.
</p>
)}
<Editor
key={company.version}
record={company}
countries={countries}
fields={[
'name',
'incorporation_country_code',
'registration',
'sector',
'role',
'description',
]}
/>
{organizations
.filter((o) => o.country)
.map((org) => (
<div key={org.id} className="mt-3 space-y-2">
<p>
País mestre de {org.name}: {org.country}. A
reutilização altera somente esta declaração;
manifestações anteriores conservam o seu
valor.
</p>
<button
className={button}
onClick={() =>
router.post(
`/investidor/companies/${company.id}/organization-country`,
{
version: company.version,
organization_id: org.id,
organization_version:
org.version,
},
{ preserveScroll: true },
)
}
>
Reutilizar país de {org.name}
</button>
</div>
))}
<button
className={button + ' mt-4'}
onClick={() =>
router.post('/investidor/manifestacoes', {
company_id: company.id,
})
}
>
Preparar manifestação desta empresa
</button>
</section>
))}
{companies.length < 20 && (
<section className={card}>
<h3 className="text-xl font-bold">Acrescentar empresa</h3>
<Editor
key={'new-' + companies.length}
record={{ version: 0, payload: {} }}
company
countries={countries}
fields={[
'name',
'incorporation_country_code',
'registration',
'sector',
'role',
'description',
]}
/>
</section>
)}
<h2 className="text-2xl font-bold">
Organizações representadas — cadastro mestre
</h2>
<p>
O país de constituição é independente da residência e da origem
da solicitação. Não se associa uma empresa privada a uma
organização por semelhança de nome. A declaração do
representante não é uma decisão externa nem comprova por si a
representação legal.
</p>
{!organizationCountryAvailable && (
<p role="status">
Extensão do país de constituição ainda não instalada neste
ambiente.
</p>
)}
{organizationCountryAvailable && organizations.length === 0 && (
<p>
Sem representação organizacional registada para esta conta.
</p>
)}
{organizations.map((org) => (
<OrganizationEditor
key={org.id + org.version}
organization={org}
countries={countries}
/>
))}
</Frame>
);
}
function OrganizationEditor({
organization,
countries,
}: {
organization: Organization;
countries: Country[];
}) {
const form = useForm({
version: organization.version,
country: organization.country ?? '',
source_reference: organization.provenance?.reference ?? '',
});
const id = useId();
useEffect(() => {
if (Object.keys(form.errors).length)
document
.getElementById(id)
?.querySelector<HTMLElement>('[aria-invalid="true"]')
?.focus();
}, [form.errors, id]);
return (
<section
className={card}
aria-label={`Cadastro mestre: ${organization.name}`}
>
<h3 className="text-xl font-bold">{organization.name}</h3>
<p>
Versão {organization.version}; origem do país:{' '}
{organization.provenance?.kind === 'representative_declaration'
? 'declaração do representante'
: 'não informada'}
.
</p>
<form
className="mt-4 space-y-4"
id={id}
onSubmit={(event) => {
event.preventDefault();
form.put(
`/investidor/organizations/${organization.id}/country`,
{ preserveScroll: true },
);
}}
>
<Field label="País de constituição da organização">
<CountrySelect
id={id + '-country'}
label="País de constituição da organização"
countries={countries}
value={form.data.country}
disabled={!organization.canEdit}
error={form.errors.country}
onChange={(country) => form.setData('country', country)}
/>
</Field>
<label className="block" htmlFor={id + '-source'}>
Fonte ou referência deste país
</label>
<textarea
id={id + '-source'}
className={input}
value={form.data.source_reference}
disabled={!organization.canEdit}
maxLength={2000}
aria-invalid={!!form.errors.source_reference}
aria-describedby={
form.errors.source_reference
? id + '-source-error'
: undefined
}
onChange={(event) =>
form.setData('source_reference', event.target.value)
}
/>
{form.errors.source_reference && (
<p id={id + '-source-error'} role="alert">
{form.errors.source_reference}
</p>
)}
{form.errors.version && (
<p role="alert">{form.errors.version}</p>
)}
<button
className={button}
disabled={!organization.canEdit || form.processing}
>
Guardar país no cadastro mestre
</button>
</form>
</section>
);
}
function Editor({
record,
fields,
company = false,
countries,
}: {
record: RecordData & { id?: string };
fields: string[];
company?: boolean;
countries: Country[];
}) {
const isCompany = company || !!record.id;
const form = useForm({
version: record.version,
payload: Object.fromEntries(
[...fields, 'country'].map((key) => [
key,
record.payload[key] ?? '',
]),
),
});
return (
<form
className="mt-4 space-y-4"
onSubmit={(e) => {
e.preventDefault();
const options = { preserveScroll: true };
if (isCompany)
form.post(
'/investidor/companies' +
(record.id ? '/' + record.id : ''),
options,
);
else form.put('/investidor/profile', options);
}}
>
<div className="grid gap-4 md:grid-cols-2">
{record.payload.country && (
<p>
País anteriormente registado: {record.payload.country}.
Conservado sem atribuir automaticamente residência,
constituição ou origem da solicitação.
</p>
)}
{fields.map((key) => (
<Field key={key} label={labels[key]}>
{key.endsWith('_country_code') ? (
<CountrySelect
id={key + (record.id ?? 'account')}
countries={countries}
label={labels[key]}
error={form.errors[`payload.${key}`]}
value={form.data.payload[key]}
onChange={(value) =>
form.setData('payload', {
...form.data.payload,
[key]: value,
})
}
/>
) : (
<input
className={input}
value={form.data.payload[key]}
required={
isCompany &&
['name', 'country', 'role'].includes(key)
}
maxLength={
key === 'description' ||
key === 'experience'
? 2000
: key === 'investment_capacity'
? 1000
: 200
}
onChange={(e) =>
form.setData('payload', {
...form.data.payload,
[key]: e.target.value,
})
}
/>
)}
{!key.endsWith('_country_code') &&
form.errors[`payload.${key}`] && (
<p role="alert" className="text-red-700">
{form.errors[`payload.${key}`]}
</p>
)}
</Field>
))}
</div>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key} className="text-red-700">
{value}
</p>
))}
<button className={button} disabled={form.processing}>
{isCompany
? 'Guardar declaração da empresa'
: 'Guardar perfil de investimento'}
</button>
</form>
);
}