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'; import { businessModalities } from './business-types'; 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
('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> >({}); const [receipt, setReceipt] = useState(''); const key = useRef(draft.key); const update = (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] ? ( ) : null; const submit = async (event: FormEvent) => { 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> = {}; 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 ( Voltar à oportunidade

Oportunidade: {record.title}

{receipt ? (

Pedido recebido

Referência: {receipt}

Acompanhar manifestações

A equipa fará a triagem antes de qualquer partilha com o proponente.

) : (
País de origem do pedido (opcional) update('declared_origin_country_code', value) } />

País de onde apresenta este pedido. Pode ser diferente do país do requerente.

update('fullName', e.target.value)} /> {fieldError('fullName')} update('email', e.target.value)} /> {fieldError('email')} update('phone', e.target.value)} /> {fieldError('phone')} {fieldError('investorType')}
update('country', value)} />
update('sectorInterest', e.target.value) } /> {fieldError('sectorInterest')} {fieldError('modality')} update('investmentRange', e.target.value) } /> {fieldError('investmentRange')}