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

334 lines
14 KiB
TypeScript

import { useInterestDraft } from '@/hooks/use-interest-draft';
import { useRef, useState } from 'react';
import { Link } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { newSubmissionKey } from '@/lib/portal-api';
import { Frame, Field, button, card, input } from './shared';
import CountrySelect, { type Country } from '@/components/country-select';
type Opportunity = {
id: string;
slug: string;
title: string;
sector?: { name: string } | null;
};
type Props = {
record: Opportunity;
modalities: string[];
returnUrl?: string;
countries: Country[];
};
type Form = {
declared_origin_country_code: string;
fullName: string;
email: string;
phone: string;
investorType: string;
country: string;
sectorInterest: string;
modality: string;
investmentRange: string;
message: string;
privacyConsent: boolean;
shareWithProponent: boolean;
};
export default function BusinessInterest({
record,
modalities,
returnUrl = '/negocios',
countries,
}: Props) {
const draft = useInterestDraft<Form>('business:' + record.id, {
declared_origin_country_code: '',
fullName: '',
email: '',
phone: '',
investorType: 'empresa',
country: '',
sectorInterest: record.sector?.name ?? '',
modality: modalities[0] ?? '',
investmentRange: '',
message: '',
privacyConsent: false,
shareWithProponent: false,
});
const {form, setForm} = draft;
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [fieldErrors, setFieldErrors] = useState<Partial<Record<keyof Form, string>>>({});
const [receipt, setReceipt] = useState('');
const key = useRef(draft.key);
const update = <K extends keyof Form>(field: K, value: Form[K]) => {
setForm((current) => ({ ...current, [field]: value }));
setFieldErrors((current) => ({ ...current, [field]: undefined }));
};
const fieldId = (field: keyof Form) => `business-interest-${field}`;
const feedback = (field: keyof Form) => ({
id: fieldId(field),
name: field,
'aria-invalid': !!fieldErrors[field],
'aria-describedby': fieldErrors[field] ? `${fieldId(field)}-error` : undefined,
});
const fieldError = (field: keyof Form) => fieldErrors[field] ? (
<p id={`${fieldId(field)}-error`} role="alert" className="text-sm text-red-700">
{fieldErrors[field]}
</p>
) : null;
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!form.privacyConsent) {
setError('Aceite o tratamento de dados para enviar o pedido.');
return;
}
setBusy(true);
setError('');
const xsrf = decodeURIComponent(
document.cookie
.split('; ')
.find((cookie) => cookie.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '',
);
try {
const response = await fetch('/api/v1/interest-requests', {
method: 'POST',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': xsrf,
'Idempotency-Key': key.current,
},
body: JSON.stringify({
...form,
existingBusinessId: record.id,
}),
});
if (response.status === 401) { draft.authenticate(); return; }
const data = await response.json();
if (!response.ok) {
const errors: Partial<Record<keyof Form, string>> = {};
for (const [field, messages] of Object.entries(data.errors ?? {})) {
if (field in form && Array.isArray(messages)) {
errors[field as keyof Form] = messages.filter((message): message is string => typeof message === 'string').join(' ');
}
}
setFieldErrors(errors);
setError(data.message ?? 'Não foi possível enviar a manifestação.');
const first = Object.keys(errors)[0] as keyof Form | undefined;
window.setTimeout(() => document.getElementById(first ? fieldId(first) : 'business-interest-feedback')?.focus(), 0);
return;
}
setFieldErrors({});
draft.clear();
setReceipt(data.data.reference);
key.current = newSubmissionKey();
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: 'Não foi possível enviar a manifestação.',
);
} finally {
setBusy(false);
}
};
return (
<Frame title="Manifestar interesse">
<Link href={returnUrl} className="underline">
Voltar à oportunidade
</Link>
<p>
Oportunidade: <strong>{record.title}</strong>
</p>
{receipt ? (
<section className={card} role="status">
<h2 className="text-xl font-bold">Pedido recebido</h2>
<p>Referência: {receipt}</p><Link href="/investidor/manifestacoes" className="underline">Acompanhar manifestações</Link>
<p>
A equipa fará a triagem antes de qualquer partilha com o
proponente.
</p>
</section>
) : (
<form className={`${card} space-y-4`} onSubmit={submit}>
<div className="space-y-1 text-sm font-medium"><span>País de origem declarado desta solicitação</span>
<CountrySelect
countries={countries}
id={fieldId('declared_origin_country_code')}
error={fieldErrors.declared_origin_country_code}
value={form.declared_origin_country_code}
label="País de origem declarado desta solicitação"
onChange={(value) =>
update('declared_origin_country_code', value)
}
/>
<p className="text-sm">
Origem opcional e independente do país do
investidor.
</p>
</div>
<Field label="Nome ou denominação">
<input
className={input}
required
minLength={3}
maxLength={150}
{...feedback('fullName')}
value={form.fullName}
onChange={(e) => update('fullName', e.target.value)}
/>
{fieldError('fullName')}
</Field>
<Field label="Email">
<input
className={input}
type="email"
required
maxLength={150}
{...feedback('email')}
value={form.email}
onChange={(e) => update('email', e.target.value)}
/>
{fieldError('email')}
</Field>
<Field label="Telefone">
<input
className={input}
type="tel"
maxLength={30}
{...feedback('phone')}
value={form.phone}
onChange={(e) => update('phone', e.target.value)}
/>
{fieldError('phone')}
</Field>
<Field label="Tipo de investidor">
<select
className={input}
{...feedback('investorType')}
value={form.investorType}
onChange={(e) =>
update('investorType', e.target.value)
}
>
<option value="empresa">Empresa</option>
<option value="individual">Pessoa singular</option>
<option value="fundo">Fundo</option>
<option value="entidade_publica">
Entidade pública
</option>
<option value="outro">Outro</option>
</select>
{fieldError('investorType')}
</Field>
<div className="space-y-1 text-sm font-medium"><span>País</span>
<CountrySelect
countries={countries}
required
label="País do requerente"
allowLegacyValue
id={fieldId('country')}
error={fieldErrors.country}
value={form.country}
onChange={(value) => update('country', value)}
/>
</div>
<Field label="Sector de interesse">
<input
className={input}
required
maxLength={150}
{...feedback('sectorInterest')}
value={form.sectorInterest}
onChange={(e) =>
update('sectorInterest', e.target.value)
}
/>
{fieldError('sectorInterest')}
</Field>
<Field label="Modalidade pretendida">
<select
className={input}
required
{...feedback('modality')}
value={form.modality}
onChange={(e) => update('modality', e.target.value)}
>
{modalities.map((modality) => (
<option key={modality} value={modality}>
{modality.replaceAll('_', ' ')}
</option>
))}
</select>
{fieldError('modality')}
</Field>
<Field label="Intervalo de investimento">
<input
className={input}
maxLength={80}
{...feedback('investmentRange')}
value={form.investmentRange}
onChange={(e) =>
update('investmentRange', e.target.value)
}
/>
{fieldError('investmentRange')}
</Field>
<Field label="Motivação e pedido">
<textarea
className={input}
required
minLength={20}
maxLength={2000}
rows={5}
{...feedback('message')}
value={form.message}
onChange={(e) => update('message', e.target.value)}
/>
{fieldError('message')}
</Field>
<label className="flex items-start gap-3">
<input
type="checkbox"
required
{...feedback('privacyConsent')}
checked={form.privacyConsent}
onChange={(e) =>
update('privacyConsent', e.target.checked)
}
/>
<span>
Autorizo o tratamento destes dados para responder a
esta manifestação. O envio não confirma
elegibilidade nem permite partilha automática com o
proponente.
</span>
</label>
<label className="flex items-start gap-3">
<input
type="checkbox"
checked={form.shareWithProponent}
onChange={(e) =>
update('shareWithProponent', e.target.checked)
}
/>
<span>
Autorizo, se necessário para avaliar esta
manifestação, a partilha do meu nome, email,
telefone e mensagem com o proponente. Esta
autorização é opcional e pode ser retirada junto da
equipa.
</span>
</label>
{fieldError('privacyConsent')}
{error && <p id="business-interest-feedback" tabIndex={-1} role="alert">{error}</p>}
<button className={button} disabled={busy}>
{busy ? 'A enviar…' : 'Enviar manifestação'}
</button>
</form>
)}
</Frame>
);
}