fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -118,5 +118,6 @@ export default function Register({ passwordRules }: Props) {
|
||||
|
||||
Register.layout = {
|
||||
title: 'Criar conta',
|
||||
description: 'Crie uma conta simples para continuar e acompanhar a sua operação. Não é necessário configurar MFA para participar.',
|
||||
description:
|
||||
'Crie uma conta simples para continuar e acompanhar a sua operação. Não é necessário configurar MFA para participar.',
|
||||
};
|
||||
|
||||
@@ -146,7 +146,9 @@ export default function Case({
|
||||
const requestForm = useForm({
|
||||
service_version_id: services[0]?.id ?? '',
|
||||
client_key: createOperationKey(),
|
||||
opportunity: new URLSearchParams(usePage().url.split('?')[1] ?? '').get('opportunity'),
|
||||
opportunity: new URLSearchParams(usePage().url.split('?')[1] ?? '').get(
|
||||
'opportunity',
|
||||
),
|
||||
});
|
||||
const stageForm = useForm({
|
||||
version: dossier.version,
|
||||
|
||||
@@ -139,7 +139,10 @@ export default function RequestPage({
|
||||
values={form.data.payload}
|
||||
boundRevision={boundContextRevision}
|
||||
readOnly={!canEdit}
|
||||
allowedFields={[...Object.keys(definition.fields), 'context_opportunity'].filter(
|
||||
allowedFields={[
|
||||
...Object.keys(definition.fields),
|
||||
'context_opportunity',
|
||||
].filter(
|
||||
(k) =>
|
||||
request.status !== 'returned' ||
|
||||
request.editable_fields.includes(k),
|
||||
|
||||
@@ -1,12 +1,48 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { Frame, input, button, card } from './shared';
|
||||
import { ClassificationEditor, ClassificationSummary, classificationStates, type ClassificationRelation, type ClassificationOptions, type PublicClassification } from '@/components/opportunity-classification';
|
||||
import {
|
||||
ClassificationEditor,
|
||||
ClassificationSummary,
|
||||
classificationStates,
|
||||
type ClassificationRelation,
|
||||
type ClassificationOptions,
|
||||
type PublicClassification,
|
||||
} from '@/components/opportunity-classification';
|
||||
|
||||
type ReviewRow = { hash: string; relation: ClassificationRelation; state: string; dimension: string; can_review: boolean; history: { state: string; at: string; reason: string }[] };
|
||||
type Supplement = { id: string; title: string; status: string; version_no: number; rows: ReviewRow[]; publication: PublicClassification[]; preview: PublicClassification[]; publication_version: number | null; can_prepare: boolean; can_disclose: boolean; options: ClassificationOptions; authorities: { id: string; label_pt_mz: string }[]; documents: { id: string; payload: { title?: string }; file: { file_name: string } }[] };
|
||||
type ReviewRow = {
|
||||
hash: string;
|
||||
relation: ClassificationRelation;
|
||||
state: string;
|
||||
dimension: string;
|
||||
can_review: boolean;
|
||||
history: { state: string; at: string; reason: string }[];
|
||||
};
|
||||
type Supplement = {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
version_no: number;
|
||||
rows: ReviewRow[];
|
||||
publication: PublicClassification[];
|
||||
preview: PublicClassification[];
|
||||
publication_version: number | null;
|
||||
can_prepare: boolean;
|
||||
can_disclose: boolean;
|
||||
options: ClassificationOptions;
|
||||
authorities: { id: string; label_pt_mz: string }[];
|
||||
documents: {
|
||||
id: string;
|
||||
payload: { title?: string };
|
||||
file: { file_name: string };
|
||||
}[];
|
||||
};
|
||||
|
||||
export default function BusinessClassification({ supplement }: { supplement: Supplement }) {
|
||||
export default function BusinessClassification({
|
||||
supplement,
|
||||
}: {
|
||||
supplement: Supplement;
|
||||
}) {
|
||||
const [current, setCurrent] = useState(supplement);
|
||||
const [rows, setRows] = useState(supplement.rows.map((r) => r.relation));
|
||||
const [reason, setReason] = useState('');
|
||||
@@ -16,64 +52,287 @@ export default function BusinessClassification({ supplement }: { supplement: Sup
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [preview, setPreview] = useState(false);
|
||||
const alert = useRef<HTMLDivElement>(null);
|
||||
const dirty = JSON.stringify(rows) !== JSON.stringify(current.rows.map((r) => r.relation));
|
||||
const dirty =
|
||||
JSON.stringify(rows) !==
|
||||
JSON.stringify(current.rows.map((r) => r.relation));
|
||||
async function act(action: string, fields: Record<string, unknown> = {}) {
|
||||
setBusy(true); setError(''); setErrors({}); setMessage('');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
try {
|
||||
const token = decodeURIComponent(document.cookie.split('; ').find((v) => v.startsWith('XSRF-TOKEN='))?.slice(11) ?? '');
|
||||
const response = await fetch(`/api/v1/existing-business/listings/${current.id}/classification`, { method: 'POST', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-XSRF-TOKEN': token }, body: JSON.stringify({ action, version_no: current.version_no, reason, ...fields }) });
|
||||
const token = decodeURIComponent(
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
const response = await fetch(
|
||||
`/api/v1/existing-business/listings/${current.id}/classification`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action,
|
||||
version_no: current.version_no,
|
||||
reason,
|
||||
...fields,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
const details = Object.fromEntries(Object.entries(result.errors ?? {}).map(([key, value]) => [key, (value as string[]).join(' ')]));
|
||||
const details = Object.fromEntries(
|
||||
Object.entries(result.errors ?? {}).map(([key, value]) => [
|
||||
key,
|
||||
(value as string[]).join(' '),
|
||||
]),
|
||||
);
|
||||
setErrors(details);
|
||||
throw new Error(Object.values(details)[0] || result.message || 'Não foi possível concluir. Os valores preparados permanecem no formulário.');
|
||||
throw new Error(
|
||||
Object.values(details)[0] ||
|
||||
result.message ||
|
||||
'Não foi possível concluir. Os valores preparados permanecem no formulário.',
|
||||
);
|
||||
}
|
||||
setCurrent(result.supplement); setRows(result.supplement.rows.map((r: ReviewRow) => r.relation)); setPreview(false);
|
||||
setMessage(action === 'prepare' ? 'Classificação guardada e recuperada. A publicação anterior mantém-se.' : action === 'review' ? 'Decisão registada. A divulgação continua separada.' : action === 'withdraw' ? 'Projeção da classificação retirada; anúncio preservado.' : 'Nova fotografia da classificação divulgada; anúncio preservado.');
|
||||
setCurrent(result.supplement);
|
||||
setRows(result.supplement.rows.map((r: ReviewRow) => r.relation));
|
||||
setPreview(false);
|
||||
setMessage(
|
||||
action === 'prepare'
|
||||
? 'Classificação guardada e recuperada. A publicação anterior mantém-se.'
|
||||
: action === 'review'
|
||||
? 'Decisão registada. A divulgação continua separada.'
|
||||
: action === 'withdraw'
|
||||
? 'Projeção da classificação retirada; anúncio preservado.'
|
||||
: 'Nova fotografia da classificação divulgada; anúncio preservado.',
|
||||
);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Não foi possível concluir. Preserve os valores e atualize a página.');
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível concluir. Preserve os valores e atualize a página.',
|
||||
);
|
||||
requestAnimationFrame(() => alert.current?.focus());
|
||||
} finally { setBusy(false); }
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
const previewRows = current.preview;
|
||||
return <Frame title="Classificação do anúncio">
|
||||
<div className="mx-auto max-w-5xl space-y-5">
|
||||
<Link className="underline" href={`/investidor/negocios/${current.id}`}>Voltar ao mesmo anúncio</Link>
|
||||
<h1 className="text-2xl font-bold">{current.title}</h1>
|
||||
<p>Anúncio {current.status === 'published' ? 'publicado' : 'em preparação'} · versão {current.version_no}</p>
|
||||
<p>Este suplemento altera apenas a classificação. Conteúdo, confidencialidade e workflow do anúncio mantêm-se. Guardar ou confirmar uma relação não a divulga.</p>
|
||||
{error && <div ref={alert} tabIndex={-1} role="alert" className="rounded border border-red-600 p-3">{error}</div>}
|
||||
{message && <p role="status">{message}</p>}
|
||||
{current.can_prepare && <section className={card}>
|
||||
<ClassificationEditor rows={rows} onChange={setRows} options={current.options} documents={current.documents} authorities={current.authorities} errors={errors} />
|
||||
</section>}
|
||||
<label className="grid gap-1">Fundamento da ação <textarea className={input} value={reason} onChange={(e) => setReason(e.target.value)} minLength={20} maxLength={1000} /></label>
|
||||
<p className="text-sm">Indique o fundamento da operação, com pelo menos 20 caracteres. A nota permanece privada.</p>
|
||||
{current.can_prepare && <button className={button} disabled={busy} onClick={() => void act('prepare', { rows })}>Guardar classificação privada</button>}
|
||||
<section className="space-y-4" aria-label="Decisões por relação">
|
||||
<h2 className="text-xl font-bold">Relações guardadas e decisões</h2>
|
||||
{!current.rows.length && <p>Ainda não existem relações guardadas.</p>}
|
||||
{current.rows.map((r) => <article key={r.hash} className={card}>
|
||||
<h3 className="font-bold">{current.options.targets[r.relation.classification!.target_type]?.find((t) => String(t.id) === r.relation.related_id)?.label ?? 'Referência indisponível'}</h3>
|
||||
<p>{current.options.dimensions[r.dimension]} · {current.options.purposes[r.relation.classification!.purpose]} · {classificationStates[r.state]}</p>
|
||||
<p>Fonte: {r.relation.classification!.source_reference || 'Por indicar'} · {r.relation.classification!.citation || 'Citação por indicar'}</p>
|
||||
<p>Fundamento: {r.relation.classification!.justification || 'Por indicar'}</p>
|
||||
{r.can_review ? <div className="flex flex-wrap gap-2">{['confirmed', 'in_validation', 'rejected', 'revoked', 'archived'].map((state) => <button key={state} className={button} disabled={busy || dirty} onClick={() => void act('review', { hash: r.hash, state })}>{classificationStates[state]}</button>)}</div> : <p>Decisão indisponível nesta sessão: requer Validador independente, âmbito, responsabilidade e MFA aplicáveis.</p>}
|
||||
{!!r.history.length && <details><summary>Histórico de decisões</summary><ul>{r.history.map((h, i) => <li key={i}>{h.at} · {classificationStates[h.state]} · {h.reason}</li>)}</ul></details>}
|
||||
</article>)}
|
||||
</section>
|
||||
<section className={card} aria-label="Fotografia pública atual">
|
||||
<h2 className="text-xl font-bold">Fotografia pública atual</h2>
|
||||
<p>{current.publication_version ? `Divulgada na versão ${current.publication_version}.` : 'Sem classificação divulgada; o teaser anterior mantém-se.'}</p>
|
||||
<ClassificationSummary rows={current.publication} />
|
||||
</section>
|
||||
{current.can_disclose && <section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-bold">Divulgação expressa da classificação</h2>
|
||||
<p>Apenas as relações guardadas com intenção de divulgação pública integram a fotografia. Notas, contactos, critérios privados e ficheiros de suporte permanecem privados.</p>
|
||||
<button className={button} disabled={busy || dirty} onClick={() => setPreview(!preview)}>Conferir nova fotografia pública</button>
|
||||
{preview && <div><ClassificationSummary rows={previewRows} /><button className={button} disabled={busy || dirty} onClick={() => void act('disclose')}>Divulgar esta classificação</button></div>}
|
||||
<button className={button} disabled={busy} onClick={() => void act('withdraw')}>Retirar apenas a classificação pública</button>
|
||||
</section>}
|
||||
</div>
|
||||
</Frame>;
|
||||
return (
|
||||
<Frame title="Classificação do anúncio">
|
||||
<div className="mx-auto max-w-5xl space-y-5">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investidor/negocios/${current.id}`}
|
||||
>
|
||||
Voltar ao mesmo anúncio
|
||||
</Link>
|
||||
<h1 className="text-2xl font-bold">{current.title}</h1>
|
||||
<p>
|
||||
Anúncio{' '}
|
||||
{current.status === 'published'
|
||||
? 'publicado'
|
||||
: 'em preparação'}{' '}
|
||||
· versão {current.version_no}
|
||||
</p>
|
||||
<p>
|
||||
Este suplemento altera apenas a classificação. Conteúdo,
|
||||
confidencialidade e workflow do anúncio mantêm-se. Guardar
|
||||
ou confirmar uma relação não a divulga.
|
||||
</p>
|
||||
{error && (
|
||||
<div
|
||||
ref={alert}
|
||||
tabIndex={-1}
|
||||
role="alert"
|
||||
className="rounded border border-red-600 p-3"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
{current.can_prepare && (
|
||||
<section className={card}>
|
||||
<ClassificationEditor
|
||||
rows={rows}
|
||||
onChange={setRows}
|
||||
options={current.options}
|
||||
documents={current.documents}
|
||||
authorities={current.authorities}
|
||||
errors={errors}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<label className="grid gap-1">
|
||||
Fundamento da ação{' '}
|
||||
<textarea
|
||||
className={input}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Indique o fundamento da operação, com pelo menos 20
|
||||
caracteres. A nota permanece privada.
|
||||
</p>
|
||||
{current.can_prepare && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void act('prepare', { rows })}
|
||||
>
|
||||
Guardar classificação privada
|
||||
</button>
|
||||
)}
|
||||
<section
|
||||
className="space-y-4"
|
||||
aria-label="Decisões por relação"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Relações guardadas e decisões
|
||||
</h2>
|
||||
{!current.rows.length && (
|
||||
<p>Ainda não existem relações guardadas.</p>
|
||||
)}
|
||||
{current.rows.map((r) => (
|
||||
<article key={r.hash} className={card}>
|
||||
<h3 className="font-bold">
|
||||
{current.options.targets[
|
||||
r.relation.classification!.target_type
|
||||
]?.find(
|
||||
(t) =>
|
||||
String(t.id) === r.relation.related_id,
|
||||
)?.label ?? 'Referência indisponível'}
|
||||
</h3>
|
||||
<p>
|
||||
{current.options.dimensions[r.dimension]} ·{' '}
|
||||
{
|
||||
current.options.purposes[
|
||||
r.relation.classification!.purpose
|
||||
]
|
||||
}{' '}
|
||||
· {classificationStates[r.state]}
|
||||
</p>
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{r.relation.classification!.source_reference ||
|
||||
'Por indicar'}{' '}
|
||||
·{' '}
|
||||
{r.relation.classification!.citation ||
|
||||
'Citação por indicar'}
|
||||
</p>
|
||||
<p>
|
||||
Fundamento:{' '}
|
||||
{r.relation.classification!.justification ||
|
||||
'Por indicar'}
|
||||
</p>
|
||||
{r.can_review ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
'confirmed',
|
||||
'in_validation',
|
||||
'rejected',
|
||||
'revoked',
|
||||
'archived',
|
||||
].map((state) => (
|
||||
<button
|
||||
key={state}
|
||||
className={button}
|
||||
disabled={busy || dirty}
|
||||
onClick={() =>
|
||||
void act('review', {
|
||||
hash: r.hash,
|
||||
state,
|
||||
})
|
||||
}
|
||||
>
|
||||
{classificationStates[state]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p>
|
||||
Decisão indisponível nesta sessão: requer
|
||||
Validador independente, âmbito,
|
||||
responsabilidade e MFA aplicáveis.
|
||||
</p>
|
||||
)}
|
||||
{!!r.history.length && (
|
||||
<details>
|
||||
<summary>Histórico de decisões</summary>
|
||||
<ul>
|
||||
{r.history.map((h, i) => (
|
||||
<li key={i}>
|
||||
{h.at} ·{' '}
|
||||
{classificationStates[h.state]}{' '}
|
||||
· {h.reason}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<section className={card} aria-label="Fotografia pública atual">
|
||||
<h2 className="text-xl font-bold">
|
||||
Fotografia pública atual
|
||||
</h2>
|
||||
<p>
|
||||
{current.publication_version
|
||||
? `Divulgada na versão ${current.publication_version}.`
|
||||
: 'Sem classificação divulgada; o teaser anterior mantém-se.'}
|
||||
</p>
|
||||
<ClassificationSummary rows={current.publication} />
|
||||
</section>
|
||||
{current.can_disclose && (
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Divulgação expressa da classificação
|
||||
</h2>
|
||||
<p>
|
||||
Apenas as relações guardadas com intenção de
|
||||
divulgação pública integram a fotografia. Notas,
|
||||
contactos, critérios privados e ficheiros de suporte
|
||||
permanecem privados.
|
||||
</p>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || dirty}
|
||||
onClick={() => setPreview(!preview)}
|
||||
>
|
||||
Conferir nova fotografia pública
|
||||
</button>
|
||||
{preview && (
|
||||
<div>
|
||||
<ClassificationSummary rows={previewRows} />
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || dirty}
|
||||
onClick={() => void act('disclose')}
|
||||
>
|
||||
Divulgar esta classificação
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void act('withdraw')}
|
||||
>
|
||||
Retirar apenas a classificação pública
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,10 +53,12 @@ export default function BusinessInterest({
|
||||
privacyConsent: false,
|
||||
shareWithProponent: false,
|
||||
});
|
||||
const {form, setForm} = draft;
|
||||
const { form, setForm } = draft;
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [fieldErrors, setFieldErrors] = useState<Partial<Record<keyof Form, string>>>({});
|
||||
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]) => {
|
||||
@@ -68,13 +70,20 @@ export default function BusinessInterest({
|
||||
id: fieldId(field),
|
||||
name: field,
|
||||
'aria-invalid': !!fieldErrors[field],
|
||||
'aria-describedby': fieldErrors[field] ? `${fieldId(field)}-error` : undefined,
|
||||
'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 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) {
|
||||
@@ -104,19 +113,41 @@ export default function BusinessInterest({
|
||||
existingBusinessId: record.id,
|
||||
}),
|
||||
});
|
||||
if (response.status === 401) { draft.authenticate(); return; }
|
||||
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 ?? {})) {
|
||||
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(' ');
|
||||
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.');
|
||||
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);
|
||||
window.setTimeout(
|
||||
() =>
|
||||
document
|
||||
.getElementById(
|
||||
first
|
||||
? fieldId(first)
|
||||
: 'business-interest-feedback',
|
||||
)
|
||||
?.focus(),
|
||||
0,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setFieldErrors({});
|
||||
@@ -144,7 +175,13 @@ export default function BusinessInterest({
|
||||
{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>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.
|
||||
@@ -152,7 +189,8 @@ export default function BusinessInterest({
|
||||
</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>
|
||||
<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')}
|
||||
@@ -222,7 +260,8 @@ export default function BusinessInterest({
|
||||
</select>
|
||||
{fieldError('investorType')}
|
||||
</Field>
|
||||
<div className="space-y-1 text-sm font-medium"><span>País</span>
|
||||
<div className="space-y-1 text-sm font-medium">
|
||||
<span>País</span>
|
||||
<CountrySelect
|
||||
countries={countries}
|
||||
required
|
||||
@@ -322,7 +361,15 @@ export default function BusinessInterest({
|
||||
</span>
|
||||
</label>
|
||||
{fieldError('privacyConsent')}
|
||||
{error && <p id="business-interest-feedback" tabIndex={-1} role="alert">{error}</p>}
|
||||
{error && (
|
||||
<p
|
||||
id="business-interest-feedback"
|
||||
tabIndex={-1}
|
||||
role="alert"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button className={button} disabled={busy}>
|
||||
{busy ? 'A enviar…' : 'Enviar manifestação'}
|
||||
</button>
|
||||
|
||||
@@ -192,8 +192,7 @@ export default function BusinessWizard({
|
||||
const initial: Business['payload'] = {
|
||||
...record.payload,
|
||||
opportunity_type:
|
||||
record.payload.opportunity_type ??
|
||||
modalityFormType ?? '',
|
||||
record.payload.opportunity_type ?? modalityFormType ?? '',
|
||||
wizard_version: '2',
|
||||
};
|
||||
if (
|
||||
@@ -500,9 +499,27 @@ export default function BusinessWizard({
|
||||
)}
|
||||
>
|
||||
<div lang={english ? 'en' : 'pt'} className="space-y-5">
|
||||
<p>{t('Modalidade registada', 'Registered modality')}: {businessModalities[record.modality] ?? record.modality}</p>
|
||||
{!modalityFormType && <p role="status">{t('Pode guardar e recuperar esta preparação. O formulário específico de submissão desta modalidade ainda não está disponível; os dados e a modalidade original serão preservados.', 'You can save and recover this draft. Its specific submission form is not available yet; the original modality and data are preserved.')}</p>}
|
||||
<a className="underline" href={`/investidor/negocios/${record.id}/classificacao`}>{t('Classificação multidimensional deste anúncio', 'Multidimensional classification of this listing')}</a>
|
||||
<p>
|
||||
{t('Modalidade registada', 'Registered modality')}:{' '}
|
||||
{businessModalities[record.modality] ?? record.modality}
|
||||
</p>
|
||||
{!modalityFormType && (
|
||||
<p role="status">
|
||||
{t(
|
||||
'Pode guardar e recuperar esta preparação. O formulário específico de submissão desta modalidade ainda não está disponível; os dados e a modalidade original serão preservados.',
|
||||
'You can save and recover this draft. Its specific submission form is not available yet; the original modality and data are preserved.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<a
|
||||
className="underline"
|
||||
href={`/investidor/negocios/${record.id}/classificacao`}
|
||||
>
|
||||
{t(
|
||||
'Classificação multidimensional deste anúncio',
|
||||
'Multidimensional classification of this listing',
|
||||
)}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
|
||||
@@ -113,7 +113,14 @@ function Editor({
|
||||
};
|
||||
return (
|
||||
<Frame title={record.payload.title}>
|
||||
<p><Link className="underline" href={`/investidor/negocios/${record.id}/classificacao`}>Classificação multidimensional deste anúncio</Link></p>
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investidor/negocios/${record.id}/classificacao`}
|
||||
>
|
||||
Classificação multidimensional deste anúncio
|
||||
</Link>
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={owner ? '/investidor/negocios' : '/management/negocios'}
|
||||
@@ -260,7 +267,11 @@ function Editor({
|
||||
designados. Esta autorização não permite publicação.
|
||||
</label>
|
||||
)}
|
||||
{(canTriage || canReview || canApproveLevelOne || canApproveLevelTwo || canPublish) && (
|
||||
{(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.'
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import CatalogueGuideLinks from '@/components/catalogue-guide-links';
|
||||
import OpportunityCorridorGroups, { type CorridorGroup } from '@/components/opportunity-corridor-groups';
|
||||
import OpportunityCorridorGroups, {
|
||||
type CorridorGroup,
|
||||
} from '@/components/opportunity-corridor-groups';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import type { EducationalArticle } from '@/components/educational-article-card';
|
||||
import OpportunitySearchFilters from '@/components/opportunity-search-filters';
|
||||
@@ -10,7 +12,7 @@ import Map from '@/components/interactive-investment-map';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import type { InvestmentMapArea } from '@/components/interactive-investment-map';
|
||||
import { type TerritoryOption } from '@/components/investment-territory';
|
||||
import { Frame, button, card, money, api, groupLabels } from './shared';
|
||||
import { Frame, button, card, money, api } from './shared';
|
||||
import type { Opportunity, References } from './shared';
|
||||
|
||||
type Feature = {
|
||||
@@ -52,12 +54,28 @@ export default function Catalogue({
|
||||
}) {
|
||||
const page = usePage<{ auth: { user: unknown } }>();
|
||||
const { auth } = page.props;
|
||||
const [investmentSelection, setInvestmentSelection] = useState<number[]>(() => {
|
||||
try { return JSON.parse(sessionStorage.getItem('investment-opportunity-selection') ?? '[]'); } catch { return []; }
|
||||
});
|
||||
const [investmentSelection, setInvestmentSelection] = useState<number[]>(
|
||||
() => {
|
||||
try {
|
||||
return JSON.parse(
|
||||
sessionStorage.getItem(
|
||||
'investment-opportunity-selection',
|
||||
) ?? '[]',
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
);
|
||||
function selectInvestment(id: number, checked: boolean) {
|
||||
const next = checked ? [...new Set([...investmentSelection, id])] : investmentSelection.filter(x => x !== id);
|
||||
setInvestmentSelection(next); sessionStorage.setItem('investment-opportunity-selection', JSON.stringify(next));
|
||||
const next = checked
|
||||
? [...new Set([...investmentSelection, id])]
|
||||
: investmentSelection.filter((x) => x !== id);
|
||||
setInvestmentSelection(next);
|
||||
sessionStorage.setItem(
|
||||
'investment-opportunity-selection',
|
||||
JSON.stringify(next),
|
||||
);
|
||||
}
|
||||
const form = useForm({
|
||||
perspective: String(filters.perspective ?? ''),
|
||||
@@ -103,7 +121,7 @@ export default function Catalogue({
|
||||
: Number(filters.maturity_level) === 8
|
||||
? 'stage:operational'
|
||||
: filters.maturity_level
|
||||
? `historical:${filters.maturity_level}`
|
||||
? `historical:${inputText(filters.maturity_level)}`
|
||||
: ''),
|
||||
),
|
||||
before: String(filters.before ?? ''),
|
||||
@@ -114,13 +132,24 @@ export default function Catalogue({
|
||||
});
|
||||
const view = String(filters.view ?? 'grid');
|
||||
const selectedStructures = [
|
||||
...(references.zones ?? []).filter((zone) =>
|
||||
['park_id', 'zee_id', 'zfi_id'].some((key) => filters[key] === zone.id),
|
||||
).map((zone) => ({ ...zone, url: `/zonas/${zone.id}` })),
|
||||
...(references.zones ?? [])
|
||||
.filter((zone) =>
|
||||
['park_id', 'zee_id', 'zfi_id'].some(
|
||||
(key) => filters[key] === zone.id,
|
||||
),
|
||||
)
|
||||
.map((zone) => ({ ...zone, url: `/zonas/${zone.id}` })),
|
||||
...(['clusters', 'corridors', 'projects'] as const).flatMap((group) =>
|
||||
references[group].filter((record) => filters[
|
||||
{ clusters: 'cluster_id', corridors: 'corridor_id', projects: 'project_id' }[group]
|
||||
] === record.id),
|
||||
references[group].filter(
|
||||
(record) =>
|
||||
filters[
|
||||
{
|
||||
clusters: 'cluster_id',
|
||||
corridors: 'corridor_id',
|
||||
projects: 'project_id',
|
||||
}[group]
|
||||
] === record.id,
|
||||
),
|
||||
),
|
||||
];
|
||||
const [territoryPath, setTerritoryPath] = useState(territorySelection);
|
||||
@@ -129,7 +158,11 @@ export default function Catalogue({
|
||||
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
|
||||
const comparisonRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (view === 'corridors' && comparison.length) comparisonRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
if (view === 'corridors' && comparison.length)
|
||||
comparisonRef.current?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
});
|
||||
}, [comparison, view]);
|
||||
const [points, setPoints] = useState<Feature[] | null>(null);
|
||||
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
|
||||
@@ -383,8 +416,10 @@ export default function Catalogue({
|
||||
/>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Oportunidades publicadas
|
||||
{filters.sector && ` · ${references.sectors.find((sector) => sector.slug === filters.sector)?.name ?? filters.sector}`}
|
||||
{territorySelection.length > 0 && ` · ${territorySelection.map((territory) => territory.name).join(' / ')}`}
|
||||
{filters.sector &&
|
||||
` · ${inputText(references.sectors.find((sector) => sector.slug === filters.sector)?.name ?? filters.sector)}`}
|
||||
{territorySelection.length > 0 &&
|
||||
` · ${territorySelection.map((territory) => territory.name).join(' / ')}`}
|
||||
</h2>
|
||||
<SearchState
|
||||
loading={searchLoading}
|
||||
@@ -392,15 +427,42 @@ export default function Catalogue({
|
||||
total={results.total}
|
||||
retry={() => runSearch()}
|
||||
/>
|
||||
{!searchLoading && !searchError && results.total === 0 && selectedStructures.length > 0 && (
|
||||
<section className={card} aria-label="Estrutura seleccionada">
|
||||
<p className="font-semibold">Sem oportunidades publicadas associadas com estes filtros.</p>
|
||||
<p>A estrutura continua disponível para consulta. A sua selecção não confirma benefícios nem disponibilidade para investimento.</p>
|
||||
{selectedStructures.map((record) => (
|
||||
record.url ? <Link key={record.id} className="block underline" href={searchTerritoryHref(record.url, page.url)}>
|
||||
Consultar ficha: {record.name}
|
||||
</Link> : <p key={record.id}>{record.name} — sem ficha pública detalhada disponível.</p>
|
||||
))}
|
||||
{!searchLoading &&
|
||||
!searchError &&
|
||||
results.total === 0 &&
|
||||
selectedStructures.length > 0 && (
|
||||
<section
|
||||
className={card}
|
||||
aria-label="Estrutura seleccionada"
|
||||
>
|
||||
<p className="font-semibold">
|
||||
Sem oportunidades publicadas associadas com estes
|
||||
filtros.
|
||||
</p>
|
||||
<p>
|
||||
A estrutura continua disponível para consulta. A sua
|
||||
selecção não confirma benefícios nem disponibilidade
|
||||
para investimento.
|
||||
</p>
|
||||
{selectedStructures.map((record) =>
|
||||
record.url ? (
|
||||
<Link
|
||||
key={record.id}
|
||||
className="block underline"
|
||||
href={searchTerritoryHref(
|
||||
record.url,
|
||||
page.url,
|
||||
)}
|
||||
>
|
||||
Consultar ficha: {record.name}
|
||||
</Link>
|
||||
) : (
|
||||
<p key={record.id}>
|
||||
{record.name} — sem ficha pública detalhada
|
||||
disponível.
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
@@ -431,25 +493,35 @@ export default function Catalogue({
|
||||
Pesquisar noutras províncias (remover localização)
|
||||
</button>
|
||||
)}
|
||||
{['grid', 'list', 'map', 'combined', 'corridors'].map((value, i) => (
|
||||
<button
|
||||
key={value}
|
||||
disabled={searchLoading || !!searchError}
|
||||
aria-pressed={view === value}
|
||||
className="rounded border px-4 py-2"
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams(query());
|
||||
params.set('view', value);
|
||||
router.get(
|
||||
`${catalogueUrl}?${params}`,
|
||||
{},
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{['Grelha', 'Lista', 'Mapa', 'Lista e mapa', 'Por corredor'][i]}
|
||||
</button>
|
||||
))}
|
||||
{['grid', 'list', 'map', 'combined', 'corridors'].map(
|
||||
(value, i) => (
|
||||
<button
|
||||
key={value}
|
||||
disabled={searchLoading || !!searchError}
|
||||
aria-pressed={view === value}
|
||||
className="rounded border px-4 py-2"
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams(query());
|
||||
params.set('view', value);
|
||||
router.get(
|
||||
`${catalogueUrl}?${params}`,
|
||||
{},
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{
|
||||
[
|
||||
'Grelha',
|
||||
'Lista',
|
||||
'Mapa',
|
||||
'Lista e mapa',
|
||||
'Por corredor',
|
||||
][i]
|
||||
}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<a
|
||||
className="underline"
|
||||
aria-disabled={searchLoading || !!searchError}
|
||||
@@ -581,8 +653,29 @@ export default function Catalogue({
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{view === 'corridors' && !searchLoading && !searchError && <OpportunityCorridorGroups groups={corridorGroups} selected={investmentSelection} onSelect={selectInvestment} onClear={()=>{setInvestmentSelection([]);sessionStorage.removeItem('investment-opportunity-selection');}} onCompare={ids=>void api('/api/v1/investment/compare?'+ids.map(id=>'ids[]='+id).join('&')).then(data=>setComparison(data.records)).catch(e=>setError(e.message))}/>}
|
||||
{view !== 'corridors' && !searchLoading &&
|
||||
{view === 'corridors' && !searchLoading && !searchError && (
|
||||
<OpportunityCorridorGroups
|
||||
groups={corridorGroups}
|
||||
selected={investmentSelection}
|
||||
onSelect={selectInvestment}
|
||||
onClear={() => {
|
||||
setInvestmentSelection([]);
|
||||
sessionStorage.removeItem(
|
||||
'investment-opportunity-selection',
|
||||
);
|
||||
}}
|
||||
onCompare={(ids) =>
|
||||
void api(
|
||||
'/api/v1/investment/compare?' +
|
||||
ids.map((id) => 'ids[]=' + id).join('&'),
|
||||
)
|
||||
.then((data) => setComparison(data.records))
|
||||
.catch((e) => setError(e.message))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{view !== 'corridors' &&
|
||||
!searchLoading &&
|
||||
!searchError &&
|
||||
(view !== 'map' || error || points?.length === 0) && (
|
||||
<div
|
||||
@@ -596,7 +689,11 @@ export default function Catalogue({
|
||||
<article key={r.id} className={card + ' space-y-3'}>
|
||||
<p className="text-sm">
|
||||
{r.sector?.name} ·{' '}
|
||||
{r.territorial_summary || [r.province, r.district].filter(Boolean).join(' / ') || 'Localização não indicada'}
|
||||
{r.territorial_summary ||
|
||||
[r.province, r.district]
|
||||
.filter(Boolean)
|
||||
.join(' / ') ||
|
||||
'Localização não indicada'}
|
||||
</p>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
@@ -607,7 +704,15 @@ export default function Catalogue({
|
||||
</h2>
|
||||
<p>{r.summary}</p>
|
||||
<p className="font-semibold">{money(r)}</p>
|
||||
<p>{r.proactive?(r.proactive.group==='ideas'?'Ideia em preparação':r.proactive.group==='needs'?'Necessidade identificada':'O que existe'):r.maturity_label}</p>
|
||||
<p>
|
||||
{r.proactive
|
||||
? r.proactive.group === 'ideas'
|
||||
? 'Ideia em preparação'
|
||||
: r.proactive.group === 'needs'
|
||||
? 'Necessidade identificada'
|
||||
: 'O que existe'
|
||||
: r.maturity_label}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
className="underline"
|
||||
@@ -624,7 +729,21 @@ export default function Catalogue({
|
||||
? 'Retirar favorito'
|
||||
: 'Guardar favorito'}
|
||||
</button>
|
||||
<label className="flex gap-2"><input type="checkbox" checked={investmentSelection.includes(r.id)} onChange={e => selectInvestment(r.id,e.target.checked)} />Escolher para preparar investimento</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={investmentSelection.includes(
|
||||
r.id,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
selectInvestment(
|
||||
r.id,
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
Escolher para preparar investimento
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -653,15 +772,19 @@ export default function Catalogue({
|
||||
)}
|
||||
{!searchLoading && !searchError && !results.total && (
|
||||
<p className={card}>
|
||||
Não há oportunidades publicadas com estes filtros no cadastro consultado.
|
||||
A informação disponível pode ser incompleta. Pode{' '}
|
||||
Não há oportunidades publicadas com estes filtros no
|
||||
cadastro consultado. A informação disponível pode ser
|
||||
incompleta. Pode{' '}
|
||||
<Link href="/apoio" className="underline">
|
||||
peça apoio
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className={view === 'corridors' ? 'hidden' : 'flex gap-6'}>
|
||||
<nav
|
||||
aria-label="Paginação"
|
||||
className={view === 'corridors' ? 'hidden' : 'flex gap-6'}
|
||||
>
|
||||
{results.prev_page_url && (
|
||||
<Link href={results.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
@@ -684,7 +807,36 @@ export default function Catalogue({
|
||||
Comparar {selected.length} oportunidades
|
||||
</button>
|
||||
)}
|
||||
{view !== 'corridors' && !!investmentSelection.length && <section className={card}><p>{investmentSelection.length} oportunidades escolhidas, conservadas ao mudar de página.</p><Link className={button} href={'/investimentos/iniciar?' + investmentSelection.map(id => 'opportunities[]='+id).join('&')}>Preparar investimento com as oportunidades escolhidas</Link><button className="ml-4 underline" onClick={() => {setInvestmentSelection([]);sessionStorage.removeItem('investment-opportunity-selection');}}>Limpar escolha</button></section>}
|
||||
{view !== 'corridors' && !!investmentSelection.length && (
|
||||
<section className={card}>
|
||||
<p>
|
||||
{investmentSelection.length} oportunidades escolhidas,
|
||||
conservadas ao mudar de página.
|
||||
</p>
|
||||
<Link
|
||||
className={button}
|
||||
href={
|
||||
'/investimentos/iniciar?' +
|
||||
investmentSelection
|
||||
.map((id) => 'opportunities[]=' + id)
|
||||
.join('&')
|
||||
}
|
||||
>
|
||||
Preparar investimento com as oportunidades escolhidas
|
||||
</Link>
|
||||
<button
|
||||
className="ml-4 underline"
|
||||
onClick={() => {
|
||||
setInvestmentSelection([]);
|
||||
sessionStorage.removeItem(
|
||||
'investment-opportunity-selection',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Limpar escolha
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
{comparison.length > 0 && (
|
||||
<div ref={comparisonRef} className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-left">
|
||||
@@ -742,7 +894,10 @@ export default function Catalogue({
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{territorial.map((d) => (
|
||||
<Link
|
||||
href={searchTerritoryHref(`/carteira/${d.id}`, page.url)}
|
||||
href={searchTerritoryHref(
|
||||
`/carteira/${d.id}`,
|
||||
page.url,
|
||||
)}
|
||||
key={d.id}
|
||||
className={card}
|
||||
>
|
||||
@@ -766,3 +921,4 @@ export default function Catalogue({
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
import { inputText } from '@/lib/input-text';
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import {ProactiveSummary} from '@/components/proactive-investment';
|
||||
import { ProactiveSummary } from '@/components/proactive-investment';
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
import InvestmentComplements, { type ComplementOption } from '@/components/investment-complements';
|
||||
import { searchTerritoryHref, investmentPreparationHref } from '@/lib/search-territory';
|
||||
import InvestmentComplements, {
|
||||
type ComplementOption,
|
||||
} from '@/components/investment-complements';
|
||||
import {
|
||||
searchTerritoryHref,
|
||||
investmentPreparationHref,
|
||||
} from '@/lib/search-territory';
|
||||
import type { EducationalArticle } from '@/components/educational-article-card';
|
||||
import { ClassificationSummary } from '@/components/opportunity-classification';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
@@ -33,33 +38,73 @@ export default function Detail({
|
||||
}) {
|
||||
const page = usePage<{ auth: { user: unknown } }>();
|
||||
const { auth } = page.props;
|
||||
const dossierContext = new URLSearchParams(page.url.split('?')[1] ?? '').get('context');
|
||||
const dossierContext = new URLSearchParams(
|
||||
page.url.split('?')[1] ?? '',
|
||||
).get('context');
|
||||
const [sharing, setSharing] = useState('');
|
||||
return (
|
||||
<Frame title={r.title}>
|
||||
{r.maturity_label === 'Em preparação' && <p className="rounded border border-amber-700 bg-amber-50 p-4"><strong>Em preparação.</strong> Consulte a oportunidade e prepare o seu investimento. A execução depende das condições e autorizações aplicáveis ao projecto.</p>}
|
||||
{r.maturity_label === 'Em preparação' && (
|
||||
<p className="rounded border border-amber-700 bg-amber-50 p-4">
|
||||
<strong>Em preparação.</strong> Consulte a oportunidade e
|
||||
prepare o seu investimento. A execução depende das condições
|
||||
e autorizações aplicáveis ao projecto.
|
||||
</p>
|
||||
)}
|
||||
<Link
|
||||
className={button}
|
||||
href={investmentPreparationHref(r.id, page.url, dossierOrigin?.id)}
|
||||
href={investmentPreparationHref(
|
||||
r.id,
|
||||
page.url,
|
||||
dossierOrigin?.id,
|
||||
)}
|
||||
>
|
||||
Iniciar ou continuar investimento com esta oportunidade
|
||||
</Link>
|
||||
<PartnershipSourceLinks type="investment" id={r.id} />
|
||||
{auth.user&&dossierContext&&<nav aria-label="Preparar esta oportunidade" className="flex flex-wrap gap-4">
|
||||
<Link className="underline" href={`/simulador-fiscal?context=${encodeURIComponent(dossierContext)}&opportunity=opportunity%3A${r.id}`}>Simular esta oportunidade</Link>
|
||||
<Link className="underline" href={`/investimentos/${encodeURIComponent(dossierContext)}?opportunity=opportunity%3A${r.id}`}>Etapas e pedidos desta oportunidade</Link>
|
||||
<Link className="underline" href={`/investidor/terra-duat/novo?context=${encodeURIComponent(dossierContext)}&opportunity=opportunity%3A${r.id}`}>Terra/DUAT desta oportunidade</Link>
|
||||
<Link className="underline" href={`/balcao-virtual/dossiers/${encodeURIComponent(dossierContext)}?opportunity=opportunity%3A${r.id}`}>Balcão desta oportunidade</Link>
|
||||
</nav>}
|
||||
{auth.user && dossierContext && (
|
||||
<nav
|
||||
aria-label="Preparar esta oportunidade"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/simulador-fiscal?context=${encodeURIComponent(dossierContext)}&opportunity=opportunity%3A${r.id}`}
|
||||
>
|
||||
Simular esta oportunidade
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${encodeURIComponent(dossierContext)}?opportunity=opportunity%3A${r.id}`}
|
||||
>
|
||||
Etapas e pedidos desta oportunidade
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investidor/terra-duat/novo?context=${encodeURIComponent(dossierContext)}&opportunity=opportunity%3A${r.id}`}
|
||||
>
|
||||
Terra/DUAT desta oportunidade
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${encodeURIComponent(dossierContext)}?opportunity=opportunity%3A${r.id}`}
|
||||
>
|
||||
Balcão desta oportunidade
|
||||
</Link>
|
||||
</nav>
|
||||
)}
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar à pesquisa
|
||||
</Link>
|
||||
<ProactiveSummary value={r.proactive}/>
|
||||
<ProactiveSummary value={r.proactive} />
|
||||
{dossierOrigin && (
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref(`/carteira/${dossierOrigin.id}`, page.url)}
|
||||
href={searchTerritoryHref(
|
||||
`/carteira/${dossierOrigin.id}`,
|
||||
page.url,
|
||||
)}
|
||||
>
|
||||
Voltar ao dossier: {dossierOrigin.title}
|
||||
</Link>
|
||||
@@ -69,7 +114,7 @@ export default function Detail({
|
||||
{r.reference} · {r.sector?.name} · {r.province} {r.district}
|
||||
</p>
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<InvestmentComplements items={complements}/>
|
||||
<InvestmentComplements items={complements} />
|
||||
<ClassificationSummary rows={c.classification ?? []} />
|
||||
<TerritorialSources sources={c.source_evidence} />
|
||||
<section className={card + ' space-y-3'}>
|
||||
@@ -103,7 +148,14 @@ export default function Detail({
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link className={button} href={investmentPreparationHref(r.id, page.url, dossierOrigin?.id)}>
|
||||
<Link
|
||||
className={button}
|
||||
href={investmentPreparationHref(
|
||||
r.id,
|
||||
page.url,
|
||||
dossierOrigin?.id,
|
||||
)}
|
||||
>
|
||||
Iniciar ou continuar o roteiro deste investimento
|
||||
</Link>
|
||||
{auth.user ? (
|
||||
@@ -263,7 +315,10 @@ export default function Detail({
|
||||
<span key={dossier.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref(`/carteira/${dossier.id}`, page.url)}
|
||||
href={searchTerritoryHref(
|
||||
`/carteira/${dossier.id}`,
|
||||
page.url,
|
||||
)}
|
||||
>
|
||||
Consultar dossier: {dossier.title}
|
||||
</Link>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1773,7 +1773,10 @@ function Editor({
|
||||
<p key={o.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref(`/oportunidades/${o.slug}?zone_id=${z.id}`, pageUrl)}
|
||||
href={searchTerritoryHref(
|
||||
`/oportunidades/${o.slug}?zone_id=${z.id}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
{o.title}
|
||||
</Link>
|
||||
@@ -1830,7 +1833,10 @@ function Editor({
|
||||
<p key={r.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref(`/carteira/${r.id}`, pageUrl)}
|
||||
href={searchTerritoryHref(
|
||||
`/carteira/${r.id}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
{r.title}
|
||||
</Link>
|
||||
|
||||
@@ -100,34 +100,80 @@ export default function Zones({
|
||||
const pageUrl = usePage().url;
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const searchForm=useRef<HTMLFormElement|null>(null);
|
||||
const searchTimer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined);
|
||||
const cancelSearch=useRef<(()=>void)|undefined>(undefined);
|
||||
const searchSequence=useRef(0);
|
||||
const [searching,setSearching]=useState(false);
|
||||
const [searchError,setSearchError]=useState('');
|
||||
const appliedKey=JSON.stringify([filters,territorySelection]);
|
||||
useEffect(()=>{searchForm.current?.reset();},[appliedKey]);
|
||||
useEffect(()=>()=>{clearTimeout(searchTimer.current);cancelSearch.current?.();},[]);
|
||||
const runSearch=(path?:TerritoryOption[])=>{
|
||||
clearTimeout(searchTimer.current);cancelSearch.current?.();
|
||||
if(!searchForm.current)return;
|
||||
const sequence=++searchSequence.current;
|
||||
const params=territorialSearchParams(new FormData(searchForm.current),path);
|
||||
setSearching(true);setSearchError('');
|
||||
router.get(`${management?'/management/investment/zones':'/zonas'}?${params}`,{}, {
|
||||
preserveState:true,preserveScroll:true,replace:true,
|
||||
onCancelToken:token=>{cancelSearch.current=()=>token.cancel();},
|
||||
onError:()=>{if(sequence===searchSequence.current)setSearchError('A pesquisa não foi concluída. Confira os filtros e tente novamente.');},
|
||||
onNetworkError:()=>{if(sequence===searchSequence.current)setSearchError('Ligação indisponível. Os filtros escolhidos foram preservados.');return false;},
|
||||
onHttpException:()=>{if(sequence===searchSequence.current)setSearchError('Não foi possível consultar esta selecção.');return false;},
|
||||
onFinish:()=>{if(sequence===searchSequence.current)setSearching(false);},
|
||||
});
|
||||
const searchForm = useRef<HTMLFormElement | null>(null);
|
||||
const searchTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const cancelSearch = useRef<(() => void) | undefined>(undefined);
|
||||
const searchSequence = useRef(0);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [searchError, setSearchError] = useState('');
|
||||
const appliedKey = JSON.stringify([filters, territorySelection]);
|
||||
useEffect(() => {
|
||||
searchForm.current?.reset();
|
||||
}, [appliedKey]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
clearTimeout(searchTimer.current);
|
||||
cancelSearch.current?.();
|
||||
},
|
||||
[],
|
||||
);
|
||||
const runSearch = (path?: TerritoryOption[]) => {
|
||||
clearTimeout(searchTimer.current);
|
||||
cancelSearch.current?.();
|
||||
if (!searchForm.current) return;
|
||||
const sequence = ++searchSequence.current;
|
||||
const params = territorialSearchParams(
|
||||
new FormData(searchForm.current),
|
||||
path,
|
||||
);
|
||||
setSearching(true);
|
||||
setSearchError('');
|
||||
router.get(
|
||||
`${management ? '/management/investment/zones' : '/zonas'}?${params}`,
|
||||
{},
|
||||
{
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
replace: true,
|
||||
onCancelToken: (token) => {
|
||||
cancelSearch.current = () => token.cancel();
|
||||
},
|
||||
onError: () => {
|
||||
if (sequence === searchSequence.current)
|
||||
setSearchError(
|
||||
'A pesquisa não foi concluída. Confira os filtros e tente novamente.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (sequence === searchSequence.current)
|
||||
setSearchError(
|
||||
'Ligação indisponível. Os filtros escolhidos foram preservados.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onHttpException: () => {
|
||||
if (sequence === searchSequence.current)
|
||||
setSearchError(
|
||||
'Não foi possível consultar esta selecção.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (sequence === searchSequence.current)
|
||||
setSearching(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
const exportParams = new URLSearchParams();
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].forEach((field, index) => {
|
||||
if (territorySelection[index]) exportParams.set(field, territorySelection[index].id);
|
||||
});
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].forEach(
|
||||
(field, index) => {
|
||||
if (territorySelection[index])
|
||||
exportParams.set(field, territorySelection[index].id);
|
||||
},
|
||||
);
|
||||
for (const key of [
|
||||
'q',
|
||||
'category',
|
||||
@@ -183,9 +229,28 @@ export default function Zones({
|
||||
>
|
||||
<Link href="/clusters">Por Cluster</Link>
|
||||
<Link href="/corredores">Por Corredor</Link>
|
||||
<Link href={searchTerritoryHref('/zonas?category=zee', pageUrl)}>Por ZEE</Link>
|
||||
<Link href={searchTerritoryHref('/zonas?category=zfi', pageUrl)}>Por ZFI</Link>
|
||||
<Link href={searchTerritoryHref('/zonas?category=industrial_park', pageUrl)}>
|
||||
<Link
|
||||
href={searchTerritoryHref(
|
||||
'/zonas?category=zee',
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
Por ZEE
|
||||
</Link>
|
||||
<Link
|
||||
href={searchTerritoryHref(
|
||||
'/zonas?category=zfi',
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
Por ZFI
|
||||
</Link>
|
||||
<Link
|
||||
href={searchTerritoryHref(
|
||||
'/zonas?category=industrial_park',
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
Parques industriais
|
||||
</Link>
|
||||
</nav>
|
||||
@@ -194,10 +259,14 @@ export default function Zones({
|
||||
<form
|
||||
ref={searchForm}
|
||||
method="get"
|
||||
onChange={(event)=>{
|
||||
if(!event.target.getAttribute('name'))return;
|
||||
clearTimeout(searchTimer.current);cancelSearch.current?.();searchSequence.current++;
|
||||
setSearching(true);setSearchError('');searchTimer.current=setTimeout(()=>runSearch(),350);
|
||||
onChange={(event) => {
|
||||
if (!event.target.getAttribute('name')) return;
|
||||
clearTimeout(searchTimer.current);
|
||||
cancelSearch.current?.();
|
||||
searchSequence.current++;
|
||||
setSearching(true);
|
||||
setSearchError('');
|
||||
searchTimer.current = setTimeout(() => runSearch(), 350);
|
||||
}}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -333,13 +402,35 @@ export default function Zones({
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
<TerritoryFields initial={territorySelection} onChange={path=>runSearch(path)} />
|
||||
<button type="button" className="underline" onClick={()=>runSearch([])}>Todo o território (remover localização)</button>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
onChange={(path) => runSearch(path)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => runSearch([])}
|
||||
>
|
||||
Todo o território (remover localização)
|
||||
</button>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<h2 className="text-xl font-semibold">{searching?'A pesquisar a selecção…':searchError?'Pesquisa por concluir':`${records.total} registos disponíveis · ${territorySelection.length?territorySelection.map(node=>node.name).join(' / '):'Todo o território'}`}</h2>
|
||||
{!searching&&!searchError&&records.total>0&&<p>A mostrar {records.from??1} a {records.to??records.data.length} de {records.total}. Página {records.current_page??1} de {records.last_page??1}.</p>}
|
||||
{searchError&&<p role="alert">{searchError}</p>}
|
||||
<h2 className="text-xl font-semibold">
|
||||
{searching
|
||||
? 'A pesquisar a selecção…'
|
||||
: searchError
|
||||
? 'Pesquisa por concluir'
|
||||
: `${records.total} registos disponíveis · ${territorySelection.length ? territorySelection.map((node) => node.name).join(' / ') : 'Todo o território'}`}
|
||||
</h2>
|
||||
{!searching && !searchError && records.total > 0 && (
|
||||
<p>
|
||||
A mostrar {records.from ?? 1} a{' '}
|
||||
{records.to ?? records.data.length} de {records.total}.
|
||||
Página {records.current_page ?? 1} de{' '}
|
||||
{records.last_page ?? 1}.
|
||||
</p>
|
||||
)}
|
||||
{searchError && <p role="alert">{searchError}</p>}
|
||||
{!management && !searching && !searchError && (
|
||||
<a
|
||||
className="underline"
|
||||
@@ -353,9 +444,21 @@ export default function Zones({
|
||||
Não foram encontrados resultados para esta pesquisa.
|
||||
</p>
|
||||
)}
|
||||
{!searching && !searchError && records.data.map((zone) => (
|
||||
<article className={card} key={zone.id}>
|
||||
<h2 className="text-xl font-bold">
|
||||
{!searching &&
|
||||
!searchError &&
|
||||
records.data.map((zone) => (
|
||||
<article className={card} key={zone.id}>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={catalogueDetailHref(
|
||||
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
|
||||
exportParams.toString(),
|
||||
)}
|
||||
>
|
||||
{zone.name}
|
||||
</Link>
|
||||
</h2>
|
||||
<Link
|
||||
className="underline"
|
||||
href={catalogueDetailHref(
|
||||
@@ -363,123 +466,121 @@ export default function Zones({
|
||||
exportParams.toString(),
|
||||
)}
|
||||
>
|
||||
{zone.name}
|
||||
Consultar ficha
|
||||
</Link>
|
||||
</h2>
|
||||
<Link
|
||||
className="underline"
|
||||
href={catalogueDetailHref(
|
||||
`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`,
|
||||
exportParams.toString(),
|
||||
{!management && (
|
||||
<Link
|
||||
className="ml-4 underline"
|
||||
href={searchTerritoryHref(
|
||||
`/oportunidades?${new URLSearchParams({ [zone.category === 'zee' ? 'zee_id' : zone.category === 'zfi' ? 'zfi_id' : 'park_id']: zone.id })}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
Ver oportunidades associadas
|
||||
</Link>
|
||||
)}
|
||||
>
|
||||
Consultar ficha
|
||||
</Link>
|
||||
{!management && (
|
||||
<Link
|
||||
className="ml-4 underline"
|
||||
href={searchTerritoryHref(`/oportunidades?${new URLSearchParams({ [zone.category === 'zee' ? 'zee_id' : zone.category === 'zfi' ? 'zfi_id' : 'park_id']: zone.id })}`, pageUrl)}
|
||||
>
|
||||
Ver oportunidades associadas
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
{zone.code} ·{' '}
|
||||
{zone.category === 'industrial_park'
|
||||
? 'Parque industrial'
|
||||
: zone.category.toUpperCase()}{' '}
|
||||
·{' '}
|
||||
{[zone.district, zone.province]
|
||||
.filter(Boolean)
|
||||
.join(', ') || 'Localização por confirmar'}
|
||||
</p>
|
||||
{zone.legal_regime && (
|
||||
<p>
|
||||
Regime jurídico:{' '}
|
||||
{parkLabels[zone.legal_regime] ??
|
||||
(['zee', 'zfi'].includes(zone.legal_regime)
|
||||
? zone.legal_regime.toUpperCase()
|
||||
: 'Por confirmar')}
|
||||
{zone.code} ·{' '}
|
||||
{zone.category === 'industrial_park'
|
||||
? 'Parque industrial'
|
||||
: zone.category.toUpperCase()}{' '}
|
||||
·{' '}
|
||||
{[zone.district, zone.province]
|
||||
.filter(Boolean)
|
||||
.join(', ') || 'Localização por confirmar'}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.development_status && (
|
||||
<p>
|
||||
Desenvolvimento:{' '}
|
||||
{parkLabels[zone.development_status] ??
|
||||
'Por confirmar'}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.availability_status && (
|
||||
<p>
|
||||
Disponibilidade para instalação:{' '}
|
||||
{parkLabels[zone.availability_status] ??
|
||||
'Não informada'}
|
||||
</p>
|
||||
)}
|
||||
{zone.area_value && (
|
||||
<p>
|
||||
Área indicada: {zone.area_value} {zone.area_unit}
|
||||
</p>
|
||||
)}
|
||||
{zone.locations?.length ? (
|
||||
<p>
|
||||
Abrangência:{' '}
|
||||
{zone.locations
|
||||
.map((location) => location.name)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{zone.activities?.length ? (
|
||||
<p>
|
||||
Actividades:{' '}
|
||||
{zone.activities
|
||||
.map(
|
||||
(activity) =>
|
||||
`${activity.name} (${({ potential: 'Potencial referido pela fonte', proposed: 'Proposta', authorized: 'Autorizada por documento', conditional: 'Condicionada', excluded: 'Excluída' } as Record<string, string>)[activity.status] ?? 'Por confirmar'})`,
|
||||
)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{!!zone.source_evidence?.length && (
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{zone.source_evidence.map((source, index) => (
|
||||
<span key={source.url}>
|
||||
{index > 0 ? ' · ' : ''}
|
||||
<a
|
||||
className="underline"
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{source.title}
|
||||
</a>
|
||||
{source.source_date
|
||||
? ` (${source.source_date})`
|
||||
: ' (data da fonte não informada)'}{' '}
|
||||
— {source.supports}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
{zone.category === 'industrial_park' && (
|
||||
<p>
|
||||
{zone.resources?.length
|
||||
? `${zone.resources.length} recursos descritos; consulte o âmbito e a fonte na ficha.`
|
||||
: 'Infraestruturas, serviços, acessos e capacidades: não informados.'}{' '}
|
||||
{!zone.activities?.length &&
|
||||
'Atividades: não informadas.'}
|
||||
</p>
|
||||
)}
|
||||
<p>{zone.description}</p>
|
||||
{management && <p>Validação: {zone.validation_status}</p>}
|
||||
{management && (
|
||||
<p>
|
||||
Versão {zone.version_no} · {zone.publication_status}
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{zone.legal_regime && (
|
||||
<p>
|
||||
Regime jurídico:{' '}
|
||||
{parkLabels[zone.legal_regime] ??
|
||||
(['zee', 'zfi'].includes(zone.legal_regime)
|
||||
? zone.legal_regime.toUpperCase()
|
||||
: 'Por confirmar')}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.development_status && (
|
||||
<p>
|
||||
Desenvolvimento:{' '}
|
||||
{parkLabels[zone.development_status] ??
|
||||
'Por confirmar'}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable &&
|
||||
zone.availability_status && (
|
||||
<p>
|
||||
Disponibilidade para instalação:{' '}
|
||||
{parkLabels[zone.availability_status] ??
|
||||
'Não informada'}
|
||||
</p>
|
||||
)}
|
||||
{zone.area_value && (
|
||||
<p>
|
||||
Área indicada: {zone.area_value}{' '}
|
||||
{zone.area_unit}
|
||||
</p>
|
||||
)}
|
||||
{zone.locations?.length ? (
|
||||
<p>
|
||||
Abrangência:{' '}
|
||||
{zone.locations
|
||||
.map((location) => location.name)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{zone.activities?.length ? (
|
||||
<p>
|
||||
Actividades:{' '}
|
||||
{zone.activities
|
||||
.map(
|
||||
(activity) =>
|
||||
`${activity.name} (${({ potential: 'Potencial referido pela fonte', proposed: 'Proposta', authorized: 'Autorizada por documento', conditional: 'Condicionada', excluded: 'Excluída' } as Record<string, string>)[activity.status] ?? 'Por confirmar'})`,
|
||||
)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{!!zone.source_evidence?.length && (
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{zone.source_evidence.map((source, index) => (
|
||||
<span key={source.url}>
|
||||
{index > 0 ? ' · ' : ''}
|
||||
<a
|
||||
className="underline"
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{source.title}
|
||||
</a>
|
||||
{source.source_date
|
||||
? ` (${source.source_date})`
|
||||
: ' (data da fonte não informada)'}{' '}
|
||||
— {source.supports}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
{zone.category === 'industrial_park' && (
|
||||
<p>
|
||||
{zone.resources?.length
|
||||
? `${zone.resources.length} recursos descritos; consulte o âmbito e a fonte na ficha.`
|
||||
: 'Infraestruturas, serviços, acessos e capacidades: não informados.'}{' '}
|
||||
{!zone.activities?.length &&
|
||||
'Atividades: não informadas.'}
|
||||
</p>
|
||||
)}
|
||||
<p>{zone.description}</p>
|
||||
{management && (
|
||||
<p>Validação: {zone.validation_status}</p>
|
||||
)}
|
||||
{management && (
|
||||
<p>
|
||||
Versão {zone.version_no} ·{' '}
|
||||
{zone.publication_status}
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação" className="flex gap-4 underline">
|
||||
{!searching && !searchError && records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import { SelectedComplements, type Complement } from '@/components/investment-complements';
|
||||
import {
|
||||
SelectedComplements,
|
||||
type Complement,
|
||||
} from '@/components/investment-complements';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import { contextApi, type ContextReference, type OpportunityChoice } from '@/lib/investor-context';
|
||||
import {
|
||||
contextApi,
|
||||
type ContextReference,
|
||||
type OpportunityChoice,
|
||||
} from '@/lib/investor-context';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
export default function ContextStart({
|
||||
contexts,
|
||||
@@ -20,27 +27,96 @@ export default function ContextStart({
|
||||
step?: string | null;
|
||||
entryQuery?: Record<string, string>;
|
||||
entryComplements?: Complement[];
|
||||
entrySubmission?: {id:string;version:number} | null;
|
||||
entrySubmission?: { id: string; version: number } | null;
|
||||
}) {
|
||||
const [chosen, setChosen] = useState('');
|
||||
const [title, setTitle] = useState(entryComplements[0]?.kind === 'need' ? `Preparação de ${entryComplements[0].title} — ${entryComplements[0].origin.title}`.slice(0,200) : source?.title ?? opportunityChoices[0]?.opportunity.title ?? '');
|
||||
const [title, setTitle] = useState(
|
||||
entryComplements[0]?.kind === 'need'
|
||||
? `Preparação de ${entryComplements[0].title} — ${entryComplements[0].origin.title}`.slice(
|
||||
0,
|
||||
200,
|
||||
)
|
||||
: (source?.title ?? opportunityChoices[0]?.opportunity.title ?? ''),
|
||||
);
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [key] = useState(createOperationKey);
|
||||
const sourceSuffix = opportunityChoices.length ? '?' + opportunityChoices.map(c => `opportunities[]=${encodeURIComponent(c.opportunity.id)}`).join('&') : source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const suffix = sourceSuffix || Object.keys(entryQuery).length ? (sourceSuffix || '?')+(sourceSuffix ? '&' : '')+'selection_key='+encodeURIComponent(key)+'&'+new URLSearchParams(entryQuery).toString() : '';
|
||||
const sourceSuffix = opportunityChoices.length
|
||||
? '?' +
|
||||
opportunityChoices
|
||||
.map(
|
||||
(c) =>
|
||||
`opportunities[]=${encodeURIComponent(c.opportunity.id)}`,
|
||||
)
|
||||
.join('&')
|
||||
: source
|
||||
? '?source=' + encodeURIComponent(source.key)
|
||||
: '';
|
||||
const suffix =
|
||||
sourceSuffix || Object.keys(entryQuery).length
|
||||
? (sourceSuffix || '?') +
|
||||
(sourceSuffix ? '&' : '') +
|
||||
'selection_key=' +
|
||||
encodeURIComponent(key) +
|
||||
'&' +
|
||||
new URLSearchParams(entryQuery).toString()
|
||||
: '';
|
||||
const continueIn = async (id: string) => {
|
||||
if (entrySubmission) {
|
||||
const view = await contextApi<{case:{version:number}}>(`/investimentos/${id}/contexto`);
|
||||
await contextApi(`/investidor/manifestacoes/${entrySubmission.id}/contexto`, {case_id:id,case_version:view.case.version,version:entrySubmission.version});
|
||||
const view = await contextApi<{ case: { version: number } }>(
|
||||
`/investimentos/${id}/contexto`,
|
||||
);
|
||||
await contextApi(
|
||||
`/investidor/manifestacoes/${entrySubmission.id}/contexto`,
|
||||
{
|
||||
case_id: id,
|
||||
case_version: view.case.version,
|
||||
version: entrySubmission.version,
|
||||
},
|
||||
);
|
||||
}
|
||||
window.location.assign(`/investimentos/${id}/contexto/editar${suffix}`);
|
||||
};
|
||||
return (
|
||||
<Frame title="Iniciar ou continuar um investimento">
|
||||
<SelectedComplements items={entryComplements}/>
|
||||
{!!opportunityChoices.length && <section className={card}><h2 className="font-bold">Oportunidades escolhidas</h2><ul>{opportunityChoices.map(c => <li key={c.opportunity.key}><Link className="underline" href={c.opportunity.href}>{c.opportunity.title}</Link> · {c.territory?.title ?? 'Localização por escolher'}{c.portfolio_origins?.map(origin=><p key={origin.id}>Associação escolhida: <Link className="underline" href={origin.href}>{origin.title}</Link></p>)}</li>)}</ul><p>Confirme a localização de cada ficha na comparação do dossier. Ao continuar um dossier, as escolhas já guardadas conservam-se.</p></section>}
|
||||
<SelectedComplements items={entryComplements} />
|
||||
{!!opportunityChoices.length && (
|
||||
<section className={card}>
|
||||
<h2 className="font-bold">Oportunidades escolhidas</h2>
|
||||
<ul>
|
||||
{opportunityChoices.map((c) => (
|
||||
<li key={c.opportunity.key}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={c.opportunity.href}
|
||||
>
|
||||
{c.opportunity.title}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
{c.territory?.title ??
|
||||
'Localização por escolher'}
|
||||
{c.portfolio_origins?.map((origin) => (
|
||||
<p key={origin.id}>
|
||||
Associação escolhida:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={origin.href}
|
||||
>
|
||||
{origin.title}
|
||||
</Link>
|
||||
</p>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Confirme a localização de cada ficha na comparação do
|
||||
dossier. Ao continuar um dossier, as escolhas já
|
||||
guardadas conservam-se.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p>
|
||||
Ideia, oportunidade, sector e localização convergem no mesmo
|
||||
dossier. A referência é para preparação e não confirma direitos
|
||||
@@ -53,11 +129,28 @@ export default function ContextStart({
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>
|
||||
{source.kind === 'portfolio' && <p>Sector documentado: {source.analysis?.documented_sector ?? 'Por definir'}. Cobertura documental: {source.analysis?.documented_location ?? 'Por definir'}. Confirme o enquadramento e a localização do seu investimento no dossier.</p>}
|
||||
{source.kind === 'portfolio' && (
|
||||
<p>
|
||||
Sector documentado:{' '}
|
||||
{source.analysis?.documented_sector ??
|
||||
'Por definir'}
|
||||
. Cobertura documental:{' '}
|
||||
{source.analysis?.documented_location ??
|
||||
'Por definir'}
|
||||
. Confirme o enquadramento e a localização do seu
|
||||
investimento no dossier.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
{entrySubmission && <p>Ao continuar, esta manifestação será associada ao dossier escolhido, conservando a ficha de origem. Nenhum pedido será submetido.</p>}
|
||||
{entrySubmission && (
|
||||
<p>
|
||||
Ao continuar, esta manifestação será associada ao
|
||||
dossier escolhido, conservando a ficha de origem. Nenhum
|
||||
pedido será submetido.
|
||||
</p>
|
||||
)}
|
||||
<h2 className="text-xl font-bold">
|
||||
Continuar um dossier existente
|
||||
</h2>
|
||||
@@ -81,8 +174,18 @@ export default function ContextStart({
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (step && !source && !opportunityChoices.length) {window.location.assign(`/investimentos/${chosen}#${step}`);return;}
|
||||
setBusy(true);setError('');void continueIn(chosen).catch(e=>{setError(e.message);setBusy(false);});
|
||||
if (step && !source && !opportunityChoices.length) {
|
||||
window.location.assign(
|
||||
`/investimentos/${chosen}#${step}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError('');
|
||||
void continueIn(chosen).catch((e) => {
|
||||
setError(e.message);
|
||||
setBusy(false);
|
||||
});
|
||||
}}
|
||||
>
|
||||
{step && !source && !opportunityChoices.length
|
||||
@@ -90,9 +193,20 @@ export default function ContextStart({
|
||||
: 'Preparar neste dossier'}
|
||||
</button>
|
||||
)}
|
||||
{chosen && !entrySubmission && <Link className={button} href={step && !source && !opportunityChoices.length ? `/investimentos/${chosen}#${step}` : `/investimentos/${chosen}/contexto/editar${suffix}`}>
|
||||
{step && !source && !opportunityChoices.length ? 'Abrir ' + step + ' no mesmo dossier' : 'Preparar neste dossier'}
|
||||
</Link>}
|
||||
{chosen && !entrySubmission && (
|
||||
<Link
|
||||
className={button}
|
||||
href={
|
||||
step && !source && !opportunityChoices.length
|
||||
? `/investimentos/${chosen}#${step}`
|
||||
: `/investimentos/${chosen}/contexto/editar${suffix}`
|
||||
}
|
||||
>
|
||||
{step && !source && !opportunityChoices.length
|
||||
? 'Abrir ' + step + ' no mesmo dossier'
|
||||
: 'Preparar neste dossier'}
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
Se já preparou este investimento, continue nele. Não é
|
||||
necessário criar outro dossier.
|
||||
@@ -116,7 +230,8 @@ export default function ContextStart({
|
||||
>
|
||||
<h2 className="text-xl font-bold">Iniciar uma nova ideia</h2>
|
||||
<p>
|
||||
Organize a sua ideia e acompanhe a preparação do investimento.
|
||||
Organize a sua ideia e acompanhe a preparação do
|
||||
investimento.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Título do investimento
|
||||
|
||||
@@ -3,7 +3,12 @@ import {
|
||||
PreparationImpact,
|
||||
} from '@/components/private-investment-preparation';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import InvestmentComplements, { SelectedComplements, complementInput, type Complement, type ComplementOption } from '@/components/investment-complements';
|
||||
import InvestmentComplements, {
|
||||
SelectedComplements,
|
||||
complementInput,
|
||||
type Complement,
|
||||
type ComplementOption,
|
||||
} from '@/components/investment-complements';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, button, card, input } from '@/pages/investment/shared';
|
||||
@@ -51,44 +56,119 @@ export default function ContextEditor({
|
||||
entrySources?: string[];
|
||||
entryComplements?: Complement[];
|
||||
entryTerritory?: ContextReference | null;
|
||||
entryLocationDifferences?: {title:string;saved:string;requested:string}[];
|
||||
draft?: {draft_sequence?:number;needs_review?:boolean;selection?:Partial<Record<Slot,string>>;declarations?:Record<string,string>;replace_fields?:string[];document_links?:Record<string,string|null>}|null;
|
||||
entryLocationDifferences?: {
|
||||
title: string;
|
||||
saved: string;
|
||||
requested: string;
|
||||
}[];
|
||||
draft?: {
|
||||
draft_sequence?: number;
|
||||
needs_review?: boolean;
|
||||
selection?: Partial<Record<Slot, string>>;
|
||||
declarations?: Record<string, string>;
|
||||
replace_fields?: string[];
|
||||
document_links?: Record<string, string | null>;
|
||||
} | null;
|
||||
}) {
|
||||
const navigation = useNavigationContext();
|
||||
const [complements, setComplements] = useState<Complement[]>(entryComplements);
|
||||
const [complementOptions, setComplementOptions] = useState<ComplementOption[]>([]);
|
||||
const [complements, setComplements] =
|
||||
useState<Complement[]>(entryComplements);
|
||||
const [complementOptions, setComplementOptions] = useState<
|
||||
ComplementOption[]
|
||||
>([]);
|
||||
const [complementError, setComplementError] = useState('');
|
||||
const [choices, setChoices] = useState<OpportunityChoice[]>(requestedChoices ?? initial.context.opportunity_choices ?? []);
|
||||
const [manageChoices, setManageChoices] = useState(requestedChoices !== null || !!initial.context.opportunity_choices?.length);
|
||||
const complementContexts = JSON.stringify([...choices.flatMap(c => [{origin:c.opportunity.key, territory_id:c.territory?.id ?? null}, ...(c.portfolio_origins ?? []).map(p => ({origin:'portfolio:'+p.id,territory_id:c.territory?.id ?? null}))]), ...complements.filter(c => c.origin.key.startsWith('portfolio:')).map(c => ({origin:c.origin.key,territory_id:c.territory_id}))].filter((c,i,all) => all.findIndex(other => other.origin === c.origin && other.territory_id === c.territory_id) === i));
|
||||
const [choices, setChoices] = useState<OpportunityChoice[]>(
|
||||
requestedChoices ?? initial.context.opportunity_choices ?? [],
|
||||
);
|
||||
const [manageChoices, setManageChoices] = useState(
|
||||
requestedChoices !== null ||
|
||||
!!initial.context.opportunity_choices?.length,
|
||||
);
|
||||
const complementContexts = JSON.stringify(
|
||||
[
|
||||
...choices.flatMap((c) => [
|
||||
{
|
||||
origin: c.opportunity.key,
|
||||
territory_id: c.territory?.id ?? null,
|
||||
},
|
||||
...(c.portfolio_origins ?? []).map((p) => ({
|
||||
origin: 'portfolio:' + p.id,
|
||||
territory_id: c.territory?.id ?? null,
|
||||
})),
|
||||
]),
|
||||
...complements
|
||||
.filter((c) => c.origin.key.startsWith('portfolio:'))
|
||||
.map((c) => ({
|
||||
origin: c.origin.key,
|
||||
territory_id: c.territory_id,
|
||||
})),
|
||||
].filter(
|
||||
(c, i, all) =>
|
||||
all.findIndex(
|
||||
(other) =>
|
||||
other.origin === c.origin &&
|
||||
other.territory_id === c.territory_id,
|
||||
) === i,
|
||||
),
|
||||
);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setComplementError(''); setComplementOptions([]);
|
||||
const contexts = JSON.parse(complementContexts) as {origin:string;territory_id:string|null}[];
|
||||
setComplementError('');
|
||||
setComplementOptions([]);
|
||||
const contexts = JSON.parse(complementContexts) as {
|
||||
origin: string;
|
||||
territory_id: string | null;
|
||||
}[];
|
||||
const load = async () => {
|
||||
const items: ComplementOption[] = [];
|
||||
const issues: string[] = [];
|
||||
for(let index=0;index<contexts.length;index+=100) {
|
||||
const result = await contextApi<{items:ComplementOption[];issues:{message:string}[]}>('/complementos-investimento', {contexts:contexts.slice(index,index+100)});
|
||||
items.push(...result.items);issues.push(...result.issues.map(issue => issue.message));
|
||||
if(!active) return;
|
||||
for (let index = 0; index < contexts.length; index += 100) {
|
||||
const result = await contextApi<{
|
||||
items: ComplementOption[];
|
||||
issues: { message: string }[];
|
||||
}>('/complementos-investimento', {
|
||||
contexts: contexts.slice(index, index + 100),
|
||||
});
|
||||
items.push(...result.items);
|
||||
issues.push(...result.issues.map((issue) => issue.message));
|
||||
if (!active) return;
|
||||
}
|
||||
if (active) {
|
||||
setComplementOptions(items);
|
||||
setComplementError([...new Set(issues)].join(' '));
|
||||
}
|
||||
if(active) {setComplementOptions(items);setComplementError([...new Set(issues)].join(' '));}
|
||||
};
|
||||
void load().catch(e => {if(active) setComplementError(e.message);});
|
||||
return () => {active=false;};
|
||||
void load().catch((e) => {
|
||||
if (active) setComplementError(e.message);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [complementContexts]);
|
||||
const [view, setView] = useState(initial);
|
||||
const [preparation, setPreparation] = useState(initial.private_investment);
|
||||
const [options, setOptions] = useState(initialOptions);
|
||||
const [query, setQuery] = useState('');
|
||||
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(() =>
|
||||
({...(draft?.selection ?? {}), ...(entryTerritory && !draft?.selection?.territory && !initial.context.selection.territory ? {territory: entryTerritory.key} : {}), ...(source?.kind === 'portfolio' ? {portfolio: source.key} : draft?.selection ? {} : source
|
||||
? {
|
||||
[source.kind === 'business' ? 'opportunity' : source.kind]:
|
||||
source.key,
|
||||
}
|
||||
: {})}),
|
||||
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(
|
||||
() => ({
|
||||
...draft?.selection,
|
||||
...(entryTerritory &&
|
||||
!draft?.selection?.territory &&
|
||||
!initial.context.selection.territory
|
||||
? { territory: entryTerritory.key }
|
||||
: {}),
|
||||
...(source?.kind === 'portfolio'
|
||||
? { portfolio: source.key }
|
||||
: draft?.selection
|
||||
? {}
|
||||
: source
|
||||
? {
|
||||
[source.kind === 'business'
|
||||
? 'opportunity'
|
||||
: source.kind]: source.key,
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
const [declarations, setDeclarations] = useState<Record<string, string>>(
|
||||
draft?.declarations ?? {},
|
||||
@@ -96,58 +176,160 @@ export default function ContextEditor({
|
||||
const [documentLinks, setDocumentLinks] = useState<
|
||||
Record<string, string | null>
|
||||
>(draft?.document_links ?? {});
|
||||
const [replace, setReplace] = useState<string[]>(draft?.replace_fields ?? []);
|
||||
const [replace, setReplace] = useState<string[]>(
|
||||
draft?.replace_fields ?? [],
|
||||
);
|
||||
const [plan, setPlan] = useState<ContextPlan | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [corridors,setCorridors]=useState<CorridorOption[]>([]);
|
||||
const [parks,setParks]=useState<Options['parks']>([]);
|
||||
const [corridorLoading,setCorridorLoading]=useState(true);
|
||||
const [corridorError,setCorridorError]=useState('');
|
||||
const [corridorRetry,setCorridorRetry]=useState(0);
|
||||
const [draftStatus,setDraftStatus]=useState('');
|
||||
const [draftRetry,setDraftRetry]=useState(0);
|
||||
const queue=useRef<Promise<unknown>>(Promise.resolve());
|
||||
const firstCorridor=choices[0]?.corridor_key ?? corridors.find(c=>c.name===choices[0]?.coverage)?.key;
|
||||
const firstTerritory=choices[0]?.territory?.id;
|
||||
useEffect(()=>{
|
||||
let active=true;setCorridorLoading(true);setCorridorError('');
|
||||
const params=new URLSearchParams();if(firstCorridor)params.set('corridor',firstCorridor);if(firstTerritory)params.set('territory',firstTerritory);
|
||||
void contextApi<{corridors:CorridorOption[];parks:Options['parks']}>('/investimentos/opcoes-corredor?'+params).then(data=>{
|
||||
if(!active)return;setCorridors(data.corridors);setParks(data.parks);
|
||||
const park=Object.hasOwn(changes,'park')?changes.park:view.context.selection.park?.key;
|
||||
if(!manageChoices&&firstCorridor&&park&&!data.parks.some(p=>'park:'+p.id===park)){
|
||||
setChanges(old=>({...old,park:''}));setPlan(null);setMessage('A zona ou parque anterior foi retirado porque não tem enquadramento compatível com a localização escolhida.');
|
||||
}
|
||||
}).catch(e=>{if(active)setCorridorError(e.message)}).finally(()=>{if(active)setCorridorLoading(false)});
|
||||
return()=>{active=false};
|
||||
},[firstCorridor,firstTerritory,corridorRetry]);
|
||||
const draftBody=JSON.stringify({complements:complements.map(complementInput),entry_sources:entrySources,version:view.case.version,selection:changes,declarations,replace_fields:replace,document_links:documentLinks,
|
||||
...(manageChoices?{opportunity_choices:choices.map(c=>({source:c.opportunity.key,park:c.park?.key??null,portfolio_origins:(c.portfolio_origins??[]).map(r=>r.id),corridor_key:c.corridor_key,territory:c.territory?.key??null,location_reason:c.location_reason,confirm_location_change:!!c.confirm_location_change,activities:c.activities??[]}))}:{})});
|
||||
const latestDraft=useRef(draftBody);latestDraft.current=draftBody;
|
||||
const skipNextDraft=useRef(false);
|
||||
const confirmedDraftBody=useRef<string|null>(null);
|
||||
const sequence=useRef({body:'',value:Math.max(Date.now(),draft?.draft_sequence??0)});
|
||||
if(sequence.current.body!==draftBody)sequence.current={body:draftBody,value:Math.max(Date.now(),sequence.current.value+1)};
|
||||
useEffect(()=>{
|
||||
if(busy||corridorLoading||corridorError)return;
|
||||
if(skipNextDraft.current){skipNextDraft.current=false;confirmedDraftBody.current=draftBody;setDraftStatus('Dados confirmados.');return;}
|
||||
if(draftBody===confirmedDraftBody.current)return;
|
||||
const [corridors, setCorridors] = useState<CorridorOption[]>([]);
|
||||
const [parks, setParks] = useState<Options['parks']>([]);
|
||||
const [corridorLoading, setCorridorLoading] = useState(true);
|
||||
const [corridorError, setCorridorError] = useState('');
|
||||
const [corridorRetry, setCorridorRetry] = useState(0);
|
||||
const [draftStatus, setDraftStatus] = useState('');
|
||||
const [draftRetry, setDraftRetry] = useState(0);
|
||||
const queue = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const firstCorridor =
|
||||
choices[0]?.corridor_key ??
|
||||
corridors.find((c) => c.name === choices[0]?.coverage)?.key;
|
||||
const firstTerritory = choices[0]?.territory?.id;
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setCorridorLoading(true);
|
||||
setCorridorError('');
|
||||
const params = new URLSearchParams();
|
||||
if (firstCorridor) params.set('corridor', firstCorridor);
|
||||
if (firstTerritory) params.set('territory', firstTerritory);
|
||||
void contextApi<{
|
||||
corridors: CorridorOption[];
|
||||
parks: Options['parks'];
|
||||
}>('/investimentos/opcoes-corredor?' + params)
|
||||
.then((data) => {
|
||||
if (!active) return;
|
||||
setCorridors(data.corridors);
|
||||
setParks(data.parks);
|
||||
const park = Object.hasOwn(changes, 'park')
|
||||
? changes.park
|
||||
: view.context.selection.park?.key;
|
||||
if (
|
||||
!manageChoices &&
|
||||
firstCorridor &&
|
||||
park &&
|
||||
!data.parks.some((p) => 'park:' + p.id === park)
|
||||
) {
|
||||
setChanges((old) => ({ ...old, park: '' }));
|
||||
setPlan(null);
|
||||
setMessage(
|
||||
'A zona ou parque anterior foi retirado porque não tem enquadramento compatível com a localização escolhida.',
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active) setCorridorError(e.message);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setCorridorLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [firstCorridor, firstTerritory, corridorRetry]);
|
||||
const draftBody = JSON.stringify({
|
||||
complements: complements.map(complementInput),
|
||||
entry_sources: entrySources,
|
||||
version: view.case.version,
|
||||
selection: changes,
|
||||
declarations,
|
||||
replace_fields: replace,
|
||||
document_links: documentLinks,
|
||||
...(manageChoices
|
||||
? {
|
||||
opportunity_choices: choices.map((c) => ({
|
||||
source: c.opportunity.key,
|
||||
park: c.park?.key ?? null,
|
||||
portfolio_origins: (c.portfolio_origins ?? []).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
corridor_key: c.corridor_key,
|
||||
territory: c.territory?.key ?? null,
|
||||
location_reason: c.location_reason,
|
||||
confirm_location_change: !!c.confirm_location_change,
|
||||
activities: c.activities ?? [],
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const latestDraft = useRef(draftBody);
|
||||
latestDraft.current = draftBody;
|
||||
const skipNextDraft = useRef(false);
|
||||
const confirmedDraftBody = useRef<string | null>(null);
|
||||
const sequence = useRef({
|
||||
body: '',
|
||||
value: Math.max(Date.now(), draft?.draft_sequence ?? 0),
|
||||
});
|
||||
if (sequence.current.body !== draftBody)
|
||||
sequence.current = {
|
||||
body: draftBody,
|
||||
value: Math.max(Date.now(), sequence.current.value + 1),
|
||||
};
|
||||
useEffect(() => {
|
||||
if (busy || corridorLoading || corridorError) return;
|
||||
if (skipNextDraft.current) {
|
||||
skipNextDraft.current = false;
|
||||
confirmedDraftBody.current = draftBody;
|
||||
setDraftStatus('Dados confirmados.');
|
||||
return;
|
||||
}
|
||||
if (draftBody === confirmedDraftBody.current) return;
|
||||
setDraftStatus('A guardar rascunho…');
|
||||
const timer=setTimeout(()=>{
|
||||
const savedSequence=sequence.current.value;
|
||||
queue.current=queue.current.catch(()=>{}).then(()=>contextApi('/investimentos/'+view.case.id+'/contexto/rascunho',{...JSON.parse(draftBody),draft_sequence:savedSequence},'POST',draftBody.length<60000))
|
||||
.then(()=>{if(latestDraft.current===draftBody)setDraftStatus('Rascunho guardado.');})
|
||||
.catch(e=>{if(latestDraft.current===draftBody)setDraftStatus('Rascunho não guardado: '+e.message)});
|
||||
},400);
|
||||
return()=>clearTimeout(timer);
|
||||
},[draftBody,busy,corridorLoading,corridorError,draftRetry]);
|
||||
useEffect(()=>{
|
||||
const flush=()=>{const body=latestDraft.current;if(body!==confirmedDraftBody.current&&body.length<60000)void contextApi('/investimentos/'+initial.case.id+'/contexto/rascunho',{...JSON.parse(body),draft_sequence:sequence.current.value},'POST',true).catch(()=>{});};
|
||||
window.addEventListener('pagehide',flush);
|
||||
return()=>{window.removeEventListener('pagehide',flush);flush();};
|
||||
},[initial.case.id]);
|
||||
const timer = setTimeout(() => {
|
||||
const savedSequence = sequence.current.value;
|
||||
queue.current = queue.current
|
||||
.catch(() => {})
|
||||
.then(() =>
|
||||
contextApi(
|
||||
'/investimentos/' + view.case.id + '/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(draftBody),
|
||||
draft_sequence: savedSequence,
|
||||
},
|
||||
'POST',
|
||||
draftBody.length < 60000,
|
||||
),
|
||||
)
|
||||
.then(() => {
|
||||
if (latestDraft.current === draftBody)
|
||||
setDraftStatus('Rascunho guardado.');
|
||||
})
|
||||
.catch((e) => {
|
||||
if (latestDraft.current === draftBody)
|
||||
setDraftStatus('Rascunho não guardado: ' + e.message);
|
||||
});
|
||||
}, 400);
|
||||
return () => clearTimeout(timer);
|
||||
}, [draftBody, busy, corridorLoading, corridorError, draftRetry]);
|
||||
useEffect(() => {
|
||||
const flush = () => {
|
||||
const body = latestDraft.current;
|
||||
if (body !== confirmedDraftBody.current && body.length < 60000)
|
||||
void contextApi(
|
||||
'/investimentos/' + initial.case.id + '/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(body),
|
||||
draft_sequence: sequence.current.value,
|
||||
},
|
||||
'POST',
|
||||
true,
|
||||
).catch(() => {});
|
||||
};
|
||||
window.addEventListener('pagehide', flush);
|
||||
return () => {
|
||||
window.removeEventListener('pagehide', flush);
|
||||
flush();
|
||||
};
|
||||
}, [initial.case.id]);
|
||||
const [operation, setOperation] = useState(createOperationKey);
|
||||
const [requestBody, setRequestBody] = useState<Record<
|
||||
string,
|
||||
@@ -194,7 +376,22 @@ export default function ContextEditor({
|
||||
setMessage('');
|
||||
const body = {
|
||||
complements: complements.map(complementInput),
|
||||
...(manageChoices ? {opportunity_choices: choices.map(c => ({source:c.opportunity.key,park:c.park?.key??null,portfolio_origins:(c.portfolio_origins??[]).map(r=>r.id),corridor_key:c.corridor_key,territory:c.territory?.key ?? null,location_reason:c.location_reason,confirm_location_change:!!c.confirm_location_change,activities:c.activities??[]}))} : {}),
|
||||
...(manageChoices
|
||||
? {
|
||||
opportunity_choices: choices.map((c) => ({
|
||||
source: c.opportunity.key,
|
||||
park: c.park?.key ?? null,
|
||||
portfolio_origins: (c.portfolio_origins ?? []).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
corridor_key: c.corridor_key,
|
||||
territory: c.territory?.key ?? null,
|
||||
location_reason: c.location_reason,
|
||||
confirm_location_change: !!c.confirm_location_change,
|
||||
activities: c.activities ?? [],
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
version: view.case.version,
|
||||
selection: changes,
|
||||
declarations,
|
||||
@@ -222,7 +419,7 @@ export default function ContextEditor({
|
||||
async function confirm() {
|
||||
if (!plan || !requestBody) return;
|
||||
setBusy(true);
|
||||
await queue.current.catch(()=>{});
|
||||
await queue.current.catch(() => {});
|
||||
setError('');
|
||||
try {
|
||||
await contextApi(
|
||||
@@ -237,9 +434,13 @@ export default function ContextEditor({
|
||||
const next = await contextApi<ContextView>(
|
||||
`/investimentos/${view.case.id}/contexto`,
|
||||
);
|
||||
skipNextDraft.current=true;
|
||||
skipNextDraft.current = true;
|
||||
// The entry has been consumed: refreshing must recover saved choices, not reapply a removed association.
|
||||
window.history.replaceState(window.history.state, '', `/investimentos/${view.case.id}/contexto/editar${window.location.hash}`);
|
||||
window.history.replaceState(
|
||||
window.history.state,
|
||||
'',
|
||||
`/investimentos/${view.case.id}/contexto/editar${window.location.hash}`,
|
||||
);
|
||||
setView(next);
|
||||
setChoices(next.context.opportunity_choices ?? []);
|
||||
setComplements(next.context.complements ?? []);
|
||||
@@ -273,23 +474,76 @@ export default function ContextEditor({
|
||||
>
|
||||
Voltar ao dossier
|
||||
</Link>
|
||||
<p>{view.case.title}</p>
|
||||
<p>
|
||||
{view.case.title}
|
||||
Confirme as oportunidades e a localização, complete os dados
|
||||
disponíveis e reveja antes de guardar.
|
||||
</p>
|
||||
<p>Confirme as oportunidades e a localização, complete os dados disponíveis e reveja antes de guardar.</p>
|
||||
<SelectedComplements items={complements} onRemove={busy ? undefined : key => {setComplements(items => items.filter(item => item.key !== key));setPlan(null);}}/>
|
||||
{complementError && <p role="alert">{complementError} As escolhas anteriores foram conservadas.</p>}
|
||||
<InvestmentComplements items={complementOptions} dossierId={view.case.id} onNavigate={async href => {
|
||||
if(busy) return;
|
||||
setBusy(true);setError('');
|
||||
try {
|
||||
await queue.current.catch(()=>{});
|
||||
await contextApi('/investimentos/'+view.case.id+'/contexto/rascunho', {...JSON.parse(latestDraft.current), draft_sequence:++sequence.current.value}, 'POST');
|
||||
router.visit(href);
|
||||
} catch(e) {setError(e instanceof Error ? e.message : 'Não foi possível conservar as escolhas antes de abrir o complemento.');}
|
||||
finally {setBusy(false);}
|
||||
}}/>
|
||||
{!!entryLocationDifferences.length && <aside className="rounded border border-amber-500 p-3" aria-label="Localização anterior conservada">{entryLocationDifferences.map(row=><p key={row.title}>{row.title}: a localização recebida ({row.requested}) não substituiu a escolha guardada ({row.saved}). Pode rever a localização abaixo antes de confirmar.</p>)}</aside>}
|
||||
<SelectedComplements
|
||||
items={complements}
|
||||
onRemove={
|
||||
busy
|
||||
? undefined
|
||||
: (key) => {
|
||||
setComplements((items) =>
|
||||
items.filter((item) => item.key !== key),
|
||||
);
|
||||
setPlan(null);
|
||||
}
|
||||
}
|
||||
/>
|
||||
{complementError && (
|
||||
<p role="alert">
|
||||
{complementError} As escolhas anteriores foram
|
||||
conservadas.
|
||||
</p>
|
||||
)}
|
||||
<InvestmentComplements
|
||||
items={complementOptions}
|
||||
dossierId={view.case.id}
|
||||
onNavigate={async (href) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await queue.current.catch(() => {});
|
||||
await contextApi(
|
||||
'/investimentos/' +
|
||||
view.case.id +
|
||||
'/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(latestDraft.current),
|
||||
draft_sequence: ++sequence.current.value,
|
||||
},
|
||||
'POST',
|
||||
);
|
||||
router.visit(href);
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível conservar as escolhas antes de abrir o complemento.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{!!entryLocationDifferences.length && (
|
||||
<aside
|
||||
className="rounded border border-amber-500 p-3"
|
||||
aria-label="Localização anterior conservada"
|
||||
>
|
||||
{entryLocationDifferences.map((row) => (
|
||||
<p key={row.title}>
|
||||
{row.title}: a localização recebida (
|
||||
{row.requested}) não substituiu a escolha
|
||||
guardada ({row.saved}). Pode rever a localização
|
||||
abaixo antes de confirmar.
|
||||
</p>
|
||||
))}
|
||||
</aside>
|
||||
)}
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
@@ -307,23 +561,149 @@ export default function ContextEditor({
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<section className={card + ' space-y-4'}>
|
||||
{corridorError&&<p role="alert">{corridorError} <button className="underline" onClick={()=>setCorridorRetry(v=>v+1)}>Tentar novamente</button></p>}
|
||||
{corridorLoading&&<p role="status">A carregar opções do corredor…</p>}
|
||||
{corridorError && (
|
||||
<p role="alert">
|
||||
{corridorError}{' '}
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() => setCorridorRetry((v) => v + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{corridorLoading && (
|
||||
<p role="status">A carregar opções do corredor…</p>
|
||||
)}
|
||||
<p role="status">{draftStatus}</p>
|
||||
{draft?.needs_review&&<p role="status">O rascunho foi recuperado, mas o dossier recebeu outras alterações. Reveja os dados antes de confirmar.</p>}
|
||||
{draftStatus.startsWith('Rascunho não guardado')&&<button type="button" className="underline" onClick={()=>setDraftRetry(v=>v+1)}>Tentar guardar novamente</button>}
|
||||
<OpportunityChoices corridors={corridors} choices={choices} disabled={busy||corridorLoading||!!corridorError} onChange={next=>{setChoices(next);setManageChoices(true);setPlan(null);}}/>
|
||||
{(changes.portfolio || view.context.selection.portfolio) && <p className="rounded border p-3">
|
||||
Origem documental: <a className="underline" href={source?.kind === 'portfolio' ? source.href : view.context.selection.portfolio?.href}>{source?.kind === 'portfolio' ? source.title : view.context.selection.portfolio?.title}</a>.
|
||||
{' '}A ficha é conservada como origem. Escolha o sector e a localização do investimento abaixo; a cobertura documental não é uma implantação atribuída.
|
||||
</p>}
|
||||
{entryTerritory && view.context.selection.territory && entryTerritory.key !== view.context.selection.territory.key && <p role="status">A pesquisa indicava {entryTerritory.title}. Conservou-se a localização guardada, {view.context.selection.territory.title}; pode alterá-la explicitamente abaixo e conferir os impactos.</p>}
|
||||
<ContextDocuments source={source ?? view.context.selection.opportunity} />
|
||||
{view.context.revision > 0 && !Object.keys(changes).length && JSON.stringify(choices) === JSON.stringify(view.context.opportunity_choices ?? []) && <InvestmentRequirements assessment={view.context.requirements_assessment} contextId={view.case.id}/>}
|
||||
<label className="block">Acrescentar uma oportunidade à escolha<select className={input} value="" onChange={e=>{const o=options.opportunities.find(o=>o.key===e.target.value);if(o && !choices.some(c=>c.opportunity.key===o.key)){setChoices([...choices,{opportunity:{...o,id:o.key.split(':')[1],href:'/oportunidades',version:null,sha256:'',fields:{}},territory:null,location_reason:'',location_state:'undetermined'}]);setManageChoices(true);setPlan(null);}}}><option value="">Seleccionar ficha</option>{options.opportunities.filter(o=>o.kind==='opportunity'&&!choices.some(c=>c.opportunity.key===o.key)).map(o=><option key={o.key} value={o.key}>{o.title}</option>)}</select></label>
|
||||
<h2 className="text-xl font-bold">
|
||||
Dados do investimento
|
||||
</h2>
|
||||
{draft?.needs_review && (
|
||||
<p role="status">
|
||||
O rascunho foi recuperado, mas o dossier recebeu
|
||||
outras alterações. Reveja os dados antes de
|
||||
confirmar.
|
||||
</p>
|
||||
)}
|
||||
{draftStatus.startsWith('Rascunho não guardado') && (
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => setDraftRetry((v) => v + 1)}
|
||||
>
|
||||
Tentar guardar novamente
|
||||
</button>
|
||||
)}
|
||||
<OpportunityChoices
|
||||
corridors={corridors}
|
||||
choices={choices}
|
||||
disabled={busy || corridorLoading || !!corridorError}
|
||||
onChange={(next) => {
|
||||
setChoices(next);
|
||||
setManageChoices(true);
|
||||
setPlan(null);
|
||||
}}
|
||||
/>
|
||||
{(changes.portfolio ||
|
||||
view.context.selection.portfolio) && (
|
||||
<p className="rounded border p-3">
|
||||
Origem documental:{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href={
|
||||
source?.kind === 'portfolio'
|
||||
? source.href
|
||||
: view.context.selection.portfolio?.href
|
||||
}
|
||||
>
|
||||
{source?.kind === 'portfolio'
|
||||
? source.title
|
||||
: view.context.selection.portfolio?.title}
|
||||
</a>
|
||||
. A ficha é conservada como origem. Escolha o sector
|
||||
e a localização do investimento abaixo; a cobertura
|
||||
documental não é uma implantação atribuída.
|
||||
</p>
|
||||
)}
|
||||
{entryTerritory &&
|
||||
view.context.selection.territory &&
|
||||
entryTerritory.key !==
|
||||
view.context.selection.territory.key && (
|
||||
<p role="status">
|
||||
A pesquisa indicava {entryTerritory.title}.
|
||||
Conservou-se a localização guardada,{' '}
|
||||
{view.context.selection.territory.title}; pode
|
||||
alterá-la explicitamente abaixo e conferir os
|
||||
impactos.
|
||||
</p>
|
||||
)}
|
||||
<ContextDocuments
|
||||
source={source ?? view.context.selection.opportunity}
|
||||
/>
|
||||
{view.context.revision > 0 &&
|
||||
!Object.keys(changes).length &&
|
||||
JSON.stringify(choices) ===
|
||||
JSON.stringify(
|
||||
view.context.opportunity_choices ?? [],
|
||||
) && (
|
||||
<InvestmentRequirements
|
||||
assessment={
|
||||
view.context.requirements_assessment
|
||||
}
|
||||
contextId={view.case.id}
|
||||
/>
|
||||
)}
|
||||
<label className="block">
|
||||
Acrescentar uma oportunidade à escolha
|
||||
<select
|
||||
className={input}
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
const o = options.opportunities.find(
|
||||
(o) => o.key === e.target.value,
|
||||
);
|
||||
if (
|
||||
o &&
|
||||
!choices.some(
|
||||
(c) => c.opportunity.key === o.key,
|
||||
)
|
||||
) {
|
||||
setChoices([
|
||||
...choices,
|
||||
{
|
||||
opportunity: {
|
||||
...o,
|
||||
id: o.key.split(':')[1],
|
||||
href: '/oportunidades',
|
||||
version: null,
|
||||
sha256: '',
|
||||
fields: {},
|
||||
},
|
||||
territory: null,
|
||||
location_reason: '',
|
||||
location_state: 'undetermined',
|
||||
},
|
||||
]);
|
||||
setManageChoices(true);
|
||||
setPlan(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccionar ficha</option>
|
||||
{options.opportunities
|
||||
.filter(
|
||||
(o) =>
|
||||
o.kind === 'opportunity' &&
|
||||
!choices.some(
|
||||
(c) => c.opportunity.key === o.key,
|
||||
),
|
||||
)
|
||||
.map((o) => (
|
||||
<option key={o.key} value={o.key}>
|
||||
{o.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<h2 className="text-xl font-bold">Dados do investimento</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label className="min-w-0 flex-1">
|
||||
Pesquisar oportunidades
|
||||
@@ -441,49 +821,81 @@ export default function ContextEditor({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!manageChoices && <><label className="grid min-w-0 gap-1">
|
||||
{choices.length>1?'Zona ou parque da primeira oportunidade':'ZEE, ZFI ou parque consultado'}
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={busy||corridorLoading||!!corridorError||(!!firstCorridor&&!firstTerritory)}
|
||||
value={selected('park')}
|
||||
onChange={(e) => change('park', e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Sem ZEE, ZFI ou parque seleccionado
|
||||
</option>
|
||||
{(firstCorridor?parks:options.parks).map((p) => (
|
||||
<option key={p.id} value={'park:' + p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{firstCorridor&&!corridorLoading&&!corridorError&&<p>{!firstTerritory?'Escolha a localização para consultar zonas e parques.':!parks.length?'Não existem zonas ou parques com enquadramento documentado compatível nesta localização.':'A consulta não confirma disponibilidade de lotes, admissão ou incentivos.'}</p>}
|
||||
</>}
|
||||
{!manageChoices&&<><h3 className="font-semibold">
|
||||
Localização — escolher até ao nível conhecido
|
||||
</h3>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
disabled={busy || manageChoices}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(path) =>
|
||||
change(
|
||||
'territory',
|
||||
path.length
|
||||
? 'territory:' + path[path.length - 1].id
|
||||
: '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
{view.context.selection.territory && (
|
||||
<p>
|
||||
Referência guardada:{' '}
|
||||
{view.context.selection.territory.title}
|
||||
</p>
|
||||
{!manageChoices && (
|
||||
<>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
{choices.length > 1
|
||||
? 'Zona ou parque da primeira oportunidade'
|
||||
: 'ZEE, ZFI ou parque consultado'}
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={
|
||||
busy ||
|
||||
corridorLoading ||
|
||||
!!corridorError ||
|
||||
(!!firstCorridor && !firstTerritory)
|
||||
}
|
||||
value={selected('park')}
|
||||
onChange={(e) =>
|
||||
change('park', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Sem ZEE, ZFI ou parque seleccionado
|
||||
</option>
|
||||
{(firstCorridor
|
||||
? parks
|
||||
: options.parks
|
||||
).map((p) => (
|
||||
<option
|
||||
key={p.id}
|
||||
value={'park:' + p.id}
|
||||
>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{firstCorridor &&
|
||||
!corridorLoading &&
|
||||
!corridorError && (
|
||||
<p>
|
||||
{!firstTerritory
|
||||
? 'Escolha a localização para consultar zonas e parques.'
|
||||
: !parks.length
|
||||
? 'Não existem zonas ou parques com enquadramento documentado compatível nesta localização.'
|
||||
: 'A consulta não confirma disponibilidade de lotes, admissão ou incentivos.'}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{!manageChoices && (
|
||||
<>
|
||||
<h3 className="font-semibold">
|
||||
Localização — escolher até ao nível conhecido
|
||||
</h3>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
disabled={busy || manageChoices}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(path) =>
|
||||
change(
|
||||
'territory',
|
||||
path.length
|
||||
? 'territory:' +
|
||||
path[path.length - 1].id
|
||||
: '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
{view.context.selection.territory && (
|
||||
<p>
|
||||
Referência guardada:{' '}
|
||||
{view.context.selection.territory.title}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>}
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
@@ -687,9 +1099,16 @@ export default function ContextEditor({
|
||||
<h2 className="text-xl font-bold">
|
||||
Comparação antes da confirmação
|
||||
</h2>
|
||||
{!!plan.opportunity_choices?.length && <OpportunityChoices choices={plan.opportunity_choices}/>}
|
||||
<SelectedComplements items={plan.complements ?? []}/>
|
||||
<InvestmentRequirements assessment={plan.requirements_assessment} contextId={view.case.id}/>
|
||||
{!!plan.opportunity_choices?.length && (
|
||||
<OpportunityChoices
|
||||
choices={plan.opportunity_choices}
|
||||
/>
|
||||
)}
|
||||
<SelectedComplements items={plan.complements ?? []} />
|
||||
<InvestmentRequirements
|
||||
assessment={plan.requirements_assessment}
|
||||
contextId={view.case.id}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[36rem] table-fixed text-left">
|
||||
<thead>
|
||||
@@ -706,15 +1125,23 @@ export default function ContextEditor({
|
||||
<td className="p-2">
|
||||
{plan.documents_preserved}{' '}
|
||||
documentos.{' '}
|
||||
{plan.maintained.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
: conserva «{x.value}»; a
|
||||
fonte propõe «{x.proposed}».
|
||||
</p>
|
||||
))}
|
||||
{plan.maintained
|
||||
.filter(
|
||||
(x) =>
|
||||
!x.field.endsWith(
|
||||
'_id',
|
||||
),
|
||||
)
|
||||
.map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
: conserva «{x.value}»;
|
||||
a fonte propõe «
|
||||
{x.proposed}».
|
||||
</p>
|
||||
))}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -722,23 +1149,30 @@ export default function ContextEditor({
|
||||
Atualizado pela nova seleção
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.updated.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
:{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.before,
|
||||
)}{' '}
|
||||
→{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.after,
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{plan.updated
|
||||
.filter(
|
||||
(x) =>
|
||||
!x.field.endsWith(
|
||||
'_id',
|
||||
),
|
||||
)
|
||||
.map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
:{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.before,
|
||||
)}{' '}
|
||||
→{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.after,
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{Object.values(plan.selection).map(
|
||||
(r) =>
|
||||
r && (
|
||||
@@ -760,10 +1194,11 @@ export default function ContextEditor({
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.dependent_results.length}{' '}
|
||||
resultados financeiros afectados. Etapas a rever: {plan.review_steps.length}
|
||||
. Dados já preenchidos nos
|
||||
formulários conservam-se até à sua
|
||||
conferência.
|
||||
resultados financeiros afectados.
|
||||
Etapas a rever:{' '}
|
||||
{plan.review_steps.length}. Dados já
|
||||
preenchidos nos formulários
|
||||
conservam-se até à sua conferência.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -776,7 +1211,8 @@ export default function ContextEditor({
|
||||
anteriores.{' '}
|
||||
{plan.requests.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.protocol || 'Pedido guardado'}
|
||||
{r.protocol ||
|
||||
'Pedido guardado'}
|
||||
</p>
|
||||
))}
|
||||
</td>
|
||||
|
||||
@@ -18,7 +18,13 @@ export default function InvestmentContexts({
|
||||
}: {
|
||||
contexts: InvestmentContext[];
|
||||
contentSource?: LegacyArticle;
|
||||
zoneSource?: { zone_id: string; consulted_public_version: number; title: string; href: string; notice: string };
|
||||
zoneSource?: {
|
||||
zone_id: string;
|
||||
consulted_public_version: number;
|
||||
title: string;
|
||||
href: string;
|
||||
notice: string;
|
||||
};
|
||||
sectorSource?: { id: number; name: string; slug: string; href: string };
|
||||
}) {
|
||||
const [key] = useState(() => createOperationKey());
|
||||
@@ -36,7 +42,14 @@ export default function InvestmentContexts({
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-4 md:p-8">
|
||||
<Head title="Os meus investimentos" />
|
||||
<h1 className="text-2xl font-semibold">Os meus investimentos</h1>
|
||||
{zoneSource && <section className="rounded border p-4"><h2>Parque escolhido: {zoneSource.title}</h2><Link className="underline" href={zoneSource.href}>Consultar parque</Link></section>}
|
||||
{zoneSource && (
|
||||
<section className="rounded border p-4">
|
||||
<h2>Parque escolhido: {zoneSource.title}</h2>
|
||||
<Link className="underline" href={zoneSource.href}>
|
||||
Consultar parque
|
||||
</Link>
|
||||
</section>
|
||||
)}
|
||||
{sectorSource && (
|
||||
<p>
|
||||
Preparar uma ideia em{' '}
|
||||
@@ -73,7 +86,26 @@ export default function InvestmentContexts({
|
||||
Guardado em{' '}
|
||||
{new Date(item.updated_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
{zoneSource && <button type="button" className="mt-3 rounded border p-2" onClick={()=>router.post(`/investimentos/${item.id}/parques`,{version:item.version,zone_id:zoneSource.zone_id,consulted_public_version:zoneSource.consulted_public_version,confirm:true})}>Confirmar referência neste dossier</button>}
|
||||
{zoneSource && (
|
||||
<button
|
||||
type="button"
|
||||
className="mt-3 rounded border p-2"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/investimentos/${item.id}/parques`,
|
||||
{
|
||||
version: item.version,
|
||||
zone_id: zoneSource.zone_id,
|
||||
consulted_public_version:
|
||||
zoneSource.consulted_public_version,
|
||||
confirm: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Confirmar referência neste dossier
|
||||
</button>
|
||||
)}
|
||||
{sectorSource && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import {ProactiveSummary,proactiveView} from '@/components/proactive-investment';
|
||||
import {
|
||||
ProactiveSummary,
|
||||
proactiveView,
|
||||
} from '@/components/proactive-investment';
|
||||
import {
|
||||
PreparationSummary,
|
||||
type Preparation,
|
||||
@@ -97,7 +100,11 @@ function Result({ result }: { result: PathResult }) {
|
||||
const values = recoverPathResult(result);
|
||||
return (
|
||||
<li className="space-y-1 rounded border p-3">
|
||||
{result.context_opportunity && <p>Oportunidade desta análise: {result.context_opportunity}</p>}
|
||||
{result.context_opportunity && (
|
||||
<p>
|
||||
Oportunidade desta análise: {result.context_opportunity}
|
||||
</p>
|
||||
)}
|
||||
{result.context_state === 'review_required' && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -124,8 +131,8 @@ function Result({ result }: { result: PathResult }) {
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Estimativa recalculada pelas fórmulas da ferramenta a partir
|
||||
dos dados preenchidos. Não
|
||||
constitui decisão de financiamento.
|
||||
dos dados preenchidos. Não constitui decisão de
|
||||
financiamento.
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
@@ -171,8 +178,14 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
];
|
||||
const states = path.canWrite ? ownerStates : reviewStates;
|
||||
return (
|
||||
<details id={step.code} open={path.next?.code===step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<summary className="cursor-pointer font-semibold">{step.title} · {pathStates[step.state]}</summary>
|
||||
<details
|
||||
id={step.code}
|
||||
open={path.next?.code === step.code}
|
||||
className="space-y-3 rounded-xl border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
{step.title} · {pathStates[step.state]}
|
||||
</summary>
|
||||
<p>{pathStates[step.state]}</p>
|
||||
{step.context_review_required && (
|
||||
<label className="block rounded border border-amber-600 bg-amber-50 p-3">
|
||||
@@ -233,18 +246,32 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
: action === 'operate'
|
||||
? 'Operação'
|
||||
: 'Execução'}{' '}
|
||||
aguarda {gaps.map(code=>path.steps.find(item=>item.code===code)?.title??code).join(', ')}. Pode continuar a preparar.
|
||||
aguarda{' '}
|
||||
{gaps
|
||||
.map(
|
||||
(code) =>
|
||||
path.steps.find(
|
||||
(item) => item.code === code,
|
||||
)?.title ?? code,
|
||||
)
|
||||
.join(', ')}
|
||||
. Pode continuar a preparar.
|
||||
</p>
|
||||
))}
|
||||
<details className="text-xs"><summary className="cursor-pointer underline">Fonte e referência desta etapa</summary><p>
|
||||
Referência interna {step.code}.{' '}
|
||||
Documento original, parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p></details>
|
||||
<details className="text-xs">
|
||||
<summary className="cursor-pointer underline">
|
||||
Fonte e referência desta etapa
|
||||
</summary>
|
||||
<p>
|
||||
Referência interna {step.code}. Documento original,
|
||||
parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p>
|
||||
</details>
|
||||
{step.preparation_allowed && (path.canWrite || path.canReview) && (
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
@@ -433,7 +460,13 @@ export default function InvestmentPath(path: Path) {
|
||||
function support() {
|
||||
router.post(
|
||||
`/balcao-virtual/dossiers/${path.case.id}/pedidos`,
|
||||
{ service_version_id: service, client_key: requestKey, opportunity: new URLSearchParams(window.location.search).get('opportunity') },
|
||||
{
|
||||
service_version_id: service,
|
||||
client_key: requestKey,
|
||||
opportunity: new URLSearchParams(window.location.search).get(
|
||||
'opportunity',
|
||||
),
|
||||
},
|
||||
{ onError: (errors) => setError(Object.values(errors).join('; ')) },
|
||||
);
|
||||
}
|
||||
@@ -444,17 +477,56 @@ export default function InvestmentPath(path: Path) {
|
||||
Os meus investimentos
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
|
||||
{path.investment_context?.selection.portfolio && <p className="rounded border p-4">
|
||||
Origem documental: <Link className="underline" href={path.investment_context.selection.portfolio.href}>{path.investment_context.selection.portfolio.title}</Link>.
|
||||
{' '}A localização do investimento é escolhida no contexto.
|
||||
</p>}
|
||||
{!!path.opportunity_options?.length && <label className="block rounded border p-4">Oportunidade em tratamento
|
||||
<select className="ml-2 rounded border p-2" value={path.context_opportunity ?? ''} onChange={event => router.get(`/investimentos/${path.case.id}`, event.target.value ? {opportunity:event.target.value} : {}, {preserveState:false})}>
|
||||
<option value="">Escolha a oportunidade</option>
|
||||
{path.opportunity_options.map(choice => <option key={choice.opportunity.key} value={choice.opportunity.key}>{choice.opportunity.title} — {choice.territory?.title ?? 'Localização por definir'}</option>)}
|
||||
</select>
|
||||
{!path.context_opportunity && path.opportunity_options.length > 1 && <p>Escolha para consultar as etapas, os requisitos e o pedido de terra correspondentes. Os dados comuns conservam-se.</p>}
|
||||
</label>}
|
||||
{path.investment_context?.selection.portfolio && (
|
||||
<p className="rounded border p-4">
|
||||
Origem documental:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={path.investment_context.selection.portfolio.href}
|
||||
>
|
||||
{path.investment_context.selection.portfolio.title}
|
||||
</Link>
|
||||
. A localização do investimento é escolhida no contexto.
|
||||
</p>
|
||||
)}
|
||||
{!!path.opportunity_options?.length && (
|
||||
<label className="block rounded border p-4">
|
||||
Oportunidade em tratamento
|
||||
<select
|
||||
className="ml-2 rounded border p-2"
|
||||
value={path.context_opportunity ?? ''}
|
||||
onChange={(event) =>
|
||||
router.get(
|
||||
`/investimentos/${path.case.id}`,
|
||||
event.target.value
|
||||
? { opportunity: event.target.value }
|
||||
: {},
|
||||
{ preserveState: false },
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Escolha a oportunidade</option>
|
||||
{path.opportunity_options.map((choice) => (
|
||||
<option
|
||||
key={choice.opportunity.key}
|
||||
value={choice.opportunity.key}
|
||||
>
|
||||
{choice.opportunity.title} —{' '}
|
||||
{choice.territory?.title ??
|
||||
'Localização por definir'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{!path.context_opportunity &&
|
||||
path.opportunity_options.length > 1 && (
|
||||
<p>
|
||||
Escolha para consultar as etapas, os requisitos
|
||||
e o pedido de terra correspondentes. Os dados
|
||||
comuns conservam-se.
|
||||
</p>
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
<ContextDocuments
|
||||
source={path.investment_context?.selection.opportunity}
|
||||
/>
|
||||
@@ -464,9 +536,7 @@ export default function InvestmentPath(path: Path) {
|
||||
/>
|
||||
{path.investment_context && (
|
||||
<section className="space-y-2 rounded border border-emerald-300 bg-emerald-50 p-4">
|
||||
<h2 className="font-semibold">
|
||||
As suas escolhas
|
||||
</h2>
|
||||
<h2 className="font-semibold">As suas escolhas</h2>
|
||||
{Object.values(path.investment_context.selection).map(
|
||||
(ref) => (
|
||||
<p key={ref.key}>
|
||||
@@ -503,9 +573,7 @@ export default function InvestmentPath(path: Path) {
|
||||
<Link className="underline" href={zone.href}>
|
||||
{zone.title}
|
||||
</Link>
|
||||
<p>
|
||||
{zone.selected_at}
|
||||
</p>
|
||||
<p>{zone.selected_at}</p>
|
||||
<p>{zone.notice}</p>
|
||||
</article>
|
||||
))}
|
||||
@@ -547,11 +615,38 @@ export default function InvestmentPath(path: Path) {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!!path.investment_context?.opportunity_choices?.length && <OpportunityChoices contextId={path.case.id} choices={path.investment_context.opportunity_choices}/>}
|
||||
{path.investment_context?.opportunity_choices?.map(choice=><ProactiveSummary key={choice.opportunity.key} value={proactiveView(choice.opportunity.analysis?.proactive)}/>)}
|
||||
{!path.investment_context?.opportunity_choices?.length&&<ProactiveSummary value={proactiveView(path.investment_context?.selection.opportunity?.analysis?.proactive)}/>}
|
||||
<SelectedComplements items={path.investment_context?.complements ?? []}/>
|
||||
<InvestmentRequirements assessment={path.investment_context?.requirements_assessment} contextId={path.case.id} excludedSteps={path.steps.filter((step) => !step.preparation_allowed).map((step) => step.code)}/>
|
||||
{!!path.investment_context?.opportunity_choices?.length && (
|
||||
<OpportunityChoices
|
||||
contextId={path.case.id}
|
||||
choices={path.investment_context.opportunity_choices}
|
||||
/>
|
||||
)}
|
||||
{path.investment_context?.opportunity_choices?.map((choice) => (
|
||||
<ProactiveSummary
|
||||
key={choice.opportunity.key}
|
||||
value={proactiveView(
|
||||
choice.opportunity.analysis?.proactive,
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
{!path.investment_context?.opportunity_choices?.length && (
|
||||
<ProactiveSummary
|
||||
value={proactiveView(
|
||||
path.investment_context?.selection.opportunity?.analysis
|
||||
?.proactive,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<SelectedComplements
|
||||
items={path.investment_context?.complements ?? []}
|
||||
/>
|
||||
<InvestmentRequirements
|
||||
assessment={path.investment_context?.requirements_assessment}
|
||||
contextId={path.case.id}
|
||||
excludedSteps={path.steps
|
||||
.filter((step) => !step.preparation_allowed)
|
||||
.map((step) => step.code)}
|
||||
/>
|
||||
{!!path.content_sources?.length && (
|
||||
<section
|
||||
className="space-y-2 rounded-xl border p-4"
|
||||
@@ -706,34 +801,68 @@ export default function InvestmentPath(path: Path) {
|
||||
</form>
|
||||
)}
|
||||
{path.steps.some((step) => !step.preparation_allowed) && (
|
||||
<section className="rounded-xl border p-4" aria-label="Etapas sem aplicação">
|
||||
<h2 className="font-semibold">Não precisa de preparar neste contexto</h2>
|
||||
<section
|
||||
className="rounded-xl border p-4"
|
||||
aria-label="Etapas sem aplicação"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
Não precisa de preparar neste contexto
|
||||
</h2>
|
||||
<ul>
|
||||
{path.steps.filter((step) => !step.preparation_allowed).map((step) => (
|
||||
<li key={step.code}>{step.title}: {step.reason || 'Conforme as escolhas guardadas.'}</li>
|
||||
))}
|
||||
{path.steps
|
||||
.filter((step) => !step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<li key={step.code}>
|
||||
{step.title}:{' '}
|
||||
{step.reason ||
|
||||
'Conforme as escolhas guardadas.'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-sm">Pode rever estas escolhas acima. Os dados e o histórico destas etapas ficam conservados.</p>
|
||||
<p className="text-sm">
|
||||
Pode rever estas escolhas acima. Os dados e o histórico
|
||||
destas etapas ficam conservados.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{Object.entries(path.phases).filter(([number]) => path.steps.some((step) => step.phase === Number(number) && step.preparation_allowed)).map(([number, label]) => (
|
||||
<details open={path.steps.some(step=>step.phase===Number(number)&&step.code===path.next?.code)} className="space-y-3 rounded border p-4" key={number}>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</summary>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number) && step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
step={step}
|
||||
path={path}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
{Object.entries(path.phases)
|
||||
.filter(([number]) =>
|
||||
path.steps.some(
|
||||
(step) =>
|
||||
step.phase === Number(number) &&
|
||||
step.preparation_allowed,
|
||||
),
|
||||
)
|
||||
.map(([number, label]) => (
|
||||
<details
|
||||
open={path.steps.some(
|
||||
(step) =>
|
||||
step.phase === Number(number) &&
|
||||
step.code === path.next?.code,
|
||||
)}
|
||||
className="space-y-3 rounded border p-4"
|
||||
key={number}
|
||||
>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</summary>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter(
|
||||
(step) =>
|
||||
step.phase === Number(number) &&
|
||||
step.preparation_allowed,
|
||||
)
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
step={step}
|
||||
path={path}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Resultados devolvidos ao dossier
|
||||
|
||||
@@ -104,9 +104,15 @@ export default function LandCase({
|
||||
};
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<InvestmentConsumerIdentity raw={payload.context_opportunity_snapshot}/>
|
||||
<InvestmentConsumerIdentity
|
||||
raw={payload.context_opportunity_snapshot}
|
||||
/>
|
||||
<header className="space-y-2">
|
||||
{returnDossier && <Link className="underline" href={returnDossier.url}>Voltar ao dossier: {returnDossier.title}</Link>}
|
||||
{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>
|
||||
|
||||
@@ -45,7 +45,7 @@ export default function PrintCase({
|
||||
Imprimir / guardar como PDF
|
||||
</button>
|
||||
</div>
|
||||
<InvestmentConsumerIdentity raw={p.context_opportunity_snapshot}/>
|
||||
<InvestmentConsumerIdentity raw={p.context_opportunity_snapshot} />
|
||||
<header className="space-y-2 border-b pb-4">
|
||||
<p>InvesteMoz · modelo de preparação · {modelVersion}</p>
|
||||
<h1 className="text-2xl font-bold">
|
||||
|
||||
@@ -6,7 +6,10 @@ export default function ManagementAccess({
|
||||
}: {
|
||||
registrationEnabled: boolean;
|
||||
}) {
|
||||
const { auth, contentManagementHref } = usePage<{ auth: Auth; contentManagementHref?: string | null }>().props;
|
||||
const { auth, contentManagementHref } = usePage<{
|
||||
auth: Auth;
|
||||
contentManagementHref?: string | null;
|
||||
}>().props;
|
||||
const user = auth.user;
|
||||
const action =
|
||||
'inline-flex rounded-lg bg-slate-900 px-5 py-3 font-medium text-white';
|
||||
@@ -55,8 +58,17 @@ export default function ManagementAccess({
|
||||
</>
|
||||
) : contentManagementHref ? (
|
||||
<>
|
||||
<p>Abra a entrada de gestão para cadastrar oportunidades e gerir documentos e legislação, conforme as funções já atribuídas à sua conta.</p>
|
||||
<Link className={action} href={contentManagementHref}>Abrir gestão de conteúdos e oportunidades</Link>
|
||||
<p>
|
||||
Abra a entrada de gestão para cadastrar
|
||||
oportunidades e gerir documentos e legislação,
|
||||
conforme as funções já atribuídas à sua conta.
|
||||
</p>
|
||||
<Link
|
||||
className={action}
|
||||
href={contentManagementHref}
|
||||
>
|
||||
Abrir gestão de conteúdos e oportunidades
|
||||
</Link>
|
||||
</>
|
||||
) : auth.canManagePortal ? (
|
||||
<>
|
||||
|
||||
@@ -3,40 +3,212 @@ import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { states } from './shared';
|
||||
|
||||
type Access = {
|
||||
procurement?: {index:string;create:string};
|
||||
opportunities?: {index: string; create: string | null; profileWorkflow: boolean};
|
||||
documents?: {index: string; edit: boolean};
|
||||
procurement?: { index: string; create: string };
|
||||
opportunities?: {
|
||||
index: string;
|
||||
create: string | null;
|
||||
profileWorkflow: boolean;
|
||||
};
|
||||
documents?: { index: string; edit: boolean };
|
||||
};
|
||||
export default function ContentHub({access, counts}: {access: Access; counts: Record<string, Record<string, number>>}) {
|
||||
return <Frame title="Gestão de conteúdos e oportunidades">
|
||||
<p>Use os cadastros e a biblioteca existentes. Guardar um rascunho, analisar um ficheiro e publicar são operações distintas. Cada acção respeita a sua autorização actual.</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{access.procurement && <section className={card}><h2 className="text-xl font-semibold">Concursos e anúncios</h2><p>Cadastre o procedimento e os lotes, guarde e recupere a preparação, reveja a prévia e publique os actos autorizados. Esclarecimentos, prorrogações, resultados e cancelamentos conservam versões e histórico. Divulgação de oportunidade e abertura de concurso são operações distintas.</p><Link className={button} href={access.procurement.create}>Novo concurso/anúncio</Link><Link className="block underline" href={access.procurement.index}>Gerir concursos e anúncios</Link><Link className="block underline" href="/concursos">Catálogo público</Link></section>}
|
||||
{access.opportunities && <section className={card}>
|
||||
<h2 className="text-xl font-semibold">Oportunidades</h2>
|
||||
<p>Escolha a modalidade, o sector e a localização; preencha, guarde o rascunho e siga as acções de submissão, revisão e publicação disponíveis no seu perfil.</p>
|
||||
<p>Sector económico e modalidade são escolhas distintas. Pode guardar preparação incompleta; o editor identifica os campos e variantes ainda sem suporte de submissão.</p>
|
||||
{access.opportunities.create && <Link className={button} href={access.opportunities.create}>Nova oportunidade</Link>}
|
||||
<Link className="block underline" href={access.opportunities.index}>Gerir oportunidades e histórico</Link>
|
||||
{access.opportunities.profileWorkflow && <Link className="block underline" href="/minhas-oportunidades/lotes/agronegocio">Rever o lote das 34 oportunidades de Agronegócio</Link>}
|
||||
<p>Para divulgar um resumo ainda em preparação, abra a ficha e escolha <strong>Divulgação promocional</strong>: prepare o texto público, reveja a prévia e confirme divulgar, actualizar ou retirar. Esta operação não conclui a validação do investimento.</p>
|
||||
<ul>{Object.entries(counts.opportunities ?? {}).map(([state, total]) => <li key={state}><Link className="underline" href={`${access.opportunities!.index}?status=${state}`}>{states[state] ?? state}: {total}</Link></li>)}</ul>
|
||||
<p className="text-sm">As etapas e a independência já definidas para oportunidades mantêm-se. Esta entrada não atribui autorização para rever ou publicar.</p>
|
||||
{!access.opportunities.profileWorkflow && <p>O seu acesso actual abre o cadastro legado de rascunhos. A submissão, revisão e publicação de novas oportunidades utilizam os perfis operacionais já existentes; a administração de conteúdos não substitui essa designação. Esta entrada não apresenta o rascunho legado como percurso completo de publicação.</p>}
|
||||
</section>}
|
||||
{access.documents && <section className={card}>
|
||||
<h2 className="text-xl font-semibold">Documentos e legislação</h2>
|
||||
<p>Carregue o original ou reutilize um ficheiro existente; acompanhe a análise, complete os metadados e associações e defina o acesso. Depois publique explicitamente, se autorizado.</p>
|
||||
<div className="flex flex-wrap gap-3"><Link className={button} href={`${access.documents.index}?intent=document#receber`}>Novo documento</Link>
|
||||
{access.documents.edit && <Link className={button} href={`${access.documents.index}?intent=legislation#receber`}>Nova legislação</Link>}</div>
|
||||
<Link className="block underline" href={`${access.documents.index}#conteudos`}>Gerir conteúdos, versões e histórico</Link>
|
||||
{!access.documents.edit && <p>O seu acesso permite carregar e analisar ficheiros próprios; não inclui cadastro editorial nem publicação.</p>}
|
||||
<p>Publicados: {counts.documents?.published ?? 0} · Não publicados: {counts.documents?.unpublished ?? 0}. A lista distingue rascunhos de conteúdos retirados através do histórico.</p>
|
||||
<p className="text-sm">Publicar legislação permite consultá-la. Não a activa como regra executável no simulador.</p>
|
||||
</section>}
|
||||
</div>
|
||||
<section className={card}><h2 className="font-semibold">Como concluir sem apoio técnico</h2>
|
||||
<ol className="list-decimal space-y-2 pl-5"><li>Abra a acção pretendida e use os campos do editor existente.</li><li>Guarde a preparação. As mensagens indicam o estado e o que precisa de corrigir.</li><li>Reabra pela gestão, pesquise o título e consulte o histórico.</li><li>Use as acções autorizadas de publicação ou retirada. Os originais e as revisões são preservados.</li></ol>
|
||||
</section>
|
||||
</Frame>;
|
||||
export default function ContentHub({
|
||||
access,
|
||||
counts,
|
||||
}: {
|
||||
access: Access;
|
||||
counts: Record<string, Record<string, number>>;
|
||||
}) {
|
||||
return (
|
||||
<Frame title="Gestão de conteúdos e oportunidades">
|
||||
<p>
|
||||
Use os cadastros e a biblioteca existentes. Guardar um rascunho,
|
||||
analisar um ficheiro e publicar são operações distintas. Cada
|
||||
acção respeita a sua autorização actual.
|
||||
</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{access.procurement && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Concursos e anúncios
|
||||
</h2>
|
||||
<p>
|
||||
Cadastre o procedimento e os lotes, guarde e
|
||||
recupere a preparação, reveja a prévia e publique os
|
||||
actos autorizados. Esclarecimentos, prorrogações,
|
||||
resultados e cancelamentos conservam versões e
|
||||
histórico. Divulgação de oportunidade e abertura de
|
||||
concurso são operações distintas.
|
||||
</p>
|
||||
<Link
|
||||
className={button}
|
||||
href={access.procurement.create}
|
||||
>
|
||||
Novo concurso/anúncio
|
||||
</Link>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={access.procurement.index}
|
||||
>
|
||||
Gerir concursos e anúncios
|
||||
</Link>
|
||||
<Link className="block underline" href="/concursos">
|
||||
Catálogo público
|
||||
</Link>
|
||||
</section>
|
||||
)}
|
||||
{access.opportunities && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">Oportunidades</h2>
|
||||
<p>
|
||||
Escolha a modalidade, o sector e a localização;
|
||||
preencha, guarde o rascunho e siga as acções de
|
||||
submissão, revisão e publicação disponíveis no seu
|
||||
perfil.
|
||||
</p>
|
||||
<p>
|
||||
Sector económico e modalidade são escolhas
|
||||
distintas. Pode guardar preparação incompleta; o
|
||||
editor identifica os campos e variantes ainda sem
|
||||
suporte de submissão.
|
||||
</p>
|
||||
{access.opportunities.create && (
|
||||
<Link
|
||||
className={button}
|
||||
href={access.opportunities.create}
|
||||
>
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
className="block underline"
|
||||
href={access.opportunities.index}
|
||||
>
|
||||
Gerir oportunidades e histórico
|
||||
</Link>
|
||||
{access.opportunities.profileWorkflow && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/minhas-oportunidades/lotes/agronegocio"
|
||||
>
|
||||
Rever o lote das 34 oportunidades de Agronegócio
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
Para divulgar um resumo ainda em preparação, abra a
|
||||
ficha e escolha{' '}
|
||||
<strong>Divulgação promocional</strong>: prepare o
|
||||
texto público, reveja a prévia e confirme divulgar,
|
||||
actualizar ou retirar. Esta operação não conclui a
|
||||
validação do investimento.
|
||||
</p>
|
||||
<ul>
|
||||
{Object.entries(counts.opportunities ?? {}).map(
|
||||
([state, total]) => (
|
||||
<li key={state}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${access.opportunities!.index}?status=${state}`}
|
||||
>
|
||||
{states[state] ?? state}: {total}
|
||||
</Link>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
<p className="text-sm">
|
||||
As etapas e a independência já definidas para
|
||||
oportunidades mantêm-se. Esta entrada não atribui
|
||||
autorização para rever ou publicar.
|
||||
</p>
|
||||
{!access.opportunities.profileWorkflow && (
|
||||
<p>
|
||||
O seu acesso actual abre o cadastro legado de
|
||||
rascunhos. A submissão, revisão e publicação de
|
||||
novas oportunidades utilizam os perfis
|
||||
operacionais já existentes; a administração de
|
||||
conteúdos não substitui essa designação. Esta
|
||||
entrada não apresenta o rascunho legado como
|
||||
percurso completo de publicação.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{access.documents && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Documentos e legislação
|
||||
</h2>
|
||||
<p>
|
||||
Carregue o original ou reutilize um ficheiro
|
||||
existente; acompanhe a análise, complete os
|
||||
metadados e associações e defina o acesso. Depois
|
||||
publique explicitamente, se autorizado.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link
|
||||
className={button}
|
||||
href={`${access.documents.index}?intent=document#receber`}
|
||||
>
|
||||
Novo documento
|
||||
</Link>
|
||||
{access.documents.edit && (
|
||||
<Link
|
||||
className={button}
|
||||
href={`${access.documents.index}?intent=legislation#receber`}
|
||||
>
|
||||
Nova legislação
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`${access.documents.index}#conteudos`}
|
||||
>
|
||||
Gerir conteúdos, versões e histórico
|
||||
</Link>
|
||||
{!access.documents.edit && (
|
||||
<p>
|
||||
O seu acesso permite carregar e analisar
|
||||
ficheiros próprios; não inclui cadastro
|
||||
editorial nem publicação.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Publicados: {counts.documents?.published ?? 0} · Não
|
||||
publicados: {counts.documents?.unpublished ?? 0}. A
|
||||
lista distingue rascunhos de conteúdos retirados
|
||||
através do histórico.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Publicar legislação permite consultá-la. Não a
|
||||
activa como regra executável no simulador.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
<section className={card}>
|
||||
<h2 className="font-semibold">
|
||||
Como concluir sem apoio técnico
|
||||
</h2>
|
||||
<ol className="list-decimal space-y-2 pl-5">
|
||||
<li>
|
||||
Abra a acção pretendida e use os campos do editor
|
||||
existente.
|
||||
</li>
|
||||
<li>
|
||||
Guarde a preparação. As mensagens indicam o estado e o
|
||||
que precisa de corrigir.
|
||||
</li>
|
||||
<li>
|
||||
Reabra pela gestão, pesquise o título e consulte o
|
||||
histórico.
|
||||
</li>
|
||||
<li>
|
||||
Use as acções autorizadas de publicação ou retirada. Os
|
||||
originais e as revisões são preservados.
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,22 +4,181 @@ import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Management, button, control } from './shared';
|
||||
|
||||
type Entry = {key:string;id:number|null;title:string;summary:string;description:string;corridor:string;status:string|null;href:string|null};
|
||||
type Preview = {id:number;token:string;projection:{title:string;summary:string;description:string};operation_key:string};
|
||||
export default function AgribusinessBatch({entries,manifestHash,canRegister}:{entries:Entry[];manifestHash:string;canRegister:boolean}) {
|
||||
const [previews,setPreviews]=useState<Preview[]>([]); const [reason,setReason]=useState(''); const [confirmed,setConfirmed]=useState(false); const [busy,setBusy]=useState(false); const [message,setMessage]=useState('');
|
||||
const base='/minhas-oportunidades/lotes/agronegocio';
|
||||
async function run(action:'register'|'preview'|'disclose') {setBusy(true);setMessage('');try {
|
||||
if(action==='register'){await profileJson(base+'/cadastrar',{manifest_hash:manifestHash,confirm:true});router.reload();}
|
||||
if(action==='preview'){const result=await profileJson(base+'/previa',{}) as {previews:Preview[]};setPreviews(result.previews.map(p=>({...p,operation_key:createOperationKey()})));setConfirmed(false);}
|
||||
if(action==='disclose'){await profileJson(base+'/divulgar',{previews:previews.map(({id,token,operation_key})=>({id,token,operation_key})),reason,confirm:confirmed});setPreviews([]);setMessage('As 34 fichas foram divulgadas como Em preparação; a execução não foi autorizada.');router.reload();}
|
||||
}catch(e){setMessage(e instanceof Error?e.message:'Operação não concluída. A versão anterior foi preservada.');}finally{setBusy(false);}}
|
||||
return <Management title="Oportunidades de Agronegócio"><p>Reveja as oportunidades, complete a informação disponível e confira a prévia antes de divulgar.</p>
|
||||
<p>{entries.filter(e=>e.id).length} cadastradas · {entries.filter(e=>e.status==='published').length} divulgadas</p>
|
||||
{canRegister && <button className={button} disabled={busy} onClick={()=>void run('register')}>Cadastrar ou recuperar as 34 fichas privadamente</button>}
|
||||
{entries.every(e=>e.id) && <button className={button+' ml-3'} disabled={busy} onClick={()=>void run('preview')}>Pré-visualizar divulgação das 34 fichas</button>}
|
||||
<ul className="my-5 space-y-3">{entries.map(e=><li key={e.key} className="rounded border p-3"><h2>{e.title}</h2><p>{e.summary}</p><p>{e.corridor} · {e.status??'Por cadastrar'}</p>{e.id&&<Link className="underline" href={`/minhas-oportunidades/${e.id}/edit`}>Rever e editar a ficha</Link>}</li>)}</ul>
|
||||
{!!previews.length && <section aria-label="Prévia pública das 34 fichas"><h2>Conteúdo a divulgar — Em preparação</h2>{previews.map(p=><details key={p.id} className="my-3 rounded border p-3"><summary>{p.projection.title}</summary><p>{p.projection.summary}</p><p className="whitespace-pre-line">{p.projection.description}</p></details>)}<label className="block">Motivo<textarea className={control} value={reason} onChange={e=>setReason(e.target.value)}/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>Confirmo a divulgação destes resumos em preparação; não é autorização de execução.</label><button className={button} disabled={busy||!confirmed||reason.trim().length<20} onClick={()=>void run('disclose')}>Divulgar as 34 oportunidades no catálogo</button></section>}
|
||||
{message&&<p role="status">{message}</p>}<Link className="block underline" href="/oportunidades?sector=agronegocio">Consultar catálogo de Agronegócio</Link>
|
||||
</Management>;
|
||||
type Entry = {
|
||||
key: string;
|
||||
id: number | null;
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
corridor: string;
|
||||
status: string | null;
|
||||
href: string | null;
|
||||
};
|
||||
type Preview = {
|
||||
id: number;
|
||||
token: string;
|
||||
projection: { title: string; summary: string; description: string };
|
||||
operation_key: string;
|
||||
};
|
||||
export default function AgribusinessBatch({
|
||||
entries,
|
||||
manifestHash,
|
||||
canRegister,
|
||||
}: {
|
||||
entries: Entry[];
|
||||
manifestHash: string;
|
||||
canRegister: boolean;
|
||||
}) {
|
||||
const [previews, setPreviews] = useState<Preview[]>([]);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const base = '/minhas-oportunidades/lotes/agronegocio';
|
||||
async function run(action: 'register' | 'preview' | 'disclose') {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
if (action === 'register') {
|
||||
await profileJson(base + '/cadastrar', {
|
||||
manifest_hash: manifestHash,
|
||||
confirm: true,
|
||||
});
|
||||
router.reload();
|
||||
}
|
||||
if (action === 'preview') {
|
||||
const result = (await profileJson(base + '/previa', {})) as {
|
||||
previews: Preview[];
|
||||
};
|
||||
setPreviews(
|
||||
result.previews.map((p) => ({
|
||||
...p,
|
||||
operation_key: createOperationKey(),
|
||||
})),
|
||||
);
|
||||
setConfirmed(false);
|
||||
}
|
||||
if (action === 'disclose') {
|
||||
await profileJson(base + '/divulgar', {
|
||||
previews: previews.map(({ id, token, operation_key }) => ({
|
||||
id,
|
||||
token,
|
||||
operation_key,
|
||||
})),
|
||||
reason,
|
||||
confirm: confirmed,
|
||||
});
|
||||
setPreviews([]);
|
||||
setMessage(
|
||||
'As 34 fichas foram divulgadas como Em preparação; a execução não foi autorizada.',
|
||||
);
|
||||
router.reload();
|
||||
}
|
||||
} catch (e) {
|
||||
setMessage(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Operação não concluída. A versão anterior foi preservada.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management title="Oportunidades de Agronegócio">
|
||||
<p>
|
||||
Reveja as oportunidades, complete a informação disponível e
|
||||
confira a prévia antes de divulgar.
|
||||
</p>
|
||||
<p>
|
||||
{entries.filter((e) => e.id).length} cadastradas ·{' '}
|
||||
{entries.filter((e) => e.status === 'published').length}{' '}
|
||||
divulgadas
|
||||
</p>
|
||||
{canRegister && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void run('register')}
|
||||
>
|
||||
Cadastrar ou recuperar as 34 fichas privadamente
|
||||
</button>
|
||||
)}
|
||||
{entries.every((e) => e.id) && (
|
||||
<button
|
||||
className={button + ' ml-3'}
|
||||
disabled={busy}
|
||||
onClick={() => void run('preview')}
|
||||
>
|
||||
Pré-visualizar divulgação das 34 fichas
|
||||
</button>
|
||||
)}
|
||||
<ul className="my-5 space-y-3">
|
||||
{entries.map((e) => (
|
||||
<li key={e.key} className="rounded border p-3">
|
||||
<h2>{e.title}</h2>
|
||||
<p>{e.summary}</p>
|
||||
<p>
|
||||
{e.corridor} · {e.status ?? 'Por cadastrar'}
|
||||
</p>
|
||||
{e.id && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/minhas-oportunidades/${e.id}/edit`}
|
||||
>
|
||||
Rever e editar a ficha
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!!previews.length && (
|
||||
<section aria-label="Prévia pública das 34 fichas">
|
||||
<h2>Conteúdo a divulgar — Em preparação</h2>
|
||||
{previews.map((p) => (
|
||||
<details key={p.id} className="my-3 rounded border p-3">
|
||||
<summary>{p.projection.title}</summary>
|
||||
<p>{p.projection.summary}</p>
|
||||
<p className="whitespace-pre-line">
|
||||
{p.projection.description}
|
||||
</p>
|
||||
</details>
|
||||
))}
|
||||
<label className="block">
|
||||
Motivo
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>
|
||||
Confirmo a divulgação destes resumos em preparação; não
|
||||
é autorização de execução.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy || !confirmed || reason.trim().length < 20
|
||||
}
|
||||
onClick={() => void run('disclose')}
|
||||
>
|
||||
Divulgar as 34 oportunidades no catálogo
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/oportunidades?sector=agronegocio"
|
||||
>
|
||||
Consultar catálogo de Agronegócio
|
||||
</Link>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,160 @@
|
||||
import { Head, router, usePage } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
type Row={id:string;protocol:string;status:string;version:number;analyst_id:number|null;due_at:string|null;etag?:string};
|
||||
export default function DeskAssignments(){
|
||||
const {requests,analysts,kind,flash}=usePage<{requests:Row[];analysts:{id:number;name:string}[];kind?:'interest';flash?:{success?:string}}>().props;
|
||||
const alertRef=useRef<HTMLDivElement>(null);
|
||||
const stateNames:Record<string,string>={received:'Recebido',submitted:'Submetido',in_review:'Em revisão',reviewed:'Revisto',qualification:'Em qualificação',qualified:'Qualificado',contacted:'Contactado',contact_accepted:'Contacto aceite',referred:'Encaminhado',due_diligence:'Em diligência',negotiation:'Em negociação',pending:'Pendente',accepted:'Aceite',rejected:'Recusado',returned:'Devolvido',processing:'Em tratamento',draft:'Rascunho'};
|
||||
const title=kind==='interest'?'Atribuições de interesses':'Atribuições do Balcão';
|
||||
const [selected,setSelected]=useState<Record<string,string>>({});
|
||||
const [reason,setReason]=useState<Record<string,string>>({});
|
||||
const [errors,setErrors]=useState<Record<string,string>>({});
|
||||
const [busy,setBusy]=useState<string|null>(null);
|
||||
function assign(row:Row){setBusy(row.id);setErrors({});router.post(kind==='interest'?`/management/interests/${row.id}/responsavel`:`/balcao-virtual/pedidos/${row.id}/responsavel`,{...(kind==='interest'?{etag:row.etag}:{version:row.version}),analyst_id:selected[row.id]??String(row.analyst_id??''),reason:reason[row.id]??''},{preserveScroll:true,onError:e=>{setErrors(e);queueMicrotask(()=>alertRef.current?.focus());},onFinish:()=>setBusy(null)});}
|
||||
return <main className="mx-auto max-w-5xl space-y-6 p-6"><Head title={title}/><h1 className="text-2xl font-semibold">{title}</h1><p>Atribua o acompanhamento de um pedido. Esta lista não dá acesso ao conteúdo privado do dossier. O proponente não pode ser designado como analista do seu pedido.</p><a href={kind==='interest'?'/management/interests':'/balcao-virtual/painel'} className="underline">{kind==='interest'?'Interesses atribuídos':'Voltar ao Balcão'}</a><div ref={alertRef} role="alert" tabIndex={-1}>{Object.values(errors).join(' ')}</div>{flash?.success&&<p role="status">{flash.success}</p>}{requests.length===0?<p>Não há pedidos para atribuir.</p>:requests.map(row=><section key={row.id} className="space-y-3 rounded border p-4"><h2 className="font-semibold">{row.protocol||row.id}</h2><p>Estado: {stateNames[row.status]??'Por esclarecer'}</p><label className="block">Responsável<select className="ml-2 border p-2" value={selected[row.id]??String(row.analyst_id??'')} onChange={e=>setSelected({...selected,[row.id]:e.target.value})}><option value="">Seleccione</option>{analysts.map(a=><option key={a.id} value={a.id}>{a.name}</option>)}</select></label><label className="block">Fundamento<textarea className="block w-full border p-2" value={reason[row.id]??''} onChange={e=>setReason({...reason,[row.id]:e.target.value})}/></label><button className="rounded bg-emerald-900 px-4 py-2 text-white" disabled={busy!==null} onClick={()=>assign(row)}>{busy===row.id?'A guardar…':'Guardar atribuição'}</button></section>)}</main>;
|
||||
type Row = {
|
||||
id: string;
|
||||
protocol: string;
|
||||
status: string;
|
||||
version: number;
|
||||
analyst_id: number | null;
|
||||
due_at: string | null;
|
||||
etag?: string;
|
||||
};
|
||||
export default function DeskAssignments() {
|
||||
const { requests, analysts, kind, flash } = usePage<{
|
||||
requests: Row[];
|
||||
analysts: { id: number; name: string }[];
|
||||
kind?: 'interest';
|
||||
flash?: { success?: string };
|
||||
}>().props;
|
||||
const alertRef = useRef<HTMLDivElement>(null);
|
||||
const stateNames: Record<string, string> = {
|
||||
received: 'Recebido',
|
||||
submitted: 'Submetido',
|
||||
in_review: 'Em revisão',
|
||||
reviewed: 'Revisto',
|
||||
qualification: 'Em qualificação',
|
||||
qualified: 'Qualificado',
|
||||
contacted: 'Contactado',
|
||||
contact_accepted: 'Contacto aceite',
|
||||
referred: 'Encaminhado',
|
||||
due_diligence: 'Em diligência',
|
||||
negotiation: 'Em negociação',
|
||||
pending: 'Pendente',
|
||||
accepted: 'Aceite',
|
||||
rejected: 'Recusado',
|
||||
returned: 'Devolvido',
|
||||
processing: 'Em tratamento',
|
||||
draft: 'Rascunho',
|
||||
};
|
||||
const title =
|
||||
kind === 'interest'
|
||||
? 'Atribuições de interesses'
|
||||
: 'Atribuições do Balcão';
|
||||
const [selected, setSelected] = useState<Record<string, string>>({});
|
||||
const [reason, setReason] = useState<Record<string, string>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
function assign(row: Row) {
|
||||
setBusy(row.id);
|
||||
setErrors({});
|
||||
router.post(
|
||||
kind === 'interest'
|
||||
? `/management/interests/${row.id}/responsavel`
|
||||
: `/balcao-virtual/pedidos/${row.id}/responsavel`,
|
||||
{
|
||||
...(kind === 'interest'
|
||||
? { etag: row.etag }
|
||||
: { version: row.version }),
|
||||
analyst_id: selected[row.id] ?? String(row.analyst_id ?? ''),
|
||||
reason: reason[row.id] ?? '',
|
||||
},
|
||||
{
|
||||
preserveScroll: true,
|
||||
onError: (e) => {
|
||||
setErrors(e);
|
||||
queueMicrotask(() => alertRef.current?.focus());
|
||||
},
|
||||
onFinish: () => setBusy(null),
|
||||
},
|
||||
);
|
||||
}
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<Head title={title} />
|
||||
<h1 className="text-2xl font-semibold">{title}</h1>
|
||||
<p>
|
||||
Atribua o acompanhamento de um pedido. Esta lista não dá acesso
|
||||
ao conteúdo privado do dossier. O proponente não pode ser
|
||||
designado como analista do seu pedido.
|
||||
</p>
|
||||
<a
|
||||
href={
|
||||
kind === 'interest'
|
||||
? '/management/interests'
|
||||
: '/balcao-virtual/painel'
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
{kind === 'interest'
|
||||
? 'Interesses atribuídos'
|
||||
: 'Voltar ao Balcão'}
|
||||
</a>
|
||||
<div ref={alertRef} role="alert" tabIndex={-1}>
|
||||
{Object.values(errors).join(' ')}
|
||||
</div>
|
||||
{flash?.success && <p role="status">{flash.success}</p>}
|
||||
{requests.length === 0 ? (
|
||||
<p>Não há pedidos para atribuir.</p>
|
||||
) : (
|
||||
requests.map((row) => (
|
||||
<section
|
||||
key={row.id}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
{row.protocol || row.id}
|
||||
</h2>
|
||||
<p>
|
||||
Estado: {stateNames[row.status] ?? 'Por esclarecer'}
|
||||
</p>
|
||||
<label className="block">
|
||||
Responsável
|
||||
<select
|
||||
className="ml-2 border p-2"
|
||||
value={
|
||||
selected[row.id] ??
|
||||
String(row.analyst_id ?? '')
|
||||
}
|
||||
onChange={(e) =>
|
||||
setSelected({
|
||||
...selected,
|
||||
[row.id]: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{analysts.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
className="block w-full border p-2"
|
||||
value={reason[row.id] ?? ''}
|
||||
onChange={(e) =>
|
||||
setReason({
|
||||
...reason,
|
||||
[row.id]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className="rounded bg-emerald-900 px-4 py-2 text-white"
|
||||
disabled={busy !== null}
|
||||
onClick={() => assign(row)}
|
||||
>
|
||||
{busy === row.id
|
||||
? 'A guardar…'
|
||||
: 'Guardar atribuição'}
|
||||
</button>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,32 @@ type Plan = {
|
||||
installed: boolean;
|
||||
imported: boolean;
|
||||
publication: string;
|
||||
rows: { table: string; id: string; code: string; status: string; current_visibility: string | null }[];
|
||||
rows: {
|
||||
table: string;
|
||||
id: string;
|
||||
code: string;
|
||||
status: string;
|
||||
current_visibility: string | null;
|
||||
}[];
|
||||
sources: { name: string; sha256: string; ready: boolean }[];
|
||||
scan: { at: string; files: { name: string; sha256: string; scan: { result: string; engine: string } }[] } | null;
|
||||
operations: Record<Operation, { ready: boolean; hash: string; reasons: string[]; backupDate: string | null; evidence_mode: string }>;
|
||||
scan: {
|
||||
at: string;
|
||||
files: {
|
||||
name: string;
|
||||
sha256: string;
|
||||
scan: { result: string; engine: string };
|
||||
}[];
|
||||
} | null;
|
||||
operations: Record<
|
||||
Operation,
|
||||
{
|
||||
ready: boolean;
|
||||
hash: string;
|
||||
reasons: string[];
|
||||
backupDate: string | null;
|
||||
evidence_mode: string;
|
||||
}
|
||||
>;
|
||||
};
|
||||
const labels: Record<Operation, string> = {
|
||||
schema: 'Instalar apenas o esquema',
|
||||
@@ -27,63 +49,217 @@ export default function EconomicReferences({ plan }: { plan: Plan }) {
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [receipt, setReceipt] = useState<Record<string, unknown> | null>(null);
|
||||
const last = useRef<{ operation: Operation; payload: Record<string, unknown> } | null>(null);
|
||||
const [receipt, setReceipt] = useState<Record<string, unknown> | null>(
|
||||
null,
|
||||
);
|
||||
const last = useRef<{
|
||||
operation: Operation;
|
||||
payload: Record<string, unknown>;
|
||||
} | null>(null);
|
||||
|
||||
async function perform(operation: Operation, replay = false) {
|
||||
const payload = replay && last.current?.operation === operation ? last.current.payload : {
|
||||
hash: plan.operations[operation].hash,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
reason,
|
||||
confirm,
|
||||
};
|
||||
const payload =
|
||||
replay && last.current?.operation === operation
|
||||
? last.current.payload
|
||||
: {
|
||||
hash: plan.operations[operation].hash,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
reason,
|
||||
confirm,
|
||||
};
|
||||
if (!replay) last.current = { operation, payload };
|
||||
setBusy(true); setError('');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = document.cookie.split('; ').find((s) => s.startsWith('XSRF-TOKEN='))?.split('=').slice(1).join('=') ?? '';
|
||||
const response = await fetch(`/management/economic-references/lot-01/${operation}`, {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-XSRF-TOKEN': decodeURIComponent(token) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const token =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((s) => s.startsWith('XSRF-TOKEN='))
|
||||
?.split('=')
|
||||
.slice(1)
|
||||
.join('=') ?? '';
|
||||
const response = await fetch(
|
||||
`/management/economic-references/lot-01/${operation}`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(Object.values(data.errors ?? {}).flat().join(' ') || data.message || 'Não foi possível concluir esta operação.');
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(data.errors ?? {})
|
||||
.flat()
|
||||
.join(' ') ||
|
||||
data.message ||
|
||||
'Não foi possível concluir esta operação.',
|
||||
);
|
||||
setReceipt(data.receipt);
|
||||
router.reload({ only: ['plan'] });
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Operação indisponível. Atualize a prévia e consulte o motivo.');
|
||||
} finally { setBusy(false); }
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Operação indisponível. Atualize a prévia e consulte o motivo.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <Management title="Referências económicas — lote delimitado">
|
||||
<p>Destino: {plan.target.database}:{plan.target.port}</p>
|
||||
<p>Esquema: {plan.installed ? 'instalado' : 'pendente'} · Importação: {plan.imported ? 'recuperada' : 'pendente'} · Publicação: {plan.publication}</p>
|
||||
<p>Divisão 01 como subsector e subclasse 01120 como atividade apenas neste recorte. Os cinco níveis originais permanecem. A divergência documental 600/579 continua aberta; não há conformidade normativa integral declarada.</p>
|
||||
<p>Os cinco elos do CLU-01 são um modelo editorial, sem operadores, capacidades ou relações comerciais confirmados. Importar não publica referências, documentos ou anúncios.</p>
|
||||
<details><summary>Revisão e manifesto</summary><p className="break-all">Código: {plan.code_hash}</p><p className="break-all">Manifesto: {plan.manifest_sha256}</p></details>
|
||||
<section className="my-4" aria-label="Originais privados e scan">
|
||||
<h2 className="text-lg font-semibold">Originais privados</h2>
|
||||
{plan.sources.map((s) => <p className="break-words" key={s.sha256}>{s.name}: {s.ready ? 'bytes conferidos' : 'ausente ou divergente'} · <span className="break-all">{s.sha256}</span></p>)}
|
||||
<p>{plan.scan ? `Scan registado em ${plan.scan.at}.` : 'O scan real será executado na importação e novamente antes da publicação.'}</p>
|
||||
{plan.scan?.files.map((s) => <p key={s.sha256}>{s.name}: {s.scan.result} · {s.scan.engine}</p>)}
|
||||
</section>
|
||||
<label className="block" htmlFor="economic-reason">Justificação desta operação</label>
|
||||
<textarea id="economic-reason" className={control} value={reason} minLength={20} maxLength={1000} onChange={(e) => setReason(e.target.value)} />
|
||||
<label className="my-3 block"><input type="checkbox" checked={confirm} onChange={(e) => setConfirm(e.target.checked)} /> Confirmo somente a ação selecionada para este lote.</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(Object.keys(labels) as Operation[]).map((operation) => <section className="rounded border p-3" key={operation}>
|
||||
<h2 className="font-semibold">{labels[operation]}</h2>
|
||||
<p>{operation === 'schema' ? 'Migration nominal, sem importar dados.' : operation === 'import' ? 'Apenas ausências, privadamente; repetição sem duplicações.' : operation === 'publish' ? 'Expor apenas as referências do manifesto. Não divulga relações de investimentos.' : 'Retirada expressa e auditada; preserva UUID, decisões e recuperação histórica.'}</p>
|
||||
<p>Backup/restauro: {plan.operations[operation].backupDate ?? (plan.operations[operation].evidence_mode === 'isolated_QA' ? 'Ensaio QA isolado' : 'prova própria ainda necessária')}</p>
|
||||
{plan.operations[operation].reasons.map((r) => <p className="text-sm" key={r}>{r}</p>)}
|
||||
<button className={button} disabled={busy || !confirm || reason.trim().length < 20 || !plan.operations[operation].ready} onClick={() => perform(operation)}>{labels[operation]}</button>
|
||||
</section>)}
|
||||
</div>
|
||||
{error && <p className="my-3" role="alert">{error}</p>}
|
||||
{receipt && <section className="my-4" aria-live="polite"><h2 className="text-lg font-semibold">Recibo da operação</h2><pre className="overflow-auto whitespace-pre-wrap break-all text-sm">{JSON.stringify(receipt, null, 2)}</pre><button className={button} disabled={busy || !last.current} onClick={() => last.current && perform(last.current.operation, true)}>Repetir pedido anterior, sem duplicar</button></section>}
|
||||
<section className="mt-4"><h2 className="text-lg font-semibold">Referências previstas e recuperadas</h2>
|
||||
{plan.rows.map((r) => <p key={r.id}>{r.code}: {r.status} · {r.current_visibility ?? 'a inserir privadamente'}</p>)}
|
||||
</section>
|
||||
<p className="mt-4">Reversão após uso é parcial e compatível: conservar schema/dados, fontes funcionais e build de compatibilidade. Trocar código não retira publicação automaticamente.</p>
|
||||
</Management>;
|
||||
return (
|
||||
<Management title="Referências económicas — lote delimitado">
|
||||
<p>
|
||||
Destino: {plan.target.database}:{plan.target.port}
|
||||
</p>
|
||||
<p>
|
||||
Esquema: {plan.installed ? 'instalado' : 'pendente'} ·
|
||||
Importação: {plan.imported ? 'recuperada' : 'pendente'} ·
|
||||
Publicação: {plan.publication}
|
||||
</p>
|
||||
<p>
|
||||
Divisão 01 como subsector e subclasse 01120 como atividade
|
||||
apenas neste recorte. Os cinco níveis originais permanecem. A
|
||||
divergência documental 600/579 continua aberta; não há
|
||||
conformidade normativa integral declarada.
|
||||
</p>
|
||||
<p>
|
||||
Os cinco elos do CLU-01 são um modelo editorial, sem operadores,
|
||||
capacidades ou relações comerciais confirmados. Importar não
|
||||
publica referências, documentos ou anúncios.
|
||||
</p>
|
||||
<details>
|
||||
<summary>Revisão e manifesto</summary>
|
||||
<p className="break-all">Código: {plan.code_hash}</p>
|
||||
<p className="break-all">Manifesto: {plan.manifest_sha256}</p>
|
||||
</details>
|
||||
<section className="my-4" aria-label="Originais privados e scan">
|
||||
<h2 className="text-lg font-semibold">Originais privados</h2>
|
||||
{plan.sources.map((s) => (
|
||||
<p className="break-words" key={s.sha256}>
|
||||
{s.name}:{' '}
|
||||
{s.ready ? 'bytes conferidos' : 'ausente ou divergente'}{' '}
|
||||
· <span className="break-all">{s.sha256}</span>
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
{plan.scan
|
||||
? `Scan registado em ${plan.scan.at}.`
|
||||
: 'O scan real será executado na importação e novamente antes da publicação.'}
|
||||
</p>
|
||||
{plan.scan?.files.map((s) => (
|
||||
<p key={s.sha256}>
|
||||
{s.name}: {s.scan.result} · {s.scan.engine}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<label className="block" htmlFor="economic-reason">
|
||||
Justificação desta operação
|
||||
</label>
|
||||
<textarea
|
||||
id="economic-reason"
|
||||
className={control}
|
||||
value={reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
<label className="my-3 block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirm}
|
||||
onChange={(e) => setConfirm(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo somente a ação selecionada para este lote.
|
||||
</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(Object.keys(labels) as Operation[]).map((operation) => (
|
||||
<section className="rounded border p-3" key={operation}>
|
||||
<h2 className="font-semibold">{labels[operation]}</h2>
|
||||
<p>
|
||||
{operation === 'schema'
|
||||
? 'Migration nominal, sem importar dados.'
|
||||
: operation === 'import'
|
||||
? 'Apenas ausências, privadamente; repetição sem duplicações.'
|
||||
: operation === 'publish'
|
||||
? 'Expor apenas as referências do manifesto. Não divulga relações de investimentos.'
|
||||
: 'Retirada expressa e auditada; preserva UUID, decisões e recuperação histórica.'}
|
||||
</p>
|
||||
<p>
|
||||
Backup/restauro:{' '}
|
||||
{plan.operations[operation].backupDate ??
|
||||
(plan.operations[operation].evidence_mode ===
|
||||
'isolated_QA'
|
||||
? 'Ensaio QA isolado'
|
||||
: 'prova própria ainda necessária')}
|
||||
</p>
|
||||
{plan.operations[operation].reasons.map((r) => (
|
||||
<p className="text-sm" key={r}>
|
||||
{r}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!confirm ||
|
||||
reason.trim().length < 20 ||
|
||||
!plan.operations[operation].ready
|
||||
}
|
||||
onClick={() => perform(operation)}
|
||||
>
|
||||
{labels[operation]}
|
||||
</button>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="my-3" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{receipt && (
|
||||
<section className="my-4" aria-live="polite">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Recibo da operação
|
||||
</h2>
|
||||
<pre className="overflow-auto text-sm break-all whitespace-pre-wrap">
|
||||
{JSON.stringify(receipt, null, 2)}
|
||||
</pre>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || !last.current}
|
||||
onClick={() =>
|
||||
last.current &&
|
||||
perform(last.current.operation, true)
|
||||
}
|
||||
>
|
||||
Repetir pedido anterior, sem duplicar
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section className="mt-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Referências previstas e recuperadas
|
||||
</h2>
|
||||
{plan.rows.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.code}: {r.status} ·{' '}
|
||||
{r.current_visibility ?? 'a inserir privadamente'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<p className="mt-4">
|
||||
Reversão após uso é parcial e compatível: conservar
|
||||
schema/dados, fontes funcionais e build de compatibilidade.
|
||||
Trocar código não retira publicação automaticamente.
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Head } from "@inertiajs/react";
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import FiscalQaPreview from "@/components/fiscal-qa-preview";
|
||||
import { readVersionedArithmeticReportReference } from "@/lib/simulation-form";
|
||||
import { Head } from '@inertiajs/react';
|
||||
import { useRef, useState, type FormEvent } from 'react';
|
||||
import FiscalQaPreview from '@/components/fiscal-qa-preview';
|
||||
import { readVersionedArithmeticReportReference } from '@/lib/simulation-form';
|
||||
import {
|
||||
isApiSimulationCreateResponseV1,
|
||||
isApiSimulationReadResponseV1,
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
isApiSimulationResultSnapshotV1,
|
||||
type ApiSimulationExecutionV1,
|
||||
type ApiSimulationHistoryEntryV1,
|
||||
} from "@/lib/simulation-contract";
|
||||
} from '@/lib/simulation-contract';
|
||||
|
||||
class ReviewOperationError extends Error {}
|
||||
|
||||
@@ -19,9 +19,9 @@ export default function FiscalQaReview({
|
||||
}: {
|
||||
rule: { id: string; code: string; version: number };
|
||||
}) {
|
||||
const [base, setBase] = useState("");
|
||||
const [date, setDate] = useState("");
|
||||
const [currency, setCurrency] = useState("");
|
||||
const [base, setBase] = useState('');
|
||||
const [date, setDate] = useState('');
|
||||
const [currency, setCurrency] = useState('');
|
||||
const [declared, setDeclared] = useState(false);
|
||||
const [selected, setSelected] = useState<ApiSimulationExecutionV1 | null>(
|
||||
null,
|
||||
@@ -33,7 +33,7 @@ export default function FiscalQaReview({
|
||||
snapshot: unknown;
|
||||
} | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [message, setMessage] = useState('');
|
||||
const key = useRef<string | null>(null);
|
||||
const gate = useRef(false);
|
||||
const changed = () => {
|
||||
@@ -41,12 +41,12 @@ export default function FiscalQaReview({
|
||||
};
|
||||
const statusLabel = (status: string) =>
|
||||
({
|
||||
queued: "na fila",
|
||||
running: "em processamento",
|
||||
completed: "concluída",
|
||||
failed: "não concluída",
|
||||
cancelled: "cancelada",
|
||||
})[status] ?? "recebida";
|
||||
queued: 'na fila',
|
||||
running: 'em processamento',
|
||||
completed: 'concluída',
|
||||
failed: 'não concluída',
|
||||
cancelled: 'cancelada',
|
||||
})[status] ?? 'recebida';
|
||||
|
||||
async function request(
|
||||
url: string,
|
||||
@@ -54,20 +54,20 @@ export default function FiscalQaReview({
|
||||
): Promise<unknown> {
|
||||
const xsrf = decodeURIComponent(
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((part) => part.startsWith("XSRF-TOKEN="))
|
||||
?.slice(11) ?? "",
|
||||
.split('; ')
|
||||
.find((part) => part.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
const response = await fetch(url, {
|
||||
method: body ? "POST" : "GET",
|
||||
credentials: "same-origin",
|
||||
method: body ? 'POST' : 'GET',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Accept: 'application/json',
|
||||
...(body
|
||||
? {
|
||||
"Content-Type": "application/json",
|
||||
"X-XSRF-TOKEN": xsrf,
|
||||
"Idempotency-Key": key.current!,
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': xsrf,
|
||||
'Idempotency-Key': key.current!,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
@@ -76,8 +76,8 @@ export default function FiscalQaReview({
|
||||
if (!response.ok)
|
||||
throw new ReviewOperationError(
|
||||
response.status === 401 || response.status === 419
|
||||
? "A sessão expirou. Inicie sessão e consulte o histórico antes de voltar a calcular."
|
||||
: "Não foi possível concluir a operação. Reveja as entradas e consulte o histórico antes de tentar novamente.",
|
||||
? 'A sessão expirou. Inicie sessão e consulte o histórico antes de voltar a calcular.'
|
||||
: 'Não foi possível concluir a operação. Reveja as entradas e consulte o histórico antes de tentar novamente.',
|
||||
);
|
||||
return response.json();
|
||||
}
|
||||
@@ -86,15 +86,15 @@ export default function FiscalQaReview({
|
||||
if (gate.current) return;
|
||||
gate.current = true;
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
await work();
|
||||
} catch (cause) {
|
||||
console.error("[fiscal-qa-review]", cause);
|
||||
console.error('[fiscal-qa-review]', cause);
|
||||
setMessage(
|
||||
cause instanceof ReviewOperationError
|
||||
? cause.message
|
||||
: "Não foi possível concluir a ligação ao servidor. Consulte o histórico antes de tentar novamente.",
|
||||
: 'Não foi possível concluir a ligação ao servidor. Consulte o histórico antes de tentar novamente.',
|
||||
);
|
||||
} finally {
|
||||
gate.current = false;
|
||||
@@ -106,7 +106,7 @@ export default function FiscalQaReview({
|
||||
const payload = await request(`/api/v1/simulations/${id}`);
|
||||
if (!isApiSimulationReadResponseV1(payload))
|
||||
throw new ReviewOperationError(
|
||||
"O resultado guardado tem formato incompatível.",
|
||||
'O resultado guardado tem formato incompatível.',
|
||||
);
|
||||
setSelected(payload.data);
|
||||
setReport(null);
|
||||
@@ -123,38 +123,38 @@ export default function FiscalQaReview({
|
||||
base,
|
||||
currency,
|
||||
reference_date: date,
|
||||
operation: "internal_general_net",
|
||||
operation: 'internal_general_net',
|
||||
},
|
||||
);
|
||||
if (!isApiSimulationCreateResponseV1(payload))
|
||||
throw new ReviewOperationError(
|
||||
"A execução devolveu um formato incompatível.",
|
||||
'A execução devolveu um formato incompatível.',
|
||||
);
|
||||
let simulation = await recover(payload.data.id);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 10 &&
|
||||
["queued", "running"].includes(simulation.status);
|
||||
['queued', 'running'].includes(simulation.status);
|
||||
attempt++
|
||||
) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
simulation = await recover(payload.data.id);
|
||||
}
|
||||
setMessage(
|
||||
simulation.status === "completed"
|
||||
? "Execução concluída e gravada no histórico. Pode recuperar esta execução e consultar o relatório guardado."
|
||||
: "A execução foi gravada e continua pendente. Consulte o histórico para a recuperar.",
|
||||
simulation.status === 'completed'
|
||||
? 'Execução concluída e gravada no histórico. Pode recuperar esta execução e consultar o relatório guardado.'
|
||||
: 'A execução foi gravada e continua pendente. Consulte o histórico para a recuperar.',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
const payload = await request(
|
||||
"/api/v1/simulations/history?per_page=10",
|
||||
'/api/v1/simulations/history?per_page=10',
|
||||
);
|
||||
if (!isApiSimulationHistoryResponseV1(payload))
|
||||
throw new ReviewOperationError(
|
||||
"O histórico devolveu um formato incompatível.",
|
||||
'O histórico devolveu um formato incompatível.',
|
||||
);
|
||||
setHistory(payload.data);
|
||||
}
|
||||
@@ -163,7 +163,7 @@ export default function FiscalQaReview({
|
||||
const reference = readVersionedArithmeticReportReference(selected);
|
||||
if (!selected || !reference)
|
||||
throw new ReviewOperationError(
|
||||
"O relatório ainda não está disponível para esta execução.",
|
||||
'O relatório ainda não está disponível para esta execução.',
|
||||
);
|
||||
const payload = (await request(
|
||||
`/api/v1/simulations/${selected.id}/reports/${reference.id}`,
|
||||
@@ -180,7 +180,7 @@ export default function FiscalQaReview({
|
||||
!isApiSimulationResultSnapshotV1(payload.data.report_snapshot)
|
||||
) {
|
||||
throw new ReviewOperationError(
|
||||
"O relatório guardado não corresponde à referência desta execução.",
|
||||
'O relatório guardado não corresponde à referência desta execução.',
|
||||
);
|
||||
}
|
||||
setReport({
|
||||
@@ -190,9 +190,9 @@ export default function FiscalQaReview({
|
||||
});
|
||||
}
|
||||
|
||||
const field = "mt-1 block w-full rounded border border-slate-400 p-2";
|
||||
const field = 'mt-1 block w-full rounded border border-slate-400 p-2';
|
||||
const button =
|
||||
"rounded border border-emerald-800 px-4 py-2 font-semibold disabled:opacity-50";
|
||||
'rounded border border-emerald-800 px-4 py-2 font-semibold disabled:opacity-50';
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl space-y-5 p-6">
|
||||
<Head title="Revisão do lote IVA em QA" />
|
||||
@@ -287,13 +287,13 @@ export default function FiscalQaReview({
|
||||
>
|
||||
<h2 className="font-semibold">Execução seleccionada</h2>
|
||||
<p className="break-all">
|
||||
ID: {selected.id} · estado:{" "}
|
||||
ID: {selected.id} · estado:{' '}
|
||||
{statusLabel(selected.status)}
|
||||
</p>
|
||||
<FiscalQaPreview snapshot={selected.result_snapshot} />
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || selected.status !== "completed"}
|
||||
disabled={busy || selected.status !== 'completed'}
|
||||
onClick={() => void action(loadReport)}
|
||||
>
|
||||
Consultar relatório guardado
|
||||
@@ -313,9 +313,9 @@ export default function FiscalQaReview({
|
||||
{history.map((entry) => (
|
||||
<li
|
||||
key={entry.id}
|
||||
className="break-all rounded border p-3"
|
||||
className="rounded border p-3 break-all"
|
||||
>
|
||||
{entry.id} · {statusLabel(entry.status)}{" "}
|
||||
{entry.id} · {statusLabel(entry.status)}{' '}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
@@ -323,7 +323,7 @@ export default function FiscalQaReview({
|
||||
void action(async () => {
|
||||
await recover(entry.id);
|
||||
setMessage(
|
||||
"Execução recuperada do histórico, sem recalcular.",
|
||||
'Execução recuperada do histórico, sem recalcular.',
|
||||
);
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,7 +233,13 @@ export default function Opportunities({
|
||||
<p>Atualizado: {r.updated_at}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
|
||||
{r.can_promote && <Link href={`/minhas-oportunidades/${r.id}/divulgacao`}>Divulgação promocional</Link>}
|
||||
{r.can_promote && (
|
||||
<Link
|
||||
href={`/minhas-oportunidades/${r.id}/divulgacao`}
|
||||
>
|
||||
Divulgação promocional
|
||||
</Link>
|
||||
)}
|
||||
{r.can_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import {ProactiveInvestmentEditor,newProactive,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import {
|
||||
ProactiveInvestmentEditor,
|
||||
newProactive,
|
||||
type ProactiveAnalysis,
|
||||
type ProactiveOptions,
|
||||
} from '@/components/proactive-investment';
|
||||
import { ClassificationReview } from '@/components/opportunity-classification';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
@@ -42,7 +48,13 @@ export default function OpportunityDraft({
|
||||
}: {
|
||||
record: Entry | null;
|
||||
proactiveOptions?: ProactiveOptions;
|
||||
proactiveHistory?: {version:number;at:string;state:string;problem:string;confirmation:string}[];
|
||||
proactiveHistory?: {
|
||||
version: number;
|
||||
at: string;
|
||||
state: string;
|
||||
problem: string;
|
||||
confirmation: string;
|
||||
}[];
|
||||
values: Values;
|
||||
etag: string | null;
|
||||
readOnly: boolean;
|
||||
@@ -140,11 +152,20 @@ export default function OpportunityDraft({
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const proactiveEntryUrl=usePage().url;
|
||||
const uniquePromoterContext=profileAccess?.contexts.length===1?profileAccess.contexts[0]:undefined;
|
||||
const proactiveEntryUrl = usePage().url;
|
||||
const uniquePromoterContext =
|
||||
profileAccess?.contexts.length === 1
|
||||
? profileAccess.contexts[0]
|
||||
: undefined;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(!record && !values.proactive && new URLSearchParams(proactiveEntryUrl.split('?')[1]??'').get('analysis')==='proactive' ? {proactive:newProactive()} : {}),
|
||||
...(!record &&
|
||||
!values.proactive &&
|
||||
new URLSearchParams(proactiveEntryUrl.split('?')[1] ?? '').get(
|
||||
'analysis',
|
||||
) === 'proactive'
|
||||
? { proactive: newProactive() }
|
||||
: {}),
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
@@ -174,11 +195,18 @@ export default function OpportunityDraft({
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const hasCanonicalPreparation = profileMode && canonicalOptions && Boolean(data.opportunity_category) && !data.proactive;
|
||||
const hasCanonicalPreparation =
|
||||
profileMode &&
|
||||
canonicalOptions &&
|
||||
Boolean(data.opportunity_category) &&
|
||||
!data.proactive;
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore', resourcesGroup?: string) {
|
||||
async function send(
|
||||
action: 'save' | 'delete' | 'archive' | 'restore',
|
||||
resourcesGroup?: string,
|
||||
) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
@@ -226,10 +254,25 @@ export default function OpportunityDraft({
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (resourcesGroup) router.visit(`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`);
|
||||
else if (!record) router.visit(`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`);
|
||||
if (resourcesGroup)
|
||||
router.visit(
|
||||
`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`,
|
||||
);
|
||||
else if (!record)
|
||||
router.visit(
|
||||
`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`,
|
||||
);
|
||||
else if (action !== 'save') router.reload();
|
||||
else if (profileMode) router.reload({only:['canonicalResponse','etag','history','workflowState','profileContext']});
|
||||
else if (profileMode)
|
||||
router.reload({
|
||||
only: [
|
||||
'canonicalResponse',
|
||||
'etag',
|
||||
'history',
|
||||
'workflowState',
|
||||
'profileContext',
|
||||
],
|
||||
});
|
||||
} catch {
|
||||
setMessage(
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
@@ -242,7 +285,10 @@ export default function OpportunityDraft({
|
||||
'[data-association-index][aria-invalid="true"]',
|
||||
);
|
||||
if (invalidAssociation) invalidAssociation.focus();
|
||||
else document.getElementById('opportunity-result')?.focus({preventScroll:true});
|
||||
else
|
||||
document
|
||||
.getElementById('opportunity-result')
|
||||
?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -255,13 +301,42 @@ export default function OpportunityDraft({
|
||||
}
|
||||
>
|
||||
{!profileMode && <Link href={basePath}>Voltar à gestão</Link>}
|
||||
{promotionHref && <Link className="ml-3 underline" href={promotionHref}>Divulgação promocional — Em preparação</Link>}
|
||||
{promotionHref && (
|
||||
<Link className="ml-3 underline" href={promotionHref}>
|
||||
Divulgação promocional — Em preparação
|
||||
</Link>
|
||||
)}
|
||||
{!!profileContext?.corridor_agribusiness && (
|
||||
<section className="my-4 space-y-2 rounded border p-4">
|
||||
<h2 className="font-semibold">Origem e enquadramento da oportunidade</h2>
|
||||
<p>{valueText((profileContext.corridor_agribusiness as Record<string, unknown>).corridor)}</p>
|
||||
<p>Fonte: {valueText((profileContext.corridor_agribusiness as Record<string, unknown>).source)}</p>
|
||||
<p>Em preparação. O corredor indicado na fonte não confirma implantação, promotor, viabilidade ou financiamento. Complete a ficha e reveja a prévia antes de divulgar.</p>
|
||||
<h2 className="font-semibold">
|
||||
Origem e enquadramento da oportunidade
|
||||
</h2>
|
||||
<p>
|
||||
{valueText(
|
||||
(
|
||||
profileContext.corridor_agribusiness as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
).corridor,
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{valueText(
|
||||
(
|
||||
profileContext.corridor_agribusiness as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
).source,
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
Em preparação. O corredor indicado na fonte não confirma
|
||||
implantação, promotor, viabilidade ou financiamento.
|
||||
Complete a ficha e reveja a prévia antes de divulgar.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{record && (
|
||||
@@ -277,7 +352,9 @@ export default function OpportunityDraft({
|
||||
aria-label="Disponibilidade por modalidade"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<summary className="cursor-pointer font-medium">Modalidades disponíveis e condições de submissão</summary>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Modalidades disponíveis e condições de submissão
|
||||
</summary>
|
||||
<p>
|
||||
Seis categorias base: projeto de investimento,
|
||||
imobiliário, fundiário, venda de negócio, parceria e
|
||||
@@ -336,7 +413,8 @@ export default function OpportunityDraft({
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{(profileAccess?.internalPromoter || !uniquePromoterContext) && (
|
||||
{(profileAccess?.internalPromoter ||
|
||||
!uniquePromoterContext) && (
|
||||
<option value="|">
|
||||
Selecionar o promotor real da oportunidade
|
||||
</option>
|
||||
@@ -481,13 +559,132 @@ export default function OpportunityDraft({
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
{profileMode&&Boolean(data.proactive)&&<fieldset disabled={busy||readOnly||unavailable} className="space-y-3 rounded border p-4"><legend>Contexto existente da análise</legend>
|
||||
<Field label="Título da análise"><input aria-label="Título da análise" className={control} value={String((data.canonical as Record<string,unknown>|undefined)?.official_title??data.title??'')} onChange={e=>{const title=e.target.value;setData(d=>({...d,title,...(d.canonical&&Object.prototype.hasOwnProperty.call(d.canonical,'official_title')?{canonical:{...(d.canonical as Record<string,unknown>),official_title:title}}:{})}));}}/></Field>
|
||||
<Field label="Sector da análise"><select aria-label="Sector da análise" className={control} value={String(data.sector_id??'')} onChange={e=>setData(d=>({...d,sector_id:e.target.value,...(d.canonical?{canonical:{...(d.canonical as Record<string,unknown>),sector_id:Number(e.target.value)||null}}:{})}))}><option value="">Por determinar</option>{sectors.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></Field>
|
||||
<p>Seleccione apenas o nível territorial conhecido; não exige coordenadas, montante ou promotor.</p>
|
||||
{(['province_id','district_id','admin_post_id','locality_id']as const).map((key,index)=><TerritoryLevel key={`proactive-${key}-${path[index-1]?.id??''}`} index={index} parent={path[index-1]?.id??''} selected={path[index]} endpoint="/minhas-oportunidades/territory-options" fieldError={errors[key]} onChange={value=>{const next=[...path.slice(0,index),...(value?[value]:[])];setPath(next);setData(d=>({...d,province_id:next[0]?.id??'',district_id:next[1]?.id??'',admin_post_id:next[2]?.id??'',locality_id:next[3]?.id??''}));}}/>)}
|
||||
</fieldset>}
|
||||
<fieldset disabled={busy || readOnly || unavailable}><ProactiveInvestmentEditor value={data.proactive as ProactiveAnalysis|undefined} onChange={v=>setData(d=>({...d,proactive:v}))} options={proactiveOptions} history={proactiveHistory} territoryId={path.at(-1)?.id} recordId={record?.id}/></fieldset>
|
||||
{profileMode && Boolean(data.proactive) && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<legend>Contexto existente da análise</legend>
|
||||
<Field label="Título da análise">
|
||||
<input
|
||||
aria-label="Título da análise"
|
||||
className={control}
|
||||
value={inputText(
|
||||
(
|
||||
data.canonical as
|
||||
| Record<string, unknown>
|
||||
| undefined
|
||||
)?.official_title ??
|
||||
data.title ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) => {
|
||||
const title = e.target.value;
|
||||
setData((d) => ({
|
||||
...d,
|
||||
title,
|
||||
...(d.canonical &&
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
d.canonical,
|
||||
'official_title',
|
||||
)
|
||||
? {
|
||||
canonical: {
|
||||
...(d.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
official_title: title,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector da análise">
|
||||
<select
|
||||
aria-label="Sector da análise"
|
||||
className={control}
|
||||
value={inputText(data.sector_id ?? '')}
|
||||
onChange={(e) =>
|
||||
setData((d) => ({
|
||||
...d,
|
||||
sector_id: e.target.value,
|
||||
...(d.canonical
|
||||
? {
|
||||
canonical: {
|
||||
...(d.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
sector_id:
|
||||
Number(
|
||||
e.target.value,
|
||||
) || null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="">Por determinar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<p>
|
||||
Seleccione apenas o nível territorial conhecido; não
|
||||
exige coordenadas, montante ou promotor.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`proactive-${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint="/minhas-oportunidades/territory-options"
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setPath(next);
|
||||
setData((d) => ({
|
||||
...d,
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<fieldset disabled={busy || readOnly || unavailable}>
|
||||
<ProactiveInvestmentEditor
|
||||
value={data.proactive as ProactiveAnalysis | undefined}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, proactive: v }))
|
||||
}
|
||||
options={proactiveOptions}
|
||||
history={proactiveHistory}
|
||||
territoryId={path.at(-1)?.id}
|
||||
recordId={record?.id}
|
||||
/>
|
||||
</fieldset>
|
||||
{!profileMode && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
@@ -823,18 +1020,20 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
{!hasCanonicalPreparation && <Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>}
|
||||
{!hasCanonicalPreparation && (
|
||||
<Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{!unavailable && !hasCanonicalPreparation && (
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar rascunho
|
||||
@@ -893,110 +1092,153 @@ export default function OpportunityDraft({
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
{record && (!profileMode || readOnly || unavailable || !canonicalOptions || !data.opportunity_category) && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record &&
|
||||
(!profileMode ||
|
||||
readOnly ||
|
||||
unavailable ||
|
||||
!canonicalOptions ||
|
||||
!data.opportunity_category) && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && !profileMode && (
|
||||
<Link href={`${basePath}/${record.id}/context`}>
|
||||
Associações territoriais e produtivas existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && Boolean(data.opportunity_category) && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<details><summary className="cursor-pointer font-medium">Acrescentar um contacto à oportunidade</summary><OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
{profileMode &&
|
||||
canonicalOptions &&
|
||||
Boolean(data.opportunity_category) && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<details>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Acrescentar um contacto à oportunidade
|
||||
</summary>
|
||||
<OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
organization={
|
||||
(data.organization_id ?? null) as
|
||||
| string
|
||||
| null
|
||||
}
|
||||
investors={
|
||||
canonicalOptions.contactInvestors ?? []
|
||||
}
|
||||
disabled={busy || !token}
|
||||
onSaved={(contact) => {
|
||||
setSavedContacts((prior) => [
|
||||
...prior.filter(
|
||||
(row) => row.id !== contact.id,
|
||||
),
|
||||
contact,
|
||||
]);
|
||||
setData((prior) => ({
|
||||
...prior,
|
||||
canonical: {
|
||||
...(prior.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
internal_contact_id: contact.id,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={{
|
||||
...canonicalOptions,
|
||||
contacts: [
|
||||
...canonicalOptions.contacts.filter(
|
||||
(row) =>
|
||||
!savedContacts.some(
|
||||
(saved) => saved.id === row.id,
|
||||
),
|
||||
),
|
||||
...savedContacts,
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
missingPaths={
|
||||
canonicalResponse?.completion.missing_paths
|
||||
}
|
||||
category={valueText(
|
||||
data.opportunity_category ?? '',
|
||||
)}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
investors={canonicalOptions.contactInvestors ?? []}
|
||||
disabled={busy || !token}
|
||||
onSaved={(contact) => {
|
||||
setSavedContacts((prior) => [
|
||||
...prior.filter(
|
||||
(row) => row.id !== contact.id,
|
||||
),
|
||||
contact,
|
||||
]);
|
||||
setData((prior) => ({
|
||||
...prior,
|
||||
canonical: {
|
||||
...(prior.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
internal_contact_id: contact.id,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/></details>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<string, unknown>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={{
|
||||
...canonicalOptions,
|
||||
contacts: [
|
||||
...canonicalOptions.contacts.filter(
|
||||
(row) =>
|
||||
!savedContacts.some(
|
||||
(saved) => saved.id === row.id,
|
||||
),
|
||||
),
|
||||
...savedContacts,
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
missingPaths={canonicalResponse?.completion.missing_paths}
|
||||
category={valueText(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onOpenResources={!readOnly && !unavailable && resourcesInstalled ? (group) => void send('save',group) : undefined}
|
||||
/>
|
||||
{!readOnly && !unavailable && hasCanonicalPreparation && (
|
||||
<div className="sticky bottom-0 space-y-3 rounded border bg-background p-4 shadow-sm">
|
||||
<Field label="O que alterou nesta preparação" error={errors.reason}>
|
||||
<textarea className={control} value={reason} onChange={(event) => setReason(event.target.value)} minLength={20} maxLength={1000} />
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar preparação
|
||||
</button>
|
||||
<p className="text-sm">Pode guardar incompleto e continuar mais tarde em Minhas oportunidades.</p>
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onOpenResources={
|
||||
!readOnly && !unavailable && resourcesInstalled
|
||||
? (group) => void send('save', group)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{!readOnly &&
|
||||
!unavailable &&
|
||||
hasCanonicalPreparation && (
|
||||
<div className="bg-background sticky bottom-0 space-y-3 rounded border p-4 shadow-sm">
|
||||
<Field
|
||||
label="O que alterou nesta preparação"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(event) =>
|
||||
setReason(event.target.value)
|
||||
}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar preparação
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Pode guardar incompleto e continuar mais
|
||||
tarde em Minhas oportunidades.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && profileActions.includes('publish') && (
|
||||
<section className="rounded border p-3">
|
||||
<h2>Pré-visualização da publicação</h2>
|
||||
|
||||
@@ -124,7 +124,9 @@ export default function Install({
|
||||
: 'Aplicar plano de gestão'}
|
||||
</button>
|
||||
{extension && !operationKey && (
|
||||
<p role="alert">Atualize a prévia para obter a chave desta operação.</p>
|
||||
<p role="alert">
|
||||
Atualize a prévia para obter a chave desta operação.
|
||||
</p>
|
||||
)}
|
||||
{!ready && (
|
||||
<p>
|
||||
|
||||
@@ -1,81 +1,476 @@
|
||||
import {ProactivePublicationFields,ProactiveSummary,newPublicProactive,type ProactivePublic,type ProactiveEvidence,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import {
|
||||
ProactivePublicationFields,
|
||||
ProactiveSummary,
|
||||
newPublicProactive,
|
||||
type ProactivePublic,
|
||||
type ProactiveEvidence,
|
||||
type ProactiveOptions,
|
||||
} from '@/components/proactive-investment';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { Management, Field, control, button } from './shared';
|
||||
|
||||
type Draft = {proactive_public?:ProactivePublic;proactive_reviewed?:boolean;title: string; summary: string; description: string; limitations: string; source_reference: string; edition: string; source_date: string; sector_id: number | null; territory_ids: string[]};
|
||||
type Projection = {title: string; summary: string; description: string; sector_id: number | null; maturity_label: string; territories: {id: string; label: string}[];proactive?:ProactivePublic};
|
||||
type Preview = {token: string; action: 'disclose' | 'withdraw'; projection: Projection; current: {title: string; summary: string; description: string; status: string}};
|
||||
type Draft = {
|
||||
proactive_public?: ProactivePublic;
|
||||
proactive_reviewed?: boolean;
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
limitations: string;
|
||||
source_reference: string;
|
||||
edition: string;
|
||||
source_date: string;
|
||||
sector_id: number | null;
|
||||
territory_ids: string[];
|
||||
};
|
||||
type Projection = {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
sector_id: number | null;
|
||||
maturity_label: string;
|
||||
territories: { id: string; label: string }[];
|
||||
proactive?: ProactivePublic;
|
||||
};
|
||||
type Preview = {
|
||||
token: string;
|
||||
action: 'disclose' | 'withdraw';
|
||||
projection: Projection;
|
||||
current: {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
status: string;
|
||||
};
|
||||
};
|
||||
|
||||
export default function OpportunityPromotion({proactiveEnabled=false,proactiveKind,proactiveRelations=[],proactiveEvidence=[],proactiveOptions,record, initial, etag, publicNow, reauthenticationRequired, sectors, territories, history}: {
|
||||
proactiveRelations?:{id:string;label:string;relationship:string}[];proactiveEnabled?:boolean;proactiveKind?:string;proactiveEvidence?:ProactiveEvidence[];proactiveOptions?:ProactiveOptions;
|
||||
record: {id: number; reference: string}; initial: Draft; etag: string; publicNow: boolean; reauthenticationRequired: boolean;
|
||||
sectors: {id: number; name: string}[]; territories: {id: string; name: string; location_type: string}[];
|
||||
history: {id: string; action: string; actor_user_id: number; occurred_at: string}[];
|
||||
export default function OpportunityPromotion({
|
||||
proactiveEnabled = false,
|
||||
proactiveKind,
|
||||
proactiveRelations = [],
|
||||
proactiveEvidence = [],
|
||||
proactiveOptions,
|
||||
record,
|
||||
initial,
|
||||
etag,
|
||||
publicNow,
|
||||
reauthenticationRequired,
|
||||
sectors,
|
||||
territories,
|
||||
history,
|
||||
}: {
|
||||
proactiveRelations?: { id: string; label: string; relationship: string }[];
|
||||
proactiveEnabled?: boolean;
|
||||
proactiveKind?: string;
|
||||
proactiveEvidence?: ProactiveEvidence[];
|
||||
proactiveOptions?: ProactiveOptions;
|
||||
record: { id: number; reference: string };
|
||||
initial: Draft;
|
||||
etag: string;
|
||||
publicNow: boolean;
|
||||
reauthenticationRequired: boolean;
|
||||
sectors: { id: number; name: string }[];
|
||||
territories: { id: string; name: string; location_type: string }[];
|
||||
history: {
|
||||
id: string;
|
||||
action: string;
|
||||
actor_user_id: number;
|
||||
occurred_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Draft>({...initial, source_date: initial.source_date ?? '',...(proactiveEnabled?{proactive_public:initial.proactive_public??{...newPublicProactive(),group:proactiveKind??'ideas'},proactive_reviewed:false}:{})});
|
||||
const [draft, setDraft] = useState<Draft>({
|
||||
...initial,
|
||||
source_date: initial.source_date ?? '',
|
||||
...(proactiveEnabled
|
||||
? {
|
||||
proactive_public: initial.proactive_public ?? {
|
||||
...newPublicProactive(),
|
||||
group: proactiveKind ?? 'ideas',
|
||||
},
|
||||
proactive_reviewed: false,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [operationKey, setOperationKey] = useState(createOperationKey);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string,string>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [needsMfa, setNeedsMfa] = useState(reauthenticationRequired);
|
||||
function change<K extends keyof Draft>(key: K, value: Draft[K]) { setDraft(current => ({...current, [key]:value})); setPreview(null); setConfirmed(false); }
|
||||
function report(error: unknown) {setMessage(error instanceof Error ? error.message : 'Não foi possível concluir. A ficha anterior foi preservada.'); setErrors(error instanceof ProfileValidationError ? error.fields : {}); if(error instanceof ProfileValidationError && error.reauthenticate)setNeedsMfa(true);}
|
||||
function renewAuthentication() { router.post('/logout', {}, {onSuccess:()=>router.visit(`/minhas-oportunidades/${record.id}/divulgacao`)}); }
|
||||
function change<K extends keyof Draft>(key: K, value: Draft[K]) {
|
||||
setDraft((current) => ({ ...current, [key]: value }));
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
}
|
||||
function report(error: unknown) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível concluir. A ficha anterior foi preservada.',
|
||||
);
|
||||
setErrors(error instanceof ProfileValidationError ? error.fields : {});
|
||||
if (error instanceof ProfileValidationError && error.reauthenticate)
|
||||
setNeedsMfa(true);
|
||||
}
|
||||
function renewAuthentication() {
|
||||
router.post(
|
||||
'/logout',
|
||||
{},
|
||||
{
|
||||
onSuccess: () =>
|
||||
router.visit(
|
||||
`/minhas-oportunidades/${record.id}/divulgacao`,
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
async function prepare(action: 'disclose' | 'withdraw') {
|
||||
setBusy(true); setMessage(''); setErrors({}); setPreview(null); setConfirmed(false);
|
||||
try { const result = await profileJson(`/minhas-oportunidades/${record.id}/divulgacao/previa`, {...draft, etag, action}); setPreview(result); setOperationKey(createOperationKey()); }
|
||||
catch (error) { report(error); } finally { setBusy(false); }
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
setErrors({});
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${record.id}/divulgacao/previa`,
|
||||
{ ...draft, etag, action },
|
||||
);
|
||||
setPreview(result);
|
||||
setOperationKey(createOperationKey());
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function publish() {
|
||||
if (!preview || !confirmed) return;
|
||||
setBusy(true); setErrors({});
|
||||
try {const result = await profileJson(`/minhas-oportunidades/${record.id}/divulgacao/confirmar`, {token:preview.token, operation_key:operationKey, reason, confirm:confirmed});
|
||||
setMessage(result.message); setPreview(null); setConfirmed(false); router.reload();
|
||||
} catch (error) { report(error); } finally {setBusy(false);}
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${record.id}/divulgacao/confirmar`,
|
||||
{
|
||||
token: preview.token,
|
||||
operation_key: operationKey,
|
||||
reason,
|
||||
confirm: confirmed,
|
||||
},
|
||||
);
|
||||
setMessage(result.message);
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
const labels: Record<string,string> = {promotional_summary_published:'Resumo divulgado', promotional_summary_updated:'Resumo actualizado', promotional_summary_withdrawn:'Resumo retirado'};
|
||||
return <Management title={`Divulgação promocional — ${record.reference}`}>
|
||||
<Link className="underline" href={`/minhas-oportunidades/${record.id}/view`}>Voltar à oportunidade</Link>
|
||||
<p>Prepare o resumo público e reveja a prévia antes de confirmar. A divulgação fica identificada como <strong>Em preparação</strong> e não autoriza a execução do investimento. Documentos e contactos do cadastro continuam privados.</p>
|
||||
<p role="status">{publicNow ? 'Resumo actualmente divulgado.' : 'Resumo não divulgado.'} {message}</p>
|
||||
{needsMfa && <p role="alert">Entre novamente com a sua conta e MFA para confirmar esta operação. O cadastro guardado permanece disponível; a prévia ainda não confirmada terá de ser preparada novamente. <button className="underline" onClick={renewAuthentication}>Renovar entrada com MFA</button></p>}
|
||||
{Object.entries(errors).map(([key,value]) => <p role="alert" key={key}>{key}: {value}</p>)}
|
||||
<form className="space-y-4 rounded border p-5" onSubmit={e=>{e.preventDefault(); void prepare('disclose');}}>
|
||||
{proactiveEnabled&&draft.proactive_public&&<ProactivePublicationFields value={draft.proactive_public} onChange={v=>{change('proactive_public',v);change('proactive_reviewed',false);}} evidence={proactiveEvidence} relations={proactiveRelations} options={proactiveOptions} reviewed={Boolean(draft.proactive_reviewed)} onReview={v=>change('proactive_reviewed',v)}/>}
|
||||
<Field label="Título público"><input required className={control} maxLength={255} value={draft.title} onChange={e=>change('title',e.target.value)}/></Field>
|
||||
<Field label="Resumo público"><textarea required className={control} maxLength={499} value={draft.summary} onChange={e=>change('summary',e.target.value)}/></Field>
|
||||
<Field label="Descrição pública"><textarea className={control} maxLength={6000} value={draft.description} onChange={e=>change('description',e.target.value)}/></Field>
|
||||
<Field label="Limitações e lacunas conhecidas"><textarea className={control} value={draft.limitations} onChange={e=>change('limitations',e.target.value)}/></Field>
|
||||
<Field label="Fonte do resumo"><textarea className={control} value={draft.source_reference} onChange={e=>change('source_reference',e.target.value)}/></Field>
|
||||
<Field label="Edição"><input className={control} value={draft.edition} onChange={e=>change('edition',e.target.value)}/></Field>
|
||||
<Field label="Data-base"><input className={control} type="date" value={draft.source_date} onChange={e=>change('source_date',e.target.value)}/></Field>
|
||||
<Field label="Sector divulgado"><select className={control} value={draft.sector_id ?? ''} onChange={e=>change('sector_id',e.target.value ? Number(e.target.value):null)}><option value="">Por indicar</option>{sectors.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></Field>
|
||||
<Field label="Acrescentar abrangência territorial documentada"><select className={control} value="" onChange={e=>{if(e.target.value && !draft.territory_ids.includes(e.target.value))change('territory_ids',[...draft.territory_ids,e.target.value]);}}><option value="">Seleccionar território existente</option>{territories.map(t=><option key={t.id} value={t.id}>{t.name} · {t.location_type}</option>)}</select></Field>
|
||||
<p>Seleccione apenas a abrangência que pretende divulgar e cuja origem está identificada. Abrangência não comprova implantação ou disponibilidade de terreno. Sem selecção, a localização fica por indicar.</p>
|
||||
<ul>{draft.territory_ids.map(id=><li key={id}>{territories.find(t=>t.id===id)?.name ?? 'Referência anterior indisponível'} <button type="button" className="underline" onClick={()=>change('territory_ids',draft.territory_ids.filter(t=>t!==id))}>Remover abrangência</button></li>)}</ul>
|
||||
<button className={button} disabled={busy || needsMfa}>{publicNow ? 'Rever actualização do resumo' : 'Preparar prévia de divulgação'}</button>
|
||||
{publicNow && <button type="button" className={`${button} ml-3`} disabled={busy || needsMfa} onClick={()=>void prepare('withdraw')}>Preparar retirada do resumo</button>}
|
||||
</form>
|
||||
{preview && <section className="space-y-4 rounded border p-5" aria-label="Prévia da divulgação">
|
||||
<h2 className="text-xl font-semibold">{preview.action === 'withdraw' ? 'Rever retirada do catálogo' : 'Prévia do conteúdo público'}</h2>
|
||||
<p><strong>{preview.projection.maturity_label}</strong></p>
|
||||
<ProactiveSummary value={preview.projection.proactive}/>
|
||||
<h3>{preview.projection.title}</h3><p>{preview.projection.summary}</p><p className="whitespace-pre-wrap">{preview.projection.description}</p>
|
||||
<p>Sector: {sectors.find(s=>s.id===preview.projection.sector_id)?.name ?? 'Por indicar'}</p>
|
||||
<ul>{preview.projection.territories.map(t=><li key={t.id}>{t.label}</li>)}</ul>
|
||||
{!preview.projection.territories.length && <p>Abrangência territorial por indicar.</p>}
|
||||
<p>Esta prévia ainda não alterou o portal público. {preview.action === 'withdraw' ? 'A confirmação retira o resumo da consulta pública e preserva o cadastro.' : 'Só este texto e o enquadramento apresentado serão divulgados; os anexos e contactos não são incluídos.'}</p>
|
||||
<Field label="Motivo da divulgação, alteração ou retirada"><textarea required className={control} minLength={10} maxLength={1000} value={reason} onChange={e=>setReason(e.target.value)}/></Field>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/> Confirmo o conteúdo público desta prévia e a operação indicada.</label>
|
||||
<button className={button} disabled={busy || !confirmed || reason.trim().length<10} onClick={()=>void publish()}>{preview.action === 'withdraw' ? 'Confirmar retirada do resumo' : 'Confirmar divulgação do resumo'}</button>
|
||||
<button className="ml-3 underline" disabled={busy} onClick={()=>{setPreview(null);setConfirmed(false);}}>Cancelar prévia</button>
|
||||
</section>}
|
||||
<section aria-label="Histórico da divulgação"><h2 className="text-xl font-semibold">Histórico da divulgação</h2><ul>{history.map(h=><li key={h.id}>{labels[h.action] ?? h.action} · {h.occurred_at} · responsável {h.actor_user_id}</li>)}</ul></section>
|
||||
</Management>;
|
||||
const labels: Record<string, string> = {
|
||||
promotional_summary_published: 'Resumo divulgado',
|
||||
promotional_summary_updated: 'Resumo actualizado',
|
||||
promotional_summary_withdrawn: 'Resumo retirado',
|
||||
};
|
||||
return (
|
||||
<Management title={`Divulgação promocional — ${record.reference}`}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/minhas-oportunidades/${record.id}/view`}
|
||||
>
|
||||
Voltar à oportunidade
|
||||
</Link>
|
||||
<p>
|
||||
Prepare o resumo público e reveja a prévia antes de confirmar. A
|
||||
divulgação fica identificada como <strong>Em preparação</strong>{' '}
|
||||
e não autoriza a execução do investimento. Documentos e
|
||||
contactos do cadastro continuam privados.
|
||||
</p>
|
||||
<p role="status">
|
||||
{publicNow
|
||||
? 'Resumo actualmente divulgado.'
|
||||
: 'Resumo não divulgado.'}{' '}
|
||||
{message}
|
||||
</p>
|
||||
{needsMfa && (
|
||||
<p role="alert">
|
||||
Entre novamente com a sua conta e MFA para confirmar esta
|
||||
operação. O cadastro guardado permanece disponível; a prévia
|
||||
ainda não confirmada terá de ser preparada novamente.{' '}
|
||||
<button className="underline" onClick={renewAuthentication}>
|
||||
Renovar entrada com MFA
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(errors).map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{key}: {value}
|
||||
</p>
|
||||
))}
|
||||
<form
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void prepare('disclose');
|
||||
}}
|
||||
>
|
||||
{proactiveEnabled && draft.proactive_public && (
|
||||
<ProactivePublicationFields
|
||||
value={draft.proactive_public}
|
||||
onChange={(v) => {
|
||||
change('proactive_public', v);
|
||||
change('proactive_reviewed', false);
|
||||
}}
|
||||
evidence={proactiveEvidence}
|
||||
relations={proactiveRelations}
|
||||
options={proactiveOptions}
|
||||
reviewed={Boolean(draft.proactive_reviewed)}
|
||||
onReview={(v) => change('proactive_reviewed', v)}
|
||||
/>
|
||||
)}
|
||||
<Field label="Título público">
|
||||
<input
|
||||
required
|
||||
className={control}
|
||||
maxLength={255}
|
||||
value={draft.title}
|
||||
onChange={(e) => change('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Resumo público">
|
||||
<textarea
|
||||
required
|
||||
className={control}
|
||||
maxLength={499}
|
||||
value={draft.summary}
|
||||
onChange={(e) => change('summary', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Descrição pública">
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={6000}
|
||||
value={draft.description}
|
||||
onChange={(e) => change('description', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Limitações e lacunas conhecidas">
|
||||
<textarea
|
||||
className={control}
|
||||
value={draft.limitations}
|
||||
onChange={(e) => change('limitations', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Fonte do resumo">
|
||||
<textarea
|
||||
className={control}
|
||||
value={draft.source_reference}
|
||||
onChange={(e) =>
|
||||
change('source_reference', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Edição">
|
||||
<input
|
||||
className={control}
|
||||
value={draft.edition}
|
||||
onChange={(e) => change('edition', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Data-base">
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
value={draft.source_date}
|
||||
onChange={(e) => change('source_date', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector divulgado">
|
||||
<select
|
||||
className={control}
|
||||
value={draft.sector_id ?? ''}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'sector_id',
|
||||
e.target.value ? Number(e.target.value) : null,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Acrescentar abrangência territorial documentada">
|
||||
<select
|
||||
className={control}
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.value &&
|
||||
!draft.territory_ids.includes(e.target.value)
|
||||
)
|
||||
change('territory_ids', [
|
||||
...draft.territory_ids,
|
||||
e.target.value,
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Seleccionar território existente
|
||||
</option>
|
||||
{territories.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.name} · {t.location_type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<p>
|
||||
Seleccione apenas a abrangência que pretende divulgar e cuja
|
||||
origem está identificada. Abrangência não comprova
|
||||
implantação ou disponibilidade de terreno. Sem selecção, a
|
||||
localização fica por indicar.
|
||||
</p>
|
||||
<ul>
|
||||
{draft.territory_ids.map((id) => (
|
||||
<li key={id}>
|
||||
{territories.find((t) => t.id === id)?.name ??
|
||||
'Referência anterior indisponível'}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
change(
|
||||
'territory_ids',
|
||||
draft.territory_ids.filter(
|
||||
(t) => t !== id,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Remover abrangência
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button className={button} disabled={busy || needsMfa}>
|
||||
{publicNow
|
||||
? 'Rever actualização do resumo'
|
||||
: 'Preparar prévia de divulgação'}
|
||||
</button>
|
||||
{publicNow && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${button} ml-3`}
|
||||
disabled={busy || needsMfa}
|
||||
onClick={() => void prepare('withdraw')}
|
||||
>
|
||||
Preparar retirada do resumo
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
{preview && (
|
||||
<section
|
||||
className="space-y-4 rounded border p-5"
|
||||
aria-label="Prévia da divulgação"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{preview.action === 'withdraw'
|
||||
? 'Rever retirada do catálogo'
|
||||
: 'Prévia do conteúdo público'}
|
||||
</h2>
|
||||
<p>
|
||||
<strong>{preview.projection.maturity_label}</strong>
|
||||
</p>
|
||||
<ProactiveSummary value={preview.projection.proactive} />
|
||||
<h3>{preview.projection.title}</h3>
|
||||
<p>{preview.projection.summary}</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{preview.projection.description}
|
||||
</p>
|
||||
<p>
|
||||
Sector:{' '}
|
||||
{sectors.find(
|
||||
(s) => s.id === preview.projection.sector_id,
|
||||
)?.name ?? 'Por indicar'}
|
||||
</p>
|
||||
<ul>
|
||||
{preview.projection.territories.map((t) => (
|
||||
<li key={t.id}>{t.label}</li>
|
||||
))}
|
||||
</ul>
|
||||
{!preview.projection.territories.length && (
|
||||
<p>Abrangência territorial por indicar.</p>
|
||||
)}
|
||||
<p>
|
||||
Esta prévia ainda não alterou o portal público.{' '}
|
||||
{preview.action === 'withdraw'
|
||||
? 'A confirmação retira o resumo da consulta pública e preserva o cadastro.'
|
||||
: 'Só este texto e o enquadramento apresentado serão divulgados; os anexos e contactos não são incluídos.'}
|
||||
</p>
|
||||
<Field label="Motivo da divulgação, alteração ou retirada">
|
||||
<textarea
|
||||
required
|
||||
className={control}
|
||||
minLength={10}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo o conteúdo público desta prévia e a operação
|
||||
indicada.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy || !confirmed || reason.trim().length < 10
|
||||
}
|
||||
onClick={() => void publish()}
|
||||
>
|
||||
{preview.action === 'withdraw'
|
||||
? 'Confirmar retirada do resumo'
|
||||
: 'Confirmar divulgação do resumo'}
|
||||
</button>
|
||||
<button
|
||||
className="ml-3 underline"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
}}
|
||||
>
|
||||
Cancelar prévia
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section aria-label="Histórico da divulgação">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Histórico da divulgação
|
||||
</h2>
|
||||
<ul>
|
||||
{history.map((h) => (
|
||||
<li key={h.id}>
|
||||
{labels[h.action] ?? h.action} · {h.occurred_at} ·
|
||||
responsável {h.actor_user_id}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -179,8 +179,12 @@ export default function OpportunityResources({
|
||||
readOnly?: boolean;
|
||||
countries?: { code: string; name: string }[];
|
||||
}>().props;
|
||||
const returnGroup = new URLSearchParams(usePage().url.split('?')[1] ?? '').get('return_group');
|
||||
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '') ? `#fill-${returnGroup}` : '#fill-evidence';
|
||||
const returnGroup = new URLSearchParams(
|
||||
usePage().url.split('?')[1] ?? '',
|
||||
).get('return_group');
|
||||
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '')
|
||||
? `#fill-${returnGroup}`
|
||||
: '#fill-evidence';
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
|
||||
|
||||
@@ -15,7 +15,9 @@ export default function TerritoryAssociations() {
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true); setError(''); setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setRows([]);
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
@@ -41,10 +43,10 @@ export default function TerritoryAssociations() {
|
||||
setError('');
|
||||
} catch {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
'Não foi possível concluir a pesquisa.',
|
||||
);
|
||||
} finally { if (!controller.signal.aborted) setLoading(false); }
|
||||
setError('Não foi possível concluir a pesquisa.');
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
}, 250);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
@@ -76,7 +78,12 @@ export default function TerritoryAssociations() {
|
||||
<option value="opportunities">Oportunidades</option>
|
||||
</select>
|
||||
</Field>
|
||||
<SearchState loading={loading} error={error} total={rows.length} retry={() => setRetry(value => value + 1)} />
|
||||
<SearchState
|
||||
loading={loading}
|
||||
error={error}
|
||||
total={rows.length}
|
||||
retry={() => setRetry((value) => value + 1)}
|
||||
/>
|
||||
<Field label="Pesquisar investimento">
|
||||
<input
|
||||
className={control}
|
||||
|
||||
@@ -479,7 +479,7 @@ export default function Detail(p: Props) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
return (
|
||||
<Frame title={p.record.title || 'Pré-visualização da ideia'}>
|
||||
<ComplementEntryActions target={'partnership:'+p.record.id}/>
|
||||
<ComplementEntryActions target={'partnership:' + p.record.id} />
|
||||
<div className="space-y-6">
|
||||
<p>
|
||||
{p.record.partnership_type
|
||||
|
||||
@@ -196,7 +196,8 @@ function RoomPage(p: Props) {
|
||||
onSuccess: () => {
|
||||
message.setData({
|
||||
body: '',
|
||||
client_key: createOperationKey(),
|
||||
client_key:
|
||||
createOperationKey(),
|
||||
});
|
||||
},
|
||||
},
|
||||
@@ -242,11 +243,16 @@ 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>
|
||||
)}
|
||||
{!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>
|
||||
@@ -256,22 +262,23 @@ function RoomPage(p: Props) {
|
||||
: 'Privado do autor'}{' '}
|
||||
· Análise: {d.malware_scan_status}
|
||||
</p>
|
||||
{d.owner_id === auth.user.id && (mutable || d.shared) && (
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/parcerias/salas/${p.room.id}/documentos/${d.id}/partilha`,
|
||||
{ shared: !d.shared },
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
{d.shared
|
||||
? 'Retirar autorização de partilha'
|
||||
: 'Autorizar partilha com a contraparte'}
|
||||
</button>
|
||||
)}
|
||||
{d.owner_id === auth.user.id &&
|
||||
(mutable || d.shared) && (
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/parcerias/salas/${p.room.id}/documentos/${d.id}/partilha`,
|
||||
{ shared: !d.shared },
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
{d.shared
|
||||
? 'Retirar autorização de partilha'
|
||||
: 'Autorizar partilha com a contraparte'}
|
||||
</button>
|
||||
)}
|
||||
{d.status === 'active' &&
|
||||
d.malware_scan_status === 'clean' && (
|
||||
<a
|
||||
|
||||
@@ -79,12 +79,10 @@ export default function ArticleEditor({
|
||||
body: JSON.stringify(form.data),
|
||||
},
|
||||
);
|
||||
const data = await response
|
||||
.json()
|
||||
.catch(() => ({
|
||||
message:
|
||||
'Não foi possível abrir a prévia. Recupere o editor e confirme a sessão e o MFA existentes.',
|
||||
}));
|
||||
const data = await response.json().catch(() => ({
|
||||
message:
|
||||
'Não foi possível abrir a prévia. Recupere o editor e confirme a sessão e o MFA existentes.',
|
||||
}));
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(data.errors ?? {})
|
||||
|
||||
@@ -1,100 +1,462 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { fiscalForms, fiscalFormFields, fiscalPreparationIssues, newFiscalPreparation, readFiscalPreparation, type FiscalFormKind, type FiscalPreparation } from '@/lib/fiscal-form-preparation';
|
||||
import {
|
||||
fiscalForms,
|
||||
fiscalFormFields,
|
||||
fiscalPreparationIssues,
|
||||
newFiscalPreparation,
|
||||
readFiscalPreparation,
|
||||
type FiscalFormKind,
|
||||
type FiscalPreparation,
|
||||
} from '@/lib/fiscal-form-preparation';
|
||||
|
||||
const input = 'mt-1 block w-full rounded border border-slate-400 bg-white p-3 text-slate-900';
|
||||
const button = 'rounded border border-emerald-800 px-4 py-3 font-semibold text-emerald-900 disabled:opacity-50';
|
||||
export default function FiscalForms({ initialTax = 'iva' }: { initialTax?: FiscalFormKind }) {
|
||||
const input =
|
||||
'mt-1 block w-full rounded border border-slate-400 bg-white p-3 text-slate-900';
|
||||
const button =
|
||||
'rounded border border-emerald-800 px-4 py-3 font-semibold text-emerald-900 disabled:opacity-50';
|
||||
export default function FiscalForms({
|
||||
initialTax = 'iva',
|
||||
}: {
|
||||
initialTax?: FiscalFormKind;
|
||||
}) {
|
||||
const [kind, setKind] = useState<FiscalFormKind>(initialTax);
|
||||
const [drafts, setDrafts] = useState({ iva: newFiscalPreparation('iva'), irpc: newFiscalPreparation('irpc') });
|
||||
const [drafts, setDrafts] = useState({
|
||||
iva: newFiscalPreparation('iva'),
|
||||
irpc: newFiscalPreparation('irpc'),
|
||||
});
|
||||
const [step, setStep] = useState(0);
|
||||
const [notice, setNotice] = useState('');
|
||||
const [pending, setPending] = useState<FiscalPreparation | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const p = drafts[kind], source = fiscalForms[kind], fields = fiscalFormFields(kind);
|
||||
const p = drafts[kind],
|
||||
source = fiscalForms[kind],
|
||||
fields = fiscalFormFields(kind);
|
||||
const issues = fiscalPreparationIssues(p);
|
||||
useEffect(() => {
|
||||
setKind(initialTax);
|
||||
}, [initialTax]);
|
||||
useEffect(() => {
|
||||
const warn = (e: BeforeUnloadEvent) => { if (dirty) { e.preventDefault(); e.returnValue = ''; } };
|
||||
const warn = (e: BeforeUnloadEvent) => {
|
||||
if (dirty) {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', warn);
|
||||
const unsubscribe = router.on('before', e => {
|
||||
if (dirty && !window.confirm('Os campos estão apenas nesta página. Guarde o ficheiro para continuar depois. Pretende sair?')) e.preventDefault();
|
||||
const unsubscribe = router.on('before', (e) => {
|
||||
if (
|
||||
dirty &&
|
||||
!window.confirm(
|
||||
'Os campos estão apenas nesta página. Guarde o ficheiro para continuar depois. Pretende sair?',
|
||||
)
|
||||
)
|
||||
e.preventDefault();
|
||||
});
|
||||
return () => { window.removeEventListener('beforeunload', warn); unsubscribe(); };
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', warn);
|
||||
unsubscribe();
|
||||
};
|
||||
}, [dirty]);
|
||||
function patch(update: Partial<FiscalPreparation>) {
|
||||
setDrafts(d => ({ ...d, [kind]: { ...d[kind], ...update } }));
|
||||
setDirty(true); setNotice('');
|
||||
setDrafts((d) => ({ ...d, [kind]: { ...d[kind], ...update } }));
|
||||
setDirty(true);
|
||||
setNotice('');
|
||||
}
|
||||
function download() {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(p)], { type: 'application/json' }));
|
||||
const a = document.createElement('a'); a.href = url; a.download = `investmoz-preparacao-${kind}.json`; a.click();
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([JSON.stringify(p)], { type: 'application/json' }),
|
||||
);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `investmoz-preparacao-${kind}.json`;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
setNotice('Ficheiro de preparação gerado. Guarde-o para recuperar os campos. Não foi enviado ao portal nem à AT.');
|
||||
setNotice(
|
||||
'Ficheiro de preparação gerado. Guarde-o para recuperar os campos. Não foi enviado ao portal nem à AT.',
|
||||
);
|
||||
// Other tax preparation may still contain unsaved edits.
|
||||
}
|
||||
return <div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title="Preencher formulário fiscal" />
|
||||
<div className="print:hidden"><PortalMenu /></div>
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-5 py-8">
|
||||
<div className="print:hidden"><Link href="/documentos" className="underline">Documentos e Formulários</Link></div>
|
||||
<h1 className="text-3xl font-bold">Preencher formulário fiscal</h1>
|
||||
<p>Prepare os valores de IVA ou IRPC, confira e guarde um ficheiro para continuar depois. Os campos vazios significam informação em falta.</p>
|
||||
<p className="rounded border border-amber-600 bg-amber-50 p-3">Preparação para conferência, sem submissão à Autoridade Tributária. Os valores são introduzidos por si; não há apuramento automático nem confirmação de elegibilidade de deduções.</p>
|
||||
<label className="block max-w-lg print:hidden">Formulário
|
||||
<select className={input} value={kind} onChange={e => { setKind(e.target.value as FiscalFormKind); setStep(0); setNotice(''); setPending(null); }}>
|
||||
<option value="iva">IVA — Modelo A</option><option value="irpc">IRPC — Modelo 22</option>
|
||||
</select>
|
||||
</label>
|
||||
<h2 className="text-xl font-bold">{source.title}</h2>
|
||||
<p>{source.coverage}</p>
|
||||
<nav aria-label="Etapas de preenchimento" className="flex flex-wrap gap-2 print:hidden">
|
||||
{['Identificação e período', 'Preencher valores', 'Conferir e guardar'].map((label, n) => <button type="button" key={label} className={button} aria-current={step === n ? 'step' : undefined} onClick={() => setStep(n)}>{n + 1}. {label}</button>)}
|
||||
</nav>
|
||||
<form onSubmit={e => e.preventDefault()} className="space-y-5">
|
||||
<fieldset className={`${step !== 0 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}>
|
||||
<legend className="font-bold">Identificação e período</legend>
|
||||
<label className="block">Nome ou designação social<input className={input} autoComplete="organization" maxLength={5000} value={p.name} onChange={e => patch({ name: e.target.value })} /></label>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<label>NUIT<input className={input} inputMode="numeric" maxLength={9} value={p.nuit} onChange={e => patch({ nuit: e.target.value })} /></label>
|
||||
<label>{kind === 'iva' ? 'Período — ano e mês' : 'Exercício — ano'}<input className={input} type={kind === 'iva' ? 'month' : 'text'} inputMode={kind === 'irpc' ? 'numeric' : undefined} placeholder={kind === 'iva' ? 'AAAA-MM' : 'AAAA'} maxLength={7} value={p.period} onChange={e => patch({ period: e.target.value })} /></label>
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title="Preencher formulário fiscal" />
|
||||
<div className="print:hidden">
|
||||
<PortalMenu />
|
||||
</div>
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-5 py-8">
|
||||
<div className="print:hidden">
|
||||
<Link href="/documentos" className="underline">
|
||||
Documentos e Formulários
|
||||
</Link>
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold">
|
||||
Preencher formulário fiscal
|
||||
</h1>
|
||||
<p>
|
||||
Prepare os valores de IVA ou IRPC, confira e guarde um
|
||||
ficheiro para continuar depois. Os campos vazios significam
|
||||
informação em falta.
|
||||
</p>
|
||||
<p className="rounded border border-amber-600 bg-amber-50 p-3">
|
||||
Preparação para conferência, sem submissão à Autoridade
|
||||
Tributária. Os valores são introduzidos por si; não há
|
||||
apuramento automático nem confirmação de elegibilidade de
|
||||
deduções.
|
||||
</p>
|
||||
<label className="block max-w-lg print:hidden">
|
||||
Formulário
|
||||
<select
|
||||
className={input}
|
||||
value={kind}
|
||||
onChange={(e) => {
|
||||
setKind(e.target.value as FiscalFormKind);
|
||||
setStep(0);
|
||||
setNotice('');
|
||||
setPending(null);
|
||||
}}
|
||||
>
|
||||
<option value="iva">IVA — Modelo A</option>
|
||||
<option value="irpc">IRPC — Modelo 22</option>
|
||||
</select>
|
||||
</label>
|
||||
<h2 className="text-xl font-bold">{source.title}</h2>
|
||||
<p>{source.coverage}</p>
|
||||
<nav
|
||||
aria-label="Etapas de preenchimento"
|
||||
className="flex flex-wrap gap-2 print:hidden"
|
||||
>
|
||||
{[
|
||||
'Identificação e período',
|
||||
'Preencher valores',
|
||||
'Conferir e guardar',
|
||||
].map((label, n) => (
|
||||
<button
|
||||
type="button"
|
||||
key={label}
|
||||
className={button}
|
||||
aria-current={step === n ? 'step' : undefined}
|
||||
onClick={() => setStep(n)}
|
||||
>
|
||||
{n + 1}. {label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<form
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
className="space-y-5"
|
||||
>
|
||||
<fieldset
|
||||
className={`${step !== 0 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}
|
||||
>
|
||||
<legend className="font-bold">
|
||||
Identificação e período
|
||||
</legend>
|
||||
<label className="block">
|
||||
Nome ou designação social
|
||||
<input
|
||||
className={input}
|
||||
autoComplete="organization"
|
||||
maxLength={5000}
|
||||
value={p.name}
|
||||
onChange={(e) =>
|
||||
patch({ name: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<label>
|
||||
NUIT
|
||||
<input
|
||||
className={input}
|
||||
inputMode="numeric"
|
||||
maxLength={9}
|
||||
value={p.nuit}
|
||||
onChange={(e) =>
|
||||
patch({ nuit: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{kind === 'iva'
|
||||
? 'Período — ano e mês'
|
||||
: 'Exercício — ano'}
|
||||
<input
|
||||
className={input}
|
||||
type={kind === 'iva' ? 'month' : 'text'}
|
||||
inputMode={
|
||||
kind === 'irpc' ? 'numeric' : undefined
|
||||
}
|
||||
placeholder={
|
||||
kind === 'iva' ? 'AAAA-MM' : 'AAAA'
|
||||
}
|
||||
maxLength={7}
|
||||
value={p.period}
|
||||
onChange={(e) =>
|
||||
patch({ period: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
Dados mantidos apenas nesta página até descarregar o
|
||||
ficheiro. Não há gravação automática. Guarde antes
|
||||
de sair ou actualizar.
|
||||
</p>
|
||||
</fieldset>
|
||||
<fieldset
|
||||
className={`${step !== 1 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}
|
||||
>
|
||||
<legend className="font-bold">
|
||||
Valores em meticais (MZN)
|
||||
</legend>
|
||||
<p>
|
||||
Sem separador de milhares; vírgula ou ponto para os
|
||||
cêntimos. Não preencha zero quando desconhece o
|
||||
valor.
|
||||
</p>
|
||||
{kind === 'irpc' && (
|
||||
<p>
|
||||
Crédito económico (303) e internacional (304)
|
||||
são distintos. Não utilize a mesma parcela nos
|
||||
dois campos. Esta preparação manual não verifica
|
||||
as parcelas; conserve o suporte para
|
||||
conferência.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
{fields.map((f) => (
|
||||
<div
|
||||
key={f.code}
|
||||
className="break-inside-avoid"
|
||||
>
|
||||
<label className="block">
|
||||
{f.code} — {f.label}
|
||||
<input
|
||||
className={input}
|
||||
inputMode="decimal"
|
||||
maxLength={100}
|
||||
value={p.values[f.code] ?? ''}
|
||||
onChange={(e) =>
|
||||
patch({
|
||||
values: {
|
||||
...p.values,
|
||||
[f.code]:
|
||||
e.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<details className="mt-1 text-sm print:hidden">
|
||||
<summary className="cursor-pointer underline">
|
||||
Orientação do campo
|
||||
</summary>
|
||||
<p>{f.guidance}</p>
|
||||
</details>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<section
|
||||
className={`${step !== 2 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}
|
||||
aria-label="Conferir e guardar"
|
||||
>
|
||||
<h3 className="font-bold">Conferência da preparação</h3>
|
||||
<p>
|
||||
{
|
||||
fields.filter(
|
||||
(f) => (p.values[f.code] ?? '') !== '',
|
||||
).length
|
||||
}{' '}
|
||||
de {fields.length} campos com valor. Campos vazios
|
||||
não foram convertidos em zero.
|
||||
</p>
|
||||
{issues.length > 0 ? (
|
||||
<div>
|
||||
<p>
|
||||
Por conferir — pode guardar a preparação
|
||||
incompleta:
|
||||
</p>
|
||||
<ul className="list-disc pl-6">
|
||||
{issues.map((i) => (
|
||||
<li key={i}>{i}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<p>
|
||||
Formato dos campos conferido. Os montantes e a
|
||||
aplicação fiscal ainda devem ser conferidos.
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-3 sm:grid-cols-2 print:hidden">
|
||||
{fields
|
||||
.filter((f) => (p.values[f.code] ?? '') !== '')
|
||||
.map((f) => (
|
||||
<div key={f.code}>
|
||||
<dt>
|
||||
{f.code} — {f.label}
|
||||
</dt>
|
||||
<dd className="font-semibold">
|
||||
{p.values[f.code]} MZN
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<label className="block">
|
||||
Notas e referências dos valores
|
||||
<textarea
|
||||
className={input}
|
||||
rows={4}
|
||||
maxLength={5000}
|
||||
value={p.notes}
|
||||
onChange={(e) =>
|
||||
patch({ notes: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-3 print:hidden">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={download}
|
||||
>
|
||||
Guardar ficheiro para continuar
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => window.print()}
|
||||
>
|
||||
Imprimir preparação
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
O ficheiro contém os dados introduzidos. Guarde-o
|
||||
num local privado. Não fica associado
|
||||
automaticamente ao dossier.
|
||||
</p>
|
||||
</section>
|
||||
<div className="flex justify-between gap-3 print:hidden">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={step === 0}
|
||||
onClick={() => setStep(step - 1)}
|
||||
>
|
||||
Anterior
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={step === 2}
|
||||
onClick={() => setStep(step + 1)}
|
||||
>
|
||||
Continuar
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm">Dados mantidos apenas nesta página até descarregar o ficheiro. Não há gravação automática. Guarde antes de sair ou actualizar.</p>
|
||||
</fieldset>
|
||||
<fieldset className={`${step !== 1 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}>
|
||||
<legend className="font-bold">Valores em meticais (MZN)</legend>
|
||||
<p>Sem separador de milhares; vírgula ou ponto para os cêntimos. Não preencha zero quando desconhece o valor.</p>
|
||||
{kind === 'irpc' && <p>Crédito económico (303) e internacional (304) são distintos. Não utilize a mesma parcela nos dois campos. Esta preparação manual não verifica as parcelas; conserve o suporte para conferência.</p>}
|
||||
<div className="grid gap-5 sm:grid-cols-2">{fields.map(f => <div key={f.code} className="break-inside-avoid">
|
||||
<label className="block">{f.code} — {f.label}<input className={input} inputMode="decimal" maxLength={100} value={p.values[f.code] ?? ''} onChange={e => patch({ values: { ...p.values, [f.code]: e.target.value } })} /></label>
|
||||
<details className="mt-1 text-sm print:hidden"><summary className="cursor-pointer underline">Orientação do campo</summary><p>{f.guidance}</p></details>
|
||||
</div>)}</div>
|
||||
</fieldset>
|
||||
<section className={`${step !== 2 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`} aria-label="Conferir e guardar">
|
||||
<h3 className="font-bold">Conferência da preparação</h3>
|
||||
<p>{fields.filter(f => (p.values[f.code] ?? '') !== '').length} de {fields.length} campos com valor. Campos vazios não foram convertidos em zero.</p>
|
||||
{issues.length > 0 ? <div><p>Por conferir — pode guardar a preparação incompleta:</p><ul className="list-disc pl-6">{issues.map(i => <li key={i}>{i}</li>)}</ul></div> : <p>Formato dos campos conferido. Os montantes e a aplicação fiscal ainda devem ser conferidos.</p>}
|
||||
<dl className="grid gap-3 sm:grid-cols-2 print:hidden">{fields.filter(f => (p.values[f.code] ?? '') !== '').map(f => <div key={f.code}><dt>{f.code} — {f.label}</dt><dd className="font-semibold">{p.values[f.code]} MZN</dd></div>)}</dl>
|
||||
<label className="block">Notas e referências dos valores<textarea className={input} rows={4} maxLength={5000} value={p.notes} onChange={e => patch({ notes: e.target.value })} /></label>
|
||||
<div className="flex flex-wrap gap-3 print:hidden"><button type="button" className={button} onClick={download}>Guardar ficheiro para continuar</button><button type="button" className={button} onClick={() => window.print()}>Imprimir preparação</button></div>
|
||||
<p className="text-sm">O ficheiro contém os dados introduzidos. Guarde-o num local privado. Não fica associado automaticamente ao dossier.</p>
|
||||
</form>
|
||||
<section
|
||||
className="space-y-3 rounded border p-4 print:hidden"
|
||||
aria-label="Recuperar preparação"
|
||||
>
|
||||
<label className="block">
|
||||
Recuperar ficheiro guardado
|
||||
<input
|
||||
className={input}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
onChange={async (e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (!file) return;
|
||||
try {
|
||||
if (file.size > 100_000)
|
||||
throw new Error(
|
||||
'O ficheiro é demasiado grande.',
|
||||
);
|
||||
setPending(
|
||||
readFiscalPreparation(
|
||||
await file.text(),
|
||||
),
|
||||
);
|
||||
setNotice(
|
||||
'Ficheiro lido. Confirme a recuperação abaixo.',
|
||||
);
|
||||
} catch (error) {
|
||||
setPending(null);
|
||||
setNotice(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível ler o ficheiro. Os campos actuais foram preservados.',
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{pending && (
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
Recuperar {fiscalForms[pending.kind].title},
|
||||
período {pending.period || 'por indicar'}?
|
||||
Substitui apenas os campos desse formulário
|
||||
nesta página.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setDrafts((d) => ({
|
||||
...d,
|
||||
[pending.kind]: pending,
|
||||
}));
|
||||
setKind(pending.kind);
|
||||
setStep(2);
|
||||
setPending(null);
|
||||
setDirty(true);
|
||||
setNotice('Preparação recuperada.');
|
||||
}}
|
||||
>
|
||||
Confirmar recuperação
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => setPending(null)}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<div className="flex justify-between gap-3 print:hidden"><button type="button" className={button} disabled={step === 0} onClick={() => setStep(step - 1)}>Anterior</button><button type="button" className={button} disabled={step === 2} onClick={() => setStep(step + 1)}>Continuar</button></div>
|
||||
</form>
|
||||
<section className="space-y-3 rounded border p-4 print:hidden" aria-label="Recuperar preparação">
|
||||
<label className="block">Recuperar ficheiro guardado<input className={input} type="file" accept=".json,application/json" onChange={async e => {
|
||||
const file = e.target.files?.[0]; e.target.value = ''; if (!file) return;
|
||||
try { if (file.size > 100_000) throw new Error('O ficheiro é demasiado grande.'); setPending(readFiscalPreparation(await file.text())); setNotice('Ficheiro lido. Confirme a recuperação abaixo.'); }
|
||||
catch (error) { setPending(null); setNotice(error instanceof Error ? error.message : 'Não foi possível ler o ficheiro. Os campos actuais foram preservados.'); }
|
||||
}} /></label>
|
||||
{pending && <div className="space-y-2"><p>Recuperar {fiscalForms[pending.kind].title}, período {pending.period || 'por indicar'}? Substitui apenas os campos desse formulário nesta página.</p><button type="button" className={button} onClick={() => { setDrafts(d => ({ ...d, [pending.kind]: pending })); setKind(pending.kind); setStep(2); setPending(null); setDirty(true); setNotice('Preparação recuperada.'); }}>Confirmar recuperação</button> <button type="button" className={button} onClick={() => setPending(null)}>Cancelar</button></div>}
|
||||
</section>
|
||||
{notice && <p role="status" className="rounded border p-3">{notice}</p>}
|
||||
<details className="rounded border p-4"><summary className="cursor-pointer font-semibold">Exemplar e cobertura</summary><p>{source.source}</p><p className="break-all text-sm">SHA256: {source.hash}</p><p>{source.coverage}</p><p>Os cálculos e correspondências já disponíveis no simulador permanecem separados desta introdução manual. Não se executam fórmulas nem se transportam valores entre edições automaticamente.</p></details>
|
||||
<div className="flex flex-wrap gap-4 print:hidden"><Link href="/simulador-fiscal" className="underline">Consultar cálculos e preparação M20/M22 no simulador</Link><Link href="/legislacao" className="underline">Consultar legislação</Link></div>
|
||||
</main>
|
||||
</div>;
|
||||
{notice && (
|
||||
<p role="status" className="rounded border p-3">
|
||||
{notice}
|
||||
</p>
|
||||
)}
|
||||
<details className="rounded border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Exemplar e cobertura
|
||||
</summary>
|
||||
<p>{source.source}</p>
|
||||
<p className="text-sm break-all">SHA256: {source.hash}</p>
|
||||
<p>{source.coverage}</p>
|
||||
<p>
|
||||
Os cálculos e correspondências já disponíveis no
|
||||
simulador permanecem separados desta introdução manual.
|
||||
Não se executam fórmulas nem se transportam valores
|
||||
entre edições automaticamente.
|
||||
</p>
|
||||
</details>
|
||||
<div className="flex flex-wrap gap-4 print:hidden">
|
||||
<Link href="/simulador-fiscal" className="underline">
|
||||
Consultar cálculos e preparação M20/M22 no simulador
|
||||
</Link>
|
||||
<Link href="/legislacao" className="underline">
|
||||
Consultar legislação
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -105,7 +105,14 @@ export default function LegacySector({
|
||||
? article.group.heading
|
||||
: article.title}
|
||||
</h1>
|
||||
{article.sector?.slug === 'agronegocio' && <Link className="inline-flex rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white" href="/oportunidades?sector=agronegocio&view=corridors">Explorar oportunidades por corredor</Link>}
|
||||
{article.sector?.slug === 'agronegocio' && (
|
||||
<Link
|
||||
className="inline-flex rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white"
|
||||
href="/oportunidades?sector=agronegocio&view=corridors"
|
||||
>
|
||||
Explorar oportunidades por corredor
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
Explore o setor e prepare a sua ideia com o contexto
|
||||
guardado no dossier.
|
||||
|
||||
+1306
-996
File diff suppressed because it is too large
Load Diff
@@ -538,15 +538,38 @@ export default function Services(p: Props) {
|
||||
opportunities={p.opportunities}
|
||||
/>
|
||||
)}
|
||||
{p.section === 'documents' && <section aria-label="Preencher formulários fiscais" className="space-y-3 rounded-xl border bg-white p-5">
|
||||
<h2 className="text-xl font-bold">Que formulário pretende preencher?</h2>
|
||||
<p>Abra os campos do formulário fiscal. A legislação e os guias de consulta ficam abaixo.</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className={button} href="/formularios/fiscais?imposto=iva">Preencher IVA — Modelo A</Link>
|
||||
<Link className={button} href="/formularios/fiscais?imposto=irpc">Preparar IRPC — Modelo 22</Link>
|
||||
</div>
|
||||
<p className="text-sm">Preparação manual, com gravação em ficheiro. Cobertura parcial de IRPC; sem submissão à AT.</p>
|
||||
</section>}
|
||||
{p.section === 'documents' && (
|
||||
<section
|
||||
aria-label="Preencher formulários fiscais"
|
||||
className="space-y-3 rounded-xl border bg-white p-5"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Que formulário pretende preencher?
|
||||
</h2>
|
||||
<p>
|
||||
Abra os campos do formulário fiscal. A legislação e
|
||||
os guias de consulta ficam abaixo.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link
|
||||
className={button}
|
||||
href="/formularios/fiscais?imposto=iva"
|
||||
>
|
||||
Preencher IVA — Modelo A
|
||||
</Link>
|
||||
<Link
|
||||
className={button}
|
||||
href="/formularios/fiscais?imposto=irpc"
|
||||
>
|
||||
Preparar IRPC — Modelo 22
|
||||
</Link>
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
Preparação manual, com gravação em ficheiro.
|
||||
Cobertura parcial de IRPC; sem submissão à AT.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{['procedures', 'documents', 'legislation'].includes(
|
||||
p.section,
|
||||
) && <JourneyDocumentResources stages={p.stages} />}
|
||||
@@ -589,7 +612,9 @@ export default function Services(p: Props) {
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.topics?.map((topic) => (
|
||||
<option key={topic} value={topic}>{documentFacetLabel(topic)}</option>
|
||||
<option key={topic} value={topic}>
|
||||
{documentFacetLabel(topic)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -616,7 +641,9 @@ export default function Services(p: Props) {
|
||||
value={category}
|
||||
>
|
||||
{documentTypeLabels[category] ??
|
||||
documentFacetLabel(category)}
|
||||
documentFacetLabel(
|
||||
category,
|
||||
)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -819,7 +846,10 @@ export default function Services(p: Props) {
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.languages?.map((language) => (
|
||||
<option key={language} value={language}>
|
||||
<option
|
||||
key={language}
|
||||
value={language}
|
||||
>
|
||||
{documentFacetLabel(language)}
|
||||
</option>
|
||||
))}
|
||||
|
||||
@@ -82,9 +82,17 @@ export default function Index({
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Sector documentado">
|
||||
<select className={control} value={form.data.sector} onChange={(e) => form.setData('sector', e.target.value)}>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.sector}
|
||||
onChange={(e) => form.setData('sector', e.target.value)}
|
||||
>
|
||||
<option value="">Todos os sectores</option>
|
||||
{sectors.map((sector) => <option key={sector} value={sector}>{sector}</option>)}
|
||||
{sectors.map((sector) => (
|
||||
<option key={sector} value={sector}>
|
||||
{sector}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<TerritoryFields
|
||||
@@ -163,7 +171,10 @@ export default function Index({
|
||||
(r.corridor_id || r.cluster_id || r.project_id) && (
|
||||
<Link
|
||||
className="ml-4 underline"
|
||||
href={searchTerritoryHref(`/oportunidades?${new URLSearchParams(r.corridor_id ? { corridor_id: r.corridor_id } : r.cluster_id ? { cluster_id: r.cluster_id } : { project_id: r.project_id! })}`, url)}
|
||||
href={searchTerritoryHref(
|
||||
`/oportunidades?${new URLSearchParams(r.corridor_id ? { corridor_id: r.corridor_id } : r.cluster_id ? { cluster_id: r.cluster_id } : { project_id: r.project_id! })}`,
|
||||
url,
|
||||
)}
|
||||
>
|
||||
Ver oportunidades associadas
|
||||
</Link>
|
||||
@@ -186,10 +197,16 @@ export default function Index({
|
||||
aria-label="Alternativas de exploração"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link className="underline" href={searchTerritoryHref('/oportunidades', url)}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref('/oportunidades', url)}
|
||||
>
|
||||
Ver oportunidades publicadas
|
||||
</Link>
|
||||
<Link className="underline" href={searchTerritoryHref('/zonas', url)}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref('/zonas', url)}
|
||||
>
|
||||
Consultar ZEE, ZFI e parques
|
||||
</Link>
|
||||
<Link className="underline" href="/Simulador">
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { Link, useForm, router, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { catalogueReturnHref } from '@/lib/catalogue-context';
|
||||
import { searchTerritoryHref, portfolioPreparationHref } from '@/lib/search-territory';
|
||||
import {
|
||||
searchTerritoryHref,
|
||||
portfolioPreparationHref,
|
||||
} from '@/lib/search-territory';
|
||||
import InvestmentMapPanel from '@/components/investment-map-panel';
|
||||
import StructureGeographyPanel, {
|
||||
type StructureGeography,
|
||||
@@ -10,8 +13,12 @@ import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import { Management } from '../management/shared';
|
||||
import { Layout, Field, control, button, labels, kind } from './shared';
|
||||
import type { Dossier } from './shared';
|
||||
import InvestmentComplements, { type ComplementOption } from '@/components/investment-complements';
|
||||
import ClusterCompetitivenessPublic, { type ApprovedCompetitiveness } from '@/components/cluster-competitiveness-public';
|
||||
import InvestmentComplements, {
|
||||
type ComplementOption,
|
||||
} from '@/components/investment-complements';
|
||||
import ClusterCompetitivenessPublic, {
|
||||
type ApprovedCompetitiveness,
|
||||
} from '@/components/cluster-competitiveness-public';
|
||||
export default function Show(props: Props) {
|
||||
return (
|
||||
<Editor
|
||||
@@ -97,13 +104,22 @@ function Editor({
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{competitiveness && <ClusterCompetitivenessPublic analysis={competitiveness} />}
|
||||
{competitiveness && (
|
||||
<ClusterCompetitivenessPublic analysis={competitiveness} />
|
||||
)}
|
||||
{!management && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<Link className="underline" href={portfolioPreparationHref(record.id, pageUrl)}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={portfolioPreparationHref(record.id, pageUrl)}
|
||||
>
|
||||
Preparar investimento a partir desta ficha
|
||||
</Link>
|
||||
<p>A ficha acompanha o dossier como origem documental. A localização do investimento e as ofertas associadas são escolhas próprias.</p>
|
||||
<p>
|
||||
A ficha acompanha o dossier como origem documental. A
|
||||
localização do investimento e as ofertas associadas são
|
||||
escolhas próprias.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{(record.project_id || record.cluster_id) && (
|
||||
@@ -206,7 +222,13 @@ function Editor({
|
||||
</h2>
|
||||
{zones.map((z) => (
|
||||
<p key={z.id}>
|
||||
<Link className="underline" href={searchTerritoryHref(`/zonas/${z.id}`, pageUrl)}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref(
|
||||
`/zonas/${z.id}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
{z.name}
|
||||
</Link>{' '}
|
||||
· {z.association_type} · Fonte: {z.source_reference}
|
||||
@@ -215,7 +237,7 @@ function Editor({
|
||||
</section>
|
||||
)}
|
||||
{origin && <p>Exploração iniciada em: {origin.title}</p>}
|
||||
{!management && <InvestmentComplements items={complements}/>}
|
||||
{!management && <InvestmentComplements items={complements} />}
|
||||
{!management && auth.user && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<p>
|
||||
@@ -282,7 +304,24 @@ function Editor({
|
||||
Para associar esta referência a uma manifestação privada,
|
||||
entre na sua conta. Esta ficha continuará pública e não será
|
||||
copiada nem publicada no seu nome.{' '}
|
||||
<Link className="underline" href={'/carteira/' + record.id + '/interesse' + (() => { const query = new URL(pageUrl, 'https://portal.invalid').searchParams.get('catalogue_query'); return query ? '?catalogue_query=' + encodeURIComponent(query) : ''; })()}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
'/carteira/' +
|
||||
record.id +
|
||||
'/interesse' +
|
||||
(() => {
|
||||
const query = new URL(
|
||||
pageUrl,
|
||||
'https://portal.invalid',
|
||||
).searchParams.get('catalogue_query');
|
||||
return query
|
||||
? '?catalogue_query=' +
|
||||
encodeURIComponent(query)
|
||||
: '';
|
||||
})()
|
||||
}
|
||||
>
|
||||
Entrar
|
||||
</Link>
|
||||
</p>
|
||||
@@ -314,7 +353,10 @@ function Editor({
|
||||
<article key={opportunity.id}>
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={searchTerritoryHref(`/oportunidades/${opportunity.slug}?from_dossier=${record.id}`, pageUrl)}
|
||||
href={searchTerritoryHref(
|
||||
`/oportunidades/${opportunity.slug}?from_dossier=${record.id}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
{opportunity.title}
|
||||
</Link>
|
||||
@@ -502,7 +544,10 @@ function Editor({
|
||||
{kind(r)}:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={searchTerritoryHref(`${base}/${r.id}${management ? '' : `?from=${record.id}`}`, pageUrl)}
|
||||
href={searchTerritoryHref(
|
||||
`${base}/${r.id}${management ? '' : `?from=${record.id}`}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
{r.title}
|
||||
</Link>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
@@ -127,7 +128,7 @@ export default function Edit({
|
||||
setPreview(null);
|
||||
setSaved(false);
|
||||
};
|
||||
const value = (key: string) => String(form.data.draft[key] ?? '');
|
||||
const value = (key: string) => inputText(form.data.draft[key] ?? '');
|
||||
const select = (key: string, label: string, choices: Choice[]) => (
|
||||
<Field label={label}>
|
||||
<select
|
||||
@@ -270,9 +271,8 @@ export default function Edit({
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setPreview(null);
|
||||
record
|
||||
? form.put(`/management/concursos/${record.id}`)
|
||||
: form.post('/management/concursos');
|
||||
if (record) form.put(`/management/concursos/${record.id}`);
|
||||
else form.post('/management/concursos');
|
||||
}}
|
||||
>
|
||||
<section className={`${card} grid gap-3 md:grid-cols-2`}>
|
||||
@@ -781,7 +781,7 @@ export default function Edit({
|
||||
</h3>
|
||||
<p>
|
||||
Motivo público:{' '}
|
||||
{String(preview.payload.public_reason)}
|
||||
{inputText(preview.payload.public_reason)}
|
||||
</p>
|
||||
<NoticeContent p={preview.payload} />
|
||||
<button
|
||||
@@ -792,7 +792,7 @@ export default function Edit({
|
||||
{
|
||||
act: preview.act,
|
||||
hash: preview.hash,
|
||||
reason: String(
|
||||
reason: inputText(
|
||||
preview.payload.public_reason,
|
||||
),
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { Field, control, states, type Publication } from './shared';
|
||||
@@ -151,22 +152,23 @@ export default function Index({
|
||||
className="underline"
|
||||
href={`/concursos/${item.id}${query ? '?' + query : ''}`}
|
||||
>
|
||||
{String(item.publication.payload.title)}
|
||||
{inputText(item.publication.payload.title)}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{String(item.publication.payload.organization_name)}{' '}
|
||||
{inputText(
|
||||
item.publication.payload.organization_name,
|
||||
)}{' '}
|
||||
· {states[item.state]}
|
||||
</p>
|
||||
<p>
|
||||
Entrega:{' '}
|
||||
{String(item.publication.payload.deadline).replace(
|
||||
'T',
|
||||
' ',
|
||||
)}{' '}
|
||||
· {String(item.publication.payload.timezone)}
|
||||
{inputText(
|
||||
item.publication.payload.deadline,
|
||||
).replace('T', ' ')}{' '}
|
||||
· {inputText(item.publication.payload.timezone)}
|
||||
</p>
|
||||
<p>{String(item.publication.payload.object)}</p>
|
||||
<p>{inputText(item.publication.payload.object)}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { states, type Publication } from './shared';
|
||||
@@ -54,7 +55,8 @@ export default function Manage({
|
||||
{items.map((item) => (
|
||||
<article key={item.id} className={`${card} my-3`}>
|
||||
<h2 className="font-semibold">
|
||||
{item.title ?? String(item.publication?.payload.title)}
|
||||
{item.title ??
|
||||
inputText(item.publication?.payload.title)}
|
||||
</h2>
|
||||
{watched ? (
|
||||
<>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export type Lot = { code: string; description: string; quantities: string };
|
||||
@@ -108,10 +109,12 @@ export function NoticeContent({ p }: { p: Payload }) {
|
||||
};
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h2 className="text-2xl font-semibold">{String(p.title ?? '')}</h2>
|
||||
<h2 className="text-2xl font-semibold">
|
||||
{inputText(p.title ?? '')}
|
||||
</h2>
|
||||
<p>
|
||||
<strong>Entidade:</strong>{' '}
|
||||
{String(p.organization_name ?? 'Por indicar')}
|
||||
{inputText(p.organization_name ?? 'Por indicar')}
|
||||
</p>
|
||||
<p>
|
||||
Regime:{' '}
|
||||
@@ -122,28 +125,30 @@ export function NoticeContent({ p }: { p: Payload }) {
|
||||
private: 'Concurso privado',
|
||||
other: 'Outro regime documentado',
|
||||
} as Record<string, string>
|
||||
)[String(p.regime)] ?? 'Por indicar'}
|
||||
)[inputText(p.regime)] ?? 'Por indicar'}
|
||||
</p>
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold">
|
||||
Objecto e como participar
|
||||
</h3>
|
||||
<p className="whitespace-pre-wrap">{String(p.object ?? '')}</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{inputText(p.object ?? '')}
|
||||
</p>
|
||||
<p className="my-2 rounded border p-3">
|
||||
<strong>Entrega:</strong>{' '}
|
||||
{String(p.deadline ?? 'Por indicar').replace('T', ' ')} ·{' '}
|
||||
{String(p.timezone ?? '')}
|
||||
{inputText(p.deadline ?? 'Por indicar').replace('T', ' ')} ·{' '}
|
||||
{inputText(p.timezone ?? '')}
|
||||
<br />
|
||||
{String(p.delivery_channel ?? '')} ·{' '}
|
||||
{String(p.delivery_address ?? '')}
|
||||
{inputText(p.delivery_channel ?? '')} ·{' '}
|
||||
{inputText(p.delivery_address ?? '')}
|
||||
</p>
|
||||
<p>
|
||||
Sector: {String(p.sector_name ?? 'Por indicar')} ·
|
||||
Localização: {String(p.territory_name ?? 'Por indicar')}
|
||||
Sector: {inputText(p.sector_name ?? 'Por indicar')} ·
|
||||
Localização: {inputText(p.territory_name ?? 'Por indicar')}
|
||||
</p>
|
||||
{p.project_name && (
|
||||
<p>
|
||||
Projecto relacionado: {String(p.project_name)}. Esta
|
||||
Projecto relacionado: {inputText(p.project_name)}. Esta
|
||||
relação não confirma execução ou contratação.
|
||||
</p>
|
||||
)}
|
||||
@@ -156,9 +161,10 @@ export function NoticeContent({ p }: { p: Payload }) {
|
||||
{p.deadline_previous && (
|
||||
<p className="rounded border p-3">
|
||||
<strong>Prorrogação:</strong> prazo anterior{' '}
|
||||
{String(p.deadline_previous).replace('T', ' ')} (
|
||||
{String(p.timezone_previous)}) → novo prazo{' '}
|
||||
{String(p.deadline).replace('T', ' ')} ({String(p.timezone)}
|
||||
{inputText(p.deadline_previous).replace('T', ' ')} (
|
||||
{inputText(p.timezone_previous)}) → novo prazo{' '}
|
||||
{inputText(p.deadline).replace('T', ' ')} (
|
||||
{inputText(p.timezone)}
|
||||
).
|
||||
</p>
|
||||
)}
|
||||
@@ -180,14 +186,15 @@ export function NoticeContent({ p }: { p: Payload }) {
|
||||
{links.includes(key) ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={String(p[key])}
|
||||
href={inputText(p[key])}
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{String(p[key])}
|
||||
{inputText(p[key])}
|
||||
</a>
|
||||
) : (
|
||||
(
|
||||
names[String(p[key])] ?? String(p[key])
|
||||
names[inputText(p[key])] ??
|
||||
inputText(p[key])
|
||||
).replace(/^(\d{4}-\d{2}-\d{2})T/, '$1 ')
|
||||
)}
|
||||
</dd>
|
||||
@@ -244,8 +251,8 @@ export function NoticeContent({ p }: { p: Payload }) {
|
||||
<p className="rounded border p-3">
|
||||
O InvesteMoz divulga este acto e não recebe propostas nesta
|
||||
secção. Apresente a proposta no canal indicado nos documentos.
|
||||
Esta divulgação não substitui os meios oficiais exigidos,
|
||||
não comprova envio à UFSA ou ao financiador e não equivale à
|
||||
Esta divulgação não substitui os meios oficiais exigidos, não
|
||||
comprova envio à UFSA ou ao financiador e não equivale à
|
||||
execução do investimento.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import { Head, Link, router, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { NoticeContent, states, acts, type Publication } from './shared';
|
||||
@@ -18,10 +19,10 @@ export default function Show({
|
||||
backUrl: string;
|
||||
printMode: boolean;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: unknown | null } }>().props;
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
return (
|
||||
<Frame title="Concurso e anúncio">
|
||||
<Head title={String(publication.payload.title)} />
|
||||
<Head title={inputText(publication.payload.title)} />
|
||||
<style>
|
||||
{
|
||||
'@media print { nav, header, aside, footer, [data-slot="sidebar"], .no-print {display:none!important} main {margin:0!important; width:100%!important} details {display:block} }'
|
||||
|
||||
@@ -26,7 +26,13 @@ type SecurityEntry = {
|
||||
expires_at: string;
|
||||
};
|
||||
type Pair = { first_user_id: number; second_user_id: number; version: number };
|
||||
type OperatorOrganization = { id: string; name: string; nuit: string; contact: string; director: string };
|
||||
type OperatorOrganization = {
|
||||
id: string;
|
||||
name: string;
|
||||
nuit: string;
|
||||
contact: string;
|
||||
director: string;
|
||||
};
|
||||
|
||||
function OperatorOrganizationForm() {
|
||||
const [operationKey] = useState(createOperationKey);
|
||||
@@ -34,33 +40,119 @@ function OperatorOrganizationForm() {
|
||||
const [nuit, setNuit] = useState('400993114');
|
||||
const [contact, setContact] = useState('+258868010880');
|
||||
const [director, setDirector] = useState('Osmane Nala');
|
||||
const [source, setSource] = useState('Dados e designação interna confirmados pelo responsável da Tempo em 11/10/2026.');
|
||||
const [source, setSource] = useState(
|
||||
'Dados e designação interna confirmados pelo responsável da Tempo em 11/10/2026.',
|
||||
);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await profileJson('/perfis/organizacao-operadora', { operation_key: operationKey, name, nuit, contact, director, function: 'portal_owner_operator', source_reference: source });
|
||||
setMessage(result.message); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); }
|
||||
finally { setBusy(false); }
|
||||
const result = await profileJson('/perfis/organizacao-operadora', {
|
||||
operation_key: operationKey,
|
||||
name,
|
||||
nuit,
|
||||
contact,
|
||||
director,
|
||||
function: 'portal_owner_operator',
|
||||
source_reference: source,
|
||||
});
|
||||
setMessage(result.message);
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return <section className="space-y-3" aria-label="Organização operadora">
|
||||
<h2 className="text-xl font-semibold">Organização proprietária e operadora</h2>
|
||||
<p>Reutiliza o cadastro mestre e conserva o histórico. Estes dados não atribuem representação empresarial nem papéis às contas.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => { e.preventDefault(); void save(); }}>
|
||||
<label className="block">Denominação<input required className={control} value={name} onChange={e => setName(e.target.value)} /></label>
|
||||
<label className="block">NUIT<input required className={control} value={nuit} onChange={e => setNuit(e.target.value)} pattern="[0-9]{9}" /></label>
|
||||
<label className="block">Contacto<input required type="tel" className={control} value={contact} onChange={e => setContact(e.target.value)} /></label>
|
||||
<label className="block">Director Geral<input required className={control} value={director} onChange={e => setDirector(e.target.value)} /></label>
|
||||
<label className="block">Origem dos dados<textarea aria-label="Origem dos dados" required minLength={20} maxLength={1000} className={control} value={source} onChange={e => setSource(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Guardar organização operadora</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>;
|
||||
return (
|
||||
<section className="space-y-3" aria-label="Organização operadora">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Organização proprietária e operadora
|
||||
</h2>
|
||||
<p>
|
||||
Reutiliza o cadastro mestre e conserva o histórico. Estes dados
|
||||
não atribuem representação empresarial nem papéis às contas.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Denominação
|
||||
<input
|
||||
required
|
||||
className={control}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
NUIT
|
||||
<input
|
||||
required
|
||||
className={control}
|
||||
value={nuit}
|
||||
onChange={(e) => setNuit(e.target.value)}
|
||||
pattern="[0-9]{9}"
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Contacto
|
||||
<input
|
||||
required
|
||||
type="tel"
|
||||
className={control}
|
||||
value={contact}
|
||||
onChange={(e) => setContact(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Director Geral
|
||||
<input
|
||||
required
|
||||
className={control}
|
||||
value={director}
|
||||
onChange={(e) => setDirector(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Origem dos dados
|
||||
<textarea
|
||||
aria-label="Origem dos dados"
|
||||
required
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
className={control}
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar organização operadora
|
||||
</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function InternalStaffGrant({ types, organizations, operators }: { types: string[]; organizations: { id: string; name: string }[]; operators: OperatorOrganization[] }) {
|
||||
function InternalStaffGrant({
|
||||
types,
|
||||
organizations,
|
||||
operators,
|
||||
}: {
|
||||
types: string[];
|
||||
organizations: { id: string; name: string }[];
|
||||
operators: OperatorOrganization[];
|
||||
}) {
|
||||
const [operationKey, setOperationKey] = useState(createOperationKey);
|
||||
const [subject, setSubject] = useState('');
|
||||
const [role, setRole] = useState('promoter');
|
||||
@@ -74,30 +166,179 @@ function InternalStaffGrant({ types, organizations, operators }: { types: string
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
await profileJson('/perfis/atribuicoes', { internal_designation: true, operation_key: operationKey,
|
||||
user_id: Number(subject), role, operator_organization_id: operator,
|
||||
await profileJson('/perfis/atribuicoes', {
|
||||
internal_designation: true,
|
||||
operation_key: operationKey,
|
||||
user_id: Number(subject),
|
||||
role,
|
||||
operator_organization_id: operator,
|
||||
organization_id: role === 'promoter' ? operator : scope || null,
|
||||
opportunity_types: selected, responsibilities: [], reason, confirmed_internal_designation: confirmed });
|
||||
setMessage('Designação interna atribuída e auditada.'); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); }
|
||||
finally { setBusy(false); }
|
||||
opportunity_types: selected,
|
||||
responsibilities: [],
|
||||
reason,
|
||||
confirmed_internal_designation: confirmed,
|
||||
});
|
||||
setMessage('Designação interna atribuída e auditada.');
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return <section className="space-y-3" aria-label="Designação interna">
|
||||
<h2 className="text-xl font-semibold">Atribuir função interna do portal</h2>
|
||||
<p>A proprietária define as funções da sua equipa. Esta atribuição não exige comprovativos de Promotor externo nem concede gestão empresarial. Cada oportunidade conserva o promotor real e a autorização de divulgação.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => { e.preventDefault(); void save(); }}>
|
||||
<label className="block">Conta da pessoa designada<input required type="number" min={1} className={control} value={subject} onChange={e => setSubject(e.target.value)} /></label>
|
||||
<label className="block">Função interna<select aria-label="Função interna" required className={control} value={role} onChange={e => setRole(e.target.value)}>{['promoter', 'validator', 'publisher'].map(v => <option key={v} value={v}>{v === 'promoter' ? 'Promotor' : v === 'validator' ? 'Validador' : 'Publicador'}</option>)}</select></label>
|
||||
<label className="block">Vínculo à organização operadora<select aria-label="Vínculo à organização operadora" required className={control} value={operator} onChange={e => setOperator(e.target.value)}><option value="">Selecionar organização</option>{operators.map(o => <option key={o.id} value={o.id}>{o.name} — NUIT {o.nuit}</option>)}</select></label>
|
||||
{role !== 'promoter' && <label className="block">Âmbito da função interna<select aria-label="Âmbito da função interna" className={control} value={scope} onChange={e => setScope(e.target.value)}><option value="">Todas as organizações para as categorias selecionadas</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></label>}
|
||||
<fieldset><legend>Categorias da função interna</legend>{types.map(v => <label className="block" key={v}><input type="checkbox" checked={selected.includes(v)} onChange={() => setSelected(old => old.includes(v) ? old.filter(x => x !== v) : [...old, v])} /> {v}</label>)}</fieldset>
|
||||
<label className="block"><input type="checkbox" required checked={confirmed} onChange={e => setConfirmed(e.target.checked)} /> Confirmo a designação interna expressa pelo responsável da organização operadora.</label>
|
||||
<label className="block">Fundamento da designação interna<textarea aria-label="Fundamento da designação interna" required minLength={20} maxLength={1000} className={control} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Atribuir função interna com auditoria</button>
|
||||
<button type="button" className={button} disabled={busy} onClick={() => { setOperationKey(createOperationKey()); setSubject(''); setConfirmed(false); setMessage('Nova atribuição preparada.'); }}>Preparar outra atribuição</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>;
|
||||
return (
|
||||
<section className="space-y-3" aria-label="Designação interna">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Atribuir função interna do portal
|
||||
</h2>
|
||||
<p>
|
||||
A proprietária define as funções da sua equipa. Esta atribuição
|
||||
não exige comprovativos de Promotor externo nem concede gestão
|
||||
empresarial. Cada oportunidade conserva o promotor real e a
|
||||
autorização de divulgação.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Conta da pessoa designada
|
||||
<input
|
||||
required
|
||||
type="number"
|
||||
min={1}
|
||||
className={control}
|
||||
list="staff-accounts"
|
||||
value={subject}
|
||||
onChange={(e) => setSubject(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Função interna
|
||||
<select
|
||||
aria-label="Função interna"
|
||||
required
|
||||
className={control}
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
>
|
||||
{['promoter', 'validator', 'publisher'].map((v) => (
|
||||
<option key={v} value={v}>
|
||||
{v === 'promoter'
|
||||
? 'Promotor'
|
||||
: v === 'validator'
|
||||
? 'Validador'
|
||||
: 'Publicador'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Vínculo à organização operadora
|
||||
<select
|
||||
aria-label="Vínculo à organização operadora"
|
||||
required
|
||||
className={control}
|
||||
value={operator}
|
||||
onChange={(e) => setOperator(e.target.value)}
|
||||
>
|
||||
<option value="">Selecionar organização</option>
|
||||
{operators.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name} — NUIT {o.nuit}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{role !== 'promoter' && (
|
||||
<label className="block">
|
||||
Âmbito da função interna
|
||||
<select
|
||||
aria-label="Âmbito da função interna"
|
||||
className={control}
|
||||
value={scope}
|
||||
onChange={(e) => setScope(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Todas as organizações para as categorias
|
||||
selecionadas
|
||||
</option>
|
||||
{organizations.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<fieldset>
|
||||
<legend>Categorias da função interna</legend>
|
||||
{types.map((v) => (
|
||||
<label className="block" key={v}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(v)}
|
||||
onChange={() =>
|
||||
setSelected((old) =>
|
||||
old.includes(v)
|
||||
? old.filter((x) => x !== v)
|
||||
: [...old, v],
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{v}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo a designação interna expressa pelo responsável da
|
||||
organização operadora.
|
||||
</label>
|
||||
<label className="block">
|
||||
Fundamento da designação interna
|
||||
<textarea
|
||||
aria-label="Fundamento da designação interna"
|
||||
required
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Atribuir função interna com auditoria
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setOperationKey(createOperationKey());
|
||||
setSubject('');
|
||||
setConfirmed(false);
|
||||
setMessage('Nova atribuição preparada.');
|
||||
}}
|
||||
>
|
||||
Preparar outra atribuição
|
||||
</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Grant({
|
||||
@@ -161,8 +402,9 @@ function Grant({
|
||||
Atribuir papel operacional
|
||||
</h2>
|
||||
<p>
|
||||
Promotor externo usa o pedido documental. Funções internas usam a designação da proprietária. Superutilizador é
|
||||
gerido pela dupla, sem terceira atribuição.
|
||||
Promotor externo usa o pedido documental. Funções internas usam
|
||||
a designação da proprietária. Superutilizador é gerido pela
|
||||
dupla, sem terceira atribuição.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-3"
|
||||
@@ -178,6 +420,7 @@ function Grant({
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
list="staff-accounts"
|
||||
value={user}
|
||||
onChange={(e) => setUser(e.target.value)}
|
||||
/>
|
||||
@@ -355,6 +598,7 @@ function Security({
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
list="staff-accounts"
|
||||
value={candidate}
|
||||
onChange={(e) => setCandidate(e.target.value)}
|
||||
/>
|
||||
@@ -389,7 +633,11 @@ function Security({
|
||||
'publish',
|
||||
'archive',
|
||||
].map((v) => (
|
||||
<option key={v} value={v}>{v === 'view' ? 'Consultar dossier e anexos' : v}</option>
|
||||
<option key={v} value={v}>
|
||||
{v === 'view'
|
||||
? 'Consultar dossier e anexos'
|
||||
: v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -590,9 +838,17 @@ export default function Administration({
|
||||
securityRequests,
|
||||
operatorOrganizations,
|
||||
internalTypes,
|
||||
staffAccounts,
|
||||
}: {
|
||||
operatorOrganizations: OperatorOrganization[];
|
||||
internalTypes: string[];
|
||||
staffAccounts: {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
verified: boolean;
|
||||
mfa: boolean;
|
||||
}[];
|
||||
actorId: number;
|
||||
types: string[];
|
||||
organizations: { id: string; name: string }[];
|
||||
@@ -652,7 +908,18 @@ export default function Administration({
|
||||
))}
|
||||
</section>
|
||||
<OperatorOrganizationForm />
|
||||
<InternalStaffGrant types={internalTypes} organizations={organizations} operators={operatorOrganizations} />
|
||||
<datalist id="staff-accounts">
|
||||
{staffAccounts.map((account) => (
|
||||
<option key={account.id} value={account.id}>
|
||||
{account.name} ({account.email})
|
||||
</option>
|
||||
))}
|
||||
</datalist>
|
||||
<InternalStaffGrant
|
||||
types={internalTypes}
|
||||
organizations={organizations}
|
||||
operators={operatorOrganizations}
|
||||
/>
|
||||
<Grant types={types} organizations={organizations} />
|
||||
<Security
|
||||
pair={pair}
|
||||
|
||||
@@ -2,34 +2,125 @@ import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
type Plan = {approval_id:string;requested_by:number;second_user_id:number;reason:string;expires_at:string;consumed:boolean;expired:boolean;code_current:boolean;can_confirm:boolean;mfa_confirmed_in_session:boolean;hash:string;target:{database:string;port:number}};
|
||||
export default function BootstrapConfirmation(plan:Plan) {
|
||||
type Plan = {
|
||||
approval_id: string;
|
||||
requested_by: number;
|
||||
second_user_id: number;
|
||||
reason: string;
|
||||
expires_at: string;
|
||||
consumed: boolean;
|
||||
expired: boolean;
|
||||
code_current: boolean;
|
||||
can_confirm: boolean;
|
||||
mfa_confirmed_in_session: boolean;
|
||||
hash: string;
|
||||
target: { database: string; port: number };
|
||||
};
|
||||
export default function BootstrapConfirmation(plan: Plan) {
|
||||
const [key] = useState(createOperationKey);
|
||||
const [reason,setReason] = useState('');
|
||||
const [confirmed,setConfirmed] = useState(false);
|
||||
const [busy,setBusy] = useState(false);
|
||||
const [done,setDone] = useState(plan.consumed);
|
||||
const [message,setMessage] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [done, setDone] = useState(plan.consumed);
|
||||
const [message, setMessage] = useState('');
|
||||
async function confirm() {
|
||||
setBusy(true);setMessage('');
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
await profileJson('/management/profile-install/bootstrap/'+plan.approval_id+'/confirm',{hash:plan.hash,confirm:confirmed,idempotency_key:key,reason});
|
||||
setDone(true);setMessage('Dupla inicializada por confirmação cruzada. Apenas estas duas contas foram designadas; nenhuma flag foi alterada. Inicie uma nova sessão.');
|
||||
} catch(error) {setMessage(error instanceof Error?error.message:'Resposta indisponível. Recupere este pedido antes de repetir.');}
|
||||
finally {setBusy(false);}
|
||||
await profileJson(
|
||||
'/management/profile-install/bootstrap/' +
|
||||
plan.approval_id +
|
||||
'/confirm',
|
||||
{
|
||||
hash: plan.hash,
|
||||
confirm: confirmed,
|
||||
idempotency_key: key,
|
||||
reason,
|
||||
},
|
||||
);
|
||||
setDone(true);
|
||||
setMessage(
|
||||
'Dupla inicializada por confirmação cruzada. Apenas estas duas contas foram designadas; nenhuma flag foi alterada. Inicie uma nova sessão.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível. Recupere este pedido antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return <Management title="Confirmar os dois titulares">
|
||||
<p>Base {plan.target.database}:{plan.target.port}</p>
|
||||
<p>Pedido apresentado pela conta {plan.requested_by}; confirmação reservada à conta {plan.second_user_id}.</p>
|
||||
<p>Fundamento do pedido: {plan.reason}</p><p>Expira em {plan.expires_at}.</p>
|
||||
<p>O pedido não atribui privilégios. A confirmação é uma operação distinta, com MFA e auditoria. Não altera a regra de substituição posterior.</p>
|
||||
{plan.expired && <p role="alert">Pedido expirado. Prepare novo pedido autorizado.</p>}
|
||||
{!plan.code_current && <p role="alert">Revisão ou destino alterados. Este pedido não pode ser confirmado.</p>}
|
||||
{!plan.mfa_confirmed_in_session && <p role="alert">Conclua MFA nesta sessão antes de confirmar.</p>}
|
||||
{!plan.can_confirm && !done && <p>Esta conta pode consultar, mas não confirmar o pedido.</p>}
|
||||
<label className="block">Fundamento da confirmação<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e=>setReason(e.target.value)}/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/> Confirmo apenas estas duas contas e esta base</label>
|
||||
<button className={button} disabled={busy||done||!plan.can_confirm||!plan.mfa_confirmed_in_session||!confirmed||reason.length<20} onClick={()=>void confirm()}>Confirmar designação cruzada</button>
|
||||
<p role="status">{done?'Pedido consumido; não reinicializar. ':''}{message}</p>
|
||||
</Management>;
|
||||
return (
|
||||
<Management title="Confirmar os dois titulares">
|
||||
<p>
|
||||
Base {plan.target.database}:{plan.target.port}
|
||||
</p>
|
||||
<p>
|
||||
Pedido apresentado pela conta {plan.requested_by}; confirmação
|
||||
reservada à conta {plan.second_user_id}.
|
||||
</p>
|
||||
<p>Fundamento do pedido: {plan.reason}</p>
|
||||
<p>Expira em {plan.expires_at}.</p>
|
||||
<p>
|
||||
O pedido não atribui privilégios. A confirmação é uma operação
|
||||
distinta, com MFA e auditoria. Não altera a regra de
|
||||
substituição posterior.
|
||||
</p>
|
||||
{plan.expired && (
|
||||
<p role="alert">
|
||||
Pedido expirado. Prepare novo pedido autorizado.
|
||||
</p>
|
||||
)}
|
||||
{!plan.code_current && (
|
||||
<p role="alert">
|
||||
Revisão ou destino alterados. Este pedido não pode ser
|
||||
confirmado.
|
||||
</p>
|
||||
)}
|
||||
{!plan.mfa_confirmed_in_session && (
|
||||
<p role="alert">Conclua MFA nesta sessão antes de confirmar.</p>
|
||||
)}
|
||||
{!plan.can_confirm && !done && (
|
||||
<p>Esta conta pode consultar, mas não confirmar o pedido.</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Fundamento da confirmação
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo apenas estas duas contas e esta base
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
done ||
|
||||
!plan.can_confirm ||
|
||||
!plan.mfa_confirmed_in_session ||
|
||||
!confirmed ||
|
||||
reason.length < 20
|
||||
}
|
||||
onClick={() => void confirm()}
|
||||
>
|
||||
Confirmar designação cruzada
|
||||
</button>
|
||||
<p role="status">
|
||||
{done ? 'Pedido consumido; não reinicializar. ' : ''}
|
||||
{message}
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,11 @@ type Plan = {
|
||||
holders: number[];
|
||||
version: number | null;
|
||||
rule: string;
|
||||
pending: {approval_id:string;confirmation_url:string;expires_at:string} | null;
|
||||
pending: {
|
||||
approval_id: string;
|
||||
confirmation_url: string;
|
||||
expires_at: string;
|
||||
} | null;
|
||||
};
|
||||
};
|
||||
export default function Installation(initial: Plan) {
|
||||
@@ -58,7 +62,8 @@ export default function Installation(initial: Plan) {
|
||||
? 'Schema instalado. Perfis ainda não disponibilizados; nenhuma conta ou atribuição criada.'
|
||||
: 'Schema já instalado. Nenhuma reinstalação ou duplicação.',
|
||||
);
|
||||
if (bootstrap) setConfirmationUrl(result.confirmation_url as string);
|
||||
if (bootstrap)
|
||||
setConfirmationUrl(result.confirmation_url as string);
|
||||
if (!bootstrap)
|
||||
setPlan(
|
||||
(await profileJson(
|
||||
@@ -147,7 +152,18 @@ export default function Installation(initial: Plan) {
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2>Inicialização separada dos dois superutilizadores</h2>
|
||||
<p>{plan.bootstrap.rule}</p>
|
||||
{plan.bootstrap.pending && <p>Pedido pendente até {plan.bootstrap.pending.expires_at}. <a className="underline" href={plan.bootstrap.pending.confirmation_url}>Recuperar pedido de confirmação</a>. Nenhum privilégio foi atribuído pelo pedido.</p>}
|
||||
{plan.bootstrap.pending && (
|
||||
<p>
|
||||
Pedido pendente até {plan.bootstrap.pending.expires_at}.{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href={plan.bootstrap.pending.confirmation_url}
|
||||
>
|
||||
Recuperar pedido de confirmação
|
||||
</a>
|
||||
. Nenhum privilégio foi atribuído pelo pedido.
|
||||
</p>
|
||||
)}
|
||||
{plan.bootstrap.initialized ? (
|
||||
<p>
|
||||
Dupla já inicializada:{' '}
|
||||
@@ -197,7 +213,15 @@ export default function Installation(initial: Plan) {
|
||||
)}
|
||||
</section>
|
||||
<p role="status">{message}</p>
|
||||
{confirmationUrl && <p>Endereço para o segundo titular: <a className="underline" href={confirmationUrl}>{confirmationUrl}</a>. O primeiro titular pode consultar, mas não confirmar.</p>}
|
||||
{confirmationUrl && (
|
||||
<p>
|
||||
Endereço para o segundo titular:{' '}
|
||||
<a className="underline" href={confirmationUrl}>
|
||||
{confirmationUrl}
|
||||
</a>
|
||||
. O primeiro titular pode consultar, mas não confirmar.
|
||||
</p>
|
||||
)}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,8 +7,19 @@ import { button, control } from '@/pages/management/shared';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import ProfileProofPicker from '@/components/profile-proof-picker';
|
||||
|
||||
const representations: Record<string,string> = {individual:'Em nome próprio',company:'Empresa',public_entity:'Entidade pública',association:'Associação',partner:'Parceiro ou representante'};
|
||||
const requestStates: Record<string,string> = {pending:'Em análise',approved:'Aprovado',rejected:'Devolvido ou recusado',cancelled:'Cancelado'};
|
||||
const representations: Record<string, string> = {
|
||||
individual: 'Em nome próprio',
|
||||
company: 'Empresa',
|
||||
public_entity: 'Entidade pública',
|
||||
association: 'Associação',
|
||||
partner: 'Parceiro ou representante',
|
||||
};
|
||||
const requestStates: Record<string, string> = {
|
||||
pending: 'Em análise',
|
||||
approved: 'Aprovado',
|
||||
rejected: 'Devolvido ou recusado',
|
||||
cancelled: 'Cancelado',
|
||||
};
|
||||
|
||||
type RequestEntry = {
|
||||
id: string;
|
||||
@@ -72,8 +83,9 @@ export default function RequestProfile({
|
||||
Solicitar perfil de Promotor
|
||||
</h1>
|
||||
<p>
|
||||
Indique em nome de quem vai actuar, as modalidades que pretende preparar e os comprovativos do pedido.
|
||||
Pode acompanhar a decisão nesta página. A submissão do pedido não activa o perfil.
|
||||
Indique em nome de quem vai actuar, as modalidades que pretende
|
||||
preparar e os comprovativos do pedido. Pode acompanhar a decisão
|
||||
nesta página. A submissão do pedido não activa o perfil.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-4"
|
||||
@@ -96,7 +108,9 @@ export default function RequestProfile({
|
||||
'association',
|
||||
'partner',
|
||||
].map((v) => (
|
||||
<option key={v} value={v}>{representations[v]}</option>
|
||||
<option key={v} value={v}>
|
||||
{representations[v]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -121,21 +135,29 @@ export default function RequestProfile({
|
||||
<fieldset>
|
||||
<legend>Que oportunidades pretende preparar?</legend>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{types.map((type) => (
|
||||
<label key={type} className="flex gap-2 rounded border p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(type)}
|
||||
onChange={() =>
|
||||
setSelected(toggle(selected, type))
|
||||
}
|
||||
/>{' '}
|
||||
{modalityLabels[type] ?? 'Outra modalidade'}
|
||||
</label>
|
||||
))}
|
||||
{types.map((type) => (
|
||||
<label
|
||||
key={type}
|
||||
className="flex gap-2 rounded border p-3"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(type)}
|
||||
onChange={() =>
|
||||
setSelected(toggle(selected, type))
|
||||
}
|
||||
/>{' '}
|
||||
{modalityLabels[type] ?? 'Outra modalidade'}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<ProfileProofPicker documents={documents} value={proofs} onChange={setProofs} disabled={busy} />
|
||||
<ProfileProofPicker
|
||||
documents={documents}
|
||||
value={proofs}
|
||||
onChange={setProofs}
|
||||
disabled={busy}
|
||||
/>
|
||||
{!documents.length && (
|
||||
<p>
|
||||
Sem comprovativos próprios disponíveis. Pode anexar ao
|
||||
@@ -174,7 +196,10 @@ export default function RequestProfile({
|
||||
{requests.map((r) => (
|
||||
<article key={r.id} className="border-b py-3">
|
||||
<p>
|
||||
Pedido de {new Date(r.created_at).toLocaleDateString('pt-MZ')} — {requestStates[r.status] ?? 'Estado por consultar'}
|
||||
Pedido de{' '}
|
||||
{new Date(r.created_at).toLocaleDateString('pt-MZ')}{' '}
|
||||
—{' '}
|
||||
{requestStates[r.status] ?? 'Estado por consultar'}
|
||||
</p>
|
||||
<p>
|
||||
{r.decision_reason ??
|
||||
|
||||
Reference in New Issue
Block a user