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