@@ -31,6 +31,7 @@ export type CanonicalOptions = {
|
||||
modularProfiles?: Record<string, string>;
|
||||
historyVersion?: string | null;
|
||||
schema: Schema;
|
||||
submissionTextLimits?: Record<string, { minLength?: number; maxLength?: number }>;
|
||||
definitions: Record<string, Schema>;
|
||||
contacts: { id: string; full_name: string }[];
|
||||
contactInvestors?: { id: string; legal_name: string }[];
|
||||
@@ -315,10 +316,15 @@ function Editor({
|
||||
schema = options.definitions[schema.$ref.split('/').pop()!] ?? schema;
|
||||
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
||||
const label = labels[name] ?? name.replaceAll('_', ' ');
|
||||
const parcelUnit = name === 'area_unit' && path.includes('land_rights.parcels.');
|
||||
const textLimits = path === 'canonical.demand_statement'
|
||||
? options.submissionTextLimits?.demand_statement
|
||||
: undefined;
|
||||
const descriptions = [errors[path] ? path + '-error' : '', parcelUnit ? path + '-help' : '', textLimits ? path + '-length-help' : ''].filter(Boolean).join(' ');
|
||||
const props = {
|
||||
id: path,
|
||||
'aria-invalid': !!errors[path],
|
||||
'aria-describedby': errors[path] ? path + '-error' : undefined,
|
||||
'aria-describedby': descriptions || undefined,
|
||||
};
|
||||
let input;
|
||||
if (name === 'geometry')
|
||||
@@ -409,7 +415,9 @@ function Editor({
|
||||
.filter((v) => v !== null)
|
||||
.map((v) => (
|
||||
<option key={valueText(v)} value={valueText(v)}>
|
||||
{valueText(v).replaceAll('_', ' ')}
|
||||
{name === 'area_unit'
|
||||
? ({ sqm: 'Metros quadrados (m²)', ha: 'Hectares (ha)', sqkm: 'Quilómetros quadrados (km²)' }[valueText(v) as 'sqm' | 'ha' | 'sqkm'] ?? valueText(v))
|
||||
: valueText(v).replaceAll('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -553,6 +561,21 @@ function Editor({
|
||||
{label}
|
||||
</label>
|
||||
{input}
|
||||
{textLimits && (
|
||||
<p id={path + '-length-help'} className="text-sm text-gray-600">
|
||||
Descreva a necessidade e a finalidade da oportunidade.
|
||||
Para submeter: {textLimits.minLength} a {textLimits.maxLength} caracteres.
|
||||
Texto atual: {Array.from(valueText(value ?? '').trim()).length} caracteres.
|
||||
Pode guardar o rascunho incompleto.
|
||||
</p>
|
||||
)}
|
||||
{parcelUnit && (
|
||||
<p id={path + '-help'} className="text-sm text-gray-600">
|
||||
A unidade deve ser indicada explicitamente. Registos sem
|
||||
unidade continuam por identificar; escolher outra unidade
|
||||
não converte o valor da área.
|
||||
</p>
|
||||
)}
|
||||
<FieldErrors path={path} errors={errors} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
@@ -17,6 +17,7 @@ export default function OpportunityProfileActions({
|
||||
publicationVisibility,
|
||||
conditions = [],
|
||||
conditionResponsibles = [],
|
||||
reauthenticationRequired = false,
|
||||
}: {
|
||||
id: number;
|
||||
etag: string;
|
||||
@@ -36,6 +37,7 @@ export default function OpportunityProfileActions({
|
||||
}[];
|
||||
conditionResponsibles?: { id: number; name: string }[];
|
||||
onErrors?: (errors: Record<string, string>) => void;
|
||||
reauthenticationRequired?: boolean;
|
||||
publishers?: { id: number; name: string }[];
|
||||
participants?: {
|
||||
id: number;
|
||||
@@ -54,6 +56,12 @@ export default function OpportunityProfileActions({
|
||||
const [items, setItems] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [messageIsError, setMessageIsError] = useState(false);
|
||||
const feedback = useRef<HTMLDivElement>(null);
|
||||
const [serverRequiresReauthentication, setServerRequiresReauthentication] =
|
||||
useState(false);
|
||||
const needsReauthentication =
|
||||
reauthenticationRequired || serverRequiresReauthentication;
|
||||
const [gate, setGate] = useState(gates[0] ?? '');
|
||||
const [decision, setDecision] = useState('approved');
|
||||
const [evidence, setEvidence] = useState<string[]>([]);
|
||||
@@ -92,10 +100,79 @@ export default function OpportunityProfileActions({
|
||||
suspend: 'Suspender',
|
||||
archive: 'Arquivar',
|
||||
};
|
||||
function focusFeedback() {
|
||||
requestAnimationFrame(() => feedback.current?.focus());
|
||||
}
|
||||
function renewAuthentication() {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
router.flushAll();
|
||||
// Reuse normal logout and the protected URL's intended redirect, in this window.
|
||||
router.post(
|
||||
'/logout',
|
||||
{},
|
||||
{
|
||||
preserveState: false,
|
||||
onSuccess: () =>
|
||||
router.visit(`/minhas-oportunidades/${id}/view`, {
|
||||
preserveState: false,
|
||||
}),
|
||||
onError: () => {
|
||||
setBusy(false);
|
||||
setMessageIsError(true);
|
||||
setMessage(
|
||||
'Não foi possível renovar a entrada. Os dados guardados não foram alterados.',
|
||||
);
|
||||
focusFeedback();
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
async function send(action: string) {
|
||||
if (busy) return;
|
||||
if (needsReauthentication) {
|
||||
setMessageIsError(true);
|
||||
setMessage(
|
||||
'Entre novamente nesta janela antes de executar a ação.',
|
||||
);
|
||||
focusFeedback();
|
||||
return;
|
||||
}
|
||||
const correctionItems = items
|
||||
.split('\n')
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
const inputErrors: Record<string, string> = {};
|
||||
// Mirror the existing server requirements; incomplete drafts remain saveable.
|
||||
const reasonLength = Array.from(reason.trim()).length;
|
||||
if (reasonLength < 20 || reasonLength > 1000) {
|
||||
inputErrors.reason =
|
||||
'Preencha a fundamentação com 20 a 1000 caracteres antes de executar esta ação.';
|
||||
}
|
||||
if (action === 'request_correction' && correctionItems.length === 0) {
|
||||
inputErrors.correction_items =
|
||||
'Indique pelo menos um campo ou documento a corrigir.';
|
||||
}
|
||||
if (
|
||||
action === 'request_correction' &&
|
||||
correctionItems.some((item) => Array.from(item).length > 250)
|
||||
) {
|
||||
inputErrors.correction_items =
|
||||
'Cada indicação de correção deve ter no máximo 250 caracteres.';
|
||||
}
|
||||
if (Object.keys(inputErrors).length > 0) {
|
||||
setActionErrors(inputErrors);
|
||||
onErrors?.(inputErrors);
|
||||
setMessageIsError(true);
|
||||
setMessage('A ação não foi enviada. Corrija os campos indicados.');
|
||||
focusFeedback();
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setActionErrors({});
|
||||
onErrors?.({});
|
||||
setMessageIsError(false);
|
||||
setMessage('A registar a ação…');
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${id}/workflow`,
|
||||
@@ -103,10 +180,7 @@ export default function OpportunityProfileActions({
|
||||
etag,
|
||||
action,
|
||||
reason,
|
||||
correction_items: items
|
||||
.split('\n')
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean),
|
||||
correction_items: correctionItems,
|
||||
...(['review_gate', 'respond_opinion'].includes(action)
|
||||
? {
|
||||
gate,
|
||||
@@ -116,7 +190,15 @@ export default function OpportunityProfileActions({
|
||||
: {}),
|
||||
...(action === 'review_gate'
|
||||
? {
|
||||
resolve_condition_ids: resolvedConditions,
|
||||
resolve_condition_ids: resolvedConditions.filter(
|
||||
(conditionId) =>
|
||||
conditions.some(
|
||||
(condition) =>
|
||||
condition.id === conditionId &&
|
||||
condition.gate === gate &&
|
||||
condition.status === 'open',
|
||||
),
|
||||
),
|
||||
...(conditionDescription.trim()
|
||||
? {
|
||||
condition: {
|
||||
@@ -148,26 +230,26 @@ export default function OpportunityProfileActions({
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
if (action === 'review_gate') setResolvedConditions([]);
|
||||
setMessage(result.message);
|
||||
router.visit(`/minhas-oportunidades/${id}/view`);
|
||||
router.visit(`/minhas-oportunidades/${id}/view`, {
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: focusFeedback,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ProfileValidationError) {
|
||||
setServerRequiresReauthentication(error.reauthenticate);
|
||||
setActionErrors(error.fields);
|
||||
onErrors?.(error.fields);
|
||||
const first = Object.keys(error.fields)[0];
|
||||
requestAnimationFrame(() =>
|
||||
document
|
||||
.getElementById(
|
||||
`workflow-${id}-${first?.startsWith('conditions.') ? 'conditions' : first}`,
|
||||
)
|
||||
?.focus(),
|
||||
);
|
||||
}
|
||||
setMessageIsError(true);
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível. Confira o estado antes de repetir.',
|
||||
);
|
||||
focusFeedback();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -178,6 +260,45 @@ export default function OpportunityProfileActions({
|
||||
aria-label="Workflow interno"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">Workflow interno</h2>
|
||||
{needsReauthentication && (
|
||||
<div className="rounded border p-3" role="alert">
|
||||
<p>
|
||||
A confirmação MFA desta janela precisa de renovação para
|
||||
validar ou publicar. Os dados já guardados permanecem
|
||||
disponíveis.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={renewAuthentication}
|
||||
>
|
||||
Entrar novamente nesta janela
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{message && (
|
||||
<div
|
||||
ref={feedback}
|
||||
tabIndex={-1}
|
||||
role={messageIsError ? 'alert' : 'status'}
|
||||
aria-live={messageIsError ? 'assertive' : 'polite'}
|
||||
className="rounded border p-3 focus:outline-2 focus:outline-offset-2"
|
||||
>
|
||||
<p>{message}</p>
|
||||
{messageIsError &&
|
||||
Object.entries(actionErrors).map(([key, text]) => (
|
||||
<p key={key}>
|
||||
{key === 'reason'
|
||||
? 'Fundamentação'
|
||||
: key === 'correction_items'
|
||||
? 'Campos ou documentos a corrigir'
|
||||
: key}
|
||||
: {text}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p>
|
||||
Guarde o contrato antes de submeter. Aprovação exige revisões
|
||||
especializadas desta versão; publicação exige outro utilizador
|
||||
@@ -229,9 +350,14 @@ export default function OpportunityProfileActions({
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
required
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
<span className="block text-sm">
|
||||
Explique o motivo desta ação: 20 a 1000 caracteres.
|
||||
Texto atual: {Array.from(reason.trim()).length} caracteres.
|
||||
</span>
|
||||
{actionErrors.reason && (
|
||||
<span
|
||||
id={`workflow-${id}-reason-error`}
|
||||
@@ -245,10 +371,25 @@ export default function OpportunityProfileActions({
|
||||
<label className="block">
|
||||
Campos ou documentos a corrigir, um por linha
|
||||
<textarea
|
||||
id={`workflow-${id}-correction_items`}
|
||||
aria-invalid={!!actionErrors.correction_items}
|
||||
aria-describedby={
|
||||
actionErrors.correction_items
|
||||
? `workflow-${id}-correction_items-error`
|
||||
: undefined
|
||||
}
|
||||
className={control}
|
||||
value={items}
|
||||
onChange={(e) => setItems(e.target.value)}
|
||||
/>
|
||||
{actionErrors.correction_items && (
|
||||
<span
|
||||
id={`workflow-${id}-correction_items-error`}
|
||||
role="alert"
|
||||
>
|
||||
{actionErrors.correction_items}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
{(actions.includes('review_gate') ||
|
||||
@@ -538,10 +679,13 @@ export default function OpportunityProfileActions({
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{actions.map((action) => (
|
||||
<button
|
||||
type="button"
|
||||
key={action}
|
||||
className={button}
|
||||
disabled={
|
||||
busy || (action === 'publish' && !confirmed)
|
||||
busy ||
|
||||
needsReauthentication ||
|
||||
(action === 'publish' && !confirmed)
|
||||
}
|
||||
onClick={() => void send(action)}
|
||||
>
|
||||
@@ -551,9 +695,6 @@ export default function OpportunityProfileActions({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<p role="status" aria-live="polite">
|
||||
{message}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ export function PortalGroupedMenu() {
|
||||
canManagePortal: boolean;
|
||||
};
|
||||
existingBusinessEnabled?: boolean;
|
||||
businessReviewUrl?: string | null;
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
legacyContentEnabled?: boolean;
|
||||
@@ -29,6 +30,7 @@ export function PortalGroupedMenu() {
|
||||
authenticated: !!props.auth?.user,
|
||||
manager: !!props.auth?.canManagePortal,
|
||||
businesses: props.existingBusinessEnabled,
|
||||
businessReviewUrl: props.businessReviewUrl,
|
||||
education: props.educationEnabled,
|
||||
ai: props.aiEnabled,
|
||||
legacyContent: props.legacyContentEnabled,
|
||||
|
||||
@@ -11,6 +11,7 @@ export type PortalNavAccess = {
|
||||
authenticated: boolean;
|
||||
manager: boolean;
|
||||
businesses?: boolean;
|
||||
businessReviewUrl?: string | null;
|
||||
education?: boolean;
|
||||
ai?: boolean;
|
||||
legacyContent?: boolean;
|
||||
@@ -133,6 +134,9 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...(access.authenticated && access.businesses && access.businessReviewUrl
|
||||
? [link('review-businesses', 'Revisão de negócios', access.businessReviewUrl)]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@ export class ProfileValidationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly fields: Record<string, string>,
|
||||
public readonly reauthenticate = false,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
@@ -33,6 +34,7 @@ export async function profileJson(
|
||||
Array.isArray(value) ? value.join(' ') : String(value),
|
||||
]),
|
||||
),
|
||||
response.headers.get('X-Portal-Reauthentication') === 'required',
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -54,10 +54,25 @@ export default function BusinessInterest({
|
||||
});
|
||||
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(newSubmissionKey());
|
||||
const update = <K extends keyof Form>(field: K, value: Form[K]) =>
|
||||
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) {
|
||||
@@ -88,10 +103,20 @@ export default function BusinessInterest({
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
data.message ?? 'Não foi possível enviar a manifestação.',
|
||||
);
|
||||
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({});
|
||||
setReceipt(data.data.reference);
|
||||
key.current = newSubmissionKey();
|
||||
} catch (cause) {
|
||||
@@ -123,9 +148,11 @@ export default function BusinessInterest({
|
||||
</section>
|
||||
) : (
|
||||
<form className={`${card} space-y-4`} onSubmit={submit}>
|
||||
<Field label="País de origem declarado desta solicitação">
|
||||
<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) =>
|
||||
@@ -136,16 +163,18 @@ export default function BusinessInterest({
|
||||
Origem opcional e independente do país do
|
||||
investidor.
|
||||
</p>
|
||||
</Field>
|
||||
</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
|
||||
@@ -153,22 +182,27 @@ export default function BusinessInterest({
|
||||
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)
|
||||
@@ -182,32 +216,38 @@ export default function BusinessInterest({
|
||||
</option>
|
||||
<option value="outro">Outro</option>
|
||||
</select>
|
||||
{fieldError('investorType')}
|
||||
</Field>
|
||||
<Field label="País">
|
||||
<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)}
|
||||
/>
|
||||
</Field>
|
||||
</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)}
|
||||
>
|
||||
@@ -217,16 +257,19 @@ export default function BusinessInterest({
|
||||
</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
|
||||
@@ -235,14 +278,17 @@ export default function BusinessInterest({
|
||||
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)
|
||||
@@ -271,7 +317,8 @@ export default function BusinessInterest({
|
||||
equipa.
|
||||
</span>
|
||||
</label>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{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>
|
||||
|
||||
@@ -272,6 +272,49 @@ export default function BusinessWizard({
|
||||
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;
|
||||
@@ -1126,10 +1169,41 @@ export default function BusinessWizard({
|
||||
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 ||
|
||||
|
||||
@@ -226,6 +226,7 @@ function Editor({
|
||||
className={input}
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
aria-describedby="business-transition-help"
|
||||
minLength={10}
|
||||
maxLength={1000}
|
||||
required
|
||||
@@ -257,6 +258,15 @@ function Editor({
|
||||
designados. Esta autorização não permite publicação.
|
||||
</label>
|
||||
)}
|
||||
{(canTriage || canReview || canApproveLevelOne || canApproveLevelTwo || canPublish) && (
|
||||
<p id="business-transition-help" role="status" className="my-3">
|
||||
{busy
|
||||
? 'Aguarde a conclusão da ação em curso.'
|
||||
: note.trim().length < 10
|
||||
? 'Para disponibilizar a ação, preencha «Motivo da alteração ou nota para a revisão» com pelo menos 10 caracteres. A nota fica no histórico reservado.'
|
||||
: 'Nota preenchida. Pode executar a ação disponível para o seu papel e o estado atual.'}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{owner && canEdit && (
|
||||
<button
|
||||
@@ -291,6 +301,7 @@ function Editor({
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
aria-describedby="business-transition-help"
|
||||
onClick={() => void run('triage')}
|
||||
>
|
||||
Iniciar triagem
|
||||
|
||||
@@ -521,18 +521,30 @@ export default function Catalogue({
|
||||
<Field label="Estado de preparação">
|
||||
<select
|
||||
className={input}
|
||||
aria-describedby="maturity-catalogue-note"
|
||||
value={form.data.maturity_level}
|
||||
onChange={(e) =>
|
||||
form.setData('maturity_level', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos os níveis</option>
|
||||
{MATURITY_LEVELS.map((label, index) => (
|
||||
{(references.maturityCatalogue
|
||||
? Object.values(references.maturityCatalogue.stages)
|
||||
: MATURITY_LEVELS
|
||||
).map((label, index) => (
|
||||
<option key={index + 1} value={index + 1}>
|
||||
{label}
|
||||
{references.maturityCatalogue
|
||||
? `${index + 1} — ${references.maturityCatalogue.legacyLabels[index + 1] ? `${references.maturityCatalogue.legacyLabels[index + 1]} (${references.maturityCatalogue.legacyVersion}) / ` : ''}${label} (${references.maturityCatalogue.version})`
|
||||
: label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p id="maturity-catalogue-note" className="text-sm">
|
||||
O filtro usa a posição registada. Os catálogos
|
||||
histórico e V2 conservam significados distintos nas
|
||||
posições 1–6; consulte a maturidade apresentada na
|
||||
ficha. As posições 7–8 pertencem ao catálogo V2.
|
||||
</p>
|
||||
</Field>
|
||||
{(['min_amount', 'max_amount'] as const).map((key) => (
|
||||
<Field
|
||||
|
||||
@@ -174,6 +174,14 @@ export default function Detail({
|
||||
['Promotor', r.promoter_name],
|
||||
['Investimento', money(r)],
|
||||
['Maturidade', r.maturity_label],
|
||||
[
|
||||
'Catálogo de maturidade',
|
||||
r.maturity_catalogue_version === 'spec-v2'
|
||||
? 'Oito etapas (V2)'
|
||||
: r.maturity_catalogue_version === 'legacy-v1'
|
||||
? 'Histórico — seis níveis'
|
||||
: 'Versão não registada',
|
||||
],
|
||||
['Parceria', r.financing_modality],
|
||||
['Impacto', r.expected_impact],
|
||||
['Calendário', c.profile?.target_date],
|
||||
|
||||
@@ -23,6 +23,12 @@ export type Entity = {
|
||||
geography?: StructureGeography | null;
|
||||
};
|
||||
export type References = {
|
||||
maturityCatalogue?: {
|
||||
version: string;
|
||||
stages: Record<string, string>;
|
||||
legacyVersion: string;
|
||||
legacyLabels: Record<number, string>;
|
||||
};
|
||||
zones?: { id: string; name: string; category: string }[];
|
||||
options: Option[];
|
||||
clusters: Entity[];
|
||||
@@ -44,6 +50,7 @@ export type Opportunity = {
|
||||
estimated_investment_amount: string | null;
|
||||
estimated_investment_currency: string;
|
||||
maturity_label: string | null;
|
||||
maturity_catalogue_version?: string | null;
|
||||
promoter_name: string | null;
|
||||
expected_impact: string | null;
|
||||
financing_modality: string | null;
|
||||
|
||||
@@ -427,6 +427,7 @@ export default function InvestmentPath(path: Path) {
|
||||
library: 'Biblioteca',
|
||||
opportunities: 'Oportunidades',
|
||||
territory: 'Território e mapas',
|
||||
land: 'Preparar Terra e DUAT',
|
||||
partners: 'Parcerias',
|
||||
} as Record<string, string>
|
||||
)[key]
|
||||
|
||||
@@ -24,6 +24,7 @@ type Props = {
|
||||
}[];
|
||||
disclaimer: string;
|
||||
management: boolean;
|
||||
returnDossier?: { id: string; title: string; url: string } | null;
|
||||
countryName: string;
|
||||
declaredOrigin: { code: string | null; name: string };
|
||||
territoryPaths: { id: string; name: string; location_type: string }[][];
|
||||
@@ -63,6 +64,7 @@ export default function LandCase({
|
||||
countryName,
|
||||
declaredOrigin,
|
||||
territoryPaths,
|
||||
returnDossier,
|
||||
}: Props) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [category, setCategory] = useState('other');
|
||||
@@ -102,6 +104,7 @@ export default function LandCase({
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header className="space-y-2">
|
||||
{returnDossier && <Link className="underline" href={returnDossier.url}>Voltar ao dossier: {returnDossier.title}</Link>}
|
||||
<Link href="/investidor/terra-duat" className="underline">
|
||||
Os meus pedidos Terra e DUAT
|
||||
</Link>
|
||||
@@ -287,7 +290,7 @@ export default function LandCase({
|
||||
{document.status === 'active' ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/investidor/terra-duat/${record.id}/documentos/${document.id}`}
|
||||
href={`/${management ? 'management' : 'investidor'}/terra-duat/${record.id}/documentos/${document.id}`}
|
||||
>
|
||||
{categoryLabels[document.category] ??
|
||||
document.category}
|
||||
|
||||
@@ -95,6 +95,7 @@ export default function LandForm({
|
||||
disclaimer,
|
||||
modelVersion,
|
||||
countries,
|
||||
returnDossier,
|
||||
}: {
|
||||
case: {
|
||||
id: string;
|
||||
@@ -107,10 +108,11 @@ export default function LandForm({
|
||||
disclaimer: string;
|
||||
modelVersion: string;
|
||||
countries: Country[];
|
||||
returnDossier?: { id: string; title: string; url: string } | null;
|
||||
}) {
|
||||
const [step, setStep] = useState(0);
|
||||
const initial = useMemo(
|
||||
() => existing?.payload ?? emptyPayload(user),
|
||||
() => existing?.payload ?? { ...emptyPayload(user), ...(returnDossier ? { investor_path_case_id: returnDossier.id } : {}) },
|
||||
[existing?.id],
|
||||
);
|
||||
const form = useForm({ version: existing?.version ?? 1, payload: initial });
|
||||
@@ -225,6 +227,7 @@ export default function LandForm({
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header className="space-y-2">
|
||||
{returnDossier && <Link className="underline" href={returnDossier.url}>Voltar ao dossier: {returnDossier.title}</Link>}
|
||||
<Link href="/terra-duat" className="underline">
|
||||
Terra e DUAT
|
||||
</Link>
|
||||
@@ -1289,58 +1292,84 @@ function ParcelEditor({
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const [path, setPath] = useState<TerritoryOption[]>([]);
|
||||
const [recoveryError, setRecoveryError] = useState('');
|
||||
const [recovering, setRecovering] = useState(false);
|
||||
const [recoveryRetry, setRecoveryRetry] = useState(0);
|
||||
const provinceId = parcel.province_id ?? '';
|
||||
const districtId = parcel.district_id ?? '';
|
||||
const postId = parcel.admin_post_id ?? '';
|
||||
const localityId = parcel.locality_id ?? '';
|
||||
useEffect(() => {
|
||||
const ids = [
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
]
|
||||
.map((k) => parcel[k])
|
||||
.filter(Boolean);
|
||||
if (!ids.length) {
|
||||
const ids = [provinceId, districtId, postId, localityId];
|
||||
const types = ['province', 'district', 'admin_post', 'locality'];
|
||||
const labels = ['Província', 'Distrito', 'Posto administrativo', 'Localidade'];
|
||||
const abort = new AbortController();
|
||||
setRecoveryError('');
|
||||
if (!ids.some(Boolean)) {
|
||||
setPath([]);
|
||||
setRecovering(false);
|
||||
return;
|
||||
}
|
||||
const abort = new AbortController();
|
||||
setRecovering(true);
|
||||
let level = 0;
|
||||
void (async () => {
|
||||
const result: TerritoryOption[] = [];
|
||||
let parent = '';
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const type = ['province', 'district', 'admin_post', 'locality'][
|
||||
i
|
||||
];
|
||||
for (level = 0; level < ids.length; level++) {
|
||||
const savedId = ids[level];
|
||||
if (!savedId) {
|
||||
if (ids.slice(level + 1).some(Boolean))
|
||||
throw new Error('Falta um nível anterior na localização guardada.');
|
||||
break;
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
type,
|
||||
id: ids[i],
|
||||
type: types[level],
|
||||
id: savedId,
|
||||
...(parent ? { parent_id: parent } : {}),
|
||||
});
|
||||
const response = await fetch(
|
||||
`/api/v1/investment/territory-options?${params}`,
|
||||
{
|
||||
signal: abort.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
);
|
||||
if (!response.ok) break;
|
||||
const response = await fetch(`/api/v1/investment/territory-options?${params}`, {
|
||||
signal: abort.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok)
|
||||
throw new Error(`A consulta devolveu HTTP ${response.status}.`);
|
||||
const body = await response.json();
|
||||
const option = body.data?.[0] as TerritoryOption | undefined;
|
||||
if (!option) break;
|
||||
const option = (body.data as TerritoryOption[] | undefined)?.find(
|
||||
(row) => row.id === savedId && row.location_type === types[level]
|
||||
&& (!parent || row.parent_id === parent),
|
||||
);
|
||||
if (!option)
|
||||
throw new Error('A opção guardada não foi encontrada no nível e hierarquia indicados.');
|
||||
result.push(option);
|
||||
parent = option.id;
|
||||
}
|
||||
if (!abort.signal.aborted) setPath(result);
|
||||
})().catch(() => {});
|
||||
})().catch((error: unknown) => {
|
||||
if (!abort.signal.aborted)
|
||||
setRecoveryError(`Não foi possível recuperar ${labels[level] ?? 'a localização'}. ${error instanceof Error ? error.message : 'Erro de ligação.'} Os identificadores guardados foram preservados; não volte a selecionar para contornar a falha.`);
|
||||
}).finally(() => {
|
||||
if (!abort.signal.aborted) setRecovering(false);
|
||||
});
|
||||
return () => abort.abort();
|
||||
}, []);
|
||||
}, [provinceId, districtId, postId, localityId, recoveryRetry]);
|
||||
const initial = useMemo(() => path, [path]);
|
||||
return (
|
||||
<fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2">
|
||||
<legend className="px-1 font-semibold">
|
||||
Parcela/área {index + 1}
|
||||
</legend>
|
||||
{recovering && <p role="status">A recuperar a localização guardada…</p>}
|
||||
{recoveryError && (
|
||||
<div role="alert" className="sm:col-span-2">
|
||||
<p>{recoveryError}</p>
|
||||
<button type="button" onClick={() => setRecoveryRetry((value) => value + 1)}>
|
||||
Tentar recuperar novamente
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="sm:col-span-2">
|
||||
<TerritoryFields
|
||||
disabled={recovering || Boolean(recoveryError)}
|
||||
initial={initial}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(next) => {
|
||||
|
||||
@@ -65,6 +65,7 @@ export default function OpportunityDraft({
|
||||
profileContext,
|
||||
profileAccess,
|
||||
profileActions = [],
|
||||
profileReauthenticationRequired = false,
|
||||
canonicalOptions,
|
||||
workflowState,
|
||||
canonicalResponse,
|
||||
@@ -79,6 +80,7 @@ export default function OpportunityDraft({
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
profileActions?: string[];
|
||||
profileReauthenticationRequired?: boolean;
|
||||
profileContext?: Record<string, unknown> | null;
|
||||
profileAccess?: {
|
||||
internalPromoter?: boolean;
|
||||
@@ -953,6 +955,7 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{profileMode && record && etag && (
|
||||
<OpportunityProfileActions
|
||||
reauthenticationRequired={profileReauthenticationRequired}
|
||||
conditions={
|
||||
Object.values(profileContext?.conditions ?? {}) as {
|
||||
id: string;
|
||||
|
||||
@@ -242,6 +242,11 @@ function RoomPage(p: Props) {
|
||||
? `${p.documents.length} documento(s) disponível(is) para esta conta.`
|
||||
: 'Nenhum documento está autorizado para consulta por esta conta nesta sala.'}
|
||||
</p>
|
||||
{!mutable && p.documents.some((d) => d.shared && d.owner_id === auth.user.id) && (
|
||||
<p role="status" aria-live="polite">
|
||||
A sala está encerrada. O autor pode retirar uma autorização de partilha existente; novas partilhas permanecem indisponíveis.
|
||||
</p>
|
||||
)}
|
||||
{p.documents.map((d) => (
|
||||
<article key={d.id}>
|
||||
<p>
|
||||
@@ -251,7 +256,7 @@ function RoomPage(p: Props) {
|
||||
: 'Privado do autor'}{' '}
|
||||
· Análise: {d.malware_scan_status}
|
||||
</p>
|
||||
{mutable && d.owner_id === auth.user.id && (
|
||||
{d.owner_id === auth.user.id && (mutable || d.shared) && (
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
|
||||
Reference in New Issue
Block a user