@@ -26,6 +26,7 @@ export function AppSidebar() {
|
||||
educationEnabled,
|
||||
aiEnabled,
|
||||
opportunityManagement,
|
||||
contentManagementHref,
|
||||
profileAccess,
|
||||
} = usePage<{
|
||||
auth: Auth;
|
||||
@@ -34,6 +35,7 @@ export function AppSidebar() {
|
||||
aiEnabled?: boolean;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
contentManagementHref?: string | null;
|
||||
}>().props;
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!auth.user,
|
||||
@@ -48,6 +50,9 @@ export function AppSidebar() {
|
||||
href: group.children?.find((item) => item.href)?.href ?? '/',
|
||||
icon: LayoutGrid,
|
||||
}));
|
||||
if (contentManagementHref) {
|
||||
items.unshift({ title: 'Gestão de conteúdos e oportunidades', href: contentManagementHref, icon: LayoutGrid });
|
||||
}
|
||||
if (auth.canManagePortal && opportunityManagement) {
|
||||
items.push({
|
||||
title: opportunityManagement.manage.label,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
|
||||
export default function ContentManagementEntry() {
|
||||
const { contentManagementHref } = usePage<{ contentManagementHref?: string | null }>().props;
|
||||
return contentManagementHref ? <Link className="inline-block rounded-lg border px-4 py-3 font-semibold underline" href={contentManagementHref}>Gestão de conteúdos e oportunidades</Link> : null;
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { ContextReference } from '@/lib/investor-context';
|
||||
|
||||
export default function ContextDocuments({
|
||||
@@ -6,49 +5,28 @@ export default function ContextDocuments({
|
||||
}: {
|
||||
source?: ContextReference;
|
||||
}) {
|
||||
if (!source) return null;
|
||||
if (!source?.documents?.length) return null;
|
||||
return (
|
||||
<section
|
||||
aria-label="Fonte e documentos do contexto"
|
||||
aria-label="Documentos de apoio"
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<h2 className="font-semibold">Fonte e documentos do contexto</h2>
|
||||
<p>
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>{' '}
|
||||
· versão da oportunidade {source.version ?? 'não indicada'} ·{' '}
|
||||
{source.visibility === 'private'
|
||||
? 'Preparação privada — não publicada'
|
||||
: 'Referência pública'}
|
||||
</p>
|
||||
<h2 className="font-semibold">Documentos de apoio</h2>
|
||||
{(source.documents ?? []).map((doc) => (
|
||||
<article
|
||||
key={doc.support_id}
|
||||
className="space-y-1 rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
{doc.title} · {doc.edition ?? 'Edição não indicada'} ·
|
||||
versão documental {doc.document_version} · metadados v
|
||||
{doc.metadata_version}
|
||||
{doc.title}{doc.edition ? ` · ${doc.edition}` : ''}
|
||||
</p>
|
||||
<p className="break-all">SHA256: {doc.sha256}</p>
|
||||
{doc.section && <p>Referência utilizada: {doc.section}</p>}
|
||||
<p>{doc.source_reference}</p>
|
||||
<a className="underline" href={doc.download_url}>
|
||||
Consultar original autorizado —{' '}
|
||||
Consultar documento —{' '}
|
||||
{doc.edition ?? doc.title}
|
||||
</a>
|
||||
</article>
|
||||
))}
|
||||
{!source.documents?.length && (
|
||||
<p>Sem suporte da biblioteca associado nesta versão.</p>
|
||||
)}
|
||||
<p>
|
||||
Referência guardada nesta versão do dossier. A consulta do
|
||||
original continua sujeita às permissões actuais; esta ligação
|
||||
não publica nem concede acesso adicional.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type ContextView,
|
||||
} from '@/lib/investor-context';
|
||||
import { inheritCompatibleFields } from '@/lib/context-inheritance';
|
||||
import OpportunityChoices from './investment-opportunity-choices';
|
||||
type Props = {
|
||||
contextId?: string | null;
|
||||
consumer: 'simulator' | 'land' | 'desk' | 'submission';
|
||||
@@ -27,6 +28,10 @@ const empty = (v: unknown) =>
|
||||
(Array.isArray(v) && v.length === 0);
|
||||
const text = (v: unknown) =>
|
||||
typeof v === 'string' ? v : JSON.stringify(v ?? '');
|
||||
const displayField = (values: Record<string, unknown>, key: string) =>
|
||||
key.endsWith('_id')
|
||||
? text(values[`${key}_label`]) || (empty(values[key]) ? 'não informado' : 'Referência escolhida; designação por recuperar')
|
||||
: text(values[key]) || 'não informado';
|
||||
export function DossierPrefill(props: Props) {
|
||||
const {
|
||||
contextId,
|
||||
@@ -104,7 +109,7 @@ export function DossierPrefill(props: Props) {
|
||||
),
|
||||
);
|
||||
const differences = Object.keys(source).filter(
|
||||
(k) => k !== 'context_applicability_snapshot' && text(props.values[k]) !== text(source[k]),
|
||||
(k) => k !== 'context_applicability_snapshot' && !k.endsWith('_label') && text(props.values[k]) !== text(source[k]),
|
||||
);
|
||||
const linkedRevision =
|
||||
consumer === 'simulator'
|
||||
@@ -117,39 +122,37 @@ export function DossierPrefill(props: Props) {
|
||||
aria-label="Dados do dossier neste formulário"
|
||||
>
|
||||
<h2 className="font-bold">
|
||||
Mesmo investimento · contexto v{view.context.revision}
|
||||
Dados do seu investimento
|
||||
</h2>
|
||||
<p>
|
||||
UUID {contextId} ·{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${contextId}`}
|
||||
>
|
||||
recuperar dossier
|
||||
{view.case.title}
|
||||
</Link>
|
||||
. Mestres, declarações deste formulário e conteúdo já submetido
|
||||
mantêm-se separados.
|
||||
{' · '}<Link className="underline" href={`/investimentos/${contextId}`}>Voltar ao dossier</Link>
|
||||
</p>
|
||||
<InvestmentContextAssessment contextId={contextId} raw={view.prefill.simulator?.context_applicability_snapshot} />
|
||||
{stale && (
|
||||
<p className="font-semibold" role="status">
|
||||
{linkedRevision > 0
|
||||
? `O contexto do dossier difere da revisão vinculada a este registo (v${linkedRevision}).`
|
||||
? 'Os dados do dossier mudaram desde a última análise.'
|
||||
: 'Confira os valores deste formulário para o contexto atual; não há uma revisão anterior vinculada a estas entradas.'}{' '}
|
||||
Os valores e resultados anteriores permanecem guardados;
|
||||
confira os pressupostos antes de os usar no cenário atual.
|
||||
</p>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
{Object.values(view.context.selection).map(
|
||||
(r) =>
|
||||
{consumer === 'simulator' && !!view.context.opportunity_choices?.length && <OpportunityChoices choices={view.context.opportunity_choices}/>}
|
||||
{Object.entries(view.context.selection)
|
||||
.filter(([slot]) => consumer !== 'simulator' || !view.context.opportunity_choices?.length || !['opportunity', 'territory'].includes(slot))
|
||||
.map(([, r]) =>
|
||||
r && (
|
||||
<p key={r.key}>
|
||||
Fonte disponível:{' '}
|
||||
<Link className="underline" href={r.href}>
|
||||
{r.title}
|
||||
</Link>{' '}
|
||||
· {r.kind} · v{r.version ?? 'não exposta'}. {r.key}
|
||||
</Link>
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
@@ -214,11 +217,10 @@ export function DossierPrefill(props: Props) {
|
||||
</label>
|
||||
</td>
|
||||
<td className="p-2 [overflow-wrap:anywhere]">
|
||||
{text(props.values[k]) ||
|
||||
'não informado'}
|
||||
{displayField(props.values, k)}
|
||||
</td>
|
||||
<td className="p-2 [overflow-wrap:anywhere]">
|
||||
{text(source[k]) || 'não informado'}
|
||||
{displayField(source, k)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -232,17 +234,20 @@ export function DossierPrefill(props: Props) {
|
||||
onClick={() => {
|
||||
const patch: Record<string, unknown> = {};
|
||||
for (const k of selected)
|
||||
{
|
||||
patch[k] = source[k] ?? '';
|
||||
if (`${k}_label` in source) patch[`${k}_label`] = source[`${k}_label`];
|
||||
}
|
||||
const scope = `dossier:${contextId}:${consumer}`;
|
||||
let raw = String(props.values.context_reuse ?? '');
|
||||
try {
|
||||
const metadata = JSON.parse(raw);
|
||||
if(metadata.scope === scope) {
|
||||
for(const key of selected) delete metadata.inherited?.[key];
|
||||
for(const key of Object.keys(patch)) delete metadata.inherited?.[key];
|
||||
raw=JSON.stringify(metadata);
|
||||
}
|
||||
} catch { /* Legacy metadata does not grant ownership of other fields. */ }
|
||||
const adopted=inheritCompatibleFields(scope,{...props.values,...Object.fromEntries(selected.map(key=>[key,undefined]))},patch,raw,props.allowedFields);
|
||||
const adopted=inheritCompatibleFields(scope,{...props.values,...Object.fromEntries(Object.keys(patch).map(key=>[key,undefined]))},patch,raw,props.allowedFields);
|
||||
props.onApply({...patch,...(props.persistInheritance === false ? {} : {context_reuse:adopted.metadata})}, true);
|
||||
setSelected([]);
|
||||
setReviewed(false);
|
||||
@@ -256,7 +261,7 @@ export function DossierPrefill(props: Props) {
|
||||
</button>
|
||||
</details>
|
||||
)}
|
||||
{!readOnly && reviewed && <p>Contexto v{view.context.revision} recuperado neste formulário, sem nova confirmação dos dados compatíveis. As edições locais conservam-se; as declarações e submissões formais mantêm os seus controlos próprios.</p>}
|
||||
{!readOnly && reviewed && <p>Os dados disponíveis foram recuperados. Preencha o que falta; as suas alterações conservam-se.</p>}
|
||||
<p className="text-xs">
|
||||
Associar uma referência não confirma incentivos, licenças, terra
|
||||
disponível, reserva ou autorização.
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
export type EditorialArticle = {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
author: string | null;
|
||||
body: string;
|
||||
html?: string | null;
|
||||
image_url: string | null;
|
||||
original_url: string;
|
||||
source_url?: string | null;
|
||||
published_at?: string | null;
|
||||
modified_at?: string | null;
|
||||
legacy_id?: number | null;
|
||||
image_source_url?: string | null;
|
||||
image_notice?: string | null;
|
||||
image_references?: string[];
|
||||
metadata_version?: number;
|
||||
private_preview?: boolean;
|
||||
};
|
||||
export default function EditorialReading({
|
||||
article,
|
||||
}: {
|
||||
article: EditorialArticle;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{article.private_preview && (
|
||||
<p
|
||||
role="status"
|
||||
className="rounded border border-amber-500 bg-amber-50 p-3 text-slate-900"
|
||||
>
|
||||
Prévia privada — não publica o artigo nem altera os direitos
|
||||
do original.
|
||||
</p>
|
||||
)}
|
||||
<h1 className="text-3xl font-bold">{article.title}</h1>
|
||||
{article.description && <p>{article.description}</p>}
|
||||
{article.author && <p>Autor / entidade: {article.author}</p>}
|
||||
{article.legacy_id && (
|
||||
<p>
|
||||
Arquivo do portal antigo · artigo {article.legacy_id}.
|
||||
Conteúdo editorial preservado; não corresponde por si a
|
||||
oportunidade concreta ou regra executável.
|
||||
</p>
|
||||
)}
|
||||
{(article.published_at || article.modified_at) && (
|
||||
<p>
|
||||
Origem: publicado em{' '}
|
||||
{article.published_at ?? 'data não indicada'} · modificado
|
||||
em {article.modified_at ?? 'data não indicada'}. A edição no
|
||||
portal conserva estas datas de origem.
|
||||
</p>
|
||||
)}
|
||||
{article.image_url && (
|
||||
<img
|
||||
className="max-h-96 w-full object-contain"
|
||||
src={article.image_url}
|
||||
alt={`Imagem do artigo ${article.title}`}
|
||||
/>
|
||||
)}
|
||||
{article.image_notice && (
|
||||
<p role="note" className="rounded border p-3">
|
||||
{article.image_notice}
|
||||
</p>
|
||||
)}
|
||||
{article.html ? (
|
||||
<article
|
||||
className="prose dark:prose-invert max-w-none overflow-x-auto"
|
||||
dangerouslySetInnerHTML={{ __html: article.html }}
|
||||
/>
|
||||
) : (
|
||||
<article className="space-y-5">
|
||||
{article.body.split(/\n\s*\n/).map((p, i) => (
|
||||
<p className="whitespace-pre-wrap" key={i}>
|
||||
{p}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
)}
|
||||
{!!article.image_references?.length && (
|
||||
<section aria-label="Imagens referenciadas no corpo original">
|
||||
<h2>Imagens referenciadas no corpo original</h2>
|
||||
<p>
|
||||
Referências preservadas; não confirmam um ficheiro
|
||||
disponível na biblioteca.
|
||||
</p>
|
||||
<ul>
|
||||
{article.image_references.map((url, i) => (
|
||||
<li key={url}>
|
||||
<a
|
||||
className="underline"
|
||||
href={url}
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Referência da imagem {i + 1}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
<nav aria-label="Origem do artigo" className="flex flex-wrap gap-4">
|
||||
{article.source_url && (
|
||||
<a
|
||||
className="underline"
|
||||
href={article.source_url}
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Consultar página de origem
|
||||
</a>
|
||||
)}
|
||||
{article.image_source_url && (
|
||||
<a
|
||||
className="underline"
|
||||
href={article.image_source_url}
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Referência da imagem de origem
|
||||
</a>
|
||||
)}
|
||||
<a href={article.original_url} className="underline">
|
||||
Consultar documento original
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,8 @@ export type InvestmentMapFeature = {
|
||||
};
|
||||
};
|
||||
export type InvestmentMapArea = {
|
||||
selected_territory?: boolean;
|
||||
location_type?: string;
|
||||
purpose?: string;
|
||||
geometry: GeoJsonObject;
|
||||
title: string;
|
||||
@@ -74,6 +76,13 @@ export default function InteractiveInvestmentMap({
|
||||
.addTo(instance);
|
||||
L.control.scale({ imperial: false }).addTo(instance);
|
||||
const bounds: [number, number][] = [];
|
||||
const hasSelectedBoundary = areas.some((area) => area.selected_territory);
|
||||
const administrativeLevel: Record<string, number> = {
|
||||
province: 1, district: 2, admin_post: 3, locality: 4,
|
||||
};
|
||||
const closestContextLevel = contextOnly
|
||||
? Math.max(0, ...areas.map((area) => administrativeLevel[area.location_type ?? ''] ?? 0))
|
||||
: 0;
|
||||
for (const area of areas) {
|
||||
const label = document.createElement('p');
|
||||
label.textContent = `${area.title} · ${area.purpose === 'administrative_boundary' ? 'Limite administrativo da edição indicada; não representa um local de investimento' : 'Polígono cadastrado, limites oficiais por verificar'} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
|
||||
@@ -92,7 +101,10 @@ export default function InteractiveInvestmentMap({
|
||||
.bindPopup(label)
|
||||
.addTo(instance);
|
||||
const extent = layer.getBounds();
|
||||
if (extent.isValid())
|
||||
const focusBoundary = hasSelectedBoundary
|
||||
? area.selected_territory
|
||||
: !closestContextLevel || administrativeLevel[area.location_type ?? ''] === closestContextLevel;
|
||||
if (extent.isValid() && focusBoundary)
|
||||
bounds.push(
|
||||
[extent.getSouth(), extent.getWest()],
|
||||
[extent.getNorth(), extent.getEast()],
|
||||
|
||||
@@ -61,6 +61,8 @@ export function InvestmentContextAssessment({
|
||||
if (!snapshot) return null;
|
||||
const fields = snapshot.fields ?? {};
|
||||
const zone = snapshot.zone;
|
||||
const steps = (snapshot.path?.steps ?? []).filter(step => !!step.title?.trim());
|
||||
if (!zone && !fields.investor_origin && !fields.tax_residency_country && !snapshot.preparation?.enabled) return null;
|
||||
const regime = zone?.fields?.investment_regime ?? fields.investment_regime;
|
||||
const names: Record<string, string> = {
|
||||
zee: 'ZEE',
|
||||
@@ -73,10 +75,9 @@ export function InvestmentContextAssessment({
|
||||
aria-label="Aplicabilidade ao investimento"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Aplicabilidade ao investimento · contexto v
|
||||
{snapshot.context_revision}
|
||||
Condições do investimento
|
||||
</h3>
|
||||
<p>
|
||||
{(fields.investor_origin || fields.tax_residency_country) && <p>
|
||||
Origem do investidor:{' '}
|
||||
{{
|
||||
national: 'nacional',
|
||||
@@ -84,9 +85,8 @@ export function InvestmentContextAssessment({
|
||||
mixed: 'misto',
|
||||
}[fields.investor_origin] ?? 'informação em falta'}
|
||||
. Residência fiscal declarada:{' '}
|
||||
{fields.tax_residency_country || 'informação em falta'}. Estas
|
||||
condições são distintas; uma não determina a outra.
|
||||
</p>
|
||||
{fields.tax_residency_country || 'Por preencher'}.
|
||||
</p>}
|
||||
{zone ? (
|
||||
<>
|
||||
<p>
|
||||
@@ -95,8 +95,7 @@ export function InvestmentContextAssessment({
|
||||
{names[regime ?? ''] ?? 'zona seleccionada'}.
|
||||
</strong>{' '}
|
||||
<Link className="underline" href={zone.href}>
|
||||
{zone.title} · versão {zone.version} · consultar
|
||||
ficha e fundamentos
|
||||
{zone.title} · consultar condições
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
@@ -162,39 +161,19 @@ export function InvestmentContextAssessment({
|
||||
</p>
|
||||
)}
|
||||
<p role="status">
|
||||
Benefício fiscal deste enquadramento: indeterminado. Não
|
||||
existe neste consumidor uma regra executável ligada ao
|
||||
reconhecimento e condições da zona. No simulador, o IVA
|
||||
disponível corresponde apenas ao cenário geral sem
|
||||
benefício, sobre vendas declaradas compatíveis; não
|
||||
simula o regime especial. O cenário com benefício e o
|
||||
apuramento final estão indisponíveis.
|
||||
Os benefícios desta zona ainda não estão disponíveis no simulador. O cenário geral disponível não inclui benefícios especiais nem apuramento fiscal final.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
Enquadramento geral de preparação: sem ZEE, ZFI ou parque
|
||||
seleccionado. Isso não confirma a elegibilidade para uma
|
||||
operação fiscal. O cálculo mantém o âmbito e as exclusões da
|
||||
versão publicada.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Confirmado neste quadro significa apenas dado recuperado do
|
||||
dossier; declarações e referências não são decisões jurídicas.
|
||||
Requisitos específicos não documentados permanecem
|
||||
indeterminados.
|
||||
</p>
|
||||
{snapshot.path && (
|
||||
) : null}
|
||||
{!!steps.length && (
|
||||
<details>
|
||||
<summary>
|
||||
Passos adaptados pelo percurso existente · versão{' '}
|
||||
{snapshot.path.definition_version}
|
||||
Etapas a preparar
|
||||
</summary>
|
||||
<ul className="list-disc pl-5">
|
||||
{snapshot.path.steps.map((step) => (
|
||||
{steps.map((step) => (
|
||||
<li key={step.code}>
|
||||
{step.code} — {step.title}:{' '}
|
||||
{step.title}:{' '}
|
||||
{step.context_review_required
|
||||
? 'informação alterada; rever fundamento'
|
||||
: step.applicability ===
|
||||
@@ -224,7 +203,7 @@ export function InvestmentContextAssessment({
|
||||
className="underline"
|
||||
href={`/investimentos/${contextId}/contexto/editar`}
|
||||
>
|
||||
Alterar contexto e comparar impacto antes de guardar
|
||||
Rever dados do investimento
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { TerritoryFields } from './investment-territory';
|
||||
import type { OpportunityChoice } from '@/lib/investor-context';
|
||||
import { card, input } from '@/pages/investment/shared';
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { TerritoryOption } from './investment-territory';
|
||||
|
||||
export type CorridorOption = {key:string;name:string;provinces:TerritoryOption[]};
|
||||
|
||||
function ChoiceCard({c,i,corridors,disabled,update,remove}:{c:OpportunityChoice;i:number;corridors:CorridorOption[];disabled:boolean;update:(change:Partial<OpportunityChoice>)=>void;remove?:()=>void}) {
|
||||
const [notice,setNotice]=useState('');
|
||||
const corridor=corridors.find(r=>r.key===c.corridor_key)||corridors.find(r=>r.name===c.coverage);
|
||||
const path=c.territory_path??[];
|
||||
function location(next:TerritoryOption[], key=corridor?.key) {
|
||||
update({corridor_key:key,territory_path:next,territory:next.length?{key:'territory:'+next.at(-1)!.id,kind:'territory',id:next.at(-1)!.id,title:next.map(p=>p.name).join(' / '),href:'/oportunidades',version:null,sha256:'',fields:{}}:null});
|
||||
}
|
||||
useEffect(()=>{
|
||||
if (!remove || !corridor) return;
|
||||
if (path.length && !corridor.provinces.some(p=>p.id===path[0].id)) {
|
||||
setNotice('A localização anterior foi retirada porque não pertence ao corredor escolhido. Escolha uma localização compatível.');
|
||||
location(corridor.provinces.length===1?corridor.provinces:[]);
|
||||
} else if (!path.length && corridor.provinces.length===1) {setNotice('Província seleccionada automaticamente: '+corridor.provinces[0].name+'.');location(corridor.provinces);}
|
||||
},[corridor?.key,JSON.stringify(corridor?.provinces),path[0]?.id,!!remove]);
|
||||
return <article className={card+' space-y-3'}>
|
||||
<h3 className="font-semibold"><Link className="underline" href={c.opportunity.href}>{i+1}. {c.opportunity.title}</Link></h3>
|
||||
{remove && <label className="block">Corredor para este investimento<select className={input} disabled={disabled||!corridors.length} value={corridor?.key??''} onChange={e=>{
|
||||
const next=corridors.find(r=>r.key===e.target.value);
|
||||
if(!next)return;
|
||||
const compatible=!path.length||next.provinces.some(p=>p.id===path[0].id);
|
||||
const kept=compatible?path:[];
|
||||
location(kept.length?kept:next.provinces.length===1?next.provinces:[],next.key);
|
||||
setNotice(!path.length?(next.provinces.length===1?'Província seleccionada automaticamente: '+next.provinces[0].name+'.':'Escolha uma das províncias deste corredor.'):compatible?'A localização compatível foi conservada.':'A província e os níveis territoriais incompatíveis foram retirados.');
|
||||
}}><option value="">Seleccione um corredor</option>{corridors.map(r=><option key={r.key} value={r.key}>{r.name}</option>)}</select></label>}
|
||||
{!remove&&c.coverage&&<p>Abrangência: {c.coverage}</p>}
|
||||
{notice&&<p role="status">{notice}</p>}
|
||||
<p>Localização: {c.territory?.title??'Por escolher'}</p>
|
||||
{!!c.portfolio_origins?.length && <section aria-label="Associações escolhidas"><h4 className="font-semibold">Associações escolhidas</h4><ul>{c.portfolio_origins.map(origin=><li key={origin.id}><Link className="underline" href={origin.href}>{origin.title}</Link>{remove&&<button type="button" className="ml-3 underline" disabled={disabled} onClick={()=>update({portfolio_origins:c.portfolio_origins?.filter(r=>r.id!==origin.id)})}>Retirar associação</button>}</li>)}</ul></section>}
|
||||
{remove&&<>
|
||||
<fieldset disabled={disabled}><legend>Actividades que pretende realizar nesta oportunidade</legend>{Object.entries({production:'Produção agrícola',processing:'Transformação agroindustrial',trade:'Comercialização e exportação',transport:'Transporte e logística',water:'Captação/utilização de água',forestry:'Actividade florestal',animal:'Produção/serviços pecuários'}).map(([key,label])=><label key={key} className="mr-4 inline-block"><input type="checkbox" checked={c.activities?.includes(key)??false} onChange={e=>update({activities:e.target.checked?[...(c.activities??[]),key]:(c.activities??[]).filter(x=>x!==key)})}/>{label}</label>)}</fieldset>
|
||||
<TerritoryFields initial={c.territory_path} corridor={corridor?.key} disabled={disabled} onChange={next=>location(next)}/>
|
||||
<label className="block">Motivo da alternativa territorial<textarea className={input} disabled={disabled} value={c.location_reason} onChange={e=>update({location_reason:e.target.value})}/></label>
|
||||
<label className="block"><input type="checkbox" disabled={disabled} checked={!!c.confirm_location_change} onChange={e=>update({confirm_location_change:e.target.checked})}/>Confirmo a alteração da localização anteriormente confirmada, quando existir.</label>
|
||||
<button type="button" disabled={disabled} className="underline" onClick={remove}>Retirar esta ficha da escolha</button>
|
||||
</>}
|
||||
</article>;
|
||||
}
|
||||
|
||||
export default function OpportunityChoices({choices, onChange, disabled = false, corridors=[]}: {choices: OpportunityChoice[]; onChange?: (choices: OpportunityChoice[]) => void; disabled?: boolean;corridors?:CorridorOption[]}) {
|
||||
const update = (index: number, change: Partial<OpportunityChoice>) => onChange?.(choices.map((c,i) => i === index ? {...c,...change} : c));
|
||||
return <section className="space-y-4" aria-label="Oportunidades e respectivas localizações">
|
||||
<h2 className="text-xl font-bold">Oportunidades escolhidas e localização de cada ficha</h2>
|
||||
<p>{onChange?'Escolha o corredor e confirme onde pretende realizar o investimento.':'Escolhas guardadas no dossier; cada oportunidade conserva a sua localização e associações.'}</p>
|
||||
{choices.map((c,i)=><ChoiceCard key={c.opportunity.key} c={c} i={i} corridors={corridors} disabled={disabled} update={change=>update(i,change)} remove={onChange?()=>onChange(choices.filter((_,index)=>index!==i)):undefined}/>)}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { RequirementsAssessment } from '@/lib/investor-context';
|
||||
import { card } from '@/pages/investment/shared';
|
||||
|
||||
export default function InvestmentRequirements({assessment, contextId, excludedSteps = []}: {assessment?: RequirementsAssessment | null; contextId: string; excludedSteps?: string[]}) {
|
||||
if (!assessment?.requirements.length) return null;
|
||||
const labels: Record<string,string> = {selected:'Localização escolhida; direito não inferido',missing:'Informação em falta',conditional:'Conforme as condições do projecto',declared:'Actividades declaradas; enquadrar modalidade',undetermined:'Procedimento específico por determinar'};
|
||||
const groups = new Map<string, RequirementsAssessment['requirements']>();
|
||||
for (const row of assessment.requirements) {
|
||||
if (excludedSteps.includes(row.step)) continue;
|
||||
groups.set(row.opportunity_key,[...(groups.get(row.opportunity_key)??[]),row]);
|
||||
}
|
||||
return <section className="space-y-4" aria-label="Regras e documentos por oportunidade"><h2 className="text-xl font-bold">Requisitos por oportunidade e contexto</h2>
|
||||
<p>{assessment.fiscal_notice}</p>
|
||||
{[...groups.entries()].map(([key, rows])=><details key={key} className={card}><summary className="cursor-pointer font-semibold">{rows[0].opportunity_title} · {rows.length} aspectos a conferir</summary>{rows.map(r=><article key={r.opportunity_key+':'+r.code} className="my-3 space-y-2 border-t pt-3">
|
||||
<h3 className="font-semibold">{r.title} — {r.opportunity_title}</h3><p>{labels[r.state] ?? r.state}</p><p>Entidade: {r.authority}</p><p>{r.basis}</p>
|
||||
<ul className="list-disc pl-5">{r.documents.map(d=><li key={d}>{d}</li>)}</ul>
|
||||
<a className="underline" href={r.source_url}>Consultar fundamento e procedimento</a>{' · '}<Link className="underline" href={`/investimentos/${contextId}#${r.step}`}>Preparar e acompanhar em {r.step}</Link>
|
||||
<p>{r.decision}</p>
|
||||
</article>)}</details>)}
|
||||
</section>;
|
||||
}
|
||||
@@ -189,11 +189,13 @@ export function TerritoryFields({
|
||||
onChange,
|
||||
endpoint = '/api/v1/investment/territory-options',
|
||||
disabled = false,
|
||||
corridor,
|
||||
}: {
|
||||
initial?: TerritoryOption[];
|
||||
onChange?: (path: TerritoryOption[]) => void;
|
||||
endpoint?: string;
|
||||
disabled?: boolean;
|
||||
corridor?: string | null;
|
||||
}) {
|
||||
const [path, setPath] = useState(initial);
|
||||
useEffect(() => setPath(initial), [initial]);
|
||||
@@ -219,6 +221,7 @@ export function TerritoryFields({
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={endpoint}
|
||||
corridor={corridor}
|
||||
onChange={(value) => {
|
||||
const next = replaceTerritoryPath(
|
||||
path,
|
||||
@@ -252,6 +255,7 @@ export function TerritoryLevel({
|
||||
endpoint = '/management/territory-options',
|
||||
fieldError,
|
||||
disabled = false,
|
||||
corridor,
|
||||
}: {
|
||||
index: number;
|
||||
parent: string;
|
||||
@@ -260,6 +264,7 @@ export function TerritoryLevel({
|
||||
endpoint?: string;
|
||||
fieldError?: string;
|
||||
disabled?: boolean;
|
||||
corridor?: string | null;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [page, setPage] = useState(1);
|
||||
@@ -290,6 +295,7 @@ export function TerritoryLevel({
|
||||
page: String(page),
|
||||
q: search,
|
||||
});
|
||||
if (corridor) params.set('corridor', corridor);
|
||||
const response = await fetch(`${endpoint}?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
@@ -313,7 +319,7 @@ export function TerritoryLevel({
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [index, parent, page, enabled, endpoint, retry, search]);
|
||||
}, [index, parent, page, enabled, endpoint, retry, search, corridor]);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{enabled && (
|
||||
@@ -345,7 +351,7 @@ export function TerritoryLevel({
|
||||
aria-invalid={Boolean(fieldError)}
|
||||
aria-describedby={fieldError ? `${id}-error` : undefined}
|
||||
className={control}
|
||||
disabled={!enabled || loading}
|
||||
disabled={!enabled || loading || !!error}
|
||||
value={selected?.id ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange(options.find((o) => o.id === e.target.value))
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { button, card, input } from '@/pages/investment/shared';
|
||||
|
||||
type Item = {id:number;title:string;slug:string;summary:string|null;province:string|null;district:string|null;chains:string[];stages:string[];maturity_label:string|null};
|
||||
export type CorridorGroup = {id:string;name:string;count:number;locations:string[];opportunities:Item[]};
|
||||
type Props = {groups:CorridorGroup[];selected:number[];onSelect:(id:number,checked:boolean)=>void;onCompare:(ids:number[])=>void;onClear:()=>void};
|
||||
|
||||
function Group({group,selected,onSelect}: {group:CorridorGroup} & Pick<Props,'selected'|'onSelect'>) {
|
||||
const [province,setProvince]=useState('');
|
||||
const [district,setDistrict]=useState('');
|
||||
const [chain,setChain]=useState('');
|
||||
const provinces=[...new Set(group.opportunities.map(r=>r.province).filter((s):s is string=>!!s))].sort();
|
||||
const districts=[...new Set(group.opportunities.filter(r=>!province||r.province===province).map(r=>r.district).filter((s):s is string=>!!s))].sort();
|
||||
const chains=[...new Set(group.opportunities.flatMap(r=>r.chains))].sort();
|
||||
const rows=group.opportunities.filter(r=>(!province||r.province===province)&&(!district||r.district===district)&&(!chain||r.chains.includes(chain)));
|
||||
return <section className={card+' space-y-4'} aria-label={group.name}>
|
||||
<header><h2 className="text-2xl font-bold">{group.name}</h2><p>{group.count} oportunidades publicadas</p>
|
||||
<p>{group.locations.length ? 'Localizações identificadas: '+group.locations.join(' · ') : 'Abrangência territorial por indicar.'}</p></header>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<label>Província<select className={input} value={province} onChange={e=>{setProvince(e.target.value);setDistrict('');}}><option value="">Todas as províncias</option>{provinces.map(p=><option key={p}>{p}</option>)}</select></label>
|
||||
<label>Distrito<select className={input} value={district} onChange={e=>setDistrict(e.target.value)}><option value="">Todos os distritos</option>{districts.map(d=><option key={d}>{d}</option>)}</select></label>
|
||||
<label>Cadeia de valor<select className={input} value={chain} onChange={e=>setChain(e.target.value)}><option value="">Todas as cadeias</option>{chains.map(c=><option key={c}>{c}</option>)}</select></label>
|
||||
</div>
|
||||
<p role="status">{rows.length} oportunidades com estes filtros</p>
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{rows.map(r=><article key={r.id} className="space-y-3 rounded-lg border p-4">
|
||||
<h3 className="text-lg font-semibold"><Link href={'/oportunidades/'+r.slug}>{r.title}</Link></h3>
|
||||
<p>{[r.province,r.district].filter(Boolean).join(' / ')||'Localização por escolher'}</p>
|
||||
<p>Cadeia de valor: {r.chains.join(' · ')||'Por indicar'}</p>
|
||||
{r.summary && !r.stages.includes(r.summary) && <p>{r.summary}</p>}
|
||||
<p>Etapas e actividades: {r.stages.join(' · ')||'Por indicar'}</p><p>{r.maturity_label}</p>
|
||||
<label className="flex gap-2"><input type="checkbox" checked={selected.includes(r.id)} onChange={e=>onSelect(r.id,e.target.checked)}/>Escolher para preparar investimento</label>
|
||||
<Link className="underline" href={'/oportunidades/'+r.slug}>Ver ficha</Link>
|
||||
</article>)}</div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export default function OpportunityCorridorGroups({groups,selected,onSelect,onCompare,onClear}:Props) {
|
||||
return <div className="space-y-6">
|
||||
<section className={card+' space-y-3'} aria-label="Escolhas entre corredores">
|
||||
<h2 className="text-xl font-bold">Explore por corredor e escolha onde investir</h2>
|
||||
<p>Pode escolher oportunidades de vários corredores e confirmar a localização de cada uma durante a preparação.</p>
|
||||
<p>{selected.length} oportunidades escolhidas</p>
|
||||
{!!selected.length&&<div className="flex flex-wrap gap-4"><Link className={button} href={'/investimentos/iniciar?'+selected.map(id=>'opportunities[]='+id).join('&')}>Preparar investimento com as oportunidades escolhidas</Link>
|
||||
<button className={button} disabled={selected.length>4} onClick={()=>onCompare(selected)}>Comparar as escolhidas</button>
|
||||
<button className="underline" onClick={onClear}>Limpar escolha</button>
|
||||
{selected.length>4&&<p>A comparação apresenta até quatro fichas de cada vez. Pode preparar o investimento com todas as escolhidas.</p>}</div>}
|
||||
</section>
|
||||
{groups.map(group=><Group key={group.id} group={group} selected={selected} onSelect={onSelect}/>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -48,6 +48,7 @@ export function PortalGroupedMenu() {
|
||||
existingBusinessEnabled?: boolean;
|
||||
businessReviewUrl?: string | null;
|
||||
educationEnabled?: boolean;
|
||||
procurementEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
legacyContentEnabled?: boolean;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
@@ -66,6 +67,7 @@ export function PortalGroupedMenu() {
|
||||
businesses: props.existingBusinessEnabled,
|
||||
businessReviewUrl: props.businessReviewUrl,
|
||||
education: props.educationEnabled,
|
||||
procurement: props.procurementEnabled,
|
||||
ai: props.aiEnabled,
|
||||
legacyContent: props.legacyContentEnabled,
|
||||
opportunityManagement: props.opportunityManagement,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { simulationDraftEtag } from '@/lib/simulation-draft-etag';
|
||||
import { SimulationPublishedIva, type PublishedIvaInput } from './simulation-published-iva';
|
||||
import { SimulationMonthlyIva } from './simulation-monthly-iva';
|
||||
import { inheritSimulatorFields } from '@/lib/context-inheritance';
|
||||
import { inheritSimulatorFields, reusedInvestmentValue } from '@/lib/context-inheritance';
|
||||
import { investmentLandPreparation } from '@/lib/investment-land-preparation';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
type PublicDocument,
|
||||
@@ -807,6 +809,7 @@ export function SimulationForm() {
|
||||
const canSavePersonalData = Boolean(auth?.user);
|
||||
const canAssociateDraft = Boolean(auth?.user?.email_verified_at);
|
||||
const [draft, setDraft] = useState<SimulationDraft>({});
|
||||
const [editingReused, setEditingReused] = useState<string[]>([]);
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => { if (ready) setDraft(current => inheritSimulatorFields(current)); }, [draft, ready]);
|
||||
const [contextReview, setContextReview] = useState({
|
||||
@@ -1246,7 +1249,7 @@ export function SimulationForm() {
|
||||
if (payload.data) {
|
||||
if (cancelled) return;
|
||||
draftIdRef.current = payload.data.id;
|
||||
draftEtagRef.current = response.headers.get('ETag');
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
setDraftExpiresAt(payload.data.expires_at ?? null);
|
||||
if (canSavePersonalData)
|
||||
@@ -1368,7 +1371,7 @@ export function SimulationForm() {
|
||||
if (currentDraft) {
|
||||
draftIdRef.current = currentDraft.id;
|
||||
draftEtagRef.current =
|
||||
currentResponse.headers.get('ETag');
|
||||
simulationDraftEtag(currentResponse.headers.get('ETag'));
|
||||
sessionStorage.setItem(draftIdKey, currentDraft.id);
|
||||
}
|
||||
}
|
||||
@@ -1430,7 +1433,7 @@ export function SimulationForm() {
|
||||
);
|
||||
draftIdRef.current = payload.data.id;
|
||||
setServerFieldErrors({});
|
||||
draftEtagRef.current = response.headers.get('ETag');
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
lastSavedFingerprintRef.current = fingerprint;
|
||||
sessionStorage.setItem(draftIdKey, payload.data.id);
|
||||
@@ -1591,7 +1594,7 @@ export function SimulationForm() {
|
||||
)
|
||||
throw new Error('Não foi possível abrir este dossier privado.');
|
||||
draftIdRef.current = payload.data.id;
|
||||
draftEtagRef.current = response.headers.get('ETag');
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
setDraftVersionNo(payload.data.version_no);
|
||||
setDraftExpiresAt(null);
|
||||
setSelectedAccountDraftId(payload.data.id);
|
||||
@@ -1654,7 +1657,7 @@ export function SimulationForm() {
|
||||
);
|
||||
const record = (payload as { data: ApiSimulationDraftV1 }).data;
|
||||
draftIdRef.current = record.id;
|
||||
draftEtagRef.current = response.headers.get('ETag');
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
setDraftVersionNo(record.version_no);
|
||||
setDraftExpiresAt(null);
|
||||
setSelectedAccountDraftId(record.id);
|
||||
@@ -1754,7 +1757,7 @@ export function SimulationForm() {
|
||||
(payload as { expires_at: string }).expires_at,
|
||||
);
|
||||
draftEtagRef.current =
|
||||
response.headers.get('ETag') ?? draftEtagRef.current;
|
||||
simulationDraftEtag(response.headers.get('ETag')) ?? draftEtagRef.current;
|
||||
}
|
||||
setContinueLaterSaved(true);
|
||||
setSaveStatus(
|
||||
@@ -2373,7 +2376,7 @@ export function SimulationForm() {
|
||||
);
|
||||
const draftId = draftIdValue;
|
||||
draftIdRef.current = draftId;
|
||||
draftEtagRef.current = currentResponse.headers.get('ETag');
|
||||
draftEtagRef.current = simulationDraftEtag(currentResponse.headers.get('ETag'));
|
||||
if (!draftEtagRef.current)
|
||||
throw new Error(
|
||||
'O servidor não devolveu a versão actual do rascunho. Recarregue e tente novamente.',
|
||||
@@ -2407,7 +2410,7 @@ export function SimulationForm() {
|
||||
throw new Error(
|
||||
'O servidor devolveu uma confirmação de anexação inválida.',
|
||||
);
|
||||
draftEtagRef.current = response.headers.get('ETag');
|
||||
draftEtagRef.current = simulationDraftEtag(response.headers.get('ETag'));
|
||||
const sources = payload.data?.simulation_sources;
|
||||
if (Array.isArray(sources)) setSimulationSources(sources);
|
||||
setDraft((currentDraft) => ({
|
||||
@@ -3282,6 +3285,16 @@ export function SimulationForm() {
|
||||
: 'Avalie um projecto definido. A análise fiscal acompanha os fluxos financeiros, mas não prova rentabilidade nem concede incentivos.'}
|
||||
</output>
|
||||
)}
|
||||
{current.id === 'location' && contextId && (
|
||||
<aside className="rounded border p-3" aria-label="Necessidade de terra">
|
||||
<p>{investmentLandPreparation(draft.context_applicability_snapshot).need === 'no'
|
||||
? 'Não precisa de terra neste investimento. A situação do terreno não é pedida; os valores anteriores ficam conservados.'
|
||||
: investmentLandPreparation(draft.context_applicability_snapshot).need === 'yes'
|
||||
? 'Precisa de terra neste investimento. Reveja a situação do terreno já preenchida ou indique-a quando disponível.'
|
||||
: 'Falta definir se precisa de terra. Pode guardar o rascunho e continuar sem preencher a situação do terreno.'}</p>
|
||||
<a className="underline" href={`/investimentos/${contextId}`}>Rever a necessidade de terra no dossier</a>
|
||||
</aside>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{fields.map((field) => {
|
||||
const fieldRequired =
|
||||
@@ -3294,6 +3307,16 @@ export function SimulationForm() {
|
||||
: Boolean(field.required);
|
||||
const fieldError =
|
||||
serverFieldErrors[field.key] ?? errors[field.key];
|
||||
const reused = contextId && ready && !fieldError && !editingReused.includes(`${contextId}:${field.key}`)
|
||||
? reusedInvestmentValue(`dossier:${contextId}:simulator`, field.key, draft) : null;
|
||||
if (reused !== null) return (
|
||||
<div key={field.key} id={`field-${field.key}`} className="rounded border bg-emerald-50 p-3">
|
||||
<p className="font-semibold">{field.label}</p>
|
||||
<p className="whitespace-pre-wrap [overflow-wrap:anywhere]">{reused}</p>
|
||||
<p className="text-sm">Recuperado do dossier.</p>
|
||||
<button type="button" className="underline" onClick={() => setEditingReused((keys) => [...keys, `${contextId}:${field.key}`])}>Alterar {field.label.toLocaleLowerCase('pt-MZ')}</button>
|
||||
</div>
|
||||
);
|
||||
const ivaNotes = ivaIssues.filter((issue) => issue.field === field.key).map((issue, index) => <p key={index} role="note" className="mt-1 text-sm text-amber-950">{ivaIssueText(issue)}</p>);
|
||||
if (field.options) {
|
||||
const parentKey =
|
||||
|
||||
@@ -71,6 +71,12 @@ export default function TerritoryGeometryPreview({
|
||||
? 'Limite administrativo disponível para este território.'
|
||||
: 'Sem limite administrativo acessível para este território neste perfil.'}
|
||||
</p>
|
||||
{!context.selected_geometry_available && context.areas.length > 0 && (
|
||||
<p role="note">
|
||||
O mapa mostra apenas limites dos níveis superiores como contexto.
|
||||
Estes limites não representam o território seleccionado.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
{context.context_geometry_count} limites disponíveis na
|
||||
hierarquia selecionada. São contexto administrativo, não
|
||||
@@ -93,7 +99,7 @@ export default function TerritoryGeometryPreview({
|
||||
<ul>
|
||||
{context.areas.map((area, index) => (
|
||||
<li key={index}>
|
||||
{area.title} · Fonte:{' '}
|
||||
{area.title} · {area.selected_territory ? 'Território seleccionado' : 'Contexto de nível superior'} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
</li>
|
||||
|
||||
@@ -19,6 +19,22 @@ export function inheritCompatibleFields(scope:string, values:Record<string,unkno
|
||||
const geoConflict=geo.some(key=>(!empty(values[key]) || key in previous) && signature(values[key])!==signature(source[key]) && previous[key]!==signature(values[key]));
|
||||
for(const [key,value] of Object.entries(source)) {
|
||||
if ((allowed && !allowed.includes(key)) || (empty(value) && !(key in previous))) continue;
|
||||
if (key === 'context_applicability_snapshot') {
|
||||
// Read-only assessment of the current dossier, not a deliberate form answer.
|
||||
if (signature(values[key]) !== signature(value)) patch[key] = value;
|
||||
next[key] = signature(value); inherited.push(key);
|
||||
continue;
|
||||
}
|
||||
if (key.endsWith('_label')) {
|
||||
const base = key.slice(0, -6);
|
||||
const baseOwned = previous[base] === signature(values[base]);
|
||||
const baseVacant = empty(values[base]) && !(base in previous);
|
||||
if (!(base in source) || (geo.includes(base) && geoConflict) || (!baseOwned && !baseVacant && signature(values[base]) !== signature(source[base]))) continue;
|
||||
// A label describes its identifier; it must never lag behind an adopted identifier.
|
||||
if (signature(values[key]) !== signature(value)) patch[key] = value;
|
||||
next[key] = signature(value); inherited.push(key);
|
||||
continue;
|
||||
}
|
||||
const current=values[key];
|
||||
const track = (item:unknown) => key==='parcels' ? Object.fromEntries(geo.map(field=>[field,(item as Array<Record<string,unknown>>)?.[0]?.[field] ?? ''])) : item;
|
||||
const owned=previous[key]===signature(track(current));
|
||||
@@ -42,6 +58,40 @@ export function inheritCompatibleFields(scope:string, values:Record<string,unkno
|
||||
return {patch,metadata:JSON.stringify({version:1,scope,inherited:next}),inherited,conflicts};
|
||||
}
|
||||
|
||||
/** Presentation only: a saved, unedited inherited value can be shown without asking again. */
|
||||
export function reusedInvestmentValue(scope: string, key: string, values: Record<string, unknown>): string | null {
|
||||
if (!['journey_type', 'purpose', 'project_title', 'project_summary', 'sector_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id'].includes(key)) return null;
|
||||
try {
|
||||
const metadata = JSON.parse(String(values.context_reuse ?? ''));
|
||||
if (metadata.version !== 1 || metadata.scope !== scope || empty(values[key]) || metadata.inherited?.[key] !== signature(values[key])) return null;
|
||||
if (key.endsWith('_id') || ['journey_type', 'purpose'].includes(key)) {
|
||||
const label = values[`${key}_label`];
|
||||
return typeof label === 'string' && label.trim() && metadata.inherited?.[`${key}_label`] === signature(label) ? label : null;
|
||||
}
|
||||
return typeof values[key] === 'string' ? values[key] : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** Report the lineage without changing a stored answer or disclosing the tracking hash. */
|
||||
export function investmentFieldOrigin(values: Record<string, unknown>, key: string, fallback: string): string {
|
||||
try {
|
||||
const reuse = JSON.parse(String(values.context_reuse ?? ''));
|
||||
if (reuse.version !== 1 || !/^dossier:.+:simulator$/.test(reuse.scope) || !reuse.inherited?.[key]) return fallback;
|
||||
const snapshot = JSON.parse(String(values.context_applicability_snapshot ?? ''));
|
||||
const origin = snapshot.field_provenance?.[key];
|
||||
const source = origin?.kind === 'opportunity' ? `oportunidade «${origin.title ?? 'referência guardada'}»`
|
||||
: origin?.kind === 'process_declaration' || origin?.kind === 'dossier' ? 'dados introduzidos pelo utilizador no dossier'
|
||||
: origin?.kind === 'sector' ? `catálogo sectorial «${origin.title ?? 'referência guardada'}»`
|
||||
: origin?.kind === 'territory' ? `catálogo territorial «${origin.title ?? 'referência guardada'}»`
|
||||
: origin?.kind === 'linked_simulation' ? 'simulador ligado ao mesmo dossier'
|
||||
: 'dossier de investimento';
|
||||
const version = origin?.version ? `, versão ${origin.version}` : '';
|
||||
return reuse.inherited[key] === signature(values[key])
|
||||
? `Herdado de ${source}${version}`
|
||||
: `Alterado posteriormente pelo utilizador; origem anterior: ${source}${version}`;
|
||||
} catch { return fallback; }
|
||||
}
|
||||
|
||||
export function inheritSimulatorFields<T extends Record<string,unknown>>(draft:T): T {
|
||||
const source:Record<string,unknown>={};
|
||||
const plan=draft.business_plan_snapshot ? restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot)) : null;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
export type LandPreparation = { need: 'yes' | 'no' | 'unknown'; reason: string };
|
||||
|
||||
/** Preparation decision from the same saved dossier, never evidence of a land right. */
|
||||
export function investmentLandPreparation(raw: unknown): LandPreparation {
|
||||
try {
|
||||
const snapshot = JSON.parse(String(raw ?? ''));
|
||||
if (snapshot.version !== 1) return { need: 'unknown', reason: '' };
|
||||
const decision = snapshot.land_preparation;
|
||||
if (decision && ['yes', 'no', 'unknown'].includes(decision.need))
|
||||
return { need: decision.need, reason: typeof decision.reason === 'string' ? decision.reason : '' };
|
||||
// Existing snapshots already carry S10 applicability; no reimport is required.
|
||||
const step = Array.isArray(snapshot.path?.steps) ? snapshot.path.steps.find((row: { code?: string } | null) => row?.code === 'S10') : null;
|
||||
return { need: step?.applicability === 'not_needed_for_preparation' ? 'no' : step?.applicability === 'applicable' ? 'yes' : 'unknown', reason: typeof step?.reason === 'string' ? step.reason : '' };
|
||||
} catch { return { need: 'unknown', reason: '' }; }
|
||||
}
|
||||
|
||||
export function landStatusVisible(draft: Record<string, unknown>): boolean {
|
||||
return !draft.context_applicability_snapshot || investmentLandPreparation(draft.context_applicability_snapshot).need === 'yes';
|
||||
}
|
||||
@@ -38,7 +38,26 @@ export type ContextReference = {
|
||||
visibility?: 'private' | 'public';
|
||||
state?: string | null;
|
||||
};
|
||||
export type RequirementsAssessment = {version: string; fiscal_notice: string; requirements: {opportunity_key: string; opportunity_title: string; code: string; title: string; state: string; step: string; authority: string; documents: string[]; basis: string; source_url: string; decision: string}[]};
|
||||
export type OpportunityChoice = {
|
||||
portfolio_origins?: {id:string;title:string;kind:string;href:string;version:number;sha256:string}[];
|
||||
corridor_key?: string | null;
|
||||
corridor_name?: string | null;
|
||||
allowed_provinces?: import('@/components/investment-territory').TerritoryOption[];
|
||||
activities?: string[];
|
||||
territory_path?: import('@/components/investment-territory').TerritoryOption[];
|
||||
confirm_location_change?: boolean;
|
||||
opportunity: ContextReference;
|
||||
territory: ContextReference | null;
|
||||
location_reason: string;
|
||||
location_state: string;
|
||||
coverage?: string | null;
|
||||
source?: string | null;
|
||||
source_sha256?: string | null;
|
||||
};
|
||||
export type DossierContext = {
|
||||
requirements_assessment?: RequirementsAssessment;
|
||||
opportunity_choices?: OpportunityChoice[];
|
||||
revision: number;
|
||||
selection: Partial<
|
||||
Record<
|
||||
@@ -79,6 +98,8 @@ export type ContextView = {
|
||||
notice: string;
|
||||
};
|
||||
export type ContextPlan = {
|
||||
requirements_assessment?: RequirementsAssessment;
|
||||
opportunity_choices?: OpportunityChoice[];
|
||||
private_investment?: { before: Preparation; after: Preparation } | null;
|
||||
preview_hash: string;
|
||||
version: number;
|
||||
@@ -102,8 +123,10 @@ export async function contextApi<T>(
|
||||
url: string,
|
||||
body?: unknown,
|
||||
method = 'POST',
|
||||
keepalive = false,
|
||||
): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
keepalive,
|
||||
method: body === undefined ? 'GET' : method,
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
|
||||
@@ -8,6 +8,7 @@ export type PortalNavItem = {
|
||||
children?: PortalNavItem[];
|
||||
};
|
||||
export type PortalNavAccess = {
|
||||
procurement?: boolean;
|
||||
authenticated: boolean;
|
||||
manager: boolean;
|
||||
businesses?: boolean;
|
||||
@@ -461,6 +462,7 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
),
|
||||
link('sectors', 'Sectores de investimento', '/sectores'),
|
||||
link('locations', 'Localizações', '/oportunidades?view=map'),
|
||||
...(access.procurement ? [link('procurement','Concursos e anúncios','/concursos')] : []),
|
||||
{
|
||||
id: 'related-catalogues',
|
||||
label: 'Catálogos relacionados',
|
||||
|
||||
@@ -229,8 +229,8 @@ function makeSections(
|
||||
{
|
||||
field: 'Projecto',
|
||||
value: absent(text(draft, 'project_title')),
|
||||
origin: 'Informação introduzida no dossier',
|
||||
classification: 'Declarada pelo utilizador',
|
||||
origin: rows.find(row => row[1] === 'Título')?.[3] ?? 'Informação introduzida no dossier',
|
||||
classification: 'Origem indicada no dossier',
|
||||
},
|
||||
{
|
||||
field: 'Data de geração',
|
||||
@@ -316,7 +316,16 @@ function makeSections(
|
||||
preparation.calculation_notice,
|
||||
preparation.notice,
|
||||
);
|
||||
for (const requirement of preparation.requirements ?? [])
|
||||
const omitted = (preparation.requirements ?? []).filter(
|
||||
(requirement: { state: string }) => requirement.state === 'not_applicable',
|
||||
);
|
||||
if (omitted.length)
|
||||
section?.paragraphs.push(
|
||||
`Não exigido neste contexto: ${omitted.map((requirement: { label: string; reason: string }) => `${requirement.label} (${requirement.reason})`).join('; ')}.`,
|
||||
);
|
||||
for (const requirement of preparation.requirements ?? []) {
|
||||
// Keep an explicitly associated historical document visible without requiring it again.
|
||||
if (requirement.state === 'not_applicable' && !requirement.document_id && !requirement.document) continue;
|
||||
section?.rows.push({
|
||||
field: requirement.label,
|
||||
value:
|
||||
@@ -331,6 +340,7 @@ function makeSections(
|
||||
classification:
|
||||
'Preparação informativa — simulação, sem submissão à Administração',
|
||||
});
|
||||
}
|
||||
}
|
||||
if (zone?.href)
|
||||
section?.rows.push({
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { investmentFieldOrigin } from './context-inheritance.ts';
|
||||
import { investmentLandPreparation } from './investment-land-preparation.ts';
|
||||
import { monthlyIvaInput, monthlyIvaKey, readMonthlyIvaRecord, readMonthlyIvaSettings } from './monthly-iva.ts';
|
||||
import { modeloAPurchaseReferences } from './iva-modelo-a.ts';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
@@ -686,7 +688,29 @@ export function buildProjectDossierRows(
|
||||
]);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
if (draft.context_applicability_snapshot) {
|
||||
try {
|
||||
const context = JSON.parse(String(draft.context_applicability_snapshot));
|
||||
if (context.version === 1 && Array.isArray(context.opportunity_choices)) for (const choice of context.opportunity_choices) {
|
||||
if (typeof choice?.opportunity?.title !== 'string') continue;
|
||||
rows.push(['Localização', 'Oportunidade escolhida', choice.opportunity.title, 'Referência escolhida no mesmo dossier']);
|
||||
rows.push(['Localização', 'Localização da oportunidade', typeof choice.territory?.title === 'string' ? choice.territory.title : 'Por definir', choice.opportunity.title]);
|
||||
if (Array.isArray(choice.portfolio_origins)) for (const origin of choice.portfolio_origins) {
|
||||
if (typeof origin?.title !== 'string') continue;
|
||||
rows.push(['Localização', 'Associação escolhida na carteira', origin.title, choice.opportunity.title+'; referência documental consultada, sem inferir implantação ou benefícios']);
|
||||
}
|
||||
}
|
||||
} catch { /* An unreadable context remains indeterminate; do not reconstruct associations. */ }
|
||||
const land = investmentLandPreparation(draft.context_applicability_snapshot);
|
||||
rows.push(['Localização', 'Necessidade de terra', land.need === 'no' ? 'Não' : land.need === 'yes' ? 'Sim' : 'Por definir', land.reason || 'Decisão de preparação do dossier; não comprova direitos sobre a terra']);
|
||||
if (land.need === 'yes') rows.push(['Localização', 'Situação do terreno', String(draft.land_status_label ?? ({ owned: 'Próprio', duat: 'DUAT', leased: 'Arrendado', requested: 'Pedido em curso', unknown: 'Por determinar' } as Record<string, string>)[String(draft.land_status)] ?? 'Informação em falta'), 'Informação declarada; não comprova título ou disponibilidade']);
|
||||
else rows.push(['Localização', 'Preparação do terreno', land.need === 'no' ? 'Situação do terreno não aplicável à preparação actual; valores anteriores conservados.' : 'Definir se precisa de terra; pode continuar a preparar o investimento.', 'Sem inferência de dispensa legal']);
|
||||
}
|
||||
const lineageFields: Record<string, string> = {'Título':'project_title','Resumo':'project_summary','Sector':'sector_id','Província':'province_id','Distrito':'district_id','Posto administrativo':'admin_post_id','Localidade':'locality_id'};
|
||||
return rows.map(row => {
|
||||
const key = lineageFields[row[1]];
|
||||
return key && row[2] ? [row[0], row[1], row[2], investmentFieldOrigin(draft, key, row[3])] : row;
|
||||
});
|
||||
}
|
||||
|
||||
export function exportProjectDossierCsv(
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
const levels = ['province_id', 'district_id', 'admin_post_id', 'locality_id'];
|
||||
const searchRoutes = ['/carteira', '/oportunidades', '/zonas', '/educacao'];
|
||||
|
||||
/** Carry the explicitly consulted portfolio origin and search geography into the existing preparation entry. */
|
||||
export function investmentPreparationHref(opportunity: number, pageUrl: string, origin?: string | null): string {
|
||||
const source = new URL(pageUrl, 'https://portal.invalid');
|
||||
const inherited = source.searchParams.has('catalogue_query') ? new URLSearchParams(source.searchParams.get('catalogue_query')!) : source.searchParams;
|
||||
const query = new URLSearchParams({source: `opportunity:${opportunity}`});
|
||||
if (origin) query.set('from_dossier', origin);
|
||||
for (const field of levels) if (inherited.get(field)) query.set(field, inherited.get(field)!);
|
||||
return '/investimentos/iniciar?' + query.toString();
|
||||
}
|
||||
|
||||
/** URL-scoped search context, never a saved investment or another browser tab. */
|
||||
export function searchTerritoryHref(href: string, pageUrl: string): string {
|
||||
const base = 'https://portal.invalid';
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Compression can mark the representation weak; the draft version token itself is unchanged. */
|
||||
export function simulationDraftEtag(header: string | null): string | null {
|
||||
if (header && /^W\/"sfd-[0-9a-f-]{36}-v[1-9][0-9]*"$/i.test(header)) return header.slice(2);
|
||||
return header;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { inheritSimulatorFields } from './context-inheritance.ts';
|
||||
import { landStatusVisible } from './investment-land-preparation.ts';
|
||||
import { csvCell } from './csv.js';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||
@@ -738,7 +739,7 @@ export const simulationFieldGroups: Record<
|
||||
label: 'Situação do terreno',
|
||||
options: 'land_status',
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
landStatusVisible(d) && (d.purpose !== 'simulate_only' || isInvestorProjectJourney(d)),
|
||||
},
|
||||
{
|
||||
key: 'area_required',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
@@ -51,6 +52,7 @@ export default function Dashboard({
|
||||
<Head title="Painel" />
|
||||
<h1 className="text-2xl font-semibold">Painel do portal</h1>
|
||||
<ProfileNavigation />
|
||||
<ContentManagementEntry />
|
||||
{summary ? (
|
||||
<>
|
||||
{opportunityManagement && (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, input, button, card } from '@/pages/investment/shared';
|
||||
@@ -84,6 +85,7 @@ export default function Panel({
|
||||
}, [contextTitle, form.data.title]);
|
||||
return (
|
||||
<Frame title="Balcão Virtual — acompanhamento">
|
||||
<ContentManagementEntry />
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link href="/balcao-virtual/servicos" className="underline">
|
||||
Serviços
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
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';
|
||||
@@ -25,8 +26,10 @@ export default function Catalogue({
|
||||
territorial,
|
||||
territorySelection,
|
||||
catalogueUrl,
|
||||
corridorGroups = [],
|
||||
}: {
|
||||
guides?: EducationalArticle[];
|
||||
corridorGroups?: CorridorGroup[];
|
||||
filters: Record<string, string | string[] | boolean>;
|
||||
references: References;
|
||||
results: {
|
||||
@@ -49,6 +52,13 @@ 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 []; }
|
||||
});
|
||||
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 form = useForm({
|
||||
association_type: String(filters.association_type ?? ''),
|
||||
association_target: String(filters.association_target ?? ''),
|
||||
@@ -116,6 +126,10 @@ export default function Catalogue({
|
||||
const [saved, setSaved] = useState(favourites);
|
||||
const [selected, setSelected] = useState<number[]>([]);
|
||||
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
|
||||
const comparisonRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
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[]>([]);
|
||||
const [unlocated, setUnlocated] = useState<
|
||||
@@ -411,7 +425,7 @@ export default function Catalogue({
|
||||
Alargar pesquisa (remover localização)
|
||||
</button>
|
||||
)}
|
||||
{['grid', 'list', 'map', 'combined'].map((value, i) => (
|
||||
{['grid', 'list', 'map', 'combined', 'corridors'].map((value, i) => (
|
||||
<button
|
||||
key={value}
|
||||
disabled={searchLoading || !!searchError}
|
||||
@@ -427,7 +441,7 @@ export default function Catalogue({
|
||||
);
|
||||
}}
|
||||
>
|
||||
{['Grelha', 'Lista', 'Mapa', 'Lista e mapa'][i]}
|
||||
{['Grelha', 'Lista', 'Mapa', 'Lista e mapa', 'Por corredor'][i]}
|
||||
</button>
|
||||
))}
|
||||
<a
|
||||
@@ -561,7 +575,8 @@ export default function Catalogue({
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{!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
|
||||
@@ -603,6 +618,7 @@ 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"
|
||||
@@ -639,7 +655,7 @@ export default function Catalogue({
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className="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>
|
||||
)}
|
||||
@@ -662,8 +678,9 @@ 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>}
|
||||
{comparison.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<div ref={comparisonRef} className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-left">
|
||||
<caption className="p-3 text-left font-bold">
|
||||
Comparação — montantes nas moedas de origem
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
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';
|
||||
@@ -32,9 +32,10 @@ export default function Detail({
|
||||
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>}
|
||||
<Link
|
||||
className={button}
|
||||
href={'/investimentos/iniciar?source=opportunity:' + r.id}
|
||||
href={investmentPreparationHref(r.id, page.url, dossierOrigin?.id)}
|
||||
>
|
||||
Iniciar ou continuar investimento com esta oportunidade
|
||||
</Link>
|
||||
@@ -55,14 +56,6 @@ export default function Detail({
|
||||
<p>
|
||||
{r.reference} · {r.sector?.name} · {r.province} {r.district}
|
||||
</p>
|
||||
{!r.last_validated_at && (
|
||||
<p className="rounded border border-amber-700 bg-amber-50 p-4">
|
||||
Esta ficha não regista data de validação documental.
|
||||
Confirme a origem e as condições antes de agir. Preparar uma
|
||||
manifestação expressa interesse; não confirma a oferta nem
|
||||
representa aprovação.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<ClassificationSummary rows={c.classification ?? []} />
|
||||
<TerritorialSources sources={c.source_evidence} />
|
||||
@@ -97,6 +90,9 @@ export default function Detail({
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link className={button} href={investmentPreparationHref(r.id, page.url, dossierOrigin?.id)}>
|
||||
Iniciar ou continuar o roteiro deste investimento
|
||||
</Link>
|
||||
{auth.user ? (
|
||||
<button
|
||||
className={button}
|
||||
|
||||
@@ -2,42 +2,44 @@ import ContextDocuments from '@/components/context-documents';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import { contextApi, type ContextReference } 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,
|
||||
source,
|
||||
opportunityChoices = [],
|
||||
step = null,
|
||||
entryQuery = {},
|
||||
}: {
|
||||
contexts: { id: string; title: string; version: number }[];
|
||||
source: ContextReference | null;
|
||||
opportunityChoices?: OpportunityChoice[];
|
||||
step?: string | null;
|
||||
entryQuery?: Record<string, string>;
|
||||
}) {
|
||||
const [chosen, setChosen] = useState('');
|
||||
const [title, setTitle] = useState(source?.title ?? '');
|
||||
const [title, setTitle] = useState(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 suffix = source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const sourceSuffix = opportunityChoices.length ? '?' + opportunityChoices.map(c => `opportunities[]=${encodeURIComponent(c.opportunity.id)}`).join('&') : source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const suffix = sourceSuffix ? sourceSuffix+'&selection_key='+encodeURIComponent(key)+'&'+new URLSearchParams(entryQuery).toString() : '';
|
||||
return (
|
||||
<Frame title="Iniciar ou continuar um investimento">
|
||||
{!!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
|
||||
ou benefícios.
|
||||
</p>
|
||||
<ContextDocuments source={source ?? undefined} />
|
||||
{source && (
|
||||
{source && !opportunityChoices.length && (
|
||||
<section className={card}>
|
||||
<h2 className="font-bold">Origem consultada</h2>
|
||||
<h2 className="font-bold">A sua escolha</h2>
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>
|
||||
<p>
|
||||
{source.kind} · v{source.version ?? 'não exposta'} ·{' '}
|
||||
{source.key}
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
@@ -63,14 +65,14 @@ export default function ContextStart({
|
||||
<Link
|
||||
className={button}
|
||||
href={
|
||||
step && !source
|
||||
step && !source && !opportunityChoices.length
|
||||
? `/investimentos/${chosen}#${step}`
|
||||
: `/investimentos/${chosen}/contexto/editar${suffix}`
|
||||
}
|
||||
>
|
||||
{step && !source
|
||||
{step && !source && !opportunityChoices.length
|
||||
? 'Abrir ' + step + ' no mesmo dossier'
|
||||
: 'Comparar no mesmo dossier'}
|
||||
: 'Preparar neste dossier'}
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
@@ -100,7 +102,7 @@ export default function ContextStart({
|
||||
>
|
||||
<h2 className="text-xl font-bold">Iniciar uma nova ideia</h2>
|
||||
<p>
|
||||
Utiliza o cadastro e as cinco fases/19 etapas já existentes.
|
||||
Organize a sua ideia e acompanhe a preparação do investimento.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Título do investimento
|
||||
@@ -121,7 +123,7 @@ export default function ContextStart({
|
||||
Autorizo reutilizar o meu perfil neste dossier privado.
|
||||
</label>
|
||||
<button className={button} disabled={!consent || busy}>
|
||||
Criar dossier e comparar a referência
|
||||
Criar dossier e preparar investimento
|
||||
</button>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
</form>
|
||||
|
||||
@@ -2,10 +2,9 @@ import {
|
||||
PreparationEditor,
|
||||
PreparationImpact,
|
||||
} from '@/components/private-investment-preparation';
|
||||
import { InvestmentContextAssessment } from '@/components/investment-context-assessment';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, button, card, input } from '@/pages/investment/shared';
|
||||
import {
|
||||
TerritoryFields,
|
||||
@@ -20,6 +19,10 @@ import {
|
||||
} from '@/lib/investor-context';
|
||||
import { useNavigationContext } from '@/components/navigation-context';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import OpportunityChoices from '@/components/investment-opportunity-choices';
|
||||
import InvestmentRequirements from '@/components/investment-requirements';
|
||||
import type { OpportunityChoice } from '@/lib/investor-context';
|
||||
import type { CorridorOption } from '@/components/investment-opportunity-choices';
|
||||
type Options = {
|
||||
opportunities: { key: string; title: string; kind: string }[];
|
||||
sectors: { id: number; name: string }[];
|
||||
@@ -32,36 +35,93 @@ export default function ContextEditor({
|
||||
options: initialOptions,
|
||||
source,
|
||||
territorySelection = [],
|
||||
requestedChoices = null,
|
||||
draft = null,
|
||||
entrySources = [],
|
||||
entryLocationDifferences = [],
|
||||
}: {
|
||||
initial: ContextView;
|
||||
options: Options;
|
||||
source: ContextReference | null;
|
||||
territorySelection?: TerritoryOption[];
|
||||
requestedChoices?: OpportunityChoice[] | null;
|
||||
entrySources?: string[];
|
||||
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 [choices, setChoices] = useState<OpportunityChoice[]>(requestedChoices ?? initial.context.opportunity_choices ?? []);
|
||||
const [manageChoices, setManageChoices] = useState(requestedChoices !== null || !!initial.context.opportunity_choices?.length);
|
||||
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>>>(() =>
|
||||
source
|
||||
draft?.selection ?? (source
|
||||
? {
|
||||
[source.kind === 'business' ? 'opportunity' : source.kind]:
|
||||
source.key,
|
||||
}
|
||||
: {},
|
||||
: {}),
|
||||
);
|
||||
const [declarations, setDeclarations] = useState<Record<string, string>>(
|
||||
{},
|
||||
draft?.declarations ?? {},
|
||||
);
|
||||
const [documentLinks, setDocumentLinks] = useState<
|
||||
Record<string, string | null>
|
||||
>({});
|
||||
const [replace, setReplace] = useState<string[]>([]);
|
||||
>(draft?.document_links ?? {});
|
||||
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(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({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,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 [operation, setOperation] = useState(createOperationKey);
|
||||
const [requestBody, setRequestBody] = useState<Record<
|
||||
string,
|
||||
@@ -107,6 +167,7 @@ export default function ContextEditor({
|
||||
setError('');
|
||||
setMessage('');
|
||||
const body = {
|
||||
...(manageChoices ? {opportunity_choices: choices.map(c => ({source:c.opportunity.key,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,
|
||||
@@ -134,6 +195,7 @@ export default function ContextEditor({
|
||||
async function confirm() {
|
||||
if (!plan || !requestBody) return;
|
||||
setBusy(true);
|
||||
await queue.current.catch(()=>{});
|
||||
setError('');
|
||||
try {
|
||||
await contextApi(
|
||||
@@ -148,7 +210,11 @@ export default function ContextEditor({
|
||||
const next = await contextApi<ContextView>(
|
||||
`/investimentos/${view.case.id}/contexto`,
|
||||
);
|
||||
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}`);
|
||||
setView(next);
|
||||
setChoices(next.context.opportunity_choices ?? []);
|
||||
setPreparation(next.private_investment);
|
||||
navigation.refresh();
|
||||
setChanges({});
|
||||
@@ -158,7 +224,7 @@ export default function ContextEditor({
|
||||
setPlan(null);
|
||||
setOperation(createOperationKey());
|
||||
setMessage(
|
||||
'Contexto guardado no mesmo dossier. Resultados afetados identificados para revisão; conteúdo submetido e histórico preservados.',
|
||||
'Dados guardados. Pode continuar a preparação do investimento.',
|
||||
);
|
||||
} catch (e) {
|
||||
setError(
|
||||
@@ -171,28 +237,19 @@ export default function ContextEditor({
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Frame title="Contexto do investimento">
|
||||
<InvestmentContextAssessment
|
||||
contextId={view.case.id}
|
||||
raw={view.prefill.simulator?.context_applicability_snapshot}
|
||||
/>
|
||||
<ContextDocuments source={view.context.selection.opportunity} />
|
||||
<Frame title="Preparar investimento">
|
||||
<div className="space-y-5 [overflow-wrap:anywhere]">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${view.case.id}`}
|
||||
>
|
||||
Voltar ao mesmo dossier
|
||||
Voltar ao dossier
|
||||
</Link>
|
||||
<p>
|
||||
{view.case.title} · UUID {view.case.id} · dossier v
|
||||
{view.case.version} · contexto v{view.context.revision}
|
||||
</p>
|
||||
<p className="rounded border border-emerald-300 bg-emerald-50 p-3">
|
||||
As referências apoiam a preparação. Associar uma
|
||||
oportunidade, sector ou localização não confirma incentivos,
|
||||
licença, terra disponível, reserva ou autorização.
|
||||
{view.case.title}
|
||||
</p>
|
||||
<p>Confirme as oportunidades e a localização, complete os dados disponíveis e reveja antes de guardar.</p>
|
||||
{!!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"
|
||||
@@ -210,8 +267,17 @@ 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>}
|
||||
<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);}}/>
|
||||
<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">
|
||||
Escolher referências existentes
|
||||
Dados do investimento
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label className="min-w-0 flex-1">
|
||||
@@ -241,11 +307,11 @@ export default function ContextEditor({
|
||||
</button>
|
||||
</div>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
Oportunidade
|
||||
Referência individual (sem selecção múltipla)
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
value={selected('opportunity')}
|
||||
disabled={busy}
|
||||
disabled={busy || manageChoices}
|
||||
onChange={(e) =>
|
||||
change('opportunity', e.target.value)
|
||||
}
|
||||
@@ -331,29 +397,30 @@ export default function ContextEditor({
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
ZEE, ZFI ou parque consultado
|
||||
{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}
|
||||
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>
|
||||
{options.parks.map((p) => (
|
||||
{(firstCorridor?parks:options.parks).map((p) => (
|
||||
<option key={p.id} value={'park:' + p.id}>
|
||||
{p.name} · v{p.version_no}
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<h3 className="font-semibold">
|
||||
{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}
|
||||
disabled={busy || manageChoices}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(path) =>
|
||||
change(
|
||||
@@ -367,10 +434,10 @@ export default function ContextEditor({
|
||||
{view.context.selection.territory && (
|
||||
<p>
|
||||
Referência guardada:{' '}
|
||||
{view.context.selection.territory.title} · v
|
||||
{view.context.selection.territory.version}.
|
||||
{view.context.selection.territory.title}
|
||||
</p>
|
||||
)}
|
||||
</>}
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
@@ -563,7 +630,7 @@ export default function ContextEditor({
|
||||
disabled={busy}
|
||||
onClick={() => void preview()}
|
||||
>
|
||||
Comparar impacto antes de guardar
|
||||
Rever dados antes de guardar
|
||||
</button>
|
||||
</section>
|
||||
{plan && (
|
||||
@@ -574,6 +641,8 @@ 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}/>}
|
||||
<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>
|
||||
@@ -588,10 +657,9 @@ export default function ContextEditor({
|
||||
Mantido
|
||||
</th>
|
||||
<td className="p-2">
|
||||
UUID, identidade e{' '}
|
||||
{plan.documents_preserved}{' '}
|
||||
documentos.{' '}
|
||||
{plan.maintained.map((x) => (
|
||||
{plan.maintained.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
@@ -607,7 +675,7 @@ export default function ContextEditor({
|
||||
Atualizado pela nova seleção
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.updated.map((x) => (
|
||||
{plan.updated.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
@@ -633,11 +701,7 @@ export default function ContextEditor({
|
||||
href={r.href}
|
||||
>
|
||||
{r.title}
|
||||
</Link>{' '}
|
||||
· {r.kind} · v
|
||||
{r.version ??
|
||||
'não exposta'}{' '}
|
||||
· origem {r.key}
|
||||
</Link>
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
@@ -649,14 +713,7 @@ export default function ContextEditor({
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.dependent_results.length}{' '}
|
||||
resultados financeiros acessíveis
|
||||
afetados:{' '}
|
||||
{plan.dependent_results
|
||||
.map((r) => r.id)
|
||||
.join(', ') || 'nenhum'}
|
||||
. Etapas:{' '}
|
||||
{plan.review_steps.join(', ') ||
|
||||
'nenhuma alteração de dependências'}
|
||||
resultados financeiros afectados. Etapas a rever: {plan.review_steps.length}
|
||||
. Dados já preenchidos nos
|
||||
formulários conservam-se até à sua
|
||||
conferência.
|
||||
@@ -668,12 +725,11 @@ export default function ContextEditor({
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.requests.length} pedidos e os
|
||||
snapshots, decisões e resultados
|
||||
dados, decisões e resultados
|
||||
anteriores.{' '}
|
||||
{plan.requests.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.protocol || r.id} · v
|
||||
{r.version} · {r.status}
|
||||
{r.protocol || 'Pedido guardado'}
|
||||
</p>
|
||||
))}
|
||||
</td>
|
||||
@@ -706,7 +762,7 @@ export default function ContextEditor({
|
||||
disabled={busy}
|
||||
onClick={() => void confirm()}
|
||||
>
|
||||
Confirmar e guardar o contexto
|
||||
Guardar dados do investimento
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
@@ -717,7 +773,7 @@ export default function ContextEditor({
|
||||
</h2>
|
||||
{view.results.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.id} · {r.engine} ·{' '}
|
||||
Resultado guardado —{' '}
|
||||
{r.context_state === 'review_required'
|
||||
? 'Desatualizado para o contexto atual — exige revisão/recálculo'
|
||||
: 'Guardado para o contexto indicado no dossier'}
|
||||
@@ -729,7 +785,7 @@ export default function ContextEditor({
|
||||
className="underline"
|
||||
href={'/balcao-virtual/pedidos/' + r.id}
|
||||
>
|
||||
{r.protocol || r.id}
|
||||
{r.protocol || 'Consultar pedido'}
|
||||
</Link>{' '}
|
||||
· {r.status} ·{' '}
|
||||
{r.context_state === 'historical_submission'
|
||||
|
||||
@@ -36,7 +36,7 @@ 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 consultado: {zoneSource.title} · versão {zoneSource.consulted_public_version}</h2><p>{zoneSource.notice}</p><Link className="underline" href={zoneSource.href}>Voltar à ficha pública</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{' '}
|
||||
@@ -53,7 +53,7 @@ export default function InvestmentContexts({
|
||||
<Link className="underline" href={contentSource.href}>
|
||||
{contentSource.title}
|
||||
</Link>
|
||||
. A fonte e a versão serão guardadas no dossier escolhido.
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
type Preparation,
|
||||
} from '@/components/private-investment-preparation';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import InvestmentRequirements from '@/components/investment-requirements';
|
||||
import OpportunityChoices from '@/components/investment-opportunity-choices';
|
||||
import type { DossierContext } from '@/lib/investor-context';
|
||||
import FintechInvestment, {
|
||||
type FintechView,
|
||||
@@ -117,12 +119,9 @@ function Result({ result }: { result: PathResult }) {
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Estimativa recalculada pelas fórmulas da ferramenta a partir
|
||||
das entradas guardadas, versão {result.draft_version}. Não
|
||||
dos dados preenchidos. Não
|
||||
constitui decisão de financiamento.
|
||||
</p>
|
||||
<p className="text-xs break-all">
|
||||
Evidência {result.id} · {result.engine}
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -449,16 +448,14 @@ 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">
|
||||
Contexto atual — revisão{' '}
|
||||
{path.investment_context.revision}
|
||||
As suas escolhas
|
||||
</h2>
|
||||
{Object.values(path.investment_context.selection).map(
|
||||
(ref) => (
|
||||
<p key={ref.key}>
|
||||
<Link className="underline" href={ref.href}>
|
||||
{ref.title}
|
||||
</Link>{' '}
|
||||
· versão {ref.version ?? 'não exposta'}
|
||||
</Link>
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
@@ -490,15 +487,9 @@ export default function InvestmentPath(path: Path) {
|
||||
{zone.title}
|
||||
</Link>
|
||||
<p>
|
||||
UUID {zone.zone_id} · versão consultada{' '}
|
||||
{zone.consulted_public_version} ·{' '}
|
||||
{zone.selected_at}
|
||||
</p>
|
||||
<p>{zone.notice}</p>
|
||||
<p>
|
||||
A ficha atual pode ter uma versão diferente;
|
||||
esta referência conserva a consulta registada.
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
@@ -539,6 +530,8 @@ export default function InvestmentPath(path: Path) {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!!path.investment_context?.opportunity_choices?.length && <OpportunityChoices choices={path.investment_context.opportunity_choices}/>}
|
||||
<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"
|
||||
@@ -576,15 +569,14 @@ export default function InvestmentPath(path: Path) {
|
||||
<h2 className="font-semibold">Próxima acção</h2>
|
||||
{path.next ? (
|
||||
<a className="underline" href={path.next.href}>
|
||||
{path.next.action}: {path.next.code} · {path.next.title}
|
||||
{path.next.action}: {path.next.title}
|
||||
</a>
|
||||
) : (
|
||||
<p>Reveja as pendências e o acompanhamento.</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Pode preparar etapas independentes enquanto aguarda
|
||||
informação. Percurso v{path.definition_version}; os outros
|
||||
roteiros mantêm a numeração original.
|
||||
informação. As etapas abaixo adaptam-se às suas escolhas.
|
||||
</p>
|
||||
</section>
|
||||
<nav
|
||||
@@ -693,14 +685,25 @@ export default function InvestmentPath(path: Path) {
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{Object.entries(path.phases).map(([number, label]) => (
|
||||
{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>
|
||||
<ul>
|
||||
{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>
|
||||
</section>
|
||||
)}
|
||||
{Object.entries(path.phases).filter(([number]) => path.steps.some((step) => step.phase === Number(number) && step.preparation_allowed)).map(([number, label]) => (
|
||||
<section className="space-y-3" key={number}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</h2>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number))
|
||||
.filter((step) => step.phase === Number(number) && step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
|
||||
@@ -6,7 +6,7 @@ export default function ManagementAccess({
|
||||
}: {
|
||||
registrationEnabled: boolean;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: Auth }>().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';
|
||||
@@ -29,7 +29,7 @@ export default function ManagementAccess({
|
||||
<h2 className="text-xl font-semibold">
|
||||
{!user
|
||||
? 'Preparar a sua conta'
|
||||
: auth.canManagePortal
|
||||
: contentManagementHref || auth.canManagePortal
|
||||
? 'Acesso disponível'
|
||||
: !user.email_verified_at
|
||||
? 'Verificar o seu email'
|
||||
@@ -53,6 +53,11 @@ export default function ManagementAccess({
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : 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>
|
||||
</>
|
||||
) : auth.canManagePortal ? (
|
||||
<>
|
||||
<p>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
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};
|
||||
};
|
||||
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>;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
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>;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type Entry = {
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
can_edit?: boolean;
|
||||
can_promote?: boolean;
|
||||
working_status?: string;
|
||||
draft_title?: string;
|
||||
publication?: { scope: string; label: string; public_catalog: boolean };
|
||||
@@ -232,6 +233,7 @@ 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_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ClassificationReview } from '@/components/opportunity-classification';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityContactForm from '@/components/opportunity-contact-form';
|
||||
import OpportunityCanonicalFields, {
|
||||
@@ -74,9 +75,11 @@ export default function OpportunityDraft({
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
publicationState,
|
||||
promotionHref,
|
||||
auth,
|
||||
canEditDraft = false,
|
||||
} = usePage<{
|
||||
promotionHref?: string | null;
|
||||
basePath?: string;
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
@@ -245,6 +248,15 @@ export default function OpportunityDraft({
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestã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>
|
||||
</section>
|
||||
)}
|
||||
{record && (
|
||||
<Link
|
||||
href={`/investimentos/iniciar?source=opportunity:${record.id}`}
|
||||
@@ -330,7 +342,7 @@ export default function OpportunityDraft({
|
||||
{c.organization_name ??
|
||||
c.organization_id ??
|
||||
'Âmbito individual'}{' '}
|
||||
— {c.type}
|
||||
— {modalityLabels[c.type] ?? c.type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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 = {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}[]};
|
||||
type Preview = {token: string; action: 'disclose' | 'withdraw'; projection: Projection; current: {title: string; summary: string; description: string; status: string}};
|
||||
|
||||
export default function OpportunityPromotion({record, initial, etag, publicNow, reauthenticationRequired, sectors, territories, history}: {
|
||||
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 ?? ''});
|
||||
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');}}>
|
||||
<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>
|
||||
<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>;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cloneElement, isValidElement, useId } from 'react';
|
||||
@@ -60,6 +61,7 @@ export function Management({
|
||||
return (
|
||||
<div className="space-y-6 p-4 md:p-8">
|
||||
<Head title={title} />
|
||||
<ContentManagementEntry />
|
||||
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? (
|
||||
<nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
|
||||
@@ -1,14 +1,35 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Management, Field, button, control } from '../management/shared';
|
||||
type Content = { body: string; image_resource_id: number | null };
|
||||
import EditorialReading, {
|
||||
type EditorialArticle,
|
||||
} from '@/components/editorial-reading';
|
||||
type Content = {
|
||||
body: string;
|
||||
image_resource_id: number | null;
|
||||
image_mode?: string;
|
||||
};
|
||||
export default function ArticleEditor({
|
||||
resource,
|
||||
content,
|
||||
source,
|
||||
images,
|
||||
revisions,
|
||||
}: {
|
||||
resource: { id: number; title: string; metadata_version: number };
|
||||
resource: {
|
||||
id: number;
|
||||
title: string;
|
||||
metadata_version: number;
|
||||
published: boolean;
|
||||
};
|
||||
content: Content | null;
|
||||
source?: {
|
||||
source_url?: string;
|
||||
image_source_url?: string;
|
||||
published_at?: string;
|
||||
modified_at?: string;
|
||||
legacy_id?: number;
|
||||
} | null;
|
||||
images: { id: number; title: string }[];
|
||||
revisions: {
|
||||
revision_no: number;
|
||||
@@ -16,28 +37,107 @@ export default function ArticleEditor({
|
||||
created_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
const initial = () => ({
|
||||
body: content?.body ?? '',
|
||||
image_resource_id: content?.image_resource_id
|
||||
? String(content.image_resource_id)
|
||||
: '',
|
||||
image_mode:
|
||||
content?.image_mode ??
|
||||
(content?.image_resource_id ? 'selected' : 'none'),
|
||||
metadata_version: resource.metadata_version,
|
||||
});
|
||||
const form = useForm(initial());
|
||||
const [preview, setPreview] = useState<EditorialArticle | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
form.setData(initial());
|
||||
setPreview(null);
|
||||
setError('');
|
||||
}, [resource.id, resource.metadata_version]);
|
||||
useEffect(() => {
|
||||
setPreview(null);
|
||||
}, [form.data.body, form.data.image_mode, form.data.image_resource_id]);
|
||||
const showPreview = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = document.cookie
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11);
|
||||
const response = await fetch(
|
||||
`/management/portal-services/resources/${resource.id}/article/preview`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token ?? ''),
|
||||
},
|
||||
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.',
|
||||
}));
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(data.errors ?? {})
|
||||
.flat()
|
||||
.join(' ') ||
|
||||
data.message ||
|
||||
'Não foi possível preparar a prévia.',
|
||||
);
|
||||
setPreview(data.article);
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível preparar a prévia.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Management title={`Editar artigo — ${resource.title}`}>
|
||||
<p>
|
||||
O original permanece intacto na biblioteca. Guardar o corpo
|
||||
retira a publicação até à sua ação expressa no acervo.
|
||||
O original, a origem e as versões permanecem na biblioteca.
|
||||
Guardar cria uma revisão editorial e retira a publicação até à
|
||||
sua acção expressa no acervo.
|
||||
</p>
|
||||
<p role="status">
|
||||
Revisão guardada {resource.metadata_version} ·{' '}
|
||||
{resource.published ? 'Publicado' : 'Rascunho privado'}
|
||||
</p>
|
||||
{source && (
|
||||
<p>
|
||||
Original {source.legacy_id} · publicado em{' '}
|
||||
{source.published_at} · modificado em {source.modified_at}.
|
||||
A imagem de origem mantém a sua referência mesmo quando não
|
||||
existe exemplar disponível.
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
className="max-w-3xl space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
form.put(
|
||||
`/management/portal-services/resources/${resource.id}/article`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
{!!Object.keys(form.errors).length && (
|
||||
<div role="alert">
|
||||
{Object.values(form.errors).join(' ')}
|
||||
</div>
|
||||
)}
|
||||
<Field label="Corpo do artigo" error={form.errors.body}>
|
||||
<textarea
|
||||
className={control}
|
||||
@@ -46,36 +146,93 @@ export default function ArticleEditor({
|
||||
onChange={(e) => form.setData('body', e.target.value)}
|
||||
/>
|
||||
<p>
|
||||
Texto simples. Separe os parágrafos com uma linha em
|
||||
branco.
|
||||
Texto simples, com uma linha em branco entre parágrafos.
|
||||
Se mantiver o texto original, a leitura conserva também
|
||||
a sua formatação; as correcções ficam numa edição
|
||||
separada.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Imagem da biblioteca"
|
||||
error={form.errors.image_resource_id}
|
||||
label="Tratamento da imagem"
|
||||
error={form.errors.image_mode}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.image_resource_id}
|
||||
value={form.data.image_mode}
|
||||
onChange={(e) =>
|
||||
form.setData('image_resource_id', e.target.value)
|
||||
form.setData('image_mode', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem imagem</option>
|
||||
{images.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.title}
|
||||
</option>
|
||||
))}
|
||||
<option value="original">
|
||||
Manter referência e imagem de origem disponível
|
||||
</option>
|
||||
<option value="selected">
|
||||
Escolher imagem pública da biblioteca
|
||||
</option>
|
||||
<option value="none">
|
||||
Não mostrar imagem nesta edição
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar artigo como rascunho
|
||||
</button>{' '}
|
||||
<Link className="underline" href="/management/portal-services">
|
||||
Voltar ao acervo
|
||||
</Link>
|
||||
{form.data.image_mode === 'selected' && (
|
||||
<Field
|
||||
label="Imagem da biblioteca"
|
||||
error={form.errors.image_resource_id}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.image_resource_id}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'image_resource_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione uma imagem</option>
|
||||
{images.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar artigo como rascunho
|
||||
</button>
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void showPreview()}
|
||||
>
|
||||
Pré-visualizar alterações
|
||||
</button>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/portal-services/resources/${resource.id}/article/preview`}
|
||||
>
|
||||
Ler revisão guardada
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/portal-services"
|
||||
>
|
||||
Voltar ao acervo para metadados e publicação
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{preview && (
|
||||
<section
|
||||
aria-label="Prévia das alterações"
|
||||
className="my-6 max-w-3xl rounded border p-5"
|
||||
>
|
||||
<EditorialReading article={preview} />
|
||||
</section>
|
||||
)}
|
||||
<h2>Histórico</h2>
|
||||
<ul>
|
||||
{revisions.map((r) => (
|
||||
@@ -86,8 +243,10 @@ export default function ArticleEditor({
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Título, descrição, autor e fonte são editados em Editar
|
||||
metadados no acervo.
|
||||
Título, descrição, autor, fonte, direitos e acesso são
|
||||
corrigidos em Editar metadados no acervo. Carregue e analise
|
||||
imagens na biblioteca antes de as seleccionar. Publicar continua
|
||||
a ser uma acção separada.
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
|
||||
@@ -1,42 +1,27 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
export default function Article({
|
||||
article,
|
||||
}: {
|
||||
article: {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
author: string | null;
|
||||
body: string;
|
||||
image_url: string | null;
|
||||
original_url: string;
|
||||
};
|
||||
}) {
|
||||
import EditorialReading, {
|
||||
type EditorialArticle,
|
||||
} from '@/components/editorial-reading';
|
||||
export default function Article({ article }: { article: EditorialArticle }) {
|
||||
return (
|
||||
<>
|
||||
<Head title={article.title} />
|
||||
<PortalMenu />
|
||||
<main className="mx-auto max-w-3xl space-y-6 p-6">
|
||||
<h1 className="text-3xl font-bold">{article.title}</h1>
|
||||
{article.description && <p>{article.description}</p>}
|
||||
{article.author && <p>Autor / entidade: {article.author}</p>}
|
||||
{article.image_url && (
|
||||
<img src={article.image_url} alt="Imagem do artigo" />
|
||||
)}
|
||||
<article className="space-y-5">
|
||||
{article.body.split(/\n\s*\n/).map((p, i) => (
|
||||
<p className="whitespace-pre-wrap" key={i}>
|
||||
{p}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
<Link href={article.original_url} className="underline">
|
||||
Consultar documento original
|
||||
</Link>
|
||||
<EditorialReading article={article} />
|
||||
<p>
|
||||
<Link href="/documentos" className="underline">
|
||||
Voltar à biblioteca
|
||||
<Link
|
||||
href={
|
||||
article.private_preview
|
||||
? `/management/portal-services/resources/${article.id}/article`
|
||||
: '/documentos'
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
{article.private_preview
|
||||
? 'Voltar ao editor'
|
||||
: 'Voltar à biblioteca'}
|
||||
</Link>
|
||||
</p>
|
||||
</main>
|
||||
|
||||
@@ -105,6 +105,7 @@ 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>}
|
||||
<p>
|
||||
Explore o setor e prepare a sua ideia com o contexto
|
||||
guardado no dossier.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { router, useForm, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Management, Field, control, button } from '../management/shared';
|
||||
|
||||
type DocumentFile = {
|
||||
@@ -164,7 +164,11 @@ export default function Manage({
|
||||
legacyContentEnabled = false,
|
||||
documentAccessOnly = false,
|
||||
editorialScopeOnly = false,
|
||||
managementFilters = {},
|
||||
associationOptions = {},
|
||||
}: {
|
||||
managementFilters?: {q?: string; state?: string; intent?: string};
|
||||
associationOptions?: Record<string, {value: string | number; label: string}[]>;
|
||||
legacyContentEnabled?: boolean;
|
||||
documentAccessOnly?: boolean;
|
||||
editorialScopeOnly?: boolean;
|
||||
@@ -206,12 +210,26 @@ export default function Manage({
|
||||
}) {
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [actionError, setActionError] = useState('');
|
||||
const [query, setQuery] = useState(managementFilters.q ?? '');
|
||||
const [stateFilter, setStateFilter] = useState(managementFilters.state ?? '');
|
||||
const { flash } = usePage<{flash?: {uploaded_document_id?: string}}>().props;
|
||||
const upload = useForm<{
|
||||
file: File | null;
|
||||
original_source: string;
|
||||
issuer: string;
|
||||
}>({ file: null, original_source: '', issuer: '' });
|
||||
const form = useForm<ResourceForm>(emptyResource());
|
||||
intent: string;
|
||||
}>({ file: null, original_source: '', issuer: '', intent: managementFilters.intent ?? 'document' });
|
||||
const form = useForm<ResourceForm>({...emptyResource(), ...(managementFilters.intent === 'legislation' ? {document_type: 'legislation', legislation: true} : {})});
|
||||
const chooseDocument = (id: string) => {
|
||||
const document = documents.find((item) => item.id === id);
|
||||
form.setData((current) => ({...current, document_id: id,
|
||||
issuer: current.issuer || document?.issuer || '',
|
||||
title: current.title || document?.file_name || '',
|
||||
}));
|
||||
};
|
||||
useEffect(() => {
|
||||
if (flash?.uploaded_document_id && !editingId && !form.data.document_id) chooseDocument(flash.uploaded_document_id);
|
||||
}, [flash?.uploaded_document_id]);
|
||||
const setAssociation = (
|
||||
index: number,
|
||||
key: keyof Association,
|
||||
@@ -361,6 +379,7 @@ export default function Manage({
|
||||
))}
|
||||
</section>
|
||||
<form
|
||||
id="receber"
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -420,6 +439,7 @@ export default function Manage({
|
||||
</form>
|
||||
|
||||
{!documentAccessOnly && <>
|
||||
{managementFilters.intent === 'legislation' && <p className="rounded border p-4">Nova legislação: reutilize o original, complete diploma/tipo, entidade emitente, número, datas e âmbito. Registe alterações e revogações nas associações. Publicar para consulta não activa cálculos no simulador.</p>}
|
||||
<form
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
@@ -458,9 +478,7 @@ export default function Manage({
|
||||
required
|
||||
className={control}
|
||||
value={form.data.document_id}
|
||||
onChange={(e) =>
|
||||
form.setData('document_id', e.target.value)
|
||||
}
|
||||
onChange={(e) => chooseDocument(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Seleccionar ficheiro ou registo existente
|
||||
@@ -925,6 +943,8 @@ export default function Manage({
|
||||
'document',
|
||||
'investment_type',
|
||||
'legal_source',
|
||||
'sector',
|
||||
'opportunity',
|
||||
'requirement',
|
||||
]
|
||||
.filter(
|
||||
@@ -934,8 +954,8 @@ export default function Manage({
|
||||
requirementAssociationsEnabled,
|
||||
)
|
||||
.map((v) => (
|
||||
<option key={v}>
|
||||
{v}
|
||||
<option key={v} value={v}>
|
||||
{({theme:'Tema', module:'Módulo',activity:'Actividade',stage:'Etapa',procedure:'Procedimento',entity:'Entidade',territory:'Território',document:'Documento / diploma',investment_type:'Modalidade de investimento',legal_source:'Fonte legal',requirement:'Requisito',sector:'Sector',opportunity:'Oportunidade'} as Record<string,string>)[v] ?? v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -974,6 +994,12 @@ export default function Manage({
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
) : associationOptions[association.target_type] ? (
|
||||
<select className={control} required value={association.target_key} onChange={(e) => setAssociation(index, 'target_key', e.target.value)}>
|
||||
<option value="">Seleccione um registo existente</option>
|
||||
{association.target_key && !associationOptions[association.target_type].some((o) => String(o.value) === association.target_key) && <option value={association.target_key}>Referência histórica guardada</option>}
|
||||
{associationOptions[association.target_type].map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
required
|
||||
@@ -1221,13 +1247,20 @@ export default function Manage({
|
||||
</section>
|
||||
)}
|
||||
|
||||
<h2 className="text-xl font-bold">
|
||||
<h2 id="conteudos" className="text-xl font-bold">
|
||||
Registos, pendências e duplicados por rever
|
||||
</h2>
|
||||
<form className="flex flex-wrap gap-3 rounded border p-4" aria-label="Pesquisar conteúdos" onSubmit={(e) => {e.preventDefault(); router.get('/management/portal-services', {q:query,state:stateFilter}, {preserveState:true,preserveScroll:true});}}>
|
||||
<Field label="Pesquisar título, ficheiro, número ou entidade"><input className={control} value={query} onChange={(e) => setQuery(e.target.value)} /></Field>
|
||||
<Field label="Estado do conteúdo"><select className={control} value={stateFilter} onChange={(e) => setStateFilter(e.target.value)}><option value="">Todos</option><option value="draft">Rascunhos</option><option value="published">Publicados</option><option value="withdrawn">Retirados</option></select></Field>
|
||||
<button className={button}>Pesquisar conteúdos</button>
|
||||
</form>
|
||||
<p>Mostram-se até 200 registos por pesquisa. Refine o título ou o estado para localizar conteúdos anteriores.</p>
|
||||
{!resources.length && <p role="status">Sem conteúdos correspondentes no seu âmbito de acesso.</p>}
|
||||
{resources.map((r) => (
|
||||
<article key={r.id} className="space-y-3 rounded border p-4">
|
||||
<h3 className="font-bold">
|
||||
{r.title} · {r.published ? 'Publicado' : 'Rascunho'}
|
||||
{r.title} · {r.published ? 'Publicado' : r.revisions.some((v) => ['unpublished', 'withdrawn'].includes(v.change_type)) ? 'Retirado' : 'Rascunho'}
|
||||
</h3>
|
||||
<p>
|
||||
Ficheiro: {r.file_name} · {r.file_status} ·{' '}
|
||||
@@ -1352,6 +1385,7 @@ export default function Manage({
|
||||
>
|
||||
Editar artigo
|
||||
</a>
|
||||
<a className={button} href={`/management/portal-services/resources/${r.id}/article/preview`}>Ler / pré-visualizar artigo</a>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
|
||||
@@ -0,0 +1,832 @@
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
Field,
|
||||
control,
|
||||
labels,
|
||||
acts,
|
||||
NoticeContent,
|
||||
type Draft,
|
||||
type Lot,
|
||||
type Attachment,
|
||||
type Payload,
|
||||
} from './shared';
|
||||
type Choice = {
|
||||
id: string | number;
|
||||
name?: string;
|
||||
title?: string;
|
||||
location_type?: string;
|
||||
published?: boolean;
|
||||
malware_scan_status?: string;
|
||||
};
|
||||
type References = {
|
||||
regimes: Record<string, string>;
|
||||
acts: Record<string, string>;
|
||||
organizations: Choice[];
|
||||
sectors: Choice[];
|
||||
territories: Choice[];
|
||||
opportunities: Choice[];
|
||||
projects: Choice[];
|
||||
documents: Choice[];
|
||||
};
|
||||
type RecordData = {
|
||||
id: string;
|
||||
version: number;
|
||||
draft: Draft;
|
||||
published: boolean;
|
||||
};
|
||||
type Plan = {
|
||||
id: string;
|
||||
version: number;
|
||||
act: string;
|
||||
payload: Payload;
|
||||
hash: string;
|
||||
};
|
||||
const dates = [
|
||||
'origin_published_at',
|
||||
'clarifications_at',
|
||||
'deadline',
|
||||
'opening_at',
|
||||
];
|
||||
const groups: [string, string[]][] = [
|
||||
[
|
||||
'Identificação e objecto',
|
||||
['title', 'reference', 'modality', 'object', 'quantities'],
|
||||
],
|
||||
[
|
||||
'Regime e financiamento',
|
||||
[
|
||||
'financier',
|
||||
'instrument',
|
||||
'edition',
|
||||
'rule_source',
|
||||
'financing_agreement',
|
||||
],
|
||||
],
|
||||
['Participação', ['eligibility', 'requirements', 'proposal_validity']],
|
||||
[
|
||||
'Calendário e entrega',
|
||||
[
|
||||
'origin_published_at',
|
||||
'clarifications_at',
|
||||
'deadline',
|
||||
'opening_at',
|
||||
'delivery_channel',
|
||||
'delivery_address',
|
||||
'delivery_url',
|
||||
],
|
||||
],
|
||||
['Divulgação e contacto', ['origin_url', 'dissemination']],
|
||||
];
|
||||
export default function Edit({
|
||||
record,
|
||||
references,
|
||||
history,
|
||||
}: {
|
||||
record: RecordData | null;
|
||||
references: References;
|
||||
history: {
|
||||
version: number;
|
||||
act: string;
|
||||
reason: string;
|
||||
actor_id: number;
|
||||
published_at: string | null;
|
||||
created_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const empty: Draft = {
|
||||
timezone: 'Africa/Maputo',
|
||||
lots: [],
|
||||
attachments: [],
|
||||
contact_authorized: false,
|
||||
};
|
||||
const form = useForm({
|
||||
version: record?.version ?? 0,
|
||||
reason: '',
|
||||
draft: record?.draft ?? empty,
|
||||
});
|
||||
const [act, setAct] = useState(
|
||||
record?.published ? 'clarification' : 'initial',
|
||||
);
|
||||
const [preview, setPreview] = useState<Plan | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [saved, setSaved] = useState(true);
|
||||
useEffect(() => {
|
||||
form.setData({
|
||||
version: record?.version ?? 0,
|
||||
reason: '',
|
||||
draft: record?.draft ?? empty,
|
||||
});
|
||||
setPreview(null);
|
||||
setSaved(true);
|
||||
}, [record?.id, record?.version]); // A server version is the recovery boundary.
|
||||
const change = (key: string, value: Draft[string]) => {
|
||||
form.setData('draft', { ...form.data.draft, [key]: value });
|
||||
setPreview(null);
|
||||
setSaved(false);
|
||||
};
|
||||
const value = (key: string) => String(form.data.draft[key] ?? '');
|
||||
const select = (key: string, label: string, choices: Choice[]) => (
|
||||
<Field label={label}>
|
||||
<select
|
||||
className={control}
|
||||
value={value(key)}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
key,
|
||||
e.target.value
|
||||
? key === 'sector_id' || key === 'opportunity_id'
|
||||
? Number(e.target.value)
|
||||
: e.target.value
|
||||
: null,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{choices.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name ?? o.title}
|
||||
{o.location_type ? ` · ${o.location_type}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
);
|
||||
const input = (key: string, label?: string) => (
|
||||
<Field key={key} label={label ?? labels[key] ?? key}>
|
||||
{dates.includes(key) ? (
|
||||
<input
|
||||
type="datetime-local"
|
||||
className={control}
|
||||
value={value(key)}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<textarea
|
||||
className={control}
|
||||
rows={key === 'object' ? 4 : 2}
|
||||
value={value(key)}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
);
|
||||
const lots = (form.data.draft.lots ?? []) as Lot[];
|
||||
const attachments = (form.data.draft.attachments ?? []) as Attachment[];
|
||||
const makePreview = async () => {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const token = document.cookie
|
||||
.split('; ')
|
||||
.find((v) => v.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11);
|
||||
const response = await fetch(
|
||||
`/management/concursos/${record!.id}/previa`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token ?? ''),
|
||||
},
|
||||
body: JSON.stringify({ act }),
|
||||
},
|
||||
);
|
||||
const body = await response.json();
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(body.errors ?? {})
|
||||
.flat()
|
||||
.join(' ') ||
|
||||
body.message ||
|
||||
'Não foi possível preparar a prévia.',
|
||||
);
|
||||
setPreview(body);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error ? error.message : 'Erro de ligação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Frame
|
||||
title={record ? 'Editar concurso/anúncio' : 'Novo concurso/anúncio'}
|
||||
>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className="underline" href="/management/concursos">
|
||||
Recuperar concursos
|
||||
</Link>
|
||||
<Link className="underline" href="/gestao-conteudos">
|
||||
Entrada única de gestão
|
||||
</Link>
|
||||
<a
|
||||
className="underline"
|
||||
href="/management/portal-services?intent=document#receber"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Carregar / gerir documentos e scan na biblioteca (outra
|
||||
página)
|
||||
</a>
|
||||
<button
|
||||
className="underline"
|
||||
type="button"
|
||||
onClick={() => router.reload({ only: ['references'] })}
|
||||
>
|
||||
Actualizar opções da biblioteca
|
||||
</button>
|
||||
</div>
|
||||
<p>
|
||||
Os campos destinam-se à divulgação após revisão da prévia,
|
||||
excepto as notas internas, os anexos não públicos e o contacto
|
||||
sem autorização. O vínculo a um cadastro privado não publica os
|
||||
seus dados.
|
||||
</p>
|
||||
<p>
|
||||
O rascunho pode ficar incompleto. Alterações guardadas não
|
||||
substituem o acto público; reveja a prévia e publique
|
||||
explicitamente. Publicar concurso não publica a oportunidade nem
|
||||
recebe propostas.
|
||||
</p>
|
||||
<p role="status">
|
||||
{record
|
||||
? `Versão guardada ${record.version}. ${saved ? 'Preparação recuperada do servidor.' : 'Há alterações por guardar.'}`
|
||||
: 'Preparação ainda não guardada.'}
|
||||
</p>
|
||||
{!!Object.keys(form.errors).length && (
|
||||
<div role="alert">
|
||||
{Object.values(form.errors).map((error, i) => (
|
||||
<p key={i}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setPreview(null);
|
||||
record
|
||||
? form.put(`/management/concursos/${record.id}`)
|
||||
: form.post('/management/concursos');
|
||||
}}
|
||||
>
|
||||
<section className={`${card} grid gap-3 md:grid-cols-2`}>
|
||||
{select(
|
||||
'organization_id',
|
||||
'Entidade contratante existente',
|
||||
references.organizations,
|
||||
)}
|
||||
{select(
|
||||
'opportunity_id',
|
||||
'Oportunidade relacionada existente',
|
||||
references.opportunities,
|
||||
)}
|
||||
{select(
|
||||
'project_id',
|
||||
'Projecto existente',
|
||||
references.projects,
|
||||
)}
|
||||
{select('sector_id', 'Sector', references.sectors)}
|
||||
{select(
|
||||
'territory_id',
|
||||
'Localização existente',
|
||||
references.territories,
|
||||
)}
|
||||
<p>
|
||||
Os vínculos reutilizam os cadastros; não criam nova
|
||||
entidade, oportunidade, projecto ou limite. Referências
|
||||
privadas não são transformadas em conteúdo público.
|
||||
</p>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Regime do procedimento
|
||||
</h2>
|
||||
<Field label="Regime">
|
||||
<select
|
||||
className={control}
|
||||
value={value('regime')}
|
||||
onChange={(e) => change('regime', e.target.value)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Object.entries(references.regimes).map(
|
||||
([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
{value('regime') === 'state' ? (
|
||||
<>
|
||||
<p>
|
||||
Contratação do Estado: identifique a modalidade,
|
||||
o instrumento e a edição aplicáveis.{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href="https://www.ufsa.gov.mz/divnovoreg.php"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
UFSA — Decreto n.º 79/2022
|
||||
</a>
|
||||
. A referência não atribui automaticamente
|
||||
requisitos ou prazos a todos os procedimentos.
|
||||
</p>
|
||||
{input(
|
||||
'responsible_unit',
|
||||
'UGEA / unidade responsável quando aplicável',
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{value('regime') === 'external' ? (
|
||||
<>
|
||||
<a
|
||||
className="underline"
|
||||
href="https://www.worldbank.org/ext/en/what-we-do/project-procurement/framework"
|
||||
>
|
||||
Quadro e documentos normalizados do
|
||||
Banco Mundial
|
||||
</a>{' '}
|
||||
são referências; indique a edição e o
|
||||
acordo efectivamente aplicáveis.
|
||||
</>
|
||||
) : (
|
||||
'Use as regras documentadas da entidade e deste procedimento.'
|
||||
)}{' '}
|
||||
UGEA, Cadastro Único, garantias e abertura
|
||||
pública não são impostos a este regime.
|
||||
</p>
|
||||
{input(
|
||||
'responsible_unit',
|
||||
'Unidade responsável (quando aplicável)',
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Field label="Obras, bens ou serviços">
|
||||
<select
|
||||
className={control}
|
||||
value={value('object_kind')}
|
||||
onChange={(e) =>
|
||||
change('object_kind', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Object.entries({
|
||||
works: 'Obras',
|
||||
goods: 'Bens',
|
||||
services: 'Serviços',
|
||||
mixed: 'Misto',
|
||||
other: 'Outro',
|
||||
}).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</section>
|
||||
{groups.map(([title, fields]) => (
|
||||
<section className={card} key={title}>
|
||||
<h2 className="mb-3 text-xl font-semibold">{title}</h2>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{fields.map((key) =>
|
||||
input(
|
||||
key,
|
||||
key === 'title'
|
||||
? 'Título do concurso/anúncio'
|
||||
: undefined,
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Garantias e prazo mínimo documentado
|
||||
</h2>
|
||||
<Field label="Garantias exigidas neste procedimento">
|
||||
<select
|
||||
className={control}
|
||||
value={value('guarantee_status')}
|
||||
onChange={(e) =>
|
||||
change('guarantee_status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Por determinar nos documentos
|
||||
</option>
|
||||
<option value="required">
|
||||
Exigidas nos documentos
|
||||
</option>
|
||||
<option value="not_required">Não exigidas</option>
|
||||
</select>
|
||||
</Field>
|
||||
{value('guarantee_status') === 'required' &&
|
||||
input('guarantees')}
|
||||
<Field label="Fuso horário IANA do procedimento">
|
||||
<input
|
||||
className={control}
|
||||
value={value('timezone')}
|
||||
onChange={(e) => change('timezone', e.target.value)}
|
||||
placeholder="Africa/Maputo"
|
||||
/>
|
||||
</Field>
|
||||
<p>
|
||||
As datas e horas introduzidas pertencem a este fuso.
|
||||
Publicação no InvesteMoz é registada separadamente pelo
|
||||
servidor; não reinicia o prazo.
|
||||
</p>
|
||||
<Field label="Prazo mínimo documentado em dias (opcional)">
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min="0"
|
||||
value={value('minimum_days')}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'minimum_days',
|
||||
e.target.value === ''
|
||||
? null
|
||||
: Number(e.target.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{form.data.draft.minimum_days !== null &&
|
||||
form.data.draft.minimum_days !== undefined && (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{input('minimum_source')}
|
||||
{input('minimum_edition')}
|
||||
{input('minimum_modality')}
|
||||
<Field label="Contagem documentada">
|
||||
<select
|
||||
className={control}
|
||||
value={value('minimum_day_basis')}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'minimum_day_basis',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
<option value="calendar">
|
||||
Dias corridos
|
||||
</option>
|
||||
<option value="business">
|
||||
Dias úteis — calendário documentado
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
{value('minimum_day_basis') === 'business' && (
|
||||
<>
|
||||
{input(
|
||||
'minimum_calendar_source',
|
||||
'Fonte do calendário aplicável e abrangência de feriados',
|
||||
)}
|
||||
{input(
|
||||
'minimum_working_days',
|
||||
'Dias de trabalho documentados: 1=segunda a 7=domingo, separados por vírgula',
|
||||
)}
|
||||
{input(
|
||||
'minimum_holidays',
|
||||
'Feriados / exclusões documentados (AAAA-MM-DD, separados por espaço ou vírgula)',
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p>
|
||||
Sem prazo parametrizado não é presumido um mínimo geral.
|
||||
A contagem em dias úteis usa exclusivamente os dias de
|
||||
trabalho e exclusões do calendário documentado neste
|
||||
registo; não adopta um calendário nacional por
|
||||
suposição.
|
||||
</p>
|
||||
</section>
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">Lotes</h2>
|
||||
{lots.map((lot, i) => (
|
||||
<fieldset
|
||||
className="grid gap-3 rounded border p-3 md:grid-cols-3"
|
||||
key={i}
|
||||
>
|
||||
<legend>Lote {i + 1}</legend>
|
||||
{(
|
||||
['code', 'description', 'quantities'] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
code: 'Referência do lote',
|
||||
description: 'Objecto do lote',
|
||||
quantities: 'Quantidades do lote',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={lot[key]}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'lots',
|
||||
lots.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
[key]: e.target
|
||||
.value,
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
change(
|
||||
'lots',
|
||||
lots.filter((_, n) => n !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar lote do rascunho
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
change('lots', [
|
||||
...lots,
|
||||
{ code: '', description: '', quantities: '' },
|
||||
])
|
||||
}
|
||||
>
|
||||
Acrescentar lote
|
||||
</button>
|
||||
</section>
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Documentos e anexos
|
||||
</h2>
|
||||
<p>
|
||||
Carregue e classifique os originais na biblioteca
|
||||
existente pelo link acima. Reutilize-os aqui: anúncio,
|
||||
caderno, termos de referência, formulários, anexos ou
|
||||
comprovativos. Publicar exige que cada anexo marcado
|
||||
público já esteja autorizado, publicado e com scan limpo
|
||||
na biblioteca. Os restantes ficam privados no cadastro.
|
||||
</p>
|
||||
{attachments.map((item, i) => (
|
||||
<fieldset
|
||||
key={i}
|
||||
className="space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend>Anexo {i + 1}</legend>
|
||||
<Field label={`Documento do anexo ${i + 1}`}>
|
||||
<select
|
||||
className={control}
|
||||
value={item.resource_id || ''}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
resource_id: Number(
|
||||
e.target.value,
|
||||
),
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione da biblioteca
|
||||
</option>
|
||||
{references.documents.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.title} · {d.malware_scan_status}{' '}
|
||||
·{' '}
|
||||
{d.published
|
||||
? 'publicado'
|
||||
: 'privado / rascunho'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label={`Finalidade do anexo ${i + 1}`}>
|
||||
<input
|
||||
className={control}
|
||||
value={item.purpose}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
purpose:
|
||||
e.target.value,
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={item.public}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.map((r, n) =>
|
||||
n === i
|
||||
? {
|
||||
...r,
|
||||
public: e.target
|
||||
.checked,
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
Incluir este anexo na divulgação pública
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="ml-3 underline"
|
||||
onClick={() =>
|
||||
change(
|
||||
'attachments',
|
||||
attachments.filter((_, n) => n !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar anexo do rascunho
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
change('attachments', [
|
||||
...attachments,
|
||||
{ resource_id: 0, purpose: '', public: false },
|
||||
])
|
||||
}
|
||||
>
|
||||
Reutilizar documento
|
||||
</button>
|
||||
</section>
|
||||
<section className={`${card} space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Contacto e acto a divulgar
|
||||
</h2>
|
||||
{input('public_contact')}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(
|
||||
form.data.draft.contact_authorized,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
change('contact_authorized', e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Contacto autorizado para divulgação pública
|
||||
</label>
|
||||
{input('result')}
|
||||
{input(
|
||||
'public_reason',
|
||||
'Motivo público do acto — aparece na prévia e no histórico público',
|
||||
)}
|
||||
{input(
|
||||
'internal_notes',
|
||||
'Notas internas — nunca incluídas na divulgação',
|
||||
)}
|
||||
<Field label="Motivo interno da gravação (20–1000 caracteres)">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
</section>
|
||||
</form>
|
||||
{record && (
|
||||
<section className={`${card} my-5 space-y-3`}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Pré-visualizar e publicar
|
||||
</h2>
|
||||
<Field label="Acto a publicar">
|
||||
<select
|
||||
className={control}
|
||||
value={act}
|
||||
onChange={(e) => {
|
||||
setAct(e.target.value);
|
||||
setPreview(null);
|
||||
}}
|
||||
>
|
||||
{Object.entries(references.acts).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={!saved || busy}
|
||||
onClick={makePreview}
|
||||
>
|
||||
Preparar prévia pública
|
||||
</button>
|
||||
<p>
|
||||
Guarde antes da prévia. Uma prorrogação identifica o
|
||||
prazo anterior e o novo; o fim do prazo não é
|
||||
adjudicação.
|
||||
</p>
|
||||
{message && <p role="alert">{message}</p>}
|
||||
{preview && (
|
||||
<div className="space-y-3 rounded border p-4">
|
||||
<h3 className="text-xl font-semibold">
|
||||
Prévia do conteúdo público — {acts[preview.act]}
|
||||
</h3>
|
||||
<p>
|
||||
Motivo público:{' '}
|
||||
{String(preview.payload.public_reason)}
|
||||
</p>
|
||||
<NoticeContent p={preview.payload} />
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/management/concursos/${record.id}/publicar`,
|
||||
{
|
||||
act: preview.act,
|
||||
hash: preview.hash,
|
||||
reason: String(
|
||||
preview.payload.public_reason,
|
||||
),
|
||||
},
|
||||
{ onSuccess: () => setPreview(null) },
|
||||
)
|
||||
}
|
||||
>
|
||||
Publicar este acto
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{record.published && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`/concursos/${record.id}`}
|
||||
>
|
||||
Consultar anúncio público
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Histórico de preparação e publicação
|
||||
</h2>
|
||||
{history.map((v) => (
|
||||
<p key={v.version}>
|
||||
Versão {v.version} ·{' '}
|
||||
{v.act === 'draft' ? 'Rascunho' : acts[v.act]} ·
|
||||
responsável {v.actor_id} ·{' '}
|
||||
{v.published_at ?? v.created_at} · {v.reason}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { Field, control, states, type Publication } from './shared';
|
||||
type Choice = { id: string; name: string };
|
||||
export default function Index({
|
||||
items,
|
||||
filters,
|
||||
options,
|
||||
regimes,
|
||||
management,
|
||||
}: {
|
||||
items: {
|
||||
data: { id: string; publication: Publication; state: string }[];
|
||||
current_page: number;
|
||||
links: { url: string | null; label: string; active: boolean }[];
|
||||
};
|
||||
filters: Record<string, string>;
|
||||
options: Record<string, Choice[]>;
|
||||
regimes: Record<string, string>;
|
||||
management: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
entity: filters.entity ?? '',
|
||||
sector: filters.sector ?? '',
|
||||
territory: filters.territory ?? '',
|
||||
modality: filters.modality ?? '',
|
||||
financier: filters.financier ?? '',
|
||||
state: filters.state ?? '',
|
||||
deadline_before: filters.deadline_before ?? '',
|
||||
regime: filters.regime ?? '',
|
||||
});
|
||||
const query = new URLSearchParams(
|
||||
Object.entries({ ...filters, page: String(items.current_page) }).filter(
|
||||
([, v]) => v != null && v !== '',
|
||||
),
|
||||
).toString();
|
||||
return (
|
||||
<Frame title="Concursos e anúncios">
|
||||
<p>
|
||||
Procedimentos e actos divulgados pelas entidades responsáveis.
|
||||
Uma oportunidade divulgada não é, por si, um concurso aberto.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className="underline" href="/concursos/acompanhar">
|
||||
Os concursos que acompanho
|
||||
</Link>
|
||||
{management && (
|
||||
<Link className={button} href="/management/concursos">
|
||||
Gerir concursos e anúncios
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className={`${card} grid gap-3 md:grid-cols-3`}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get('/concursos', { preserveState: true });
|
||||
}}
|
||||
>
|
||||
<Field label="Palavras-chave">
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.q}
|
||||
onChange={(e) => form.setData('q', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
'entity',
|
||||
'sector',
|
||||
'territory',
|
||||
'modality',
|
||||
'financier',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
entity: 'Entidade',
|
||||
sector: 'Sector',
|
||||
territory: 'Localização',
|
||||
modality: 'Modalidade',
|
||||
financier: 'Financiador',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{(options[key] ?? []).map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Regime">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.regime}
|
||||
onChange={(e) => form.setData('regime', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(regimes).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.state}
|
||||
onChange={(e) => form.setData('state', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(states).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Prazo até (data local do procedimento)">
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
value={form.data.deadline_before}
|
||||
onChange={(e) =>
|
||||
form.setData('deadline_before', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
{!items.data.length && (
|
||||
<p role="status">Nenhum anúncio corresponde aos filtros.</p>
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{items.data.map((item) => (
|
||||
<article key={item.id} className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/concursos/${item.id}${query ? '?' + query : ''}`}
|
||||
>
|
||||
{String(item.publication.payload.title)}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{String(item.publication.payload.organization_name)}{' '}
|
||||
· {states[item.state]}
|
||||
</p>
|
||||
<p>
|
||||
Entrega:{' '}
|
||||
{String(item.publication.payload.deadline).replace(
|
||||
'T',
|
||||
' ',
|
||||
)}{' '}
|
||||
· {String(item.publication.payload.timezone)}
|
||||
</p>
|
||||
<p>{String(item.publication.payload.object)}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<nav aria-label="Paginação">
|
||||
{items.links.map((link, i) =>
|
||||
link.url ? (
|
||||
<Link
|
||||
key={i}
|
||||
className={`mx-2 underline ${link.active ? 'font-bold' : ''}`}
|
||||
href={link.url}
|
||||
>
|
||||
{link.label
|
||||
.replace('«', '«')
|
||||
.replace('»', '»')}
|
||||
</Link>
|
||||
) : (
|
||||
<span key={i} className="mx-2">
|
||||
{link.label
|
||||
.replace('«', '«')
|
||||
.replace('»', '»')}
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { states, type Publication } from './shared';
|
||||
export default function Manage({
|
||||
items,
|
||||
watched = false,
|
||||
}: {
|
||||
items: {
|
||||
id: string;
|
||||
title?: string;
|
||||
version?: number;
|
||||
published?: boolean;
|
||||
publication?: Publication;
|
||||
state?: string;
|
||||
changed?: boolean;
|
||||
}[];
|
||||
watched?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Frame
|
||||
title={
|
||||
watched
|
||||
? 'Concursos que acompanho'
|
||||
: 'Gestão de concursos e anúncios'
|
||||
}
|
||||
>
|
||||
<Link className="underline" href="/concursos">
|
||||
Catálogo público
|
||||
</Link>
|
||||
{!watched && (
|
||||
<>
|
||||
<Link className={button} href="/management/concursos/novo">
|
||||
Novo concurso/anúncio
|
||||
</Link>
|
||||
<Link className="ml-3 underline" href="/gestao-conteudos">
|
||||
Entrada única de gestão
|
||||
</Link>
|
||||
<p>
|
||||
Guardar → recuperar → pré-visualizar → publicar →
|
||||
actualizar/prorrogar → publicar resultado ou
|
||||
cancelamento. Carregue documentos na biblioteca
|
||||
existente, acompanhe o scan e autorize separadamente os
|
||||
anexos públicos. O rascunho pode ficar incompleto.
|
||||
</p>
|
||||
<p>
|
||||
Para actualizar, reabra o concurso, guarde as
|
||||
alterações, escolha o acto e confira a prévia. A data de
|
||||
publicação no portal não substitui a data de origem.
|
||||
Acompanhar não apresenta proposta.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{!items.length && <p>Sem registos.</p>}
|
||||
{items.map((item) => (
|
||||
<article key={item.id} className={`${card} my-3`}>
|
||||
<h2 className="font-semibold">
|
||||
{item.title ?? String(item.publication?.payload.title)}
|
||||
</h2>
|
||||
{watched ? (
|
||||
<>
|
||||
<p>
|
||||
{states[item.state ?? '']} ·{' '}
|
||||
{item.changed
|
||||
? 'Há novos actos desde que começou a acompanhar'
|
||||
: 'Sem novos actos desde o registo de acompanhamento'}
|
||||
</p>
|
||||
<p>
|
||||
O acompanhamento é consultado nesta área; não
|
||||
afirma envio de alertas por email.
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/concursos/${item.id}`}
|
||||
>
|
||||
Consultar concurso
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
Versão {item.version} ·{' '}
|
||||
{item.published
|
||||
? 'Com acto publicado; alterações em preparação são separadas'
|
||||
: 'Rascunho privado'}
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/concursos/${item.id}`}
|
||||
>
|
||||
Recuperar e editar
|
||||
</Link>
|
||||
{item.published && (
|
||||
<Link
|
||||
className="ml-3 underline"
|
||||
href={`/concursos/${item.id}`}
|
||||
>
|
||||
Consultar publicação
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export type Lot = { code: string; description: string; quantities: string };
|
||||
export type Attachment = {
|
||||
resource_id: number;
|
||||
public: boolean;
|
||||
purpose: string;
|
||||
title?: string;
|
||||
available?: boolean;
|
||||
};
|
||||
export type Draft = {
|
||||
[key: string]: string | number | boolean | null | Lot[] | Attachment[];
|
||||
};
|
||||
export type Payload = Draft & {
|
||||
opportunity?: { title: string; url: string } | null;
|
||||
};
|
||||
export type Publication = {
|
||||
id: string;
|
||||
version: number;
|
||||
act: string;
|
||||
payload: Payload;
|
||||
published_at: string;
|
||||
reason: string;
|
||||
};
|
||||
export const states: Record<string, string> = {
|
||||
open: 'Aberto',
|
||||
extended: 'Prorrogado',
|
||||
deadline_ended: 'Prazo de propostas terminado',
|
||||
cancelled: 'Cancelado',
|
||||
results: 'Resultados publicados',
|
||||
};
|
||||
export const acts: Record<string, string> = {
|
||||
initial: 'Anúncio inicial',
|
||||
clarification: 'Esclarecimento',
|
||||
correction: 'Rectificação',
|
||||
extension: 'Prorrogação',
|
||||
award: 'Resultado / adjudicação',
|
||||
cancellation: 'Cancelamento',
|
||||
other: 'Outro acto',
|
||||
};
|
||||
export const labels: Record<string, string> = {
|
||||
reference: 'Referência',
|
||||
object: 'Objecto',
|
||||
responsible_unit: 'Unidade responsável / UGEA quando aplicável',
|
||||
modality: 'Modalidade',
|
||||
object_kind: 'Natureza do objecto',
|
||||
quantities: 'Quantidades essenciais',
|
||||
financier: 'Financiador',
|
||||
instrument: 'Instrumento aplicável',
|
||||
edition: 'Edição aplicável',
|
||||
rule_source: 'Fonte das regras',
|
||||
financing_agreement: 'Acordo de financiamento',
|
||||
eligibility: 'Elegibilidade',
|
||||
requirements: 'Requisitos de participação',
|
||||
proposal_validity: 'Validade da proposta',
|
||||
guarantee_status: 'Aplicabilidade de garantias',
|
||||
guarantees: 'Garantias documentadas',
|
||||
delivery_channel: 'Canal de entrega',
|
||||
delivery_address: 'Endereço / instruções para apresentar proposta',
|
||||
delivery_url: 'Plataforma de entrega',
|
||||
public_contact: 'Contacto público autorizado',
|
||||
dissemination: 'Meios de divulgação exigidos / adoptados e comprovativos',
|
||||
origin_url: 'Anúncio de origem',
|
||||
origin_published_at: 'Publicação de origem — referência do prazo',
|
||||
clarifications_at: 'Limite para esclarecimentos',
|
||||
deadline: 'Entrega de propostas',
|
||||
opening_at: 'Abertura (quando aplicável)',
|
||||
timezone: 'Fuso horário do procedimento',
|
||||
minimum_days: 'Prazo mínimo documentado (dias)',
|
||||
minimum_source: 'Fonte / citação do prazo mínimo',
|
||||
minimum_edition: 'Edição da regra de prazo',
|
||||
minimum_modality: 'Modalidade da regra de prazo',
|
||||
minimum_day_basis: 'Base de contagem do prazo',
|
||||
minimum_calendar_source: 'Fonte do calendário de dias úteis',
|
||||
minimum_working_days: 'Dias de trabalho (1=segunda, 7=domingo)',
|
||||
minimum_holidays: 'Feriados e exclusões documentados',
|
||||
result: 'Acto ou resultado documentado',
|
||||
};
|
||||
export const control =
|
||||
'w-full rounded border border-slate-400 bg-background p-2 text-foreground';
|
||||
export function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className="block space-y-1">
|
||||
<span className="font-medium">{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
export function NoticeContent({ p }: { p: Payload }) {
|
||||
const links = ['rule_source', 'origin_url', 'delivery_url'];
|
||||
const names: Record<string, string> = {
|
||||
works: 'Obras',
|
||||
goods: 'Bens',
|
||||
services: 'Serviços',
|
||||
mixed: 'Misto',
|
||||
other: 'Outro',
|
||||
required: 'Exigidas',
|
||||
not_required: 'Não exigidas',
|
||||
unknown: 'Por determinar',
|
||||
calendar: 'Dias corridos',
|
||||
business: 'Dias úteis',
|
||||
};
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h2 className="text-2xl font-semibold">{String(p.title ?? '')}</h2>
|
||||
<p>
|
||||
<strong>Entidade:</strong>{' '}
|
||||
{String(p.organization_name ?? 'Por indicar')}
|
||||
</p>
|
||||
<p>
|
||||
Regime:{' '}
|
||||
{(
|
||||
{
|
||||
state: 'Contratação pública do Estado',
|
||||
external: 'Financiamento externo',
|
||||
private: 'Concurso privado',
|
||||
other: 'Outro regime documentado',
|
||||
} as Record<string, string>
|
||||
)[String(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="my-2 rounded border p-3">
|
||||
<strong>Entrega:</strong>{' '}
|
||||
{String(p.deadline ?? 'Por indicar').replace('T', ' ')} ·{' '}
|
||||
{String(p.timezone ?? '')}
|
||||
<br />
|
||||
{String(p.delivery_channel ?? '')} ·{' '}
|
||||
{String(p.delivery_address ?? '')}
|
||||
</p>
|
||||
<p>
|
||||
Sector: {String(p.sector_name ?? 'Por indicar')} ·
|
||||
Localização: {String(p.territory_name ?? 'Por indicar')}
|
||||
</p>
|
||||
{p.project_name && (
|
||||
<p>
|
||||
Projecto relacionado: {String(p.project_name)}. Esta
|
||||
relação não confirma execução ou contratação.
|
||||
</p>
|
||||
)}
|
||||
{p.opportunity && (
|
||||
<a className="underline" href={p.opportunity.url}>
|
||||
Oportunidade relacionada: {p.opportunity.title}
|
||||
</a>
|
||||
)}
|
||||
</section>
|
||||
{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)}
|
||||
).
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-3 md:grid-cols-2">
|
||||
{Object.entries(labels)
|
||||
.filter(
|
||||
([key]) =>
|
||||
p[key] !== null &&
|
||||
p[key] !== undefined &&
|
||||
p[key] !== '',
|
||||
)
|
||||
.map(([key, label]) => (
|
||||
<div
|
||||
key={key}
|
||||
className="rounded border p-3 break-words"
|
||||
>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{links.includes(key) ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={String(p[key])}
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{String(p[key])}
|
||||
</a>
|
||||
) : (
|
||||
(
|
||||
names[String(p[key])] ?? String(p[key])
|
||||
).replace(/^(\d{4}-\d{2}-\d{2})T/, '$1 ')
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold">Lotes</h3>
|
||||
{((p.lots ?? []) as Lot[]).length ? (
|
||||
<ul>
|
||||
{(p.lots as Lot[]).map((lot, i) => (
|
||||
<li key={i}>
|
||||
{lot.code} — {lot.description} ·{' '}
|
||||
{lot.quantities}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Sem lotes indicados.</p>
|
||||
)}
|
||||
</section>
|
||||
<section>
|
||||
<h3 className="text-lg font-semibold">
|
||||
Documentos do concurso
|
||||
</h3>
|
||||
<ul>
|
||||
{((p.attachments ?? []) as Attachment[]).map((item, i) => (
|
||||
<li key={i}>
|
||||
{item.available === false ? (
|
||||
<span>
|
||||
{item.title} — documento actualmente
|
||||
indisponível
|
||||
</span>
|
||||
) : (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/documentos/${item.resource_id}/download`}
|
||||
>
|
||||
{item.title ??
|
||||
`Documento ${item.resource_id}`}{' '}
|
||||
— {item.purpose}
|
||||
</a>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!((p.attachments as Attachment[]) ?? []).length && (
|
||||
<p>
|
||||
Sem anexos públicos neste acto. Consulte o canal e o
|
||||
anúncio de origem.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<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 à
|
||||
execução do investimento.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Head, Link, router, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { NoticeContent, states, acts, type Publication } from './shared';
|
||||
export default function Show({
|
||||
id,
|
||||
publication,
|
||||
state,
|
||||
history,
|
||||
watching,
|
||||
backUrl,
|
||||
printMode,
|
||||
}: {
|
||||
id: string;
|
||||
publication: Publication;
|
||||
state: string;
|
||||
history: Publication[];
|
||||
watching: boolean;
|
||||
backUrl: string;
|
||||
printMode: boolean;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: unknown | null } }>().props;
|
||||
return (
|
||||
<Frame title="Concurso e anúncio">
|
||||
<Head title={String(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} }'
|
||||
}
|
||||
</style>
|
||||
<div className="no-print flex flex-wrap gap-4">
|
||||
<Link className="underline" href={backUrl}>
|
||||
Voltar aos resultados
|
||||
</Link>
|
||||
<Link className="underline" href={`/concursos/${id}/imprimir`}>
|
||||
Relatório imprimível
|
||||
</Link>
|
||||
{printMode && (
|
||||
<button className={button} onClick={() => window.print()}>
|
||||
Imprimir anúncio
|
||||
</button>
|
||||
)}
|
||||
{auth?.user ? (
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
watching
|
||||
? router.delete(`/concursos/${id}/acompanhar`)
|
||||
: router.put(`/concursos/${id}/acompanhar`)
|
||||
}
|
||||
>
|
||||
{watching
|
||||
? 'Deixar de acompanhar'
|
||||
: 'Acompanhar concurso'}
|
||||
</button>
|
||||
) : (
|
||||
<Link className="underline" href="/login">
|
||||
Entrar para acompanhar — conta simples
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<p className="rounded border p-3">
|
||||
<strong>{states[state]}</strong> · {acts[publication.act]} ·
|
||||
Versão {publication.version}
|
||||
</p>
|
||||
<p>
|
||||
Publicação deste acto no InvesteMoz: {publication.published_at}{' '}
|
||||
(UTC). Esta data não reinicia o prazo de origem.
|
||||
</p>
|
||||
<article className={card}>
|
||||
<NoticeContent p={publication.payload} />
|
||||
</article>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Actos publicados e histórico
|
||||
</h2>
|
||||
{history.map((v) => (
|
||||
<details key={v.id} open={printMode}>
|
||||
<summary>
|
||||
{acts[v.act]} · versão {v.version} ·{' '}
|
||||
{v.published_at} (UTC)
|
||||
</summary>
|
||||
<p className="my-2">Motivo público: {v.reason}</p>
|
||||
<NoticeContent p={v.payload} />
|
||||
</details>
|
||||
))}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user