477 lines
18 KiB
TypeScript
477 lines
18 KiB
TypeScript
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;
|
|
};
|
|
};
|
|
|
|
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 [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 [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`,
|
|
),
|
|
},
|
|
);
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
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>
|
|
);
|
|
}
|