@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user