@@ -1,7 +1,7 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { BookOpen, FolderGit2, LayoutGrid } from 'lucide-react';
|
||||
import { LayoutGrid } from 'lucide-react';
|
||||
import { portalNavigation } from '@/lib/portal-navigation';
|
||||
import AppLogo from '@/components/app-logo';
|
||||
import { NavFooter } from '@/components/nav-footer';
|
||||
import { NavMain } from '@/components/nav-main';
|
||||
import { NavUser } from '@/components/nav-user';
|
||||
import {
|
||||
@@ -14,64 +14,28 @@ import {
|
||||
SidebarMenuItem,
|
||||
} from '@/components/ui/sidebar';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { NavItem, Auth } from '@/types';
|
||||
|
||||
const mainNavItems: NavItem[] = [
|
||||
{ title: 'Painel do investidor', href: '/investidor', icon: LayoutGrid },
|
||||
{ title: 'Corredores e clusters', href: '/carteira', icon: LayoutGrid },
|
||||
{
|
||||
title: 'Dashboard',
|
||||
href: dashboard(),
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
];
|
||||
|
||||
const footerNavItems: NavItem[] = [
|
||||
{
|
||||
title: 'Repository',
|
||||
href: 'https://github.com/laravel/react-starter-kit',
|
||||
icon: FolderGit2,
|
||||
},
|
||||
{
|
||||
title: 'Documentation',
|
||||
href: 'https://laravel.com/docs/starter-kits#react',
|
||||
icon: BookOpen,
|
||||
},
|
||||
];
|
||||
import type { Auth } from '@/types';
|
||||
|
||||
export function AppSidebar() {
|
||||
const { auth } = usePage<{ auth: Auth }>().props;
|
||||
const items = auth.canManagePortal
|
||||
? [
|
||||
...mainNavItems,
|
||||
{
|
||||
title: 'Pedidos de interesse',
|
||||
href: '/management/interests',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
{
|
||||
title: 'Sectores',
|
||||
href: '/management/sectors',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
{
|
||||
title: 'Oportunidades',
|
||||
href: '/management/opportunities',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
{ title: 'CRM', href: '/management/crm/leads', icon: LayoutGrid },
|
||||
{
|
||||
title: 'Projectos',
|
||||
href: '/management/projects',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
{
|
||||
title: 'Clusters',
|
||||
href: '/management/clusters',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
]
|
||||
: mainNavItems;
|
||||
const { auth, existingBusinessEnabled, educationEnabled, aiEnabled } =
|
||||
usePage<{
|
||||
auth: Auth;
|
||||
existingBusinessEnabled?: boolean;
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
}>().props;
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!auth.user,
|
||||
manager: auth.canManagePortal,
|
||||
businesses: existingBusinessEnabled,
|
||||
education: educationEnabled,
|
||||
ai: aiEnabled,
|
||||
});
|
||||
const items = groups.map((group) => ({
|
||||
title: group.label,
|
||||
href: group.children?.find((item) => item.href)?.href ?? '/',
|
||||
icon: LayoutGrid,
|
||||
}));
|
||||
return (
|
||||
<Sidebar collapsible="icon" variant="inset">
|
||||
<SidebarHeader>
|
||||
@@ -91,7 +55,6 @@ export function AppSidebar() {
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
<NavFooter items={footerNavItems} className="mt-auto" />
|
||||
<NavUser />
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
|
||||
@@ -0,0 +1,539 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { card, input, button } from '@/pages/investment/shared';
|
||||
|
||||
export type DeskDocument = {
|
||||
id: string;
|
||||
document_id: string;
|
||||
file_name: string;
|
||||
status: string;
|
||||
malware_scan_status: string;
|
||||
category: string;
|
||||
source_reference: string;
|
||||
};
|
||||
export function DocumentReview({
|
||||
caseId,
|
||||
version,
|
||||
documents,
|
||||
requestId,
|
||||
}: {
|
||||
caseId: string;
|
||||
version: number;
|
||||
documents: DeskDocument[];
|
||||
requestId?: string;
|
||||
}) {
|
||||
const form = useForm({
|
||||
version,
|
||||
request_id: requestId ?? null,
|
||||
document: documents[0]?.id ?? '',
|
||||
outcome: 'internal_verified',
|
||||
what_checked: '',
|
||||
evidence: '',
|
||||
supports: [] as string[],
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((d) => ({ ...d, version }));
|
||||
form.post(
|
||||
`/balcao-virtual/dossiers/${caseId}/documentos/${form.data.document}/conferencia`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h3 className="text-xl font-bold">
|
||||
Conferência documental interna
|
||||
</h3>
|
||||
<p>
|
||||
O registo identifica a pessoa, o ficheiro e hash, o alcance e a
|
||||
evidência. Não equivale a aprovação, registo ou licença de uma
|
||||
instituição.
|
||||
</p>
|
||||
<label htmlFor={`review-document-${caseId}`}>Documento</label>
|
||||
<select
|
||||
id={`review-document-${caseId}`}
|
||||
className={input}
|
||||
required
|
||||
value={form.data.document}
|
||||
onChange={(e) => form.setData('document', e.target.value)}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{documents.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.file_name} · {d.malware_scan_status}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label>
|
||||
Resultado
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.outcome}
|
||||
onChange={(e) => form.setData('outcome', e.target.value)}
|
||||
>
|
||||
<option value="internal_verified">
|
||||
Conferido internamente no âmbito descrito
|
||||
</option>
|
||||
<option value="internal_issue">
|
||||
Problema documental identificado
|
||||
</option>
|
||||
<option value="contradiction_identified">
|
||||
Contradição identificada com evidência
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<fieldset className="space-y-2">
|
||||
<legend>Pressupostos abrangidos por esta conferência</legend>
|
||||
<p className="text-sm">
|
||||
Seleccione apenas os âmbitos efectivamente verificados.
|
||||
Associar um ficheiro não valida automaticamente um
|
||||
pressuposto.
|
||||
</p>
|
||||
{Object.entries({
|
||||
market_evidence: 'Mercado',
|
||||
location_evidence: 'Localização',
|
||||
resource_evidence: 'Recursos',
|
||||
funding_evidence: 'Financiamento',
|
||||
}).map(([key, label]) => (
|
||||
<label key={key} className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.supports.includes(key)}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'supports',
|
||||
e.target.checked
|
||||
? [...form.data.supports, key]
|
||||
: form.data.supports.filter(
|
||||
(x) => x !== key,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<label>
|
||||
O que foi verificado
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
value={form.data.what_checked}
|
||||
onChange={(e) =>
|
||||
form.setData('what_checked', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Evidência utilizada
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
value={form.data.evidence}
|
||||
onChange={(e) => form.setData('evidence', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !documents.length}
|
||||
>
|
||||
Registar conferência com a minha autoria
|
||||
</button>
|
||||
{Object.entries(form.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export type DeskPayment = {
|
||||
id: string;
|
||||
reference: string;
|
||||
amount: string;
|
||||
currency: string;
|
||||
source_reference: string;
|
||||
document_id: string | null;
|
||||
status: string;
|
||||
verified_by: number | null;
|
||||
reason: string | null;
|
||||
version: number;
|
||||
};
|
||||
export function RequestOperations({
|
||||
requestId,
|
||||
owner,
|
||||
reviewer,
|
||||
documents,
|
||||
payments,
|
||||
}: {
|
||||
requestId: string;
|
||||
owner: boolean;
|
||||
reviewer: boolean;
|
||||
documents: DeskDocument[];
|
||||
payments: DeskPayment[];
|
||||
}) {
|
||||
const payment = useForm({
|
||||
reference: '',
|
||||
amount: '',
|
||||
currency: 'MZN',
|
||||
source_reference: '',
|
||||
document_id: '',
|
||||
consent: false,
|
||||
});
|
||||
const review = useForm({
|
||||
payment: payments[0]?.id ?? '',
|
||||
version: payments[0]?.version ?? 1,
|
||||
status: 'internal_verified',
|
||||
reason: '',
|
||||
evidence: '',
|
||||
});
|
||||
const communication = useForm({
|
||||
channel: 'phone',
|
||||
direction: 'received',
|
||||
occurred_at: '',
|
||||
summary: '',
|
||||
evidence: '',
|
||||
client_key: crypto.randomUUID(),
|
||||
});
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Pagamentos e comunicações — registos manuais
|
||||
</h2>
|
||||
<p>
|
||||
Sem integração bancária, SMS ou WhatsApp nesta fase. Nenhum
|
||||
registo abaixo confirma automaticamente pagamento ou entrega de
|
||||
mensagem.
|
||||
</p>
|
||||
{payments.map((p) => (
|
||||
<article key={p.id} className={card}>
|
||||
<p>
|
||||
{p.reference} · {p.amount} {p.currency} ·{' '}
|
||||
{p.status === 'internal_verified'
|
||||
? 'Comprovativo conferido internamente'
|
||||
: p.status === 'internal_issue'
|
||||
? 'Problema na conferência interna'
|
||||
: 'Declarado — por conferir'}
|
||||
</p>
|
||||
<p>Fonte do valor: {p.source_reference}</p>
|
||||
<p>
|
||||
Responsável pela conferência:{' '}
|
||||
{p.verified_by ?? 'Ainda sem conferência'} · {p.reason}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{owner && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
payment.post(
|
||||
`/balcao-virtual/pedidos/${requestId}/pagamentos`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
Registar referência e comprovativo
|
||||
</h3>
|
||||
<label>
|
||||
Referência fornecida
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
value={payment.data.reference}
|
||||
onChange={(e) =>
|
||||
payment.setData('reference', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Valor declarado
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
value={payment.data.amount}
|
||||
onChange={(e) =>
|
||||
payment.setData('amount', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Moeda
|
||||
<select
|
||||
className={input}
|
||||
value={payment.data.currency}
|
||||
onChange={(e) =>
|
||||
payment.setData('currency', e.target.value)
|
||||
}
|
||||
>
|
||||
{['MZN', 'USD', 'EUR'].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Fonte do valor e finalidade
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
value={payment.data.source_reference}
|
||||
onChange={(e) =>
|
||||
payment.setData(
|
||||
'source_reference',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Comprovativo associado ao mesmo dossier
|
||||
<select
|
||||
className={input}
|
||||
value={payment.data.document_id}
|
||||
onChange={(e) =>
|
||||
payment.setData('document_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Pendente — registar referência agora
|
||||
</option>
|
||||
{documents.map((d) => (
|
||||
<option key={d.id} value={d.document_id}>
|
||||
{d.file_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={payment.data.consent}
|
||||
onChange={(e) =>
|
||||
payment.setData('consent', e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Autorizo este registo interno para o pedido.
|
||||
</label>
|
||||
<button className={button} disabled={payment.processing}>
|
||||
Guardar declaração
|
||||
</button>
|
||||
{Object.entries(payment.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{reviewer && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const current = payments.find(
|
||||
(p) => p.id === review.data.payment,
|
||||
);
|
||||
review.transform((d) => ({
|
||||
...d,
|
||||
version: current?.version ?? 1,
|
||||
}));
|
||||
review.post(
|
||||
`/balcao-virtual/pedidos/${requestId}/pagamentos/${review.data.payment}/conferencia`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
Conferir comprovativo internamente
|
||||
</h3>
|
||||
<label>
|
||||
Referência
|
||||
<select
|
||||
className={input}
|
||||
required
|
||||
value={review.data.payment}
|
||||
onChange={(e) =>
|
||||
review.setData('payment', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{payments.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.reference}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Resultado
|
||||
<select
|
||||
className={input}
|
||||
value={review.data.status}
|
||||
onChange={(e) =>
|
||||
review.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="internal_verified">
|
||||
Comprovativo conferido internamente
|
||||
</option>
|
||||
<option value="internal_issue">
|
||||
Problema identificado
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
O que foi conferido
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
value={review.data.reason}
|
||||
onChange={(e) =>
|
||||
review.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Evidência
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
value={review.data.evidence}
|
||||
onChange={(e) =>
|
||||
review.setData('evidence', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={review.processing || !payments.length}
|
||||
>
|
||||
Registar conferência
|
||||
</button>
|
||||
{Object.entries(review.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{(owner || reviewer) && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
communication.post(
|
||||
`/balcao-virtual/pedidos/${requestId}/comunicacoes`,
|
||||
{
|
||||
onSuccess: () => {
|
||||
communication.reset('summary', 'evidence');
|
||||
communication.setData(
|
||||
'client_key',
|
||||
crypto.randomUUID(),
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
Registar comunicação realizada fora do portal
|
||||
</h3>
|
||||
<label>
|
||||
Canal
|
||||
<select
|
||||
className={input}
|
||||
value={communication.data.channel}
|
||||
onChange={(e) =>
|
||||
communication.setData('channel', e.target.value)
|
||||
}
|
||||
>
|
||||
{Object.entries({
|
||||
phone: 'Telefone',
|
||||
email: 'E-mail',
|
||||
sms: 'SMS',
|
||||
whatsapp: 'WhatsApp',
|
||||
in_person: 'Presencial',
|
||||
}).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Direcção
|
||||
<select
|
||||
className={input}
|
||||
value={communication.data.direction}
|
||||
onChange={(e) =>
|
||||
communication.setData(
|
||||
'direction',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="received">Recebida</option>
|
||||
<option value="sent">Enviada manualmente</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Data real declarada
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
type="datetime-local"
|
||||
value={communication.data.occurred_at}
|
||||
onChange={(e) =>
|
||||
communication.setData(
|
||||
'occurred_at',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Resumo
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
value={communication.data.summary}
|
||||
onChange={(e) =>
|
||||
communication.setData('summary', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Evidência / referência
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
value={communication.data.evidence}
|
||||
onChange={(e) =>
|
||||
communication.setData(
|
||||
'evidence',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={communication.processing}
|
||||
>
|
||||
Guardar registo manual — sem envio
|
||||
</button>
|
||||
{Object.entries(communication.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { Map as LeafletMap, Marker } from "leaflet";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { Map as LeafletMap, Marker } from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
|
||||
export type InvestmentMapFeature = {
|
||||
geometry: { coordinates: [number, number] };
|
||||
@@ -25,11 +25,11 @@ export default function InteractiveInvestmentMap({
|
||||
const map = useRef<LeafletMap | null>(null);
|
||||
const markers = useRef(new Map<number, Marker>());
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let observer: ResizeObserver | undefined;
|
||||
void import("leaflet")
|
||||
void import('leaflet')
|
||||
.then((L) => {
|
||||
if (cancelled || !element.current) return;
|
||||
const instance = L.map(element.current, {
|
||||
@@ -39,17 +39,17 @@ export default function InteractiveInvestmentMap({
|
||||
map.current = instance;
|
||||
L.tileLayer(
|
||||
import.meta.env.VITE_MAP_TILE_URL ||
|
||||
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
{
|
||||
maxZoom: 19,
|
||||
attribution:
|
||||
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||
},
|
||||
)
|
||||
.on("tileerror", () => {
|
||||
.on('tileerror', () => {
|
||||
if (!cancelled)
|
||||
setError(
|
||||
"Mapa base indisponível. Os marcadores e a lista continuam acessíveis.",
|
||||
'Mapa base indisponível. Os marcadores e a lista continuam acessíveis.',
|
||||
);
|
||||
})
|
||||
.addTo(instance);
|
||||
@@ -65,29 +65,29 @@ export default function InteractiveInvestmentMap({
|
||||
)
|
||||
continue;
|
||||
const { properties: p } = point;
|
||||
const popup = document.createElement("div");
|
||||
const heading = document.createElement("strong");
|
||||
const popup = document.createElement('div');
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = p.title;
|
||||
popup.append(heading);
|
||||
for (const text of [
|
||||
p.category,
|
||||
p.location,
|
||||
`Corredor: ${p.corridors?.join(", ") || "Não associado"}`,
|
||||
`Cluster: ${p.clusters?.join(", ") || "Não associado"}`,
|
||||
`Projecto âncora: ${p.projects?.join(", ") || "Não associado"}`,
|
||||
`Corredor: ${p.corridors?.join(', ') || 'Não associado'}`,
|
||||
`Cluster: ${p.clusters?.join(', ') || 'Não associado'}`,
|
||||
`Projecto âncora: ${p.projects?.join(', ') || 'Não associado'}`,
|
||||
]) {
|
||||
const line = document.createElement("p");
|
||||
line.textContent = text ?? "";
|
||||
const line = document.createElement('p');
|
||||
line.textContent = text ?? '';
|
||||
popup.append(line);
|
||||
}
|
||||
if (p.url.startsWith("/") && !p.url.startsWith("//")) {
|
||||
const link = document.createElement("a");
|
||||
if (p.url.startsWith('/') && !p.url.startsWith('//')) {
|
||||
const link = document.createElement('a');
|
||||
link.href = p.url;
|
||||
link.textContent = "Abrir ficha detalhada";
|
||||
link.textContent = 'Abrir ficha detalhada';
|
||||
popup.append(link);
|
||||
}
|
||||
const icon = L.divIcon({
|
||||
className: "",
|
||||
className: '',
|
||||
html: `<span style="display:grid;place-items:center;width:32px;height:32px;border-radius:50%;background:#065f46;color:white;border:2px solid white;font-weight:bold">${index + 1}</span>`,
|
||||
iconSize: [32, 32],
|
||||
iconAnchor: [16, 16],
|
||||
@@ -99,17 +99,21 @@ export default function InteractiveInvestmentMap({
|
||||
keyboard: true,
|
||||
})
|
||||
.bindPopup(popup)
|
||||
.on("click", () => setSelected(p.id))
|
||||
.on('click', () => setSelected(p.id))
|
||||
.addTo(instance);
|
||||
markers.current.set(p.id, marker);
|
||||
bounds.push([latitude, longitude]);
|
||||
}
|
||||
if (bounds.length) instance.fitBounds(bounds, { padding: [40, 40], maxZoom: 14 });
|
||||
if (bounds.length)
|
||||
instance.fitBounds(bounds, {
|
||||
padding: [40, 40],
|
||||
maxZoom: 14,
|
||||
});
|
||||
observer = new ResizeObserver(() => instance.invalidateSize());
|
||||
observer.observe(element.current);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setError("Não foi possível iniciar o mapa.");
|
||||
if (!cancelled) setError('Não foi possível iniciar o mapa.');
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
@@ -126,8 +130,8 @@ export default function InteractiveInvestmentMap({
|
||||
>
|
||||
<h2 className="text-xl font-bold">Mapa dos investimentos</h2>
|
||||
<p>
|
||||
Arraste para navegar; use +/− para ampliar. Pode seleccionar um investimento na
|
||||
lista para o localizar.
|
||||
Arraste para navegar; use +/− para ampliar. Pode seleccionar um
|
||||
investimento na lista para o localizar.
|
||||
</p>
|
||||
{error && <p role="status">{error}</p>}
|
||||
<div
|
||||
@@ -138,7 +142,9 @@ export default function InteractiveInvestmentMap({
|
||||
{points === null ? (
|
||||
<p role="status">A carregar localizações…</p>
|
||||
) : (
|
||||
<p role="status">{points.length} investimentos com coordenadas disponíveis.</p>
|
||||
<p role="status">
|
||||
{points.length} investimentos com coordenadas disponíveis.
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-2 md:grid-cols-2">
|
||||
{(points ?? []).map((p) => (
|
||||
@@ -146,8 +152,8 @@ export default function InteractiveInvestmentMap({
|
||||
key={p.properties.id}
|
||||
className={
|
||||
selected === p.properties.id
|
||||
? "rounded border-2 border-emerald-700 p-3"
|
||||
: "rounded border p-3"
|
||||
? 'rounded border-2 border-emerald-700 p-3'
|
||||
: 'rounded border p-3'
|
||||
}
|
||||
>
|
||||
<button
|
||||
@@ -155,9 +161,14 @@ export default function InteractiveInvestmentMap({
|
||||
className="text-left font-bold underline"
|
||||
aria-pressed={selected === p.properties.id}
|
||||
onClick={() => {
|
||||
const marker = markers.current.get(p.properties.id);
|
||||
const marker = markers.current.get(
|
||||
p.properties.id,
|
||||
);
|
||||
if (marker) {
|
||||
map.current?.setView(marker.getLatLng(), 14);
|
||||
map.current?.setView(
|
||||
marker.getLatLng(),
|
||||
14,
|
||||
);
|
||||
marker.openPopup();
|
||||
setSelected(p.properties.id);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api } from "@/pages/investment/shared";
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
|
||||
export default function InvestmentCoordinates({ id }: { id: number | string }) {
|
||||
const [data, setData] = useState({
|
||||
version: 0,
|
||||
latitude: "",
|
||||
longitude: "",
|
||||
source_reference: "",
|
||||
latitude: '',
|
||||
longitude: '',
|
||||
source_reference: '',
|
||||
});
|
||||
const [ready, setReady] = useState(false);
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [message, setMessage] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api(`/management/opportunities/${id}/coordinates`)
|
||||
@@ -19,8 +19,8 @@ export default function InvestmentCoordinates({ id }: { id: number | string }) {
|
||||
if (active) {
|
||||
setData({
|
||||
...result,
|
||||
latitude: String(result.latitude ?? ""),
|
||||
longitude: String(result.longitude ?? ""),
|
||||
latitude: String(result.latitude ?? ''),
|
||||
longitude: String(result.longitude ?? ''),
|
||||
});
|
||||
setReady(true);
|
||||
}
|
||||
@@ -39,36 +39,51 @@ export default function InvestmentCoordinates({ id }: { id: number | string }) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await api(`/management/opportunities/${id}/coordinates`, {
|
||||
...data,
|
||||
confirmed_site: confirmed,
|
||||
});
|
||||
setData((previous) => ({ ...previous, version: result.version }));
|
||||
const result = await api(
|
||||
`/management/opportunities/${id}/coordinates`,
|
||||
{
|
||||
...data,
|
||||
confirmed_site: confirmed,
|
||||
},
|
||||
);
|
||||
setData((previous) => ({
|
||||
...previous,
|
||||
version: result.version,
|
||||
}));
|
||||
setMessage(
|
||||
"Coordenadas guardadas. O marcador acompanha a publicação da oportunidade.",
|
||||
'Coordenadas guardadas. O marcador acompanha a publicação da oportunidade.',
|
||||
);
|
||||
} catch (e) {
|
||||
setMessage(e instanceof Error ? e.message : "Falha ao guardar.");
|
||||
setMessage(
|
||||
e instanceof Error ? e.message : 'Falha ao guardar.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<h2 className="text-lg font-bold">Posição do investimento no mapa</h2>
|
||||
<p>Registe a posição do local em WGS84 e a referência que a confirma.</p>
|
||||
<h2 className="text-lg font-bold">
|
||||
Posição do investimento no mapa
|
||||
</h2>
|
||||
<p>
|
||||
Registe a posição do local em WGS84 e a referência que a
|
||||
confirma.
|
||||
</p>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{(["latitude", "longitude"] as const).map((field) => (
|
||||
{(['latitude', 'longitude'] as const).map((field) => (
|
||||
<label key={field}>
|
||||
{field === "latitude" ? "Latitude" : "Longitude"}
|
||||
{field === 'latitude' ? 'Latitude' : 'Longitude'}
|
||||
<input
|
||||
className="w-full rounded border p-2"
|
||||
type="number"
|
||||
step="any"
|
||||
min={field === "latitude" ? -90 : -180}
|
||||
max={field === "latitude" ? 90 : 180}
|
||||
min={field === 'latitude' ? -90 : -180}
|
||||
max={field === 'latitude' ? 90 : 180}
|
||||
required
|
||||
value={data[field]}
|
||||
onChange={(e) => setData({ ...data, [field]: e.target.value })}
|
||||
onChange={(e) =>
|
||||
setData({ ...data, [field]: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
@@ -81,7 +96,9 @@ export default function InvestmentCoordinates({ id }: { id: number | string }) {
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
value={data.source_reference}
|
||||
onChange={(e) => setData({ ...data, source_reference: e.target.value })}
|
||||
onChange={(e) =>
|
||||
setData({ ...data, source_reference: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
@@ -91,11 +108,11 @@ export default function InvestmentCoordinates({ id }: { id: number | string }) {
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>
|
||||
Confirmo que esta posição corresponde ao local do investimento e pode ser divulgada
|
||||
quando a ficha estiver publicada.
|
||||
Confirmo que esta posição corresponde ao local do investimento e
|
||||
pode ser divulgada quando a ficha estiver publicada.
|
||||
</label>
|
||||
<button
|
||||
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
|
||||
className="bg-primary text-primary-foreground rounded px-4 py-2 disabled:opacity-50"
|
||||
disabled={!ready || busy}
|
||||
>
|
||||
Guardar coordenadas
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import InteractiveInvestmentMap, { type InvestmentMapFeature } from "./interactive-investment-map";
|
||||
import { useEffect, useState } from 'react';
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapFeature,
|
||||
} from './interactive-investment-map';
|
||||
|
||||
export default function InvestmentMapPanel({
|
||||
filters,
|
||||
@@ -8,25 +10,31 @@ export default function InvestmentMapPanel({
|
||||
}) {
|
||||
const key = JSON.stringify(filters);
|
||||
const [points, setPoints] = useState<InvestmentMapFeature[] | null>(null);
|
||||
const [missing, setMissing] = useState<{ id: number; title: string; url: string }[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const [missing, setMissing] = useState<
|
||||
{ id: number; title: string; url: string }[]
|
||||
>([]);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const params = new URLSearchParams(JSON.parse(key));
|
||||
setPoints(null);
|
||||
fetch(`/api/v1/investment/map?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error("Mapa indisponível.");
|
||||
if (!response.ok) throw new Error('Mapa indisponível.');
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setPoints(data.features);
|
||||
setMissing(data.unlocated ?? []);
|
||||
setError(data.truncated ? "Cobertura limitada: refine os filtros." : "");
|
||||
setError(
|
||||
data.truncated
|
||||
? 'Cobertura limitada: refine os filtros.'
|
||||
: '',
|
||||
);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!controller.signal.aborted) setError(e.message);
|
||||
@@ -39,7 +47,10 @@ export default function InvestmentMapPanel({
|
||||
<InteractiveInvestmentMap points={points} />
|
||||
{missing.length > 0 && (
|
||||
<div>
|
||||
<p>{missing.length} investimentos aguardam coordenadas do local:</p>
|
||||
<p>
|
||||
{missing.length} investimentos aguardam coordenadas do
|
||||
local:
|
||||
</p>
|
||||
<ul>
|
||||
{missing.map((record) => (
|
||||
<li key={record.id}>
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { correctiveStates, investmentLocations, roadmapPhaseIndex, roadmapPhases, type RoadmapLink } from '@/lib/investment-roadmap';
|
||||
import {
|
||||
correctiveStates,
|
||||
investmentLocations,
|
||||
roadmapPhaseIndex,
|
||||
roadmapPhases,
|
||||
type RoadmapLink,
|
||||
} from '@/lib/investment-roadmap';
|
||||
import { roadmapSource } from '@/lib/investment-roadmap-source';
|
||||
|
||||
function Resources({ links }: { links: RoadmapLink[] }) {
|
||||
return <ul className="flex flex-wrap gap-3">
|
||||
{links.map((link) => <li key={`${link.href}-${link.label}`}><Link href={link.href} className="inline-block rounded-lg border border-emerald-800 px-4 py-2 text-emerald-900 underline underline-offset-4 focus-visible:outline-2">{link.label}</Link></li>)}
|
||||
</ul>;
|
||||
return (
|
||||
<ul className="flex flex-wrap gap-3">
|
||||
{links.map((link) => (
|
||||
<li key={`${link.href}-${link.label}`}>
|
||||
<Link
|
||||
href={link.href}
|
||||
className="inline-block rounded-lg border border-emerald-800 px-4 py-2 text-emerald-900 underline underline-offset-4 focus-visible:outline-2"
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function SourceTable({ index }: { index: number }) {
|
||||
@@ -14,15 +31,54 @@ function SourceTable({ index }: { index: number }) {
|
||||
const header = table?.[0];
|
||||
const rows = table?.slice(1) ?? [];
|
||||
if (!header) {
|
||||
return <p role="alert">A tabela não está disponível. Rever a transcrição do documento.</p>;
|
||||
return (
|
||||
<p role="alert">
|
||||
A tabela não está disponível. Rever a transcrição do documento.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return <div className="max-w-full overflow-x-auto rounded-lg border" role="region" aria-label={header.join(', ')} tabIndex={0}>
|
||||
<table className="w-full min-w-[640px] border-collapse text-left text-sm">
|
||||
<caption className="p-3 text-left text-slate-600">Transcrição do roteiro fornecido. Confirmar aplicabilidade e fontes antes de decisões de execução.</caption>
|
||||
<thead className="bg-emerald-900 text-white"><tr>{header.map((cell, i) => <th key={i} scope="col" className="border border-slate-300 p-3 align-top">{cell}</th>)}</tr></thead>
|
||||
<tbody>{rows.map((row, i) => <tr key={i} className="odd:bg-white even:bg-slate-50">{row.map((cell, j) => <td key={j} className="min-w-40 border border-slate-200 p-3 align-top whitespace-pre-line">{cell || '—'}</td>)}</tr>)}</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
return (
|
||||
<div
|
||||
className="max-w-full overflow-x-auto rounded-lg border"
|
||||
role="region"
|
||||
aria-label={header.join(', ')}
|
||||
tabIndex={0}
|
||||
>
|
||||
<table className="w-full min-w-[640px] border-collapse text-left text-sm">
|
||||
<caption className="p-3 text-left text-slate-600">
|
||||
Transcrição do roteiro fornecido. Confirmar aplicabilidade e
|
||||
fontes antes de decisões de execução.
|
||||
</caption>
|
||||
<thead className="bg-emerald-900 text-white">
|
||||
<tr>
|
||||
{header.map((cell, i) => (
|
||||
<th
|
||||
key={i}
|
||||
scope="col"
|
||||
className="border border-slate-300 p-3 align-top"
|
||||
>
|
||||
{cell}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, i) => (
|
||||
<tr key={i} className="odd:bg-white even:bg-slate-50">
|
||||
{row.map((cell, j) => (
|
||||
<td
|
||||
key={j}
|
||||
className="min-w-40 border border-slate-200 p-3 align-top whitespace-pre-line"
|
||||
>
|
||||
{cell || '—'}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvestmentRoadmap() {
|
||||
@@ -37,69 +93,308 @@ export function InvestmentRoadmap() {
|
||||
function select(index: number) {
|
||||
if (index < 0 || index >= roadmapPhases.length) return;
|
||||
setActive(index);
|
||||
window.history.replaceState(window.history.state, '', `${window.location.pathname}${window.location.search}#${roadmapPhases[index].id}`);
|
||||
window.history.replaceState(
|
||||
window.history.state,
|
||||
'',
|
||||
`${window.location.pathname}${window.location.search}#${roadmapPhases[index].id}`,
|
||||
);
|
||||
}
|
||||
return <div className="min-w-0 space-y-8">
|
||||
<header className="space-y-4">
|
||||
<p className="text-sm font-semibold text-emerald-800">DA IDEIA À OPERAÇÃO</p>
|
||||
<h2 className="text-3xl font-bold">Roteiro de implementação de ideias em Moçambique</h2>
|
||||
<p>Comece pela fase que corresponde ao seu projecto. Pode consultar, comparar alternativas e rever o plano em qualquer momento. A exploração não exige empresa constituída, documentos carregados ou aprovação prévia.</p>
|
||||
<Resources links={[{ label: 'Abrir ou continuar o dossier e simulador', href: '/simulador-fiscal' }, { label: 'Explorar oportunidades', href: '/oportunidades' }, { label: 'Pedir apoio', href: '/apoio' }]} />
|
||||
<p className="text-sm text-slate-600">No simulador, escolha o percurso de ideia/pequeno negócio ou de projecto de investimento. O dossier reúne informação, plano financeiro, riscos e relatório. Os resultados financeiros e fiscais têm pressupostos distintos; a escolha de uma zona não confirma automaticamente um incentivo.</p>
|
||||
</header>
|
||||
return (
|
||||
<div className="min-w-0 space-y-8">
|
||||
<header className="space-y-4">
|
||||
<p className="text-sm font-semibold text-emerald-800">
|
||||
DA IDEIA À OPERAÇÃO
|
||||
</p>
|
||||
<h2 className="text-3xl font-bold">
|
||||
Roteiro de implementação de ideias em Moçambique
|
||||
</h2>
|
||||
<p>
|
||||
Comece pela fase que corresponde ao seu projecto. Pode
|
||||
consultar, comparar alternativas e rever o plano em qualquer
|
||||
momento. A exploração não exige empresa constituída,
|
||||
documentos carregados ou aprovação prévia.
|
||||
</p>
|
||||
<Resources
|
||||
links={[
|
||||
{
|
||||
label: 'Abrir ou continuar o dossier e simulador',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{
|
||||
label: 'Explorar oportunidades',
|
||||
href: '/oportunidades',
|
||||
},
|
||||
{ label: 'Pedir apoio', href: '/apoio' },
|
||||
]}
|
||||
/>
|
||||
<p className="text-sm text-slate-600">
|
||||
No simulador, escolha o percurso de ideia/pequeno negócio ou
|
||||
de projecto de investimento. O dossier reúne informação,
|
||||
plano financeiro, riscos e relatório. Os resultados
|
||||
financeiros e fiscais têm pressupostos distintos; a escolha
|
||||
de uma zona não confirma automaticamente um incentivo.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<nav aria-label="Fases do roteiro" className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
|
||||
{roadmapPhases.map((item, index) => <button type="button" key={item.id} aria-pressed={active === index} aria-controls="roadmap-phase" onClick={() => select(index)} className={`rounded-xl border p-4 text-left focus-visible:outline-2 ${active === index ? 'border-emerald-900 bg-emerald-900 text-white' : 'border-slate-300 bg-white text-slate-900'}`}>
|
||||
<span className="mb-1 block text-sm">Fase {index + 1}</span><span className="font-semibold">{item.title}</span>
|
||||
</button>)}
|
||||
</nav>
|
||||
<nav
|
||||
aria-label="Fases do roteiro"
|
||||
className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5"
|
||||
>
|
||||
{roadmapPhases.map((item, index) => (
|
||||
<button
|
||||
type="button"
|
||||
key={item.id}
|
||||
aria-pressed={active === index}
|
||||
aria-controls="roadmap-phase"
|
||||
onClick={() => select(index)}
|
||||
className={`rounded-xl border p-4 text-left focus-visible:outline-2 ${active === index ? 'border-emerald-900 bg-emerald-900 text-white' : 'border-slate-300 bg-white text-slate-900'}`}
|
||||
>
|
||||
<span className="mb-1 block text-sm">
|
||||
Fase {index + 1}
|
||||
</span>
|
||||
<span className="font-semibold">{item.title}</span>
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<section id="roadmap-phase" aria-labelledby="roadmap-phase-title" className="space-y-5 rounded-xl border bg-white p-5 sm:p-7">
|
||||
<h3 id="roadmap-phase-title" className="text-2xl font-bold">{active + 1}. {phase.title}</h3>
|
||||
<p>{phase.summary}</p>
|
||||
<ol className="grid gap-4 sm:grid-cols-2">
|
||||
{phase.steps.map((step) => <li key={step.title} className="space-y-2 border-l-2 border-emerald-700 pl-4"><h4 className="font-semibold">{step.title}</h4><p>{step.description}</p><p className="text-sm text-slate-600"><strong>Resultado:</strong> {step.result}</p></li>)}
|
||||
</ol>
|
||||
<Resources links={phase.links} />
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">PC{active + 1} · Decisão, evidências e acções de revisão</summary>
|
||||
<p className="mt-3">Estes pontos orientam a decisão do promotor e das entidades competentes. Informação pendente deve ser investigada; todas as fases do portal continuam acessíveis. Uma restrição à execução deve identificar a actividade afectada, a condição aplicável e a respectiva fonte.</p>
|
||||
<dl className="space-y-3">{roadmapSource.tables[1][0].slice(1).map((heading, i) => <div key={heading}><dt className="font-semibold">{heading}</dt><dd>{roadmapSource.tables[1][active + 1][i + 1]}</dd></div>)}</dl>
|
||||
<h4 className="font-semibold">Evidência a recolher quando aplicável</h4>
|
||||
<p>{roadmapSource.tables[6][active + 1][1]}</p>
|
||||
<p className="text-sm">A lista provém do roteiro geral e requer enquadramento no sector, localização e operação do projecto.</p>
|
||||
</details>
|
||||
<div className="flex flex-wrap justify-between gap-3">
|
||||
{active > 0 && <button type="button" onClick={() => select(active - 1)} className="rounded border px-4 py-2 underline">Fase anterior</button>}
|
||||
{active < roadmapPhases.length - 1 && <button type="button" onClick={() => select(active + 1)} className="rounded bg-emerald-800 px-4 py-2 text-white">Explorar a fase seguinte</button>}
|
||||
</div>
|
||||
</section>
|
||||
<section
|
||||
id="roadmap-phase"
|
||||
aria-labelledby="roadmap-phase-title"
|
||||
className="space-y-5 rounded-xl border bg-white p-5 sm:p-7"
|
||||
>
|
||||
<h3 id="roadmap-phase-title" className="text-2xl font-bold">
|
||||
{active + 1}. {phase.title}
|
||||
</h3>
|
||||
<p>{phase.summary}</p>
|
||||
<ol className="grid gap-4 sm:grid-cols-2">
|
||||
{phase.steps.map((step) => (
|
||||
<li
|
||||
key={step.title}
|
||||
className="space-y-2 border-l-2 border-emerald-700 pl-4"
|
||||
>
|
||||
<h4 className="font-semibold">{step.title}</h4>
|
||||
<p>{step.description}</p>
|
||||
<p className="text-sm text-slate-600">
|
||||
<strong>Resultado:</strong> {step.result}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<Resources links={phase.links} />
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
PC{active + 1} · Decisão, evidências e acções de revisão
|
||||
</summary>
|
||||
<p className="mt-3">
|
||||
Estes pontos orientam a decisão do promotor e das
|
||||
entidades competentes. Informação pendente deve ser
|
||||
investigada; todas as fases do portal continuam
|
||||
acessíveis. Uma restrição à execução deve identificar a
|
||||
actividade afectada, a condição aplicável e a respectiva
|
||||
fonte.
|
||||
</p>
|
||||
<dl className="space-y-3">
|
||||
{roadmapSource.tables[1][0]
|
||||
.slice(1)
|
||||
.map((heading, i) => (
|
||||
<div key={heading}>
|
||||
<dt className="font-semibold">{heading}</dt>
|
||||
<dd>
|
||||
{
|
||||
roadmapSource.tables[1][active + 1][
|
||||
i + 1
|
||||
]
|
||||
}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<h4 className="font-semibold">
|
||||
Evidência a recolher quando aplicável
|
||||
</h4>
|
||||
<p>{roadmapSource.tables[6][active + 1][1]}</p>
|
||||
<p className="text-sm">
|
||||
A lista provém do roteiro geral e requer enquadramento
|
||||
no sector, localização e operação do projecto.
|
||||
</p>
|
||||
</details>
|
||||
<div className="flex flex-wrap justify-between gap-3">
|
||||
{active > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => select(active - 1)}
|
||||
className="rounded border px-4 py-2 underline"
|
||||
>
|
||||
Fase anterior
|
||||
</button>
|
||||
)}
|
||||
{active < roadmapPhases.length - 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => select(active + 1)}
|
||||
className="rounded bg-emerald-800 px-4 py-2 text-white"
|
||||
>
|
||||
Explorar a fase seguinte
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4" aria-labelledby="roadmap-locations">
|
||||
<h3 id="roadmap-locations" className="text-2xl font-bold">Comparar locais e estruturas de investimento</h3>
|
||||
<p>Compare localização, custos, acesso ao mercado, logística, infra-estruturas, trabalhadores e requisitos. ZEE, ZFI, parques industriais e clusters são opções territoriais ou estruturas de investimento; o sector económico da actividade é registado separadamente.</p>
|
||||
<Resources links={investmentLocations} />
|
||||
<p className="text-sm text-slate-600">Confirme os dados publicados de cada alternativa. Uma localização ou proximidade não comprova disponibilidade de espaço, serviços, elegibilidade ou benefícios fiscais.</p>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Exigências de ZEE, ZFI, parques e clusters referidas no roteiro</summary><p className="mt-3">O documento mantém pendentes de confirmação no texto oficial os artigos, a regra 70/30 e os limiares da ZFI isolada. Esta tabela permite consultar essas referências; não activa cálculos ou decisões de elegibilidade.</p><SourceTable index={5} /></details>
|
||||
</section>
|
||||
<section className="space-y-4" aria-labelledby="roadmap-locations">
|
||||
<h3 id="roadmap-locations" className="text-2xl font-bold">
|
||||
Comparar locais e estruturas de investimento
|
||||
</h3>
|
||||
<p>
|
||||
Compare localização, custos, acesso ao mercado, logística,
|
||||
infra-estruturas, trabalhadores e requisitos. ZEE, ZFI,
|
||||
parques industriais e clusters são opções territoriais ou
|
||||
estruturas de investimento; o sector económico da actividade
|
||||
é registado separadamente.
|
||||
</p>
|
||||
<Resources links={investmentLocations} />
|
||||
<p className="text-sm text-slate-600">
|
||||
Confirme os dados publicados de cada alternativa. Uma
|
||||
localização ou proximidade não comprova disponibilidade de
|
||||
espaço, serviços, elegibilidade ou benefícios fiscais.
|
||||
</p>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Exigências de ZEE, ZFI, parques e clusters referidas no
|
||||
roteiro
|
||||
</summary>
|
||||
<p className="mt-3">
|
||||
O documento mantém pendentes de confirmação no texto
|
||||
oficial os artigos, a regra 70/30 e os limiares da ZFI
|
||||
isolada. Esta tabela permite consultar essas
|
||||
referências; não activa cálculos ou decisões de
|
||||
elegibilidade.
|
||||
</p>
|
||||
<SourceTable index={5} />
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4" aria-labelledby="roadmap-tools">
|
||||
<h3 id="roadmap-tools" className="text-2xl font-bold">Ficha de projecto, conformidade e acompanhamento</h3>
|
||||
<p>Use o dossier existente para desenvolver a ideia, mercado, localização, equipa, finanças e respostas a riscos. Consulte os campos complementares do roteiro e registe a informação aplicável no plano e nos documentos do projecto.</p>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Ficha completa de dados do projecto</summary><p className="mt-3">Os marcadores de preenchimento do documento representam dados pendentes. Preencha os campos aplicáveis e justifique os que não se aplicam; dados desconhecidos não devem ser substituídos por zero.</p><SourceTable index={3} /></details>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Plano de acções correctivas</summary><p className="mt-3">Registe identificador, responsável nominal, data de abertura, prazo acordado, prioridade, estado, bloqueios, evidência de encerramento e condição de reentrada. Os prazos abaixo são alvos de gestão sugeridos pelo roteiro; não são prazos legais confirmados.</p><p>Estados: {correctiveStates.join(' · ')}.</p><SourceTable index={2} /></details>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Matriz geral de requisitos por fase</summary><SourceTable index={0} /></details>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Pontos de controlo e matriz de evidências completos</summary><SourceTable index={1} /><SourceTable index={6} /></details>
|
||||
<Resources links={[{ label: 'Continuar o dossier', href: '/simulador-fiscal' }, { label: 'Consultar documentos e formulários', href: '/documentos' }, { label: 'Acompanhar o espaço privado', href: '/investidor' }, { label: 'Procurar parceiros', href: '/parcerias' }]} />
|
||||
<p className="text-sm text-slate-600">O espaço privado exige autenticação. A consulta deste roteiro e a exploração pública permanecem disponíveis sem conta.</p>
|
||||
</section>
|
||||
<section className="space-y-4" aria-labelledby="roadmap-tools">
|
||||
<h3 id="roadmap-tools" className="text-2xl font-bold">
|
||||
Ficha de projecto, conformidade e acompanhamento
|
||||
</h3>
|
||||
<p>
|
||||
Use o dossier existente para desenvolver a ideia, mercado,
|
||||
localização, equipa, finanças e respostas a riscos. Consulte
|
||||
os campos complementares do roteiro e registe a informação
|
||||
aplicável no plano e nos documentos do projecto.
|
||||
</p>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Ficha completa de dados do projecto
|
||||
</summary>
|
||||
<p className="mt-3">
|
||||
Os marcadores de preenchimento do documento representam
|
||||
dados pendentes. Preencha os campos aplicáveis e
|
||||
justifique os que não se aplicam; dados desconhecidos
|
||||
não devem ser substituídos por zero.
|
||||
</p>
|
||||
<SourceTable index={3} />
|
||||
</details>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Plano de acções correctivas
|
||||
</summary>
|
||||
<p className="mt-3">
|
||||
Registe identificador, responsável nominal, data de
|
||||
abertura, prazo acordado, prioridade, estado, bloqueios,
|
||||
evidência de encerramento e condição de reentrada. Os
|
||||
prazos abaixo são alvos de gestão sugeridos pelo
|
||||
roteiro; não são prazos legais confirmados.
|
||||
</p>
|
||||
<p>Estados: {correctiveStates.join(' · ')}.</p>
|
||||
<SourceTable index={2} />
|
||||
</details>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Matriz geral de requisitos por fase
|
||||
</summary>
|
||||
<SourceTable index={0} />
|
||||
</details>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Pontos de controlo e matriz de evidências completos
|
||||
</summary>
|
||||
<SourceTable index={1} />
|
||||
<SourceTable index={6} />
|
||||
</details>
|
||||
<Resources
|
||||
links={[
|
||||
{
|
||||
label: 'Continuar o dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{
|
||||
label: 'Consultar documentos e formulários',
|
||||
href: '/documentos',
|
||||
},
|
||||
{
|
||||
label: 'Acompanhar o espaço privado',
|
||||
href: '/investidor',
|
||||
},
|
||||
{ label: 'Procurar parceiros', href: '/parcerias' },
|
||||
]}
|
||||
/>
|
||||
<p className="text-sm text-slate-600">
|
||||
O espaço privado exige autenticação. A consulta deste
|
||||
roteiro e a exploração pública permanecem disponíveis sem
|
||||
conta.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3 border-t pt-5" aria-labelledby="roadmap-source">
|
||||
<h3 id="roadmap-source" className="text-xl font-bold">Origem e validação das referências</h3>
|
||||
<p>Adaptado de <cite>Roteiro de Implementação de Ideias de Negócio em Moçambique</cite>, fornecido pelo proprietário do portal. A matriz é geral e provisória; a aplicabilidade depende da actividade, localização, dimensão, origem do investimento e operação.</p>
|
||||
<p>As afirmações de confirmação jurídica pertencem ao documento de origem. Esta integração não verifica a vigência dos diplomas nem aprova artigos, requisitos ou parâmetros fiscais. A obtenção de evidências orienta as decisões de execução e pode decorrer enquanto o promotor continua a preparar o projecto.</p>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Estado das fontes e artigos indicado pelo documento</summary><SourceTable index={4} /></details>
|
||||
<details className="space-y-3 rounded-lg border p-4"><summary className="cursor-pointer font-semibold">Texto completo do roteiro</summary><div className="space-y-3 pt-3">{roadmapSource.paragraphs.map((paragraph, index) => <p key={index} className="whitespace-pre-line">{paragraph}</p>)}</div><p className="text-sm">As sete tabelas do documento estão disponíveis nas secções acima. As ilustrações e o original são preservados no ficheiro de origem.</p></details>
|
||||
</section>
|
||||
</div>;
|
||||
<section
|
||||
className="space-y-3 border-t pt-5"
|
||||
aria-labelledby="roadmap-source"
|
||||
>
|
||||
<h3 id="roadmap-source" className="text-xl font-bold">
|
||||
Origem e validação das referências
|
||||
</h3>
|
||||
<p>
|
||||
Adaptado de{' '}
|
||||
<cite>
|
||||
Roteiro de Implementação de Ideias de Negócio em
|
||||
Moçambique
|
||||
</cite>
|
||||
, fornecido pelo proprietário do portal. A matriz é geral e
|
||||
provisória; a aplicabilidade depende da actividade,
|
||||
localização, dimensão, origem do investimento e operação.
|
||||
</p>
|
||||
<p>
|
||||
As afirmações de confirmação jurídica pertencem ao documento
|
||||
de origem. Esta integração não verifica a vigência dos
|
||||
diplomas nem aprova artigos, requisitos ou parâmetros
|
||||
fiscais. A obtenção de evidências orienta as decisões de
|
||||
execução e pode decorrer enquanto o promotor continua a
|
||||
preparar o projecto.
|
||||
</p>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Estado das fontes e artigos indicado pelo documento
|
||||
</summary>
|
||||
<SourceTable index={4} />
|
||||
</details>
|
||||
<details className="space-y-3 rounded-lg border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Texto completo do roteiro
|
||||
</summary>
|
||||
<div className="space-y-3 pt-3">
|
||||
{roadmapSource.paragraphs.map((paragraph, index) => (
|
||||
<p key={index} className="whitespace-pre-line">
|
||||
{paragraph}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
As sete tabelas do documento estão disponíveis nas
|
||||
secções acima. As ilustrações e o original são
|
||||
preservados no ficheiro de origem.
|
||||
</p>
|
||||
</details>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { api } from "@/pages/investment/shared";
|
||||
import { replaceTerritoryPath } from "@/lib/territory-path.js";
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
import { replaceTerritoryPath } from '@/lib/territory-path.js';
|
||||
|
||||
export type TerritoryOption = {
|
||||
id: string;
|
||||
@@ -11,18 +11,18 @@ export type TerritoryOption = {
|
||||
source_code?: string | null;
|
||||
};
|
||||
type Option = TerritoryOption;
|
||||
const levels = ["province", "district", "admin_post", "locality"];
|
||||
const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"];
|
||||
const control = "w-full rounded border bg-background p-2 text-foreground";
|
||||
const levels = ['province', 'district', 'admin_post', 'locality'];
|
||||
const labels = ['Província', 'Distrito', 'Posto administrativo', 'Localidade'];
|
||||
const control = 'w-full rounded border bg-background p-2 text-foreground';
|
||||
const emptyTerritoryPath: TerritoryOption[] = [];
|
||||
|
||||
export function ProvinceSelect({
|
||||
value,
|
||||
onChange,
|
||||
endpoint = "/api/v1/catalogs/jurisdictions",
|
||||
placeholder = "Seleccione uma província",
|
||||
endpoint = '/api/v1/catalogs/jurisdictions',
|
||||
placeholder = 'Seleccione uma província',
|
||||
className = control,
|
||||
label = "Província",
|
||||
label = 'Província',
|
||||
required = false,
|
||||
}: {
|
||||
value: string;
|
||||
@@ -36,25 +36,30 @@ export function ProvinceSelect({
|
||||
const id = useId();
|
||||
const [options, setOptions] = useState<Option[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
setError('');
|
||||
fetch(`${endpoint}?type=province&page=1`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error("Não foi possível carregar as províncias.");
|
||||
if (!response.ok)
|
||||
throw new Error('Não foi possível carregar as províncias.');
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => setOptions(data.data))
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(cause instanceof Error ? cause.message : "Erro de ligação.");
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro de ligação.',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
@@ -69,11 +74,15 @@ export function ProvinceSelect({
|
||||
aria-label={label}
|
||||
className={className}
|
||||
required={required}
|
||||
value={options.some((option) => option.name === value) ? value : ""}
|
||||
value={
|
||||
options.some((option) => option.name === value) ? value : ''
|
||||
}
|
||||
disabled={loading || Boolean(error)}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">{loading ? "A carregar províncias…" : placeholder}</option>
|
||||
<option value="">
|
||||
{loading ? 'A carregar províncias…' : placeholder}
|
||||
</option>
|
||||
{options.map((option) => (
|
||||
<option key={option.id} value={option.name}>
|
||||
{option.name}
|
||||
@@ -82,8 +91,11 @@ export function ProvinceSelect({
|
||||
</select>
|
||||
{error && (
|
||||
<span role="alert" className="block text-sm">
|
||||
{error}{" "}
|
||||
<button type="button" onClick={() => setRetry((current) => current + 1)}>
|
||||
{error}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRetry((current) => current + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</span>
|
||||
@@ -95,7 +107,7 @@ export function ProvinceSelect({
|
||||
export function TerritoryFields({
|
||||
initial = emptyTerritoryPath,
|
||||
onChange,
|
||||
endpoint = "/api/v1/catalogs/jurisdictions",
|
||||
endpoint = '/api/v1/catalogs/jurisdictions',
|
||||
}: {
|
||||
initial?: TerritoryOption[];
|
||||
onChange?: (path: TerritoryOption[]) => void;
|
||||
@@ -105,24 +117,37 @@ export function TerritoryFields({
|
||||
useEffect(() => setPath(initial), [initial]);
|
||||
return (
|
||||
<div className="grid gap-4 md:col-span-full md:grid-cols-2">
|
||||
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
|
||||
(field, index) => (
|
||||
<div key={`${field}-${path[index - 1]?.id ?? ""}`}>
|
||||
<input type="hidden" name={field} value={path[index]?.id ?? ""} />
|
||||
<TerritoryLevel
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
selected={path[index]}
|
||||
endpoint={endpoint}
|
||||
onChange={(value) => {
|
||||
const next = replaceTerritoryPath(path, index, value);
|
||||
setPath(next);
|
||||
onChange?.(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((field, index) => (
|
||||
<div key={`${field}-${path[index - 1]?.id ?? ''}`}>
|
||||
<input
|
||||
type="hidden"
|
||||
name={field}
|
||||
value={path[index]?.id ?? ''}
|
||||
/>
|
||||
<TerritoryLevel
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={endpoint}
|
||||
onChange={(value) => {
|
||||
const next = replaceTerritoryPath(
|
||||
path,
|
||||
index,
|
||||
value,
|
||||
);
|
||||
setPath(next);
|
||||
onChange?.(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -132,7 +157,7 @@ export function TerritoryLevel({
|
||||
parent,
|
||||
selected,
|
||||
onChange,
|
||||
endpoint = "/management/territory-options",
|
||||
endpoint = '/management/territory-options',
|
||||
fieldError,
|
||||
}: {
|
||||
index: number;
|
||||
@@ -146,7 +171,7 @@ export function TerritoryLevel({
|
||||
const [page, setPage] = useState(1);
|
||||
const [options, setOptions] = useState<Option[]>([]);
|
||||
const [more, setMore] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const enabled = index === 0 || Boolean(parent);
|
||||
@@ -158,7 +183,7 @@ export function TerritoryLevel({
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
type: levels[index],
|
||||
@@ -167,16 +192,21 @@ export function TerritoryLevel({
|
||||
});
|
||||
const response = await fetch(`${endpoint}?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) throw new Error("Não foi possível carregar as localizações.");
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível carregar as localizações.',
|
||||
);
|
||||
const data = await response.json();
|
||||
if (controller.signal.aborted) return;
|
||||
setOptions(data.data);
|
||||
setMore(Boolean(data.next_page_url));
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setError(e instanceof Error ? e.message : "Erro de ligação.");
|
||||
setError(
|
||||
e instanceof Error ? e.message : 'Erro de ligação.',
|
||||
);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
@@ -197,27 +227,33 @@ export function TerritoryLevel({
|
||||
aria-describedby={fieldError ? `${id}-error` : undefined}
|
||||
className={control}
|
||||
disabled={!enabled || loading}
|
||||
value={selected?.id ?? ""}
|
||||
onChange={(e) => onChange(options.find((o) => o.id === e.target.value))}
|
||||
value={selected?.id ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange(options.find((o) => o.id === e.target.value))
|
||||
}
|
||||
>
|
||||
<option value="">{enabled ? "Seleccione" : "Seleccione o nível anterior"}</option>
|
||||
<option value="">
|
||||
{enabled ? 'Seleccione' : 'Seleccione o nível anterior'}
|
||||
</option>
|
||||
{selected && !options.some((o) => o.id === selected.id) && (
|
||||
<option value={selected.id}>
|
||||
{selected.name}
|
||||
{selected.deleted_at ? " (arquivada)" : " (selecção actual)"}
|
||||
{selected.deleted_at
|
||||
? ' (arquivada)'
|
||||
: ' (selecção actual)'}
|
||||
</option>
|
||||
)}
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
{o.source_code ? ` (${o.source_code})` : ""}
|
||||
{o.source_code ? ` (${o.source_code})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{loading && <p role="status">A carregar…</p>}
|
||||
{error && (
|
||||
<div role="alert">
|
||||
{error}{" "}
|
||||
{error}{' '}
|
||||
<button type="button" onClick={() => setRetry(retry + 1)}>
|
||||
Tentar novamente
|
||||
</button>
|
||||
@@ -247,10 +283,16 @@ export function TerritoryLevel({
|
||||
);
|
||||
}
|
||||
|
||||
export default function InvestmentTerritory({ kind, id }: { kind: string; id: string | number }) {
|
||||
export default function InvestmentTerritory({
|
||||
kind,
|
||||
id,
|
||||
}: {
|
||||
kind: string;
|
||||
id: string | number;
|
||||
}) {
|
||||
const [path, setPath] = useState<Option[]>([]);
|
||||
const [version, setVersion] = useState<number | null>(null);
|
||||
const [message, setMessage] = useState("");
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
@@ -259,7 +301,9 @@ export default function InvestmentTerritory({ kind, id }: { kind: string; id: st
|
||||
if (!active) return;
|
||||
setPath(
|
||||
levels.flatMap((level) =>
|
||||
data.path.filter((o: Option) => o.location_type === level),
|
||||
data.path.filter(
|
||||
(o: Option) => o.location_type === level,
|
||||
),
|
||||
),
|
||||
);
|
||||
setVersion(data.version);
|
||||
@@ -276,38 +320,48 @@ export default function InvestmentTerritory({ kind, id }: { kind: string; id: st
|
||||
className="my-6 space-y-4 rounded border p-4"
|
||||
aria-label="Localização do investimento"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">Localização do investimento</h2>
|
||||
<p>Seleccione até ao nível conhecido. Alterar um nível limpa as selecções seguintes.</p>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Localização do investimento
|
||||
</h2>
|
||||
<p>
|
||||
Seleccione até ao nível conhecido. Alterar um nível limpa as
|
||||
selecções seguintes.
|
||||
</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{levels.map((level, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${level}-${path[index - 1]?.id ?? ""}`}
|
||||
key={`${level}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
onChange={(value) => {
|
||||
setPath(replaceTerritoryPath(path, index, value));
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
|
||||
className="bg-primary text-primary-foreground rounded px-4 py-2 disabled:opacity-50"
|
||||
disabled={version === null || busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
const data = await api(`/management/territories/${kind}/${id}`, {
|
||||
version,
|
||||
path: path.map((o) => o.id),
|
||||
});
|
||||
const data = await api(
|
||||
`/management/territories/${kind}/${id}`,
|
||||
{
|
||||
version,
|
||||
path: path.map((o) => o.id),
|
||||
},
|
||||
);
|
||||
setVersion(data.version);
|
||||
setMessage("Localização associada e guardada.");
|
||||
setMessage('Localização associada e guardada.');
|
||||
} catch (e) {
|
||||
setMessage(e instanceof Error ? e.message : "Erro ao guardar.");
|
||||
setMessage(
|
||||
e instanceof Error ? e.message : 'Erro ao guardar.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,890 @@
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import type { RequestPayload } from '@inertiajs/core';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
guidanceFinance,
|
||||
guidanceFinancialTools,
|
||||
} from '@/lib/investor-guidance-finance';
|
||||
import { input, button, card } from '@/pages/investment/shared';
|
||||
|
||||
type Recommendation = {
|
||||
code: string;
|
||||
kind: string;
|
||||
classification: string;
|
||||
explanation: string;
|
||||
href: string;
|
||||
source: {
|
||||
identifier: string;
|
||||
reference: string;
|
||||
date: string;
|
||||
nature: string;
|
||||
};
|
||||
limitations: string[];
|
||||
review: {
|
||||
decision: string;
|
||||
reason: string;
|
||||
date: string;
|
||||
stale: boolean;
|
||||
} | null;
|
||||
};
|
||||
export type Guidance = {
|
||||
version: number;
|
||||
fingerprint: string;
|
||||
rules_version: string;
|
||||
computed_at: string;
|
||||
can_write: boolean;
|
||||
facts: Record<string, string>;
|
||||
financial_draft: Record<string, unknown> | null;
|
||||
consulted: {
|
||||
module: string;
|
||||
id: string;
|
||||
version: number;
|
||||
date: string;
|
||||
status: string;
|
||||
}[];
|
||||
unavailable: string[];
|
||||
catalogue_checks: {
|
||||
code: string;
|
||||
classification: string;
|
||||
explanation: string;
|
||||
source: Record<string, unknown> | null;
|
||||
}[];
|
||||
phases: {
|
||||
id: string;
|
||||
objective: string;
|
||||
known: { field: string; value: string; status: string }[];
|
||||
questions: string[];
|
||||
evidence: {
|
||||
field: string;
|
||||
state: string;
|
||||
documents: {
|
||||
document_id: string;
|
||||
name: string;
|
||||
state: string;
|
||||
version: number;
|
||||
valid_until: string | null;
|
||||
review: {
|
||||
author: string;
|
||||
date: string;
|
||||
what_checked: string;
|
||||
evidence: string;
|
||||
scope: string;
|
||||
} | null;
|
||||
}[];
|
||||
}[];
|
||||
recommendations: Recommendation[];
|
||||
risks: {
|
||||
code: string;
|
||||
classification: string;
|
||||
explanation: string;
|
||||
restriction: boolean;
|
||||
}[];
|
||||
}[];
|
||||
tasks: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
due_at: string;
|
||||
version_no: number;
|
||||
assignee_name: string;
|
||||
assignee_user_id: number;
|
||||
accepted_at: string;
|
||||
external_sync_status: string;
|
||||
desk_request_id: string | null;
|
||||
}[];
|
||||
crm: { internal: string; external: string; reason: string };
|
||||
calculator_versions: Record<string, string>;
|
||||
};
|
||||
const fields: Record<string, string> = {
|
||||
project_title: 'Título',
|
||||
project_summary: 'Objectivo do projecto',
|
||||
activity: 'Actividade e produtos',
|
||||
target_customers: 'Clientes ou beneficiários',
|
||||
market_evidence: 'Referência da evidência de mercado',
|
||||
location: 'Localização em análise',
|
||||
location_evidence: 'Referência e dúvidas sobre o local',
|
||||
resource_plan: 'Recursos e equipa necessários',
|
||||
resource_evidence: 'Evidência de disponibilidade dos recursos',
|
||||
funding_evidence: 'Evidência do financiamento',
|
||||
expected_start_date: 'Data prevista de início',
|
||||
ready_date: 'Data de disponibilidade dos recursos',
|
||||
schedule: 'Calendário e dependências',
|
||||
demand_quantity: 'Procura declarada (quantidade, não previsão)',
|
||||
capacity_quantity: 'Capacidade declarada na mesma unidade e período',
|
||||
quantity_unit: 'Unidade comum da procura e capacidade',
|
||||
quantity_period: 'Período comum da procura e capacidade',
|
||||
resources_required: 'Quantidade de recursos necessários declarados',
|
||||
resources_available: 'Quantidade de recursos disponíveis declarados',
|
||||
resource_unit: 'Unidade comum dos recursos',
|
||||
funding_required: 'Financiamento necessário declarado',
|
||||
funding_committed: 'Financiamento comprometido declarado',
|
||||
funding_currency: 'Moeda comum do financiamento',
|
||||
funding_ready_date: 'Data declarada de disponibilidade do financiamento',
|
||||
completion_date: 'Data declarada de conclusão',
|
||||
};
|
||||
const decisionLabels: Record<string, string> = {
|
||||
accepted: 'Aceite pelo investidor',
|
||||
rejected: 'Rejeitada pelo investidor',
|
||||
corrected: 'Contestada / correcção solicitada',
|
||||
};
|
||||
const evidenceLabels: Record<string, string> = {
|
||||
absent: 'Sem informação',
|
||||
investor_declared_not_verified: 'Declaração por conferir',
|
||||
attached_unchecked: 'Documento associado, por conferir',
|
||||
internally_verified: 'Conferido internamente no âmbito descrito',
|
||||
contradiction: 'Contradição documentada',
|
||||
issue_identified: 'Problema documental identificado',
|
||||
expired: 'Validade registada terminada',
|
||||
superseded: 'Ficheiro ou versão substituída — rever',
|
||||
technical_unavailable: 'Evidência indisponível',
|
||||
};
|
||||
export function InvestorGuidance({
|
||||
caseId,
|
||||
guidance,
|
||||
manager = false,
|
||||
actorId,
|
||||
requests = [],
|
||||
}: {
|
||||
caseId: string;
|
||||
guidance: Guidance;
|
||||
manager?: boolean;
|
||||
actorId?: number;
|
||||
requests?: { id: string; protocol: string | null }[];
|
||||
}) {
|
||||
const requestedPhase = new URLSearchParams(
|
||||
usePage().url.split('?')[1] ?? '',
|
||||
).get('phase');
|
||||
const [phaseId, setPhaseId] = useState(
|
||||
guidance.phases.some((p) => p.id === requestedPhase)
|
||||
? requestedPhase!
|
||||
: guidance.phases[0].id,
|
||||
);
|
||||
const [facts, setFacts] = useState(guidance.facts);
|
||||
const [reason, setReason] = useState('');
|
||||
const [due, setDue] = useState('');
|
||||
const [requestId, setRequestId] = useState('');
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [sources, setSources] = useState<{
|
||||
status: string;
|
||||
consulted: {
|
||||
title: string;
|
||||
content: string;
|
||||
source_url: string;
|
||||
source_date: string;
|
||||
nature: string;
|
||||
}[];
|
||||
} | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const post = (path: string, data: RequestPayload) => {
|
||||
setErrors({});
|
||||
setBusy(true);
|
||||
router.post(`/balcao-virtual/dossiers/${caseId}/${path}`, data, {
|
||||
preserveScroll: true,
|
||||
onError: setErrors,
|
||||
onFinish: () => setBusy(false),
|
||||
});
|
||||
};
|
||||
const phase =
|
||||
guidance.phases.find((p) => p.id === phaseId) ?? guidance.phases[0];
|
||||
const finance = guidanceFinance(guidance.financial_draft);
|
||||
const financialTools = guidanceFinancialTools(guidance.financial_draft);
|
||||
return (
|
||||
<section
|
||||
className="space-y-5"
|
||||
aria-label="Acompanhamento contextual do investidor"
|
||||
>
|
||||
<h2 className="text-2xl font-bold">Acompanhamento do projecto</h2>
|
||||
<p>
|
||||
Orientação por regras internas. Pode regressar a qualquer fase,
|
||||
corrigir pressupostos e explorar alternativas. Não representa
|
||||
decisão oficial.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Versão {guidance.rules_version} · Avaliado em{' '}
|
||||
{guidance.computed_at}. IA externa: não configurada; nenhum
|
||||
modelo externo consultado.
|
||||
</p>
|
||||
<nav
|
||||
aria-label="Fases do percurso"
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
{guidance.phases.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
aria-pressed={p.id === phase.id}
|
||||
className="rounded border p-2"
|
||||
onClick={() => setPhaseId(p.id)}
|
||||
>
|
||||
{p.objective}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<article className={card + ' space-y-4'}>
|
||||
<h3 className="text-xl font-semibold">{phase.objective}</h3>
|
||||
<h4 className="font-semibold">
|
||||
Informação declarada pelo investidor
|
||||
</h4>
|
||||
{phase.known.length ? (
|
||||
<dl>
|
||||
{phase.known.map((f) => (
|
||||
<div key={f.field}>
|
||||
<dt className="font-medium">
|
||||
{fields[f.field] ?? f.field}
|
||||
</dt>
|
||||
<dd className="break-words">{f.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : (
|
||||
<p>Ainda sem informação declarada nesta fase.</p>
|
||||
)}
|
||||
<h4 className="font-semibold">
|
||||
Evidência e alcance da conferência
|
||||
</h4>
|
||||
{phase.evidence.map((e) => (
|
||||
<section
|
||||
key={e.field}
|
||||
className="space-y-2 rounded border p-3"
|
||||
>
|
||||
<p className="font-medium">
|
||||
{fields[e.field]}:{' '}
|
||||
{evidenceLabels[e.state] ?? e.state}
|
||||
</p>
|
||||
{e.documents.map((d) => (
|
||||
<article
|
||||
key={d.document_id}
|
||||
className="text-sm break-words"
|
||||
>
|
||||
<p>
|
||||
{d.name} · versão {d.version} ·{' '}
|
||||
{evidenceLabels[d.state] ?? d.state}
|
||||
{d.valid_until && (
|
||||
<>
|
||||
{' '}
|
||||
· Validade registada:{' '}
|
||||
{d.valid_until}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
{d.review && (
|
||||
<>
|
||||
<p>
|
||||
Verificador: {d.review.author} ·
|
||||
Data: {d.review.date}
|
||||
</p>
|
||||
<p>
|
||||
O que verificou:{' '}
|
||||
{d.review.what_checked}
|
||||
</p>
|
||||
<p>
|
||||
Evidência utilizada:{' '}
|
||||
{d.review.evidence}
|
||||
</p>
|
||||
<p>
|
||||
Alcance: conferência documental
|
||||
interna dos pressupostos indicados.
|
||||
Não equivale a aprovação, registo ou
|
||||
licença institucional.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{e.state === 'internally_verified' && (
|
||||
<p className="text-sm">
|
||||
A conferência sustenta apenas o âmbito descrito.
|
||||
Disponibilidade futura, procura e decisão
|
||||
institucional continuam a exigir evidência
|
||||
própria.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
<h4 className="font-semibold">Dúvidas por resolver</h4>
|
||||
{phase.questions.length ? (
|
||||
<ul className="list-disc pl-5">
|
||||
{phase.questions.map((q) => (
|
||||
<li key={q}>{fields[q] ?? q}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>
|
||||
Confirmar evidências e dependências com o responsável;
|
||||
preenchimento não equivale a validação.
|
||||
</p>
|
||||
)}
|
||||
<h4 className="font-semibold">Riscos identificados</h4>
|
||||
{phase.risks.map((r) => (
|
||||
<p key={r.code}>
|
||||
{r.classification === 'documented_contradiction'
|
||||
? 'Contradição documentada'
|
||||
: r.classification === 'declared_contradiction'
|
||||
? 'Contradição nos pressupostos declarados'
|
||||
: 'Informação insuficiente'}
|
||||
: {r.explanation} Este alerta orienta a preparação.
|
||||
</p>
|
||||
))}
|
||||
{!phase.risks.length && (
|
||||
<p>
|
||||
Nenhuma incompatibilidade comprovada por estas regras.
|
||||
Os dados externos não foram verificados.
|
||||
</p>
|
||||
)}
|
||||
{phase.recommendations.map((r) => (
|
||||
<section
|
||||
key={r.code}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<h4 className="font-semibold">
|
||||
Recomendação automática
|
||||
</h4>
|
||||
<p>{r.explanation}</p>
|
||||
<p className="text-sm">
|
||||
Fundamento: {r.source.identifier}, {r.source.date} (
|
||||
{r.source.nature}). Referência: {r.source.reference}
|
||||
.
|
||||
</p>
|
||||
<ul className="list-disc pl-5 text-sm">
|
||||
{r.limitations.map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
<Link className="underline" href={r.href}>
|
||||
Executar próxima acção no módulo existente
|
||||
</Link>
|
||||
{r.review && (
|
||||
<p>
|
||||
{decisionLabels[r.review.decision]}:{' '}
|
||||
{r.review.reason}.{' '}
|
||||
{r.review.stale
|
||||
? 'O contexto mudou; reveja a recomendação.'
|
||||
: 'Revisão do contexto actual.'}
|
||||
</p>
|
||||
)}
|
||||
{guidance.can_write && (
|
||||
<>
|
||||
<label className="block">
|
||||
Motivo da aceitação, rejeição ou contestação
|
||||
<textarea
|
||||
className={input}
|
||||
value={reason}
|
||||
onChange={(e) =>
|
||||
setReason(e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(
|
||||
[
|
||||
'accepted',
|
||||
'rejected',
|
||||
'corrected',
|
||||
] as const
|
||||
).map((decision) => (
|
||||
<button
|
||||
type="button"
|
||||
key={decision}
|
||||
disabled={
|
||||
busy || reason.trim().length < 3
|
||||
}
|
||||
className="rounded border p-2 disabled:opacity-50"
|
||||
onClick={() =>
|
||||
post('recomendacoes', {
|
||||
code: r.code,
|
||||
context_hash:
|
||||
guidance.fingerprint,
|
||||
decision,
|
||||
reason,
|
||||
})
|
||||
}
|
||||
>
|
||||
{decision === 'accepted'
|
||||
? 'Aceitar recomendação'
|
||||
: decision === 'rejected'
|
||||
? 'Rejeitar recomendação'
|
||||
: 'Contestar / corrigir'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{r.review?.decision === 'accepted' &&
|
||||
!r.review.stale && (
|
||||
<fieldset className="space-y-3 rounded border p-3">
|
||||
<legend>
|
||||
Assumir uma tarefa no CRM
|
||||
interno
|
||||
</legend>
|
||||
<p>
|
||||
A tarefa será atribuída a si. Um
|
||||
responsável autorizado pode
|
||||
depois reassumir ou redistribuir
|
||||
o acompanhamento.
|
||||
</p>
|
||||
<label>
|
||||
Associar ao pedido existente
|
||||
<select
|
||||
className={input}
|
||||
value={requestId}
|
||||
onChange={(e) =>
|
||||
setRequestId(
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Acompanhamento do
|
||||
dossier
|
||||
</option>
|
||||
{requests.map((r) => (
|
||||
<option
|
||||
value={r.id}
|
||||
key={r.id}
|
||||
>
|
||||
{r.protocol ??
|
||||
'Rascunho existente'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Prazo interno previsto
|
||||
<input
|
||||
className={input}
|
||||
type="datetime-local"
|
||||
value={due}
|
||||
onChange={(e) =>
|
||||
setDue(e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={consent}
|
||||
onChange={(e) =>
|
||||
setConsent(
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
Assumo esta acção e autorizo o
|
||||
seu registo no acompanhamento
|
||||
interno.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
disabled={
|
||||
busy || !due || !consent
|
||||
}
|
||||
onClick={() =>
|
||||
post('tarefas', {
|
||||
code: r.code,
|
||||
context_hash:
|
||||
guidance.fingerprint,
|
||||
due_at: due,
|
||||
consent,
|
||||
request_id:
|
||||
requestId || null,
|
||||
})
|
||||
}
|
||||
>
|
||||
Registar tarefa assumida
|
||||
</button>
|
||||
</fieldset>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
</article>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h3 className="text-xl font-semibold">
|
||||
Coerência com referências actuais
|
||||
</h3>
|
||||
{guidance.catalogue_checks.map((check) => (
|
||||
<article key={check.code}>
|
||||
<p>
|
||||
{check.classification ===
|
||||
'documented_incompatibility'
|
||||
? 'Incompatibilidade documentada no catálogo'
|
||||
: check.classification ===
|
||||
'catalogue_consistent'
|
||||
? 'Coerência no catálogo'
|
||||
: 'Informação insuficiente'}
|
||||
: {check.explanation}
|
||||
</p>
|
||||
{check.source && (
|
||||
<p className="text-xs">
|
||||
Fonte efectivamente consultada:{' '}
|
||||
{JSON.stringify(check.source)} · avaliação{' '}
|
||||
{guidance.computed_at}.
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{!guidance.catalogue_checks.length && (
|
||||
<p>
|
||||
Sem selecções autorizadas suficientes para comparar
|
||||
actividade/sector e hierarquia territorial. Procura,
|
||||
infraestrutura, recursos e financiamento requerem
|
||||
evidência própria.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
{guidance.can_write && (
|
||||
<details className={card}>
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Corrigir pressupostos ou registar uma alternativa
|
||||
</summary>
|
||||
<form
|
||||
className="mt-4 grid gap-3 sm:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
post('pressupostos', {
|
||||
version: guidance.version,
|
||||
assumptions: Object.fromEntries(
|
||||
Object.keys(fields).map((key) => [
|
||||
key,
|
||||
facts[key] ?? '',
|
||||
]),
|
||||
),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<p className="sm:col-span-2">
|
||||
As correcções são declarações do investidor no
|
||||
dossier. Reveja o plano no simulador para alterar
|
||||
cálculos; os dados oficiais e os módulos de origem
|
||||
são preservados.
|
||||
</p>
|
||||
{Object.entries(fields).map(([key, label]) => (
|
||||
<label key={key}>
|
||||
{label}
|
||||
<input
|
||||
type={
|
||||
key.endsWith('_date') ? 'date' : 'text'
|
||||
}
|
||||
className={input}
|
||||
maxLength={3000}
|
||||
value={facts[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
setFacts({
|
||||
...facts,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar pressupostos corrigidos
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h3 className="text-xl font-semibold">
|
||||
Cálculos existentes e cenários
|
||||
</h3>
|
||||
<details>
|
||||
<summary>Versões das ferramentas determinísticas</summary>
|
||||
{Object.entries(guidance.calculator_versions).map(
|
||||
([name, hash]) => (
|
||||
<p className="text-xs break-all" key={name}>
|
||||
{name} · SHA-256 do código: {hash}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</details>
|
||||
{financialTools && (
|
||||
<details>
|
||||
<summary>
|
||||
Empréstimo, orçamento, financiamento e ponto de
|
||||
equilíbrio — ferramentas existentes, snapshot v
|
||||
{financialTools.snapshotVersion}
|
||||
</summary>
|
||||
<p>
|
||||
Fonte: {financialTools.calculator}. Os erros e
|
||||
indeterminações mantêm-se separados por cálculo.
|
||||
</p>
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Componente</th>
|
||||
<th>Valor / resultado</th>
|
||||
<th>Pressuposto / limite</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{financialTools.rows.map((row, i) => (
|
||||
<tr key={i}>
|
||||
<td>{row[1]}</td>
|
||||
<td>{row[2]}</td>
|
||||
<td>{row[3]}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<pre className="overflow-auto text-xs whitespace-pre-wrap">
|
||||
{JSON.stringify(
|
||||
financialTools.assumptions,
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
<p>{finance.reason}</p>
|
||||
{finance.result && (
|
||||
<>
|
||||
<p>
|
||||
Snapshot v{finance.snapshotVersion}; calculadora{' '}
|
||||
{finance.calculator}. Os resultados usam exactamente
|
||||
o snapshot autorizado do simulador.
|
||||
</p>
|
||||
<dl>
|
||||
<dt>Facturação estimada</dt>
|
||||
<dd>
|
||||
{finance.result.totalRevenue}{' '}
|
||||
{finance.assumptions.currency}
|
||||
</dd>
|
||||
<dt>Resultado antes de impostos</dt>
|
||||
<dd>
|
||||
{finance.result.totalProfitBeforeTax}{' '}
|
||||
{finance.assumptions.currency}
|
||||
</dd>
|
||||
<dt>Caixa final</dt>
|
||||
<dd>
|
||||
{finance.result.endingCash}{' '}
|
||||
{finance.assumptions.currency}
|
||||
</dd>
|
||||
</dl>
|
||||
{finance.scenarios ? (
|
||||
<p>
|
||||
Caixa final — favorável:{' '}
|
||||
{finance.scenarios.favorable.result.endingCash};
|
||||
desfavorável:{' '}
|
||||
{
|
||||
finance.scenarios.unfavorable.result
|
||||
.endingCash
|
||||
}
|
||||
. São cenários de pressupostos, sem
|
||||
probabilidade atribuída.
|
||||
</p>
|
||||
) : (
|
||||
<p>
|
||||
Cenários alternativos indeterminados: complete
|
||||
os respectivos pressupostos no simulador.
|
||||
</p>
|
||||
)}
|
||||
<details>
|
||||
<summary>
|
||||
Pressupostos usados pela calculadora
|
||||
</summary>
|
||||
<pre className="max-h-80 overflow-auto text-xs break-all whitespace-pre-wrap">
|
||||
{JSON.stringify(finance.assumptions, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</>
|
||||
)}
|
||||
<p>
|
||||
Componentes fiscais: indeterminadas neste acompanhamento.
|
||||
Consulte o resultado fiscal e as suas versões no simulador.
|
||||
</p>
|
||||
<Link className="underline" href="/simulador-fiscal">
|
||||
Abrir o simulador e explorar alternativas
|
||||
</Link>
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h3 className="text-xl font-semibold">
|
||||
Tarefas assumidas e respostas
|
||||
</h3>
|
||||
<p>{guidance.crm.reason}</p>
|
||||
{guidance.tasks.map((task) => (
|
||||
<article
|
||||
className="space-y-2 rounded border p-3"
|
||||
key={task.id}
|
||||
>
|
||||
<p>{task.title}</p>
|
||||
<p>
|
||||
Estado: {task.status} · Responsável:{' '}
|
||||
{task.assignee_name} · Prazo interno: {task.due_at}
|
||||
</p>
|
||||
<p>
|
||||
Assumida em {task.accepted_at} · Sincronização
|
||||
externa: pendente de autorização.
|
||||
</p>
|
||||
{task.desk_request_id && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/pedidos/${task.desk_request_id}`}
|
||||
>
|
||||
Consultar o pedido e a resposta do responsável
|
||||
</Link>
|
||||
)}
|
||||
{(manager || actorId === task.assignee_user_id) && (
|
||||
<>
|
||||
<label className="block">
|
||||
Resultado ou motivo
|
||||
<textarea
|
||||
className={input}
|
||||
value={reason}
|
||||
onChange={(e) =>
|
||||
setReason(e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{['in_progress', 'done', 'cancelled'].map(
|
||||
(status) => (
|
||||
<button
|
||||
key={status}
|
||||
type="button"
|
||||
className="rounded border p-2"
|
||||
disabled={
|
||||
busy ||
|
||||
reason.trim().length < 3
|
||||
}
|
||||
onClick={() =>
|
||||
post(`tarefas/${task.id}`, {
|
||||
version:
|
||||
task.version_no,
|
||||
status,
|
||||
reason,
|
||||
})
|
||||
}
|
||||
>
|
||||
{status === 'in_progress'
|
||||
? 'Iniciar'
|
||||
: status === 'done'
|
||||
? 'Registar conclusão'
|
||||
: 'Cancelar tarefa'}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{!guidance.tasks.length && (
|
||||
<p>
|
||||
Sem tarefas assumidas. As sugestões do assistente ainda
|
||||
não são compromissos.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h3 className="text-xl font-semibold">
|
||||
Fontes efectivamente consultadas
|
||||
</h3>
|
||||
{guidance.consulted.map((s) => (
|
||||
<p key={s.module}>
|
||||
{s.module} · versão {s.version} · {s.date} · declaração
|
||||
do investidor, sem confirmação externa.
|
||||
</p>
|
||||
))}
|
||||
{guidance.unavailable.length > 0 && (
|
||||
<p>
|
||||
Parte do contexto ligado não está disponível com as suas
|
||||
permissões actuais.
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
void fetch(
|
||||
`/balcao-virtual/dossiers/${caseId}/fontes`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((v) =>
|
||||
v.startsWith('XSRF-TOKEN='),
|
||||
)
|
||||
?.slice(11) ?? '',
|
||||
),
|
||||
},
|
||||
body: JSON.stringify({ query }),
|
||||
},
|
||||
)
|
||||
.then(async (r) => {
|
||||
if (!r.ok)
|
||||
throw new Error(
|
||||
'Pesquisa indisponível; a orientação interna continua disponível.',
|
||||
);
|
||||
setSources(await r.json());
|
||||
})
|
||||
.catch((e: unknown) =>
|
||||
setErrors({
|
||||
search:
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Pesquisa indisponível.',
|
||||
}),
|
||||
)
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Pesquisar excertos de fontes públicas autorizadas
|
||||
<input
|
||||
className={input}
|
||||
value={query}
|
||||
minLength={3}
|
||||
maxLength={300}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Consultar fontes indexadas
|
||||
</button>
|
||||
</form>
|
||||
{sources && (
|
||||
<>
|
||||
<p>
|
||||
{sources.status === 'evidence_found'
|
||||
? 'Excertos encontrados'
|
||||
: sources.status === 'unavailable'
|
||||
? 'Pesquisa IA indisponível; orientação por regras mantida.'
|
||||
: 'Sem evidência nas fontes indexadas. Não implica inexistência de fonte.'}
|
||||
</p>
|
||||
{sources.consulted.map((s, i) => (
|
||||
<article key={i}>
|
||||
<p>
|
||||
{s.title} · {s.source_date} · {s.nature}
|
||||
</p>
|
||||
<blockquote>{s.content}</blockquote>
|
||||
<a
|
||||
className="underline"
|
||||
href={s.source_url}
|
||||
rel="noreferrer"
|
||||
>
|
||||
Consultar origem
|
||||
</a>
|
||||
</article>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
{Object.keys(errors).length > 0 && (
|
||||
<div role="alert" className="rounded border border-red-600 p-3">
|
||||
{Object.entries(errors).map(([k, v]) => (
|
||||
<p key={k}>{v}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { Guidance } from './investor-guidance';
|
||||
|
||||
/** Carries only an account-scoped case identifier between modules; never a contact/document payload. */
|
||||
export function JourneyCompanion() {
|
||||
const { props, url } = usePage<{ auth: { user: { id: number } | null } }>();
|
||||
const actor = props.auth?.user?.id;
|
||||
const [open, setOpen] = useState(false);
|
||||
const [cases, setCases] = useState<{ id: string; title: string }[]>([]);
|
||||
const [active, setActive] = useState('');
|
||||
const [guidance, setGuidance] = useState<Guidance | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
useEffect(() => {
|
||||
setGuidance(null);
|
||||
setCases([]);
|
||||
setActive('');
|
||||
setMessage('');
|
||||
if (!actor) return;
|
||||
try {
|
||||
const key = `investmoz-guidance-case:${actor}`;
|
||||
const routeId = url.match(
|
||||
/^\/balcao-virtual\/dossiers\/([a-f0-9-]{36})/i,
|
||||
)?.[1];
|
||||
if (routeId) sessionStorage.setItem(key, routeId);
|
||||
setActive(routeId ?? sessionStorage.getItem(key) ?? '');
|
||||
} catch {
|
||||
setMessage('Selecção de contexto disponível apenas nesta página.');
|
||||
}
|
||||
}, [actor, url]);
|
||||
useEffect(() => {
|
||||
if (!open || !actor) return;
|
||||
const controller = new AbortController();
|
||||
void fetch('/balcao-virtual/contextos', {
|
||||
credentials: 'same-origin',
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(async (r) => {
|
||||
if (!r.ok)
|
||||
throw new Error(
|
||||
'Acompanhamento em preparação; os pedidos anteriores continuam no Balcão Virtual.',
|
||||
);
|
||||
return r.json() as Promise<{
|
||||
cases: { id: string; title: string }[];
|
||||
}>;
|
||||
})
|
||||
.then((data) => setCases(data.cases))
|
||||
.catch((e: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setMessage(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Contexto indisponível.',
|
||||
);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [actor, open, url]);
|
||||
useEffect(() => {
|
||||
setGuidance(null);
|
||||
if (!open || !actor || !cases.some((c) => c.id === active)) return;
|
||||
const controller = new AbortController();
|
||||
void fetch(`/balcao-virtual/dossiers/${active}/orientacao`, {
|
||||
credentials: 'same-origin',
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(async (r) => {
|
||||
if (!r.ok)
|
||||
throw new Error('Orientação indisponível neste contexto.');
|
||||
return r.json() as Promise<Guidance>;
|
||||
})
|
||||
.then((data) => {
|
||||
setGuidance(data);
|
||||
setMessage('');
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setMessage(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Orientação indisponível.',
|
||||
);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [actor, open, active, cases, url]);
|
||||
return (
|
||||
<aside
|
||||
className="border-b bg-emerald-50 px-5 py-3 text-sm text-slate-900"
|
||||
aria-label="Assistente do percurso do investidor"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="font-semibold underline"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
Acompanhar o meu projecto neste portal
|
||||
</button>
|
||||
{open && (
|
||||
<div className="mt-3 space-y-3">
|
||||
{!actor ? (
|
||||
<p>
|
||||
<Link href="/login" className="underline">
|
||||
Entre na sua conta
|
||||
</Link>{' '}
|
||||
para recuperar os dossiers e acompanhar pedidos. A
|
||||
orientação pública e o simulador continuam
|
||||
acessíveis.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="block">
|
||||
Contexto do projecto
|
||||
<select
|
||||
className="ml-2 max-w-full rounded border bg-white p-2"
|
||||
value={active}
|
||||
onChange={(e) => {
|
||||
setActive(e.target.value);
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
`investmoz-guidance-case:${actor}`,
|
||||
e.target.value,
|
||||
);
|
||||
} catch {
|
||||
/* Selection remains in memory. */
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione um dossier
|
||||
</option>
|
||||
{cases.map((c) => (
|
||||
<option value={c.id} key={c.id}>
|
||||
{c.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{message && <p role="status">{message}</p>}
|
||||
{guidance && (
|
||||
<>
|
||||
<p>
|
||||
Regras internas {guidance.rules_version}
|
||||
. Sugestões automáticas; não são tarefas
|
||||
assumidas nem respostas humanas.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{guidance.phases.map((p) => (
|
||||
<Link
|
||||
key={p.id}
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${active}?phase=${p.id}`}
|
||||
>
|
||||
{p.objective}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<p>
|
||||
O contexto seleccionado mantém-se ao
|
||||
mudar de módulo. Os rascunhos continuam
|
||||
nos módulos de origem.
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${active}`}
|
||||
>
|
||||
Rever pressupostos, recomendações e
|
||||
tarefas deste dossier
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
<Link
|
||||
className="inline-block underline"
|
||||
href="/balcao-virtual"
|
||||
>
|
||||
Abrir o Balcão Virtual e preparar ou acompanhar
|
||||
um pedido
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from "@inertiajs/react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
export default function PartnershipSearchResults({ query }: { query: string }) {
|
||||
const [items, setItems] = useState<{ id: number; title: string }[]>([]);
|
||||
useEffect(() => {
|
||||
@@ -8,9 +8,9 @@ export default function PartnershipSearchResults({ query }: { query: string }) {
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
fetch("/api/v1/partnerships?q=" + encodeURIComponent(query), {
|
||||
fetch('/api/v1/partnerships?q=' + encodeURIComponent(query), {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data) => setItems(data?.data ?? []))
|
||||
@@ -23,14 +23,14 @@ export default function PartnershipSearchResults({ query }: { query: string }) {
|
||||
<h2 className="text-xl font-bold">Parcerias nesta pesquisa</h2>
|
||||
{items.slice(0, 5).map((item) => (
|
||||
<p key={item.id}>
|
||||
<Link className="underline" href={"/parcerias/" + item.id}>
|
||||
<Link className="underline" href={'/parcerias/' + item.id}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</p>
|
||||
))}
|
||||
<Link
|
||||
className="underline"
|
||||
href={"/parcerias?q=" + encodeURIComponent(query)}
|
||||
href={'/parcerias?q=' + encodeURIComponent(query)}
|
||||
>
|
||||
Ver todas as parcerias correspondentes
|
||||
</Link>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from "@inertiajs/react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
export default function PartnershipSourceLinks({
|
||||
type,
|
||||
id,
|
||||
@@ -17,7 +17,7 @@ export default function PartnershipSourceLinks({
|
||||
`/api/v1/partnerships/source/${encodeURIComponent(type)}/${encodeURIComponent(String(id))}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
)
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
@@ -33,7 +33,7 @@ export default function PartnershipSourceLinks({
|
||||
</h2>
|
||||
{data.items.map((item) => (
|
||||
<p key={item.id}>
|
||||
<Link className="underline" href={"/parcerias/" + item.id}>
|
||||
<Link className="underline" href={'/parcerias/' + item.id}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import {
|
||||
portalNavigation,
|
||||
currentNavigationGroup,
|
||||
currentNavigationItem,
|
||||
type PortalNavItem,
|
||||
} from '@/lib/portal-navigation';
|
||||
|
||||
export function PortalGroupedMenu() {
|
||||
const { props, url } = usePage<{
|
||||
auth: { user: unknown; canManagePortal: boolean };
|
||||
existingBusinessEnabled?: boolean;
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
portalOperator?: string | null;
|
||||
}>();
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!props.auth?.user,
|
||||
manager: !!props.auth?.canManagePortal,
|
||||
businesses: props.existingBusinessEnabled,
|
||||
education: props.educationEnabled,
|
||||
ai: props.aiEnabled,
|
||||
});
|
||||
const current = currentNavigationGroup(groups, url);
|
||||
const currentItem = currentNavigationItem(groups, url);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [branch, setBranch] = useState<string | null>(null);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const root = useRef<HTMLElement>(null);
|
||||
const id = useId();
|
||||
useEffect(() => {
|
||||
const position = () => {
|
||||
const button = open
|
||||
? document.getElementById(`${id}-${open}-button`)
|
||||
: null;
|
||||
if (!button || window.innerWidth < 640) {
|
||||
setOffset(0);
|
||||
return;
|
||||
}
|
||||
const rect = button.getBoundingClientRect();
|
||||
const width = Math.min(288, window.innerWidth - 32);
|
||||
setOffset(
|
||||
Math.max(
|
||||
16,
|
||||
Math.min(rect.left, window.innerWidth - width - 16),
|
||||
) - rect.left,
|
||||
);
|
||||
};
|
||||
position();
|
||||
window.addEventListener('resize', position);
|
||||
return () => window.removeEventListener('resize', position);
|
||||
}, [open, id]);
|
||||
useEffect(() => {
|
||||
const outside = (event: PointerEvent) => {
|
||||
if (
|
||||
event.target instanceof Node &&
|
||||
!root.current?.contains(event.target)
|
||||
) {
|
||||
setOpen(null);
|
||||
setBranch(null);
|
||||
}
|
||||
};
|
||||
document.addEventListener('pointerdown', outside);
|
||||
return () => document.removeEventListener('pointerdown', outside);
|
||||
}, []);
|
||||
const close = () => {
|
||||
setOpen(null);
|
||||
setBranch(null);
|
||||
};
|
||||
const items = (children: PortalNavItem[]) =>
|
||||
children.map((item) => (
|
||||
<li key={item.id}>
|
||||
{item.children ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
id={`${id}-${item.id}-button`}
|
||||
className="flex w-full items-center justify-between rounded-lg px-3 py-2 text-left font-semibold hover:bg-emerald-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700"
|
||||
aria-expanded={branch === item.id}
|
||||
aria-controls={`${id}-${item.id}`}
|
||||
onClick={() =>
|
||||
setBranch(branch === item.id ? null : item.id)
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
<span aria-hidden="true">
|
||||
{branch === item.id ? '−' : '+'}
|
||||
</span>
|
||||
</button>
|
||||
{branch === item.id && (
|
||||
<ul
|
||||
id={`${id}-${item.id}`}
|
||||
className="ml-3 space-y-1 border-l-2 border-emerald-200 pl-2"
|
||||
>
|
||||
{items(item.children)}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Link
|
||||
href={item.href!}
|
||||
onClick={close}
|
||||
aria-current={
|
||||
currentItem === item.id ? 'page' : undefined
|
||||
}
|
||||
className="block rounded-lg px-3 py-2 hover:bg-emerald-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
));
|
||||
return (
|
||||
<header
|
||||
ref={root}
|
||||
className="relative z-40 border-b border-slate-200 bg-white text-slate-900"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
if (branch) {
|
||||
document.getElementById(`${id}-${branch}-button`)?.focus();
|
||||
setBranch(null);
|
||||
} else if (open) {
|
||||
document.getElementById(`${id}-${open}-button`)?.focus();
|
||||
close();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="mx-auto max-w-7xl px-4 py-4 sm:px-6">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-xl font-extrabold tracking-tight text-emerald-900"
|
||||
>
|
||||
InvesteMoz
|
||||
</Link>
|
||||
<p className="max-w-2xl text-xs leading-relaxed text-slate-600">
|
||||
Iniciativa privada e independente de apoio ao
|
||||
investimento. Orientação e acompanhamento internos;
|
||||
decisões oficiais cabem às instituições competentes.
|
||||
{props.portalOperator && (
|
||||
<> Operador: {props.portalOperator}.</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<nav aria-label="Áreas do portal">
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{groups.map((group) => (
|
||||
<li
|
||||
key={group.id}
|
||||
className="relative w-full sm:w-auto"
|
||||
>
|
||||
<button
|
||||
id={`${id}-${group.id}-button`}
|
||||
type="button"
|
||||
className={`flex min-h-11 w-full items-center justify-between gap-2 rounded-lg border px-3 py-2 text-left text-sm font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700 ${current === group.id ? 'border-emerald-700 bg-emerald-50 text-emerald-950' : 'border-slate-200 hover:bg-slate-50'}`}
|
||||
aria-expanded={open === group.id}
|
||||
aria-controls={`${id}-${group.id}`}
|
||||
data-current-group={
|
||||
current === group.id || undefined
|
||||
}
|
||||
onClick={() => {
|
||||
setOpen(
|
||||
open === group.id ? null : group.id,
|
||||
);
|
||||
setBranch(null);
|
||||
}}
|
||||
>
|
||||
{group.label}
|
||||
<span aria-hidden="true">
|
||||
{open === group.id ? '▴' : '▾'}
|
||||
</span>
|
||||
{current === group.id && (
|
||||
<span className="sr-only">
|
||||
Grupo actual
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{open === group.id && (
|
||||
<ul
|
||||
id={`${id}-${group.id}`}
|
||||
style={{
|
||||
transform: `translateX(${offset}px)`,
|
||||
}}
|
||||
className="mt-2 max-h-[min(70vh,32rem)] w-full space-y-1 overflow-y-auto rounded-xl border border-slate-200 bg-white p-2 text-sm shadow-xl sm:absolute sm:top-full sm:left-0 sm:z-40 sm:w-72 sm:max-w-[calc(100vw-2rem)]"
|
||||
>
|
||||
{items(group.children ?? [])}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -21,11 +21,20 @@ type Props = {
|
||||
currentCalculation?: DossierCurrentCalculation | null;
|
||||
};
|
||||
|
||||
const defaultSections = new Set<DossierReportSectionId>(dossierReportSections.map((section) => section.id));
|
||||
const defaultSections = new Set<DossierReportSectionId>(
|
||||
dossierReportSections.map((section) => section.id),
|
||||
);
|
||||
|
||||
function filenameStem(title: string): string {
|
||||
return title.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLocaleLowerCase('en')
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 70) || 'projecto';
|
||||
return (
|
||||
title
|
||||
.normalize('NFKD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLocaleLowerCase('en')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.slice(0, 70) || 'projecto'
|
||||
);
|
||||
}
|
||||
|
||||
function download(blob: Blob, filename: string): void {
|
||||
@@ -38,20 +47,34 @@ function download(blob: Blob, filename: string): void {
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
export function ProjectDossierExport({ draft, version, references = [], currentCalculation = null }: Props) {
|
||||
export function ProjectDossierExport({
|
||||
draft,
|
||||
version,
|
||||
references = [],
|
||||
currentCalculation = null,
|
||||
}: Props) {
|
||||
const [selectedSections, setSelectedSections] = useState(defaultSections);
|
||||
const [attachments, setAttachments] = useState<DossierAttachment[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState('');
|
||||
const selected = useMemo(() => attachments.filter((item) => item.include), [attachments]);
|
||||
const selectedSectionSet = useMemo(() => selectedSections, [selectedSections]);
|
||||
const selected = useMemo(
|
||||
() => attachments.filter((item) => item.include),
|
||||
[attachments],
|
||||
);
|
||||
const selectedSectionSet = useMemo(
|
||||
() => selectedSections,
|
||||
[selectedSections],
|
||||
);
|
||||
|
||||
function addFiles(files: FileList | null): void {
|
||||
if (!files?.length) return;
|
||||
const incoming = Array.from(files);
|
||||
const combined = [...attachments.map((item) => item.file), ...incoming];
|
||||
const problem = validateDossierAttachments(combined);
|
||||
if (problem) { setError(problem); return; }
|
||||
if (problem) {
|
||||
setError(problem);
|
||||
return;
|
||||
}
|
||||
setAttachments((current) => [
|
||||
...current,
|
||||
...incoming.map((file) => ({ file, include: true, caption: '' })),
|
||||
@@ -62,17 +85,27 @@ export function ProjectDossierExport({ draft, version, references = [], currentC
|
||||
function toggleSection(id: DossierReportSectionId, checked: boolean): void {
|
||||
setSelectedSections((current) => {
|
||||
const next = new Set(current);
|
||||
if (checked) next.add(id); else next.delete(id);
|
||||
if (checked) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function updateAttachment(index: number, patch: Partial<Pick<DossierAttachment, 'include' | 'caption'>>): void {
|
||||
setAttachments((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item));
|
||||
function updateAttachment(
|
||||
index: number,
|
||||
patch: Partial<Pick<DossierAttachment, 'include' | 'caption'>>,
|
||||
): void {
|
||||
setAttachments((current) =>
|
||||
current.map((item, itemIndex) =>
|
||||
itemIndex === index ? { ...item, ...patch } : item,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function removeAttachment(index: number): void {
|
||||
setAttachments((current) => current.filter((_, itemIndex) => itemIndex !== index));
|
||||
setAttachments((current) =>
|
||||
current.filter((_, itemIndex) => itemIndex !== index),
|
||||
);
|
||||
}
|
||||
|
||||
function model() {
|
||||
@@ -85,98 +118,314 @@ export function ProjectDossierExport({ draft, version, references = [], currentC
|
||||
}
|
||||
|
||||
async function exportWord(): Promise<void> {
|
||||
setBusy('word'); setError('');
|
||||
setBusy('word');
|
||||
setError('');
|
||||
try {
|
||||
const report = model();
|
||||
const blob = await generateProjectDossierDocx(report, selected, selectedSections.has('annexes'));
|
||||
download(blob, `relatorio-investmoz-${filenameStem(report.title)}.docx`);
|
||||
const blob = await generateProjectDossierDocx(
|
||||
report,
|
||||
selected,
|
||||
selectedSections.has('annexes'),
|
||||
);
|
||||
download(
|
||||
blob,
|
||||
`relatorio-investmoz-${filenameStem(report.title)}.docx`,
|
||||
);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : 'Não foi possível gerar o relatório Word.');
|
||||
} finally { setBusy(''); }
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível gerar o relatório Word.',
|
||||
);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}
|
||||
|
||||
async function exportPackage(): Promise<void> {
|
||||
setBusy('package'); setError('');
|
||||
setBusy('package');
|
||||
setError('');
|
||||
try {
|
||||
const report = model();
|
||||
const docx = await generateProjectDossierDocx(report, selected, selectedSections.has('annexes'));
|
||||
const archive = await generateProjectDossierPackage(docx, selected, selectedSections.has('annexes'));
|
||||
download(archive, `relatorio-investmoz-${filenameStem(report.title)}-anexos.zip`);
|
||||
const docx = await generateProjectDossierDocx(
|
||||
report,
|
||||
selected,
|
||||
selectedSections.has('annexes'),
|
||||
);
|
||||
const archive = await generateProjectDossierPackage(
|
||||
docx,
|
||||
selected,
|
||||
selectedSections.has('annexes'),
|
||||
);
|
||||
download(
|
||||
archive,
|
||||
`relatorio-investmoz-${filenameStem(report.title)}-anexos.zip`,
|
||||
);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : 'Não foi possível preparar o pacote de anexos.');
|
||||
} finally { setBusy(''); }
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível preparar o pacote de anexos.',
|
||||
);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}
|
||||
|
||||
async function exportPdf(): Promise<void> {
|
||||
const printWindow = window.open('about:blank', '_blank');
|
||||
if (!printWindow) { setError('O browser bloqueou a janela de impressão. Permita pop-ups para abrir a versão PDF.'); return; }
|
||||
setBusy('pdf'); setError('');
|
||||
if (!printWindow) {
|
||||
setError(
|
||||
'O browser bloqueou a janela de impressão. Permita pop-ups para abrir a versão PDF.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setBusy('pdf');
|
||||
setError('');
|
||||
try {
|
||||
const html = await createProjectDossierPrintHtml(model(), selected, selectedSections.has('annexes'));
|
||||
printWindow.document.open(); printWindow.document.write(html); printWindow.document.close();
|
||||
const html = await createProjectDossierPrintHtml(
|
||||
model(),
|
||||
selected,
|
||||
selectedSections.has('annexes'),
|
||||
);
|
||||
printWindow.document.open();
|
||||
printWindow.document.write(html);
|
||||
printWindow.document.close();
|
||||
} catch (cause) {
|
||||
printWindow.close();
|
||||
setError(cause instanceof Error ? cause.message : 'Não foi possível preparar a versão para PDF.');
|
||||
} finally { setBusy(''); }
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível preparar a versão para PDF.',
|
||||
);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
}
|
||||
|
||||
function exportCsv(): void {
|
||||
const blob = new Blob([exportProjectDossierCsv(draft)], { type: 'text/csv;charset=utf-8' });
|
||||
download(blob, `dossier-projecto-investmoz-${filenameStem(String(draft.project_title ?? ''))}.csv`);
|
||||
const blob = new Blob([exportProjectDossierCsv(draft)], {
|
||||
type: 'text/csv;charset=utf-8',
|
||||
});
|
||||
download(
|
||||
blob,
|
||||
`dossier-projecto-investmoz-${filenameStem(String(draft.project_title ?? ''))}.csv`,
|
||||
);
|
||||
}
|
||||
|
||||
const totalBytes = attachments.reduce((sum, item) => sum + item.file.size, 0);
|
||||
const annexesIncluded = selectedSections.has('annexes');
|
||||
const imageCount = selected.filter((item) => item.file.type === 'image/png' || item.file.type === 'image/jpeg').length;
|
||||
const originalOnlyCount = selected.length - imageCount - selected.filter((item) => item.file.type === 'text/csv' || item.file.name.toLocaleLowerCase('en').endsWith('.csv') || item.file.type === 'text/plain' || item.file.name.toLocaleLowerCase('en').endsWith('.txt')).length;
|
||||
const totalBytes = attachments.reduce(
|
||||
(sum, item) => sum + item.file.size,
|
||||
0,
|
||||
);
|
||||
const _annexesIncluded = selectedSections.has('annexes');
|
||||
const imageCount = selected.filter(
|
||||
(item) =>
|
||||
item.file.type === 'image/png' || item.file.type === 'image/jpeg',
|
||||
).length;
|
||||
const originalOnlyCount =
|
||||
selected.length -
|
||||
imageCount -
|
||||
selected.filter(
|
||||
(item) =>
|
||||
item.file.type === 'text/csv' ||
|
||||
item.file.name.toLocaleLowerCase('en').endsWith('.csv') ||
|
||||
item.file.type === 'text/plain' ||
|
||||
item.file.name.toLocaleLowerCase('en').endsWith('.txt'),
|
||||
).length;
|
||||
|
||||
return (
|
||||
<section className="space-y-4 rounded border p-4" aria-labelledby="project-report-title">
|
||||
<section
|
||||
className="space-y-4 rounded border p-4"
|
||||
aria-labelledby="project-report-title"
|
||||
>
|
||||
<div>
|
||||
<h4 id="project-report-title" className="font-semibold">Relatório consolidado do projecto</h4>
|
||||
<p className="mt-1 text-sm">Word (.docx), impressão/guardar em PDF ou CSV. A exportação é feita neste dispositivo; não publica nem partilha o dossier.</p>
|
||||
<h4 id="project-report-title" className="font-semibold">
|
||||
Relatório consolidado do projecto
|
||||
</h4>
|
||||
<p className="mt-1 text-sm">
|
||||
Word (.docx), impressão/guardar em PDF ou CSV. A exportação
|
||||
é feita neste dispositivo; não publica nem partilha o
|
||||
dossier.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="font-medium">Escolha as secções a incluir</legend>
|
||||
<legend className="font-medium">
|
||||
Escolha as secções a incluir
|
||||
</legend>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{dossierReportSections.map((section) => (
|
||||
<label key={section.id} className="flex items-start gap-2 rounded border p-2 text-sm">
|
||||
<input type="checkbox" checked={selectedSections.has(section.id)} onChange={(event) => toggleSection(section.id, event.target.checked)} />
|
||||
<span>{section.title}<span className="block text-xs text-amber-900">Pode conter informação privada</span></span>
|
||||
<label
|
||||
key={section.id}
|
||||
className="flex items-start gap-2 rounded border p-2 text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedSections.has(section.id)}
|
||||
onChange={(event) =>
|
||||
toggleSection(
|
||||
section.id,
|
||||
event.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
{section.title}
|
||||
<span className="block text-xs text-amber-900">
|
||||
Pode conter informação privada
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="project-report-files" className="block font-medium">Anexos privados seleccionados pelo utilizador</label>
|
||||
<p className="text-sm">Fotografias JPEG/PNG, tabelas CSV/TSV e texto TXT podem ser incorporados. PDF, DOCX e outros formatos não suportados seguem como ficheiros originais no pacote ZIP, identificados no índice. Máximo: 10 ficheiros, 15 MB por ficheiro e 50 MB no conjunto.</p>
|
||||
<input id="project-report-files" type="file" multiple accept="image/jpeg,image/png,text/csv,text/plain,.csv,.tsv,.txt,.pdf,.doc,.docx,.xlsx,.odt" onChange={(event) => { addFiles(event.currentTarget.files); event.currentTarget.value = ''; }} />
|
||||
{attachments.length > 0 && <p className="text-xs text-slate-700">{selected.length} seleccionado(s) · {(totalBytes / (1024 * 1024)).toFixed(2)} MB no browser · {imageCount} imagem(ns) · {originalOnlyCount} original(is) não incorporado(s).</p>}
|
||||
<label
|
||||
htmlFor="project-report-files"
|
||||
className="block font-medium"
|
||||
>
|
||||
Anexos privados seleccionados pelo utilizador
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Fotografias JPEG/PNG, tabelas CSV/TSV e texto TXT podem ser
|
||||
incorporados. PDF, DOCX e outros formatos não suportados
|
||||
seguem como ficheiros originais no pacote ZIP, identificados
|
||||
no índice. Máximo: 10 ficheiros, 15 MB por ficheiro e 50 MB
|
||||
no conjunto.
|
||||
</p>
|
||||
<input
|
||||
id="project-report-files"
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/jpeg,image/png,text/csv,text/plain,.csv,.tsv,.txt,.pdf,.doc,.docx,.xlsx,.odt"
|
||||
onChange={(event) => {
|
||||
addFiles(event.currentTarget.files);
|
||||
event.currentTarget.value = '';
|
||||
}}
|
||||
/>
|
||||
{attachments.length > 0 && (
|
||||
<p className="text-xs text-slate-700">
|
||||
{selected.length} seleccionado(s) ·{' '}
|
||||
{(totalBytes / (1024 * 1024)).toFixed(2)} MB no browser
|
||||
· {imageCount} imagem(ns) · {originalOnlyCount}{' '}
|
||||
original(is) não incorporado(s).
|
||||
</p>
|
||||
)}
|
||||
<ul className="space-y-2">
|
||||
{attachments.map((item, index) => (
|
||||
<li key={`${item.file.name}-${item.file.size}-${index}`} className="grid gap-2 rounded border p-3 sm:grid-cols-[1fr_auto]">
|
||||
<li
|
||||
key={`${item.file.name}-${item.file.size}-${index}`}
|
||||
className="grid gap-2 rounded border p-3 sm:grid-cols-[1fr_auto]"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<input aria-label={`Incluir ${item.file.name}`} type="checkbox" checked={item.include} onChange={(event) => updateAttachment(index, { include: event.target.checked })} />
|
||||
<span className="min-w-0 break-words text-sm"><strong>{item.file.name}</strong><span className="block text-xs">{(item.file.size / 1024).toFixed(1)} KB · informação privada</span></span>
|
||||
<input
|
||||
aria-label={`Incluir ${item.file.name}`}
|
||||
type="checkbox"
|
||||
checked={item.include}
|
||||
onChange={(event) =>
|
||||
updateAttachment(index, {
|
||||
include: event.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="min-w-0 text-sm break-words">
|
||||
<strong>{item.file.name}</strong>
|
||||
<span className="block text-xs">
|
||||
{(item.file.size / 1024).toFixed(1)} KB
|
||||
· informação privada
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" className="rounded border px-2 py-1 text-sm" onClick={() => removeAttachment(index)}>Remover</button>
|
||||
{item.include && (item.file.type === 'image/jpeg' || item.file.type === 'image/png') && <label className="grid gap-1 text-sm sm:col-span-2">Legenda da fotografia<input className="rounded border px-3 py-2" maxLength={300} value={item.caption} onChange={(event) => updateAttachment(index, { caption: event.target.value })} /></label>}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-2 py-1 text-sm"
|
||||
onClick={() => removeAttachment(index)}
|
||||
>
|
||||
Remover
|
||||
</button>
|
||||
{item.include &&
|
||||
(item.file.type === 'image/jpeg' ||
|
||||
item.file.type === 'image/png') && (
|
||||
<label className="grid gap-1 text-sm sm:col-span-2">
|
||||
Legenda da fotografia
|
||||
<input
|
||||
className="rounded border px-3 py-2"
|
||||
maxLength={300}
|
||||
value={item.caption}
|
||||
onChange={(event) =>
|
||||
updateAttachment(index, {
|
||||
caption: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<p className="rounded bg-amber-50 p-3 text-sm">Os valores e a proveniência mantêm a classificação do dossier. Campos vazios aparecem como “Não informado”; não são convertidos em zero. O relatório identifica pressupostos, estimativas e referências sem as apresentar como resultados confirmados.</p>
|
||||
{error && <p role="alert" className="text-sm text-red-800">{error}</p>}
|
||||
<p className="rounded bg-amber-50 p-3 text-sm">
|
||||
Os valores e a proveniência mantêm a classificação do dossier.
|
||||
Campos vazios aparecem como “Não informado”; não são convertidos
|
||||
em zero. O relatório identifica pressupostos, estimativas e
|
||||
referências sem as apresentar como resultados confirmados.
|
||||
</p>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-red-800">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button type="button" className="rounded bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50" disabled={Boolean(busy) || selectedSections.size === 0} onClick={() => void exportWord()}>{busy === 'word' ? 'A gerar Word…' : 'Transferir relatório Word (.docx)'}</button>
|
||||
<button type="button" className="rounded border px-4 py-2 disabled:opacity-50" disabled={Boolean(busy) || selectedSections.size === 0} onClick={() => void exportPdf()}>{busy === 'pdf' ? 'A preparar impressão…' : 'Imprimir / guardar como PDF'}</button>
|
||||
{selected.length > 0 && <button type="button" className="rounded border px-4 py-2 disabled:opacity-50" disabled={Boolean(busy)} onClick={() => void exportPackage()}>{busy === 'package' ? 'A preparar pacote…' : 'Transferir relatório + originais (.zip)'}</button>}
|
||||
<button type="button" className="rounded border px-4 py-2" disabled={Boolean(busy)} onClick={exportCsv}>Exportar CSV complementar</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50"
|
||||
disabled={Boolean(busy) || selectedSections.size === 0}
|
||||
onClick={() => void exportWord()}
|
||||
>
|
||||
{busy === 'word'
|
||||
? 'A gerar Word…'
|
||||
: 'Transferir relatório Word (.docx)'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-4 py-2 disabled:opacity-50"
|
||||
disabled={Boolean(busy) || selectedSections.size === 0}
|
||||
onClick={() => void exportPdf()}
|
||||
>
|
||||
{busy === 'pdf'
|
||||
? 'A preparar impressão…'
|
||||
: 'Imprimir / guardar como PDF'}
|
||||
</button>
|
||||
{selected.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-4 py-2 disabled:opacity-50"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => void exportPackage()}
|
||||
>
|
||||
{busy === 'package'
|
||||
? 'A preparar pacote…'
|
||||
: 'Transferir relatório + originais (.zip)'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-4 py-2"
|
||||
disabled={Boolean(busy)}
|
||||
onClick={exportCsv}
|
||||
>
|
||||
Exportar CSV complementar
|
||||
</button>
|
||||
</div>
|
||||
{selected.length > 0 && <p className="text-xs text-slate-700">O ZIP contém o Word, os anexos marcados e um índice com o estado de incorporação. Nenhum ficheiro é carregado para o portal.</p>}
|
||||
{selected.length > 0 && (
|
||||
<p className="text-xs text-slate-700">
|
||||
O ZIP contém o Word, os anexos marcados e um índice com o
|
||||
estado de incorporação. Nenhum ficheiro é carregado para o
|
||||
portal.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,44 +1,339 @@
|
||||
import { readRows, type ProjectMilestone, type TeamNeed } from '@/lib/project-dossier';
|
||||
import {
|
||||
readRows,
|
||||
type ProjectMilestone,
|
||||
type TeamNeed,
|
||||
} from '@/lib/project-dossier';
|
||||
|
||||
const teamKeys = ['competency', 'state', 'action', 'estimated_cost', 'due_date'] as const;
|
||||
const milestoneKeys = ['title', 'due_date', 'status', 'planned_amount', 'actual_amount'] as const;
|
||||
const teamKeys = [
|
||||
'competency',
|
||||
'state',
|
||||
'action',
|
||||
'estimated_cost',
|
||||
'due_date',
|
||||
] as const;
|
||||
const milestoneKeys = [
|
||||
'title',
|
||||
'due_date',
|
||||
'status',
|
||||
'planned_amount',
|
||||
'actual_amount',
|
||||
] as const;
|
||||
|
||||
function update<T extends Record<string, string>>(rows: T[], index: number, key: keyof T, value: string): T[] {
|
||||
return rows.map((row, i) => i === index ? { ...row, [key]: value } : row);
|
||||
function update<T extends Record<string, string>>(
|
||||
rows: T[],
|
||||
index: number,
|
||||
key: keyof T,
|
||||
value: string,
|
||||
): T[] {
|
||||
return rows.map((row, i) => (i === index ? { ...row, [key]: value } : row));
|
||||
}
|
||||
|
||||
export function ProjectTeamPlanner({ value, onChange }: { value: string; onChange: (value: string) => void }) {
|
||||
export function ProjectTeamPlanner({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
const rows = readRows<TeamNeed>(value, teamKeys);
|
||||
const persist = (next: TeamNeed[]) => onChange(JSON.stringify(next));
|
||||
return <section className="space-y-4" aria-label="Necessidades de equipa e competências">
|
||||
<p className="text-sm text-slate-700">Registe competências declaradas, lacunas, resposta prevista, custo e prazo. Não é uma certificação nem uma correspondência automática a prestadores.</p>
|
||||
{rows.map((row, index) => <fieldset key={index} className="grid gap-3 rounded border p-3 sm:grid-cols-2">
|
||||
<legend className="font-medium">Necessidade {index + 1}</legend>
|
||||
<label className="text-sm">Competência ou função<input className="mt-1 w-full rounded border p-2" value={row.competency} onChange={(e) => persist(update(rows, index, 'competency', e.target.value))}/></label>
|
||||
<label className="text-sm">Disponibilidade<select className="mt-1 w-full rounded border p-2" value={row.state} onChange={(e) => persist(update(rows, index, 'state', e.target.value))}><option value="unknown">Por avaliar</option><option value="available">Disponível (declarado)</option><option value="gap">Lacuna identificada</option></select></label>
|
||||
<label className="text-sm">Resposta planeada<input className="mt-1 w-full rounded border p-2" placeholder="Formação, contratação, parceria…" value={row.action} onChange={(e) => persist(update(rows, index, 'action', e.target.value))}/></label>
|
||||
<label className="text-sm">Custo estimado (moeda do projecto)<input type="number" min="0" step="0.01" className="mt-1 w-full rounded border p-2" value={row.estimated_cost} onChange={(e) => persist(update(rows, index, 'estimated_cost', e.target.value))}/></label>
|
||||
<label className="text-sm">Prazo previsto<input type="date" className="mt-1 w-full rounded border p-2" value={row.due_date} onChange={(e) => persist(update(rows, index, 'due_date', e.target.value))}/></label>
|
||||
<button type="button" className="justify-self-start rounded border px-3 py-2 text-sm" onClick={() => persist(rows.filter((_, i) => i !== index))}>Remover necessidade {index + 1}</button>
|
||||
</fieldset>)}
|
||||
<button type="button" className="rounded border px-3 py-2" onClick={() => persist([...rows, { competency: '', state: 'unknown', action: '', estimated_cost: '', due_date: '' }])}>Adicionar competência ou lacuna</button>
|
||||
</section>;
|
||||
return (
|
||||
<section
|
||||
className="space-y-4"
|
||||
aria-label="Necessidades de equipa e competências"
|
||||
>
|
||||
<p className="text-sm text-slate-700">
|
||||
Registe competências declaradas, lacunas, resposta prevista,
|
||||
custo e prazo. Não é uma certificação nem uma correspondência
|
||||
automática a prestadores.
|
||||
</p>
|
||||
{rows.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend className="font-medium">
|
||||
Necessidade {index + 1}
|
||||
</legend>
|
||||
<label className="text-sm">
|
||||
Competência ou função
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.competency}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'competency',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Disponibilidade
|
||||
<select
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.state}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'state',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="unknown">Por avaliar</option>
|
||||
<option value="available">
|
||||
Disponível (declarado)
|
||||
</option>
|
||||
<option value="gap">Lacuna identificada</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Resposta planeada
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
placeholder="Formação, contratação, parceria…"
|
||||
value={row.action}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'action',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Custo estimado (moeda do projecto)
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.estimated_cost}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'estimated_cost',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Prazo previsto
|
||||
<input
|
||||
type="date"
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.due_date}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'due_date',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="justify-self-start rounded border px-3 py-2 text-sm"
|
||||
onClick={() =>
|
||||
persist(rows.filter((_, i) => i !== index))
|
||||
}
|
||||
>
|
||||
Remover necessidade {index + 1}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
persist([
|
||||
...rows,
|
||||
{
|
||||
competency: '',
|
||||
state: 'unknown',
|
||||
action: '',
|
||||
estimated_cost: '',
|
||||
due_date: '',
|
||||
},
|
||||
])
|
||||
}
|
||||
>
|
||||
Adicionar competência ou lacuna
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectMilestonePlanner({ value, onChange }: { value: string; onChange: (value: string) => void }) {
|
||||
export function ProjectMilestonePlanner({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
const rows = readRows<ProjectMilestone>(value, milestoneKeys);
|
||||
const persist = (next: ProjectMilestone[]) => onChange(JSON.stringify(next));
|
||||
return <section className="space-y-4" aria-label="Marcos de execução">
|
||||
<p className="text-sm text-slate-700">Compare datas e montantes planeados com o realizado. Estes valores são declarados; não alteram automaticamente o plano financeiro.</p>
|
||||
{rows.map((row, index) => <fieldset key={index} className="grid gap-3 rounded border p-3 sm:grid-cols-2">
|
||||
<legend className="font-medium">Marco {index + 1}</legend>
|
||||
<label className="text-sm">Marco ou resultado<input className="mt-1 w-full rounded border p-2" value={row.title} onChange={(e) => persist(update(rows, index, 'title', e.target.value))}/></label>
|
||||
<label className="text-sm">Prazo previsto<input type="date" className="mt-1 w-full rounded border p-2" value={row.due_date} onChange={(e) => persist(update(rows, index, 'due_date', e.target.value))}/></label>
|
||||
<label className="text-sm">Estado<select className="mt-1 w-full rounded border p-2" value={row.status} onChange={(e) => persist(update(rows, index, 'status', e.target.value))}><option value="planned">Planeado</option><option value="in_progress">Em curso</option><option value="completed">Concluído (declarado)</option></select></label>
|
||||
<label className="text-sm">Montante planeado<input type="number" min="0" step="0.01" className="mt-1 w-full rounded border p-2" value={row.planned_amount} onChange={(e) => persist(update(rows, index, 'planned_amount', e.target.value))}/></label>
|
||||
<label className="text-sm">Montante realizado<input type="number" min="0" step="0.01" className="mt-1 w-full rounded border p-2" value={row.actual_amount} onChange={(e) => persist(update(rows, index, 'actual_amount', e.target.value))}/></label>
|
||||
<button type="button" className="justify-self-start rounded border px-3 py-2 text-sm" onClick={() => persist(rows.filter((_, i) => i !== index))}>Remover marco {index + 1}</button>
|
||||
</fieldset>)}
|
||||
<button type="button" className="rounded border px-3 py-2" onClick={() => persist([...rows, { title: '', due_date: '', status: 'planned', planned_amount: '', actual_amount: '' }])}>Adicionar marco</button>
|
||||
</section>;
|
||||
const persist = (next: ProjectMilestone[]) =>
|
||||
onChange(JSON.stringify(next));
|
||||
return (
|
||||
<section className="space-y-4" aria-label="Marcos de execução">
|
||||
<p className="text-sm text-slate-700">
|
||||
Compare datas e montantes planeados com o realizado. Estes
|
||||
valores são declarados; não alteram automaticamente o plano
|
||||
financeiro.
|
||||
</p>
|
||||
{rows.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
className="grid gap-3 rounded border p-3 sm:grid-cols-2"
|
||||
>
|
||||
<legend className="font-medium">Marco {index + 1}</legend>
|
||||
<label className="text-sm">
|
||||
Marco ou resultado
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.title}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'title',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Prazo previsto
|
||||
<input
|
||||
type="date"
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.due_date}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'due_date',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Estado
|
||||
<select
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.status}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'status',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="planned">Planeado</option>
|
||||
<option value="in_progress">Em curso</option>
|
||||
<option value="completed">
|
||||
Concluído (declarado)
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Montante planeado
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.planned_amount}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'planned_amount',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
Montante realizado
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={row.actual_amount}
|
||||
onChange={(e) =>
|
||||
persist(
|
||||
update(
|
||||
rows,
|
||||
index,
|
||||
'actual_amount',
|
||||
e.target.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="justify-self-start rounded border px-3 py-2 text-sm"
|
||||
onClick={() =>
|
||||
persist(rows.filter((_, i) => i !== index))
|
||||
}
|
||||
>
|
||||
Remover marco {index + 1}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
persist([
|
||||
...rows,
|
||||
{
|
||||
title: '',
|
||||
due_date: '',
|
||||
status: 'planned',
|
||||
planned_amount: '',
|
||||
actual_amount: '',
|
||||
},
|
||||
])
|
||||
}
|
||||
>
|
||||
Adicionar marco
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,87 +1,280 @@
|
||||
import { getProjectReadiness, readPlannedRiskResponses, serializePlannedRiskResponses, type PlannedRiskResponse, type ReadinessDraft } from '@/lib/project-readiness';
|
||||
import {
|
||||
getProjectReadiness,
|
||||
readPlannedRiskResponses,
|
||||
serializePlannedRiskResponses,
|
||||
type PlannedRiskResponse,
|
||||
type ReadinessDraft,
|
||||
} from '@/lib/project-readiness';
|
||||
|
||||
type Milestone = { title: string; due_date: string; status: string; planned_amount: string; actual_amount: string };
|
||||
type Milestone = {
|
||||
title: string;
|
||||
due_date: string;
|
||||
status: string;
|
||||
planned_amount: string;
|
||||
actual_amount: string;
|
||||
};
|
||||
|
||||
function parseMilestones(value: string): Milestone[] {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value || '[]');
|
||||
return Array.isArray(parsed) ? parsed.filter((item): item is Milestone => Boolean(
|
||||
item && typeof item === 'object' && typeof item.title === 'string' &&
|
||||
typeof item.due_date === 'string' && typeof item.planned_amount === 'string',
|
||||
)) : [];
|
||||
} catch { return []; }
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item): item is Milestone =>
|
||||
Boolean(
|
||||
item &&
|
||||
typeof item === 'object' &&
|
||||
typeof item.title === 'string' &&
|
||||
typeof item.due_date === 'string' &&
|
||||
typeof item.planned_amount === 'string',
|
||||
),
|
||||
)
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const kindLabels = { missing: 'Informação em falta', unverified: 'Hipótese por verificar', risk: 'Risco identificado' };
|
||||
const kindLabels = {
|
||||
missing: 'Informação em falta',
|
||||
unverified: 'Hipótese por verificar',
|
||||
risk: 'Risco identificado',
|
||||
};
|
||||
|
||||
export function ProjectReadiness({ draft, onChange, onNavigate }: {
|
||||
export function ProjectReadiness({
|
||||
draft,
|
||||
onChange,
|
||||
onNavigate,
|
||||
}: {
|
||||
draft: ReadinessDraft;
|
||||
onChange: (key: string, value: string) => void;
|
||||
onNavigate: (fieldKey: string) => void;
|
||||
}) {
|
||||
const items = getProjectReadiness(draft);
|
||||
const responses = readPlannedRiskResponses(draft);
|
||||
const milestones = parseMilestones(typeof draft.project_execution_snapshot === 'string' ? draft.project_execution_snapshot : '');
|
||||
const currency = typeof draft.currency === 'string' && draft.currency ? draft.currency : 'moeda ainda não indicada';
|
||||
const milestones = parseMilestones(
|
||||
typeof draft.project_execution_snapshot === 'string'
|
||||
? draft.project_execution_snapshot
|
||||
: '',
|
||||
);
|
||||
const currency =
|
||||
typeof draft.currency === 'string' && draft.currency
|
||||
? draft.currency
|
||||
: 'moeda ainda não indicada';
|
||||
|
||||
function updateResponse(riskId: string, patch: Partial<PlannedRiskResponse>) {
|
||||
const current = responses.find((response) => response.risk_id === riskId) ?? {
|
||||
risk_id: riskId, action: '', owner: '', estimated_cost: '', due_date: '',
|
||||
function updateResponse(
|
||||
riskId: string,
|
||||
patch: Partial<PlannedRiskResponse>,
|
||||
) {
|
||||
const current = responses.find(
|
||||
(response) => response.risk_id === riskId,
|
||||
) ?? {
|
||||
risk_id: riskId,
|
||||
action: '',
|
||||
owner: '',
|
||||
estimated_cost: '',
|
||||
due_date: '',
|
||||
};
|
||||
const next = responses.filter((response) => response.risk_id !== riskId);
|
||||
const next = responses.filter(
|
||||
(response) => response.risk_id !== riskId,
|
||||
);
|
||||
next.push({ ...current, ...patch });
|
||||
onChange('project_risk_responses_snapshot', serializePlannedRiskResponses(next));
|
||||
onChange(
|
||||
'project_risk_responses_snapshot',
|
||||
serializePlannedRiskResponses(next),
|
||||
);
|
||||
}
|
||||
|
||||
return <section className="space-y-4" aria-labelledby="project-readiness-title">
|
||||
<div>
|
||||
<h4 id="project-readiness-title" className="text-lg font-semibold">O que precisa de esclarecer</h4>
|
||||
<p className="mt-1 text-sm text-slate-700">Os avisos abaixo resultam apenas dos campos actualmente preenchidos. Não atribuem probabilidades, perdas ou uma classificação de viabilidade.</p>
|
||||
</div>
|
||||
{items.length === 0 ? <p role="status" className="rounded border p-3 text-sm">Não foram detectadas estas lacunas automáticas. Isto não confirma a qualidade, exactidão ou viabilidade do projecto.</p> : (
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => {
|
||||
const response = responses.find((entry) => entry.risk_id === item.id) ?? { risk_id: item.id, action: '', owner: '', estimated_cost: '', due_date: '' };
|
||||
return <li key={item.id} className="rounded-lg border border-slate-300 p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-xs font-semibold uppercase tracking-wide">{kindLabels[item.kind]}</p>
|
||||
<h5 className="mt-1 font-semibold">{item.title}</h5>
|
||||
</div>
|
||||
<button type="button" className="rounded border px-3 py-2 text-sm underline focus-visible:outline-2" onClick={() => onNavigate(item.fieldKey)}>Rever informação</button>
|
||||
</div>
|
||||
<dl className="mt-3 grid gap-2 text-sm">
|
||||
<div><dt className="font-medium">Origem</dt><dd>{item.origin}</dd></div>
|
||||
<div><dt className="font-medium">Parte afectada</dt><dd>{item.affected}</dd></div>
|
||||
<div><dt className="font-medium">Possível consequência</dt><dd>{item.consequence}</dd></div>
|
||||
<div><dt className="font-medium">Acção sugerida</dt><dd>{item.nextAction}</dd></div>
|
||||
</dl>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
<label className="grid gap-1 text-sm font-medium sm:col-span-2">Resposta planeada
|
||||
<textarea className="min-h-20 rounded border p-2" maxLength={500} value={response.action} onChange={(event) => updateResponse(item.id, { action: event.target.value })} />
|
||||
</label>
|
||||
{milestones.length > 0 && <label className="grid gap-1 text-sm font-medium sm:col-span-2">Usar um marco já registado
|
||||
<select className="rounded border p-2" defaultValue="" onChange={(event) => {
|
||||
const selected = milestones[Number(event.target.value)];
|
||||
if (selected) updateResponse(item.id, { action: selected.title, due_date: selected.due_date, estimated_cost: selected.planned_amount });
|
||||
}}>
|
||||
<option value="">Escolher marco para preencher resposta, prazo e custo</option>
|
||||
{milestones.map((milestone, index) => <option key={`${milestone.title}-${index}`} value={index}>{milestone.title || `Marco ${index + 1}`}</option>)}
|
||||
</select>
|
||||
</label>}
|
||||
<label className="grid gap-1 text-sm font-medium">Responsável (se definido)
|
||||
<input className="rounded border p-2" maxLength={160} value={response.owner} onChange={(event) => updateResponse(item.id, { owner: event.target.value })} />
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm font-medium">Custo previsto ({currency})
|
||||
<input type="number" min="0" step="0.01" className="rounded border p-2" value={response.estimated_cost} onChange={(event) => updateResponse(item.id, { estimated_cost: event.target.value })} />
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm font-medium">Prazo previsto
|
||||
<input type="date" className="rounded border p-2" value={response.due_date} onChange={(event) => updateResponse(item.id, { due_date: event.target.value })} />
|
||||
</label>
|
||||
</div>
|
||||
</li>;
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>;
|
||||
return (
|
||||
<section
|
||||
className="space-y-4"
|
||||
aria-labelledby="project-readiness-title"
|
||||
>
|
||||
<div>
|
||||
<h4
|
||||
id="project-readiness-title"
|
||||
className="text-lg font-semibold"
|
||||
>
|
||||
O que precisa de esclarecer
|
||||
</h4>
|
||||
<p className="mt-1 text-sm text-slate-700">
|
||||
Os avisos abaixo resultam apenas dos campos actualmente
|
||||
preenchidos. Não atribuem probabilidades, perdas ou uma
|
||||
classificação de viabilidade.
|
||||
</p>
|
||||
</div>
|
||||
{items.length === 0 ? (
|
||||
<p role="status" className="rounded border p-3 text-sm">
|
||||
Não foram detectadas estas lacunas automáticas. Isto não
|
||||
confirma a qualidade, exactidão ou viabilidade do projecto.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => {
|
||||
const response = responses.find(
|
||||
(entry) => entry.risk_id === item.id,
|
||||
) ?? {
|
||||
risk_id: item.id,
|
||||
action: '',
|
||||
owner: '',
|
||||
estimated_cost: '',
|
||||
due_date: '',
|
||||
};
|
||||
return (
|
||||
<li
|
||||
key={item.id}
|
||||
className="rounded-lg border border-slate-300 p-4"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-xs font-semibold tracking-wide uppercase">
|
||||
{kindLabels[item.kind]}
|
||||
</p>
|
||||
<h5 className="mt-1 font-semibold">
|
||||
{item.title}
|
||||
</h5>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2 text-sm underline focus-visible:outline-2"
|
||||
onClick={() =>
|
||||
onNavigate(item.fieldKey)
|
||||
}
|
||||
>
|
||||
Rever informação
|
||||
</button>
|
||||
</div>
|
||||
<dl className="mt-3 grid gap-2 text-sm">
|
||||
<div>
|
||||
<dt className="font-medium">Origem</dt>
|
||||
<dd>{item.origin}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Parte afectada
|
||||
</dt>
|
||||
<dd>{item.affected}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Possível consequência
|
||||
</dt>
|
||||
<dd>{item.consequence}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
Acção sugerida
|
||||
</dt>
|
||||
<dd>{item.nextAction}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
<label className="grid gap-1 text-sm font-medium sm:col-span-2">
|
||||
Resposta planeada
|
||||
<textarea
|
||||
className="min-h-20 rounded border p-2"
|
||||
maxLength={500}
|
||||
value={response.action}
|
||||
onChange={(event) =>
|
||||
updateResponse(item.id, {
|
||||
action: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{milestones.length > 0 && (
|
||||
<label className="grid gap-1 text-sm font-medium sm:col-span-2">
|
||||
Usar um marco já registado
|
||||
<select
|
||||
className="rounded border p-2"
|
||||
defaultValue=""
|
||||
onChange={(event) => {
|
||||
const selected =
|
||||
milestones[
|
||||
Number(
|
||||
event.target
|
||||
.value,
|
||||
)
|
||||
];
|
||||
if (selected)
|
||||
updateResponse(
|
||||
item.id,
|
||||
{
|
||||
action: selected.title,
|
||||
due_date:
|
||||
selected.due_date,
|
||||
estimated_cost:
|
||||
selected.planned_amount,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Escolher marco para
|
||||
preencher resposta, prazo e
|
||||
custo
|
||||
</option>
|
||||
{milestones.map(
|
||||
(milestone, index) => (
|
||||
<option
|
||||
key={`${milestone.title}-${index}`}
|
||||
value={index}
|
||||
>
|
||||
{milestone.title ||
|
||||
`Marco ${index + 1}`}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="grid gap-1 text-sm font-medium">
|
||||
Responsável (se definido)
|
||||
<input
|
||||
className="rounded border p-2"
|
||||
maxLength={160}
|
||||
value={response.owner}
|
||||
onChange={(event) =>
|
||||
updateResponse(item.id, {
|
||||
owner: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm font-medium">
|
||||
Custo previsto ({currency})
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
className="rounded border p-2"
|
||||
value={response.estimated_cost}
|
||||
onChange={(event) =>
|
||||
updateResponse(item.id, {
|
||||
estimated_cost:
|
||||
event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm font-medium">
|
||||
Prazo previsto
|
||||
<input
|
||||
type="date"
|
||||
className="rounded border p-2"
|
||||
value={response.due_date}
|
||||
onChange={(event) =>
|
||||
updateResponse(item.id, {
|
||||
due_date:
|
||||
event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,23 +148,39 @@ export function SimulationBusinessPlan({
|
||||
const importPlanFile = async (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
if (file.size > MAX_BUSINESS_PLAN_SNAPSHOT_LENGTH) {
|
||||
setSnapshotError('O ficheiro excede 60 KB. Seleccione um plano JSON exportado pelo InvestMoz dentro deste limite.');
|
||||
setSnapshotError(
|
||||
'O ficheiro excede 60 KB. Seleccione um plano JSON exportado pelo InvestMoz dentro deste limite.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const source = await file.text();
|
||||
const imported = restoreBusinessPlanSnapshot(source);
|
||||
if (!imported) throw new Error('O ficheiro não contém um plano JSON reconhecido pelo InvestMoz.');
|
||||
if (!imported)
|
||||
throw new Error(
|
||||
'O ficheiro não contém um plano JSON reconhecido pelo InvestMoz.',
|
||||
);
|
||||
savePlan(imported);
|
||||
setSnapshotError('');
|
||||
} catch (cause) {
|
||||
setSnapshotError(cause instanceof Error ? cause.message : 'Não foi possível importar este plano.');
|
||||
setSnapshotError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível importar este plano.',
|
||||
);
|
||||
}
|
||||
};
|
||||
const exportPlanJson = () => {
|
||||
try {
|
||||
const snapshotJson = serializeBusinessPlanSnapshot({ ...plan, currency });
|
||||
const url = URL.createObjectURL(new Blob([snapshotJson], { type: 'application/json;charset=utf-8' }));
|
||||
const snapshotJson = serializeBusinessPlanSnapshot({
|
||||
...plan,
|
||||
currency,
|
||||
});
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([snapshotJson], {
|
||||
type: 'application/json;charset=utf-8',
|
||||
}),
|
||||
);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'plano-financeiro-investmoz.json';
|
||||
@@ -173,7 +189,11 @@ export function SimulationBusinessPlan({
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
setSnapshotError('');
|
||||
} catch (cause) {
|
||||
setSnapshotError(cause instanceof Error ? cause.message : 'Não foi possível exportar este plano.');
|
||||
setSnapshotError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível exportar este plano.',
|
||||
);
|
||||
}
|
||||
};
|
||||
type ProductScheduleKey =
|
||||
@@ -856,10 +876,27 @@ export function SimulationBusinessPlan({
|
||||
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
|
||||
<label className="grid gap-1 text-sm">
|
||||
Importar plano financeiro InvestMoz (.json, até 60 KB)
|
||||
<input type="file" accept="application/json,.json" onChange={(event) => { void importPlanFile(event.currentTarget.files?.[0]); event.currentTarget.value = ''; }} />
|
||||
<input
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
onChange={(event) => {
|
||||
void importPlanFile(event.currentTarget.files?.[0]);
|
||||
event.currentTarget.value = '';
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button type="button" className="rounded border px-3 py-2 text-sm" onClick={exportPlanJson}>Exportar plano JSON</button>
|
||||
<span className="text-xs text-slate-600">O ficheiro é lido localmente. A importação substitui os pressupostos editáveis deste plano após validação do formato.</span>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
onClick={exportPlanJson}
|
||||
>
|
||||
Exportar plano JSON
|
||||
</button>
|
||||
<span className="text-xs text-slate-600">
|
||||
O ficheiro é lido localmente. A importação substitui os
|
||||
pressupostos editáveis deste plano após validação do
|
||||
formato.
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<label className="block text-sm font-medium">
|
||||
|
||||
@@ -10,24 +10,43 @@ type Parameter = {
|
||||
rule_code?: string;
|
||||
rule_version?: number;
|
||||
validity?: { start: string; end: string | null };
|
||||
source?: { title: string; diploma: string | null; article: string | null; url: string | null };
|
||||
source?: {
|
||||
title: string;
|
||||
diploma: string | null;
|
||||
article: string | null;
|
||||
url: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
indeterminate_missing: 'Não existe parâmetro aprovado para este âmbito e período.',
|
||||
indeterminate_context: 'As condições publicadas não correspondem às respostas indicadas.',
|
||||
indeterminate_missing:
|
||||
'Não existe parâmetro aprovado para este âmbito e período.',
|
||||
indeterminate_context:
|
||||
'As condições publicadas não correspondem às respostas indicadas.',
|
||||
indeterminate_scope: 'O âmbito da regra não está suficientemente definido.',
|
||||
indeterminate_overlap: 'Há regras sobrepostas; é necessária revisão.',
|
||||
indeterminate_period_change: 'A vigência muda dentro do período seleccionado.',
|
||||
indeterminate_invalid: 'O parâmetro publicado não passou a validação de formato.',
|
||||
indeterminate_period_change:
|
||||
'A vigência muda dentro do período seleccionado.',
|
||||
indeterminate_invalid:
|
||||
'O parâmetro publicado não passou a validação de formato.',
|
||||
};
|
||||
const apiComponents: Record<string, string> = {
|
||||
irpc: 'IRPC', iva: 'IVA', ispc: 'ISPC', irps: 'IRPS', inss: 'INSS',
|
||||
withholding: 'RETENCOES', retenções: 'RETENCOES',
|
||||
irpc: 'IRPC',
|
||||
iva: 'IVA',
|
||||
ispc: 'ISPC',
|
||||
irps: 'IRPS',
|
||||
inss: 'INSS',
|
||||
withholding: 'RETENCOES',
|
||||
retenções: 'RETENCOES',
|
||||
};
|
||||
|
||||
function getXsrfToken(): string {
|
||||
return decodeURIComponent(document.cookie.split('; ').find((cookie) => cookie.startsWith('XSRF-TOKEN='))?.slice(11) ?? '');
|
||||
return decodeURIComponent(
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((cookie) => cookie.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
export function SimulationFiscalStatus({
|
||||
@@ -49,8 +68,15 @@ export function SimulationFiscalStatus({
|
||||
const [requestState, setRequestState] = useState('idle');
|
||||
|
||||
useEffect(() => {
|
||||
const apiComponent = component ? apiComponents[component.toLowerCase()] : undefined;
|
||||
if (scenarioMode !== 'approved_parameters' || !apiComponent || !periodStart || !periodEnd) {
|
||||
const apiComponent = component
|
||||
? apiComponents[component.toLowerCase()]
|
||||
: undefined;
|
||||
if (
|
||||
scenarioMode !== 'approved_parameters' ||
|
||||
!apiComponent ||
|
||||
!periodStart ||
|
||||
!periodEnd
|
||||
) {
|
||||
setParameters([]);
|
||||
setRequestState('idle');
|
||||
return;
|
||||
@@ -61,53 +87,197 @@ export function SimulationFiscalStatus({
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
signal: abort.signal,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-XSRF-TOKEN': getXsrfToken() },
|
||||
body: JSON.stringify({ component: apiComponent, period_start: periodStart, period_end: periodEnd, context: context ?? {} }),
|
||||
}).then(async (response) => {
|
||||
if (!response.ok) throw new Error('lookup_failed');
|
||||
const payload = await response.json() as { parameters?: Parameter[] };
|
||||
setParameters(Array.isArray(payload.parameters) ? payload.parameters : []);
|
||||
setRequestState('done');
|
||||
}).catch((error: unknown) => {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') return;
|
||||
setParameters([]);
|
||||
setRequestState('error');
|
||||
});
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': getXsrfToken(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
component: apiComponent,
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
context: context ?? {},
|
||||
}),
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error('lookup_failed');
|
||||
const payload = (await response.json()) as {
|
||||
parameters?: Parameter[];
|
||||
};
|
||||
setParameters(
|
||||
Array.isArray(payload.parameters) ? payload.parameters : [],
|
||||
);
|
||||
setRequestState('done');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (
|
||||
error instanceof DOMException &&
|
||||
error.name === 'AbortError'
|
||||
)
|
||||
return;
|
||||
setParameters([]);
|
||||
setRequestState('error');
|
||||
});
|
||||
return () => abort.abort();
|
||||
}, [scenarioMode, component, periodStart, periodEnd, JSON.stringify(context ?? {})]);
|
||||
}, [
|
||||
scenarioMode,
|
||||
component,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
JSON.stringify(context ?? {}),
|
||||
]);
|
||||
|
||||
const salaryViewMessages: Record<string, string> = {
|
||||
monthly_net_estimate: 'Estimativa líquida mensal; retenção mensal e apuramento anual são resultados distintos.',
|
||||
monthly_withholding: 'Retenção mensal não representa, por si só, o apuramento anual nem o cumprimento integral das obrigações fiscais.',
|
||||
annual_assessment: 'Apuramento anual; retenções mensais não o substituem.',
|
||||
monthly_net_estimate:
|
||||
'Estimativa líquida mensal; retenção mensal e apuramento anual são resultados distintos.',
|
||||
monthly_withholding:
|
||||
'Retenção mensal não representa, por si só, o apuramento anual nem o cumprimento integral das obrigações fiscais.',
|
||||
annual_assessment:
|
||||
'Apuramento anual; retenções mensais não o substituem.',
|
||||
};
|
||||
|
||||
return <section className="space-y-3 rounded-lg border border-amber-400 bg-amber-50 p-4" aria-labelledby="fiscal-status-title">
|
||||
<h3 id="fiscal-status-title" className="font-semibold">Componentes fiscais e contributivas</h3>
|
||||
<p className="text-sm">A consulta identifica parâmetros publicados e as respectivas fontes. Não executa fórmulas nem determina imposto devido ou elegibilidade fiscal.</p>
|
||||
{scenarioMode === 'approved_parameters' && <p role="status" className="text-sm">
|
||||
{requestState === 'loading' ? 'A consultar parâmetros aprovados para o período e âmbito indicados…' :
|
||||
requestState === 'error' ? 'Não foi possível consultar os parâmetros; o resultado permanece indeterminado.' :
|
||||
!periodStart || !periodEnd ? 'Indique um período exacto. Para periodicidade mensal ou trimestral, seleccione o mês ou trimestre.' :
|
||||
`Período consultado: ${periodStart} a ${periodEnd}.`}
|
||||
</p>}
|
||||
{scenarioMode === 'custom_planning' && <p role="note" className="text-sm">Modo de planeamento separado: pressupostos do utilizador, não taxas legais confirmadas. Nenhum imposto ou elegibilidade é calculado.</p>}
|
||||
{salaryView && salaryViewMessages[salaryView] && <p role="note" className="text-sm">{salaryViewMessages[salaryView]}</p>}
|
||||
<ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">{fiscalComponentCodes.map((code) => {
|
||||
const selected = code === (component === 'withholding' ? 'RETENCOES' : component?.toUpperCase());
|
||||
return <li key={code} className="rounded border border-amber-200 bg-white p-3" aria-label={`${code}: ${selected ? 'consulta seleccionada' : 'não consultado'}`}>
|
||||
<strong>{code === 'RETENCOES' ? 'Retenções' : code}</strong>
|
||||
{!selected || scenarioMode !== 'approved_parameters' ? <p className="text-sm">Sem cálculo fiscal</p> : requestState !== 'done' ? <p className="text-sm">Indeterminado — sem cálculo</p> : parameters.length === 0 ? <p className="text-sm">Indeterminado — nenhum parâmetro publicado aplicável.</p> : <div className="space-y-2 text-sm">{parameters.map((parameter) => <div key={parameter.parameter_code} className="border-t pt-2">
|
||||
<strong>{parameter.parameter_code}</strong>
|
||||
{parameter.status === 'resolved' ? <>
|
||||
<p>Parâmetro: {parameter.value} {parameter.unit}</p>
|
||||
<p>Regra {parameter.rule_code} v{parameter.rule_version}; âmbito {parameter.scope_key}</p>
|
||||
<p>Vigência: {parameter.validity?.start} a {parameter.validity?.end ?? 'sem data final'}</p>
|
||||
<p>Fonte: {parameter.source?.title}{parameter.source?.diploma ? ` — ${parameter.source.diploma}` : ''}{parameter.source?.article ? `, ${parameter.source.article}` : ''}</p>
|
||||
{parameter.source?.url && <a className="underline" href={parameter.source.url} target="_blank" rel="noreferrer">Consultar fundamento</a>}
|
||||
</> : <p>{labels[parameter.status] ?? 'Indeterminado — não foi possível validar o parâmetro.'}</p>}
|
||||
</div>)}</div>}
|
||||
</li>;
|
||||
})}</ul>
|
||||
</section>;
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded-lg border border-amber-400 bg-amber-50 p-4"
|
||||
aria-labelledby="fiscal-status-title"
|
||||
>
|
||||
<h3 id="fiscal-status-title" className="font-semibold">
|
||||
Componentes fiscais e contributivas
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
A consulta identifica parâmetros publicados e as respectivas
|
||||
fontes. Não executa fórmulas nem determina imposto devido ou
|
||||
elegibilidade fiscal.
|
||||
</p>
|
||||
{scenarioMode === 'approved_parameters' && (
|
||||
<p role="status" className="text-sm">
|
||||
{requestState === 'loading'
|
||||
? 'A consultar parâmetros aprovados para o período e âmbito indicados…'
|
||||
: requestState === 'error'
|
||||
? 'Não foi possível consultar os parâmetros; o resultado permanece indeterminado.'
|
||||
: !periodStart || !periodEnd
|
||||
? 'Indique um período exacto. Para periodicidade mensal ou trimestral, seleccione o mês ou trimestre.'
|
||||
: `Período consultado: ${periodStart} a ${periodEnd}.`}
|
||||
</p>
|
||||
)}
|
||||
{scenarioMode === 'custom_planning' && (
|
||||
<p role="note" className="text-sm">
|
||||
Modo de planeamento separado: pressupostos do utilizador,
|
||||
não taxas legais confirmadas. Nenhum imposto ou
|
||||
elegibilidade é calculado.
|
||||
</p>
|
||||
)}
|
||||
{salaryView && salaryViewMessages[salaryView] && (
|
||||
<p role="note" className="text-sm">
|
||||
{salaryViewMessages[salaryView]}
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{fiscalComponentCodes.map((code) => {
|
||||
const selected =
|
||||
code ===
|
||||
(component === 'withholding'
|
||||
? 'RETENCOES'
|
||||
: component?.toUpperCase());
|
||||
return (
|
||||
<li
|
||||
key={code}
|
||||
className="rounded border border-amber-200 bg-white p-3"
|
||||
aria-label={`${code}: ${selected ? 'consulta seleccionada' : 'não consultado'}`}
|
||||
>
|
||||
<strong>
|
||||
{code === 'RETENCOES' ? 'Retenções' : code}
|
||||
</strong>
|
||||
{!selected ||
|
||||
scenarioMode !== 'approved_parameters' ? (
|
||||
<p className="text-sm">Sem cálculo fiscal</p>
|
||||
) : requestState !== 'done' ? (
|
||||
<p className="text-sm">
|
||||
Indeterminado — sem cálculo
|
||||
</p>
|
||||
) : parameters.length === 0 ? (
|
||||
<p className="text-sm">
|
||||
Indeterminado — nenhum parâmetro publicado
|
||||
aplicável.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2 text-sm">
|
||||
{parameters.map((parameter) => (
|
||||
<div
|
||||
key={parameter.parameter_code}
|
||||
className="border-t pt-2"
|
||||
>
|
||||
<strong>
|
||||
{parameter.parameter_code}
|
||||
</strong>
|
||||
{parameter.status === 'resolved' ? (
|
||||
<>
|
||||
<p>
|
||||
Parâmetro:{' '}
|
||||
{parameter.value}{' '}
|
||||
{parameter.unit}
|
||||
</p>
|
||||
<p>
|
||||
Regra{' '}
|
||||
{parameter.rule_code} v
|
||||
{parameter.rule_version}
|
||||
; âmbito{' '}
|
||||
{parameter.scope_key}
|
||||
</p>
|
||||
<p>
|
||||
Vigência:{' '}
|
||||
{
|
||||
parameter.validity
|
||||
?.start
|
||||
}{' '}
|
||||
a{' '}
|
||||
{parameter.validity
|
||||
?.end ??
|
||||
'sem data final'}
|
||||
</p>
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{
|
||||
parameter.source
|
||||
?.title
|
||||
}
|
||||
{parameter.source
|
||||
?.diploma
|
||||
? ` — ${parameter.source.diploma}`
|
||||
: ''}
|
||||
{parameter.source
|
||||
?.article
|
||||
? `, ${parameter.source.article}`
|
||||
: ''}
|
||||
</p>
|
||||
{parameter.source?.url && (
|
||||
<a
|
||||
className="underline"
|
||||
href={
|
||||
parameter.source
|
||||
.url
|
||||
}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Consultar fundamento
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
{labels[parameter.status] ??
|
||||
'Indeterminado — não foi possível validar o parâmetro.'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
import { displayValue } from '@/lib/display-value';
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
@@ -814,7 +815,12 @@ export function SimulationForm() {
|
||||
recommendation_reason: string;
|
||||
applicability: string;
|
||||
basis_reference: string | null;
|
||||
documentary_evidence: Array<{ key: string; label: string; citation: string | null; status: string }>;
|
||||
documentary_evidence: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
citation: string | null;
|
||||
status: string;
|
||||
}>;
|
||||
}>
|
||||
>([]);
|
||||
const [linkableBusinesses, setLinkableBusinesses] = useState<
|
||||
@@ -1054,7 +1060,9 @@ export function SimulationForm() {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
let local: SimulationDraft = {};
|
||||
const requestedDraftId = new URLSearchParams(window.location.search).get('draft');
|
||||
const requestedDraftId = new URLSearchParams(
|
||||
window.location.search,
|
||||
).get('draft');
|
||||
try {
|
||||
const stored = sessionStorage.getItem(draftKey);
|
||||
if (stored) local = JSON.parse(stored) as SimulationDraft;
|
||||
@@ -1065,7 +1073,9 @@ export function SimulationForm() {
|
||||
}
|
||||
try {
|
||||
const response = await fetch(
|
||||
requestedDraftId ? `/api/v1/simulation-drafts/${encodeURIComponent(requestedDraftId)}` : '/api/v1/simulation-drafts/current',
|
||||
requestedDraftId
|
||||
? `/api/v1/simulation-drafts/${encodeURIComponent(requestedDraftId)}`
|
||||
: '/api/v1/simulation-drafts/current',
|
||||
{
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
@@ -2106,7 +2116,20 @@ export function SimulationForm() {
|
||||
className="space-y-6 rounded-xl border bg-white p-4 sm:p-6"
|
||||
aria-labelledby="simulator-step-title"
|
||||
>
|
||||
{canSavePersonalData && draftVersionNo && draftIdRef.current && <PartnershipSourceLinks type="simulation" id={draftIdRef.current}/>}
|
||||
{canSavePersonalData && draftVersionNo && draftIdRef.current && (
|
||||
<a
|
||||
className="inline-block underline"
|
||||
href={`/balcao-virtual/painel?simulation_id=${draftIdRef.current}`}
|
||||
>
|
||||
Preparar apoio no Balcão Virtual com este dossier guardado
|
||||
</a>
|
||||
)}
|
||||
{canSavePersonalData && draftVersionNo && draftIdRef.current && (
|
||||
<PartnershipSourceLinks
|
||||
type="simulation"
|
||||
id={draftIdRef.current}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2
|
||||
@@ -2619,14 +2642,14 @@ export function SimulationForm() {
|
||||
[
|
||||
'Investimento declarado',
|
||||
draft.total_investment
|
||||
? `${draft.total_investment} ${draft.currency ?? ''}`
|
||||
? `${displayValue(draft.total_investment)} ${displayValue(draft.currency)}`
|
||||
: '',
|
||||
'financial',
|
||||
],
|
||||
[
|
||||
'Estado do resultado calculado',
|
||||
result
|
||||
? `${simulationStatusLabel(result.status)} · versão ${result.version_no}${arithmeticResult.value ? ` · ${arithmeticResult.value} ${String(arithmeticSnapshot?.currency ?? '')}` : ''}`
|
||||
? `${simulationStatusLabel(result.status)} · versão ${result.version_no}${arithmeticResult.value ? ` · ${arithmeticResult.value} ${displayValue(arithmeticSnapshot?.currency)}` : ''}`
|
||||
: 'Sem resultado de cálculo guardado',
|
||||
'financial',
|
||||
],
|
||||
@@ -3037,11 +3060,30 @@ export function SimulationForm() {
|
||||
? 'origem identificada'
|
||||
: 'por confirmar'}
|
||||
</p>
|
||||
{document.documentary_evidence.length > 0 && (
|
||||
{document.documentary_evidence.length >
|
||||
0 && (
|
||||
<div className="mt-2 rounded bg-slate-50 p-2 text-sm">
|
||||
<strong>Evidência documental relacionada (não activa cálculos fiscais):</strong>
|
||||
<strong>
|
||||
Evidência documental
|
||||
relacionada (não activa
|
||||
cálculos fiscais):
|
||||
</strong>
|
||||
<ul className="list-disc pl-5">
|
||||
{document.documentary_evidence.map((item) => <li key={item.key}>{item.label}: {item.citation} A citação foi localizada no ficheiro; a interpretação e aplicação fiscal permanecem pendentes.</li>)}
|
||||
{document.documentary_evidence.map(
|
||||
(item) => (
|
||||
<li key={item.key}>
|
||||
{item.label}:{' '}
|
||||
{item.citation}{' '}
|
||||
A citação foi
|
||||
localizada no
|
||||
ficheiro; a
|
||||
interpretação e
|
||||
aplicação fiscal
|
||||
permanecem
|
||||
pendentes.
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,43 +1,271 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import InteractiveInvestmentMap from './interactive-investment-map';
|
||||
|
||||
export type DocumentedLocation = { id: string; name: string; role: string; source_reference?: string; location_type: string;
|
||||
export type DocumentedLocation = {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
source_reference?: string;
|
||||
location_type: string;
|
||||
path: { id: string; name: string; location_type: string }[];
|
||||
coordinates: { geometry_id: string; source_reference: string; geometry: { coordinates: [number, number] } }[] };
|
||||
coordinates: {
|
||||
geometry_id: string;
|
||||
source_reference: string;
|
||||
geometry: { coordinates: [number, number] };
|
||||
}[];
|
||||
};
|
||||
export type StructureGeography = {
|
||||
locations: DocumentedLocation[];
|
||||
members: { id: string; dossier_id: string; title: string; code: string; role: string; validation_status: string; source_reference: string; locations: DocumentedLocation[] }[];
|
||||
clusters: { id: string; dossier_id: string; title: string; role: string; validation_status: string; source_reference: string }[];
|
||||
chainLinks: { id: string; origin: string; destination: string; link_type: string }[];
|
||||
members: {
|
||||
id: string;
|
||||
dossier_id: string;
|
||||
title: string;
|
||||
code: string;
|
||||
role: string;
|
||||
validation_status: string;
|
||||
source_reference: string;
|
||||
locations: DocumentedLocation[];
|
||||
}[];
|
||||
clusters: {
|
||||
id: string;
|
||||
dossier_id: string;
|
||||
title: string;
|
||||
role: string;
|
||||
validation_status: string;
|
||||
source_reference: string;
|
||||
}[];
|
||||
chainLinks: {
|
||||
id: string;
|
||||
origin: string;
|
||||
destination: string;
|
||||
link_type: string;
|
||||
}[];
|
||||
chains?: { id: string; code: string; name: string; stage: string }[];
|
||||
};
|
||||
|
||||
const roles: Record<string,string> = { primary: 'Localização principal', secondary: 'Localização secundária', impact: 'Área de impacto', coverage: 'Área de abrangência documentada' };
|
||||
export function LocationList({ locations }: { locations: DocumentedLocation[] }) {
|
||||
return <div className="space-y-4">{locations.map((location, index) => <article key={`${location.id}-${location.role}-${index}`} className="rounded-lg border p-4">
|
||||
<h3 className="font-bold">{roles[location.role] ?? location.role}: {location.name}</h3>
|
||||
<dl className="grid gap-2 sm:grid-cols-2">{[['province','Província'],['district','Distrito'],['admin_post','Posto administrativo'],['locality','Localidade']].map(([type,label]) => <div key={type}><dt className="font-semibold">{label}</dt><dd>{location.path.find(node => node.location_type===type)?.name ?? 'Não documentado'}</dd></div>)}</dl>
|
||||
{location.coordinates.map(point => <p key={point.geometry_id}>Coordenadas documentadas ({location.location_type === 'site' ? 'local do projecto' : 'referência territorial; não representa a implantação'}): {point.geometry.coordinates[1]}, {point.geometry.coordinates[0]} · Fonte: {point.source_reference}</p>)}
|
||||
{!location.coordinates.length && <p>Coordenadas não documentadas.</p>}
|
||||
<p className="text-sm">Fonte da relação: {location.source_reference ?? 'Não indicada'}</p>
|
||||
<Link className="underline" href={`/oportunidades?geo_location_id=${location.id}`}>Pesquisar oportunidades neste território</Link>
|
||||
</article>)}</div>;
|
||||
const roles: Record<string, string> = {
|
||||
primary: 'Localização principal',
|
||||
secondary: 'Localização secundária',
|
||||
impact: 'Área de impacto',
|
||||
coverage: 'Área de abrangência documentada',
|
||||
};
|
||||
export function LocationList({
|
||||
locations,
|
||||
}: {
|
||||
locations: DocumentedLocation[];
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{locations.map((location, index) => (
|
||||
<article
|
||||
key={`${location.id}-${location.role}-${index}`}
|
||||
className="rounded-lg border p-4"
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
{roles[location.role] ?? location.role}: {location.name}
|
||||
</h3>
|
||||
<dl className="grid gap-2 sm:grid-cols-2">
|
||||
{[
|
||||
['province', 'Província'],
|
||||
['district', 'Distrito'],
|
||||
['admin_post', 'Posto administrativo'],
|
||||
['locality', 'Localidade'],
|
||||
].map(([type, label]) => (
|
||||
<div key={type}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd>
|
||||
{location.path.find(
|
||||
(node) => node.location_type === type,
|
||||
)?.name ?? 'Não documentado'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{location.coordinates.map((point) => (
|
||||
<p key={point.geometry_id}>
|
||||
Coordenadas documentadas (
|
||||
{location.location_type === 'site'
|
||||
? 'local do projecto'
|
||||
: 'referência territorial; não representa a implantação'}
|
||||
): {point.geometry.coordinates[1]},{' '}
|
||||
{point.geometry.coordinates[0]} · Fonte:{' '}
|
||||
{point.source_reference}
|
||||
</p>
|
||||
))}
|
||||
{!location.coordinates.length && (
|
||||
<p>Coordenadas não documentadas.</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Fonte da relação:{' '}
|
||||
{location.source_reference ?? 'Não indicada'}
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/oportunidades?geo_location_id=${location.id}`}
|
||||
>
|
||||
Pesquisar oportunidades neste território
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function StructureGeographyPanel({ geography, cluster = false, dossierId }: { geography: StructureGeography; cluster?: boolean; dossierId: string }) {
|
||||
const items = cluster ? geography.members.flatMap(member=>member.locations.map(location=>({location,title:member.title,url:`/carteira/${member.dossier_id}`}))) : geography.locations.map(location=>({location,title:location.name,url:`/carteira/${dossierId}`}));
|
||||
const points = items.flatMap(item=>item.location.location_type === 'site' ? item.location.coordinates.map(point=>({geometry:point.geometry,properties:{id:0,title:item.title,location:`${roles[item.location.role] ?? item.location.role} · ${item.location.name}`,url:item.url}})) : []).map((point,index)=>({...point,properties:{...point.properties,id:index+1}}));
|
||||
return <section className="space-y-4 rounded-xl border p-5" aria-labelledby={`documented-geography-${dossierId}`}>
|
||||
<h2 id={`documented-geography-${dossierId}`} className="text-xl font-bold">{cluster ? 'Abrangência do cluster e localizações dos membros' : 'Localização documentada do projecto'}</h2>
|
||||
<LocationList locations={geography.locations} />
|
||||
{!geography.locations.length && <p>{cluster ? 'A área própria de abrangência do cluster não está documentada em referências territoriais. As localizações dos membros abaixo não definem o seu perímetro.' : 'Sem associação territorial estruturada. Consulte a descrição de localização no dossier; os níveis desconhecidos permanecem não documentados.'}</p>}
|
||||
{cluster && <p>O mapa apresenta locais documentados dos membros. Não existe um ponto único atribuído ao cluster.</p>}
|
||||
<InteractiveInvestmentMap points={points} />
|
||||
{!points.length && <p>Sem coordenadas documentadas dos locais. Nenhum ponto foi estimado.</p>}
|
||||
{geography.members.map(member=><article key={member.id} className="space-y-3 border-t pt-4"><h3 className="font-bold"><Link className="underline" href={`/carteira/${member.dossier_id}?from=${dossierId}`}>{member.code} · {member.title}</Link></h3>
|
||||
<p>Papel: {member.role} · Relação {member.validation_status === 'validated' ? 'validada no cadastro' : 'documental de planeamento; validação pendente'} · Fonte: {member.source_reference}</p><LocationList locations={member.locations}/>{!member.locations.length && <p>Localização estruturada do membro não documentada.</p>}</article>)}
|
||||
{geography.clusters.map(item=><p key={item.id}>Cluster: <Link className="underline" href={`/carteira/${item.dossier_id}?from=${dossierId}`}>{item.title}</Link> · {item.validation_status === 'validated' ? 'validada no cadastro' : 'relação documental de planeamento; validação pendente'} · Fonte: {item.source_reference}</p>)}
|
||||
{cluster && <div><h3 className="font-bold">Elos da cadeia de valor cadastrados</h3>{geography.chains?.map(chain=><p key={chain.id}>{chain.code} · {chain.name} · {({input:'Insumos',production:'Produção',processing:'Transformação',logistics:'Logística',market:'Mercado'} as Record<string,string>)[chain.stage] ?? chain.stage}</p>)}{!geography.chains?.length && <p>Sem elos estruturados cadastrados. As actividades e lacunas descritas no dossier continuam disponíveis.</p>}</div>}
|
||||
{!!geography.chainLinks.length && <div><h3 className="font-bold">Relações entre elos da cadeia de valor</h3>{geography.chainLinks.map(link=><p key={link.id}>{link.origin} → {link.destination} · {link.link_type}</p>)}</div>}
|
||||
</section>;
|
||||
export default function StructureGeographyPanel({
|
||||
geography,
|
||||
cluster = false,
|
||||
dossierId,
|
||||
}: {
|
||||
geography: StructureGeography;
|
||||
cluster?: boolean;
|
||||
dossierId: string;
|
||||
}) {
|
||||
const items = cluster
|
||||
? geography.members.flatMap((member) =>
|
||||
member.locations.map((location) => ({
|
||||
location,
|
||||
title: member.title,
|
||||
url: `/carteira/${member.dossier_id}`,
|
||||
})),
|
||||
)
|
||||
: geography.locations.map((location) => ({
|
||||
location,
|
||||
title: location.name,
|
||||
url: `/carteira/${dossierId}`,
|
||||
}));
|
||||
const points = items
|
||||
.flatMap((item) =>
|
||||
item.location.location_type === 'site'
|
||||
? item.location.coordinates.map((point) => ({
|
||||
geometry: point.geometry,
|
||||
properties: {
|
||||
id: 0,
|
||||
title: item.title,
|
||||
location: `${roles[item.location.role] ?? item.location.role} · ${item.location.name}`,
|
||||
url: item.url,
|
||||
},
|
||||
}))
|
||||
: [],
|
||||
)
|
||||
.map((point, index) => ({
|
||||
...point,
|
||||
properties: { ...point.properties, id: index + 1 },
|
||||
}));
|
||||
return (
|
||||
<section
|
||||
className="space-y-4 rounded-xl border p-5"
|
||||
aria-labelledby={`documented-geography-${dossierId}`}
|
||||
>
|
||||
<h2
|
||||
id={`documented-geography-${dossierId}`}
|
||||
className="text-xl font-bold"
|
||||
>
|
||||
{cluster
|
||||
? 'Abrangência do cluster e localizações dos membros'
|
||||
: 'Localização documentada do projecto'}
|
||||
</h2>
|
||||
<LocationList locations={geography.locations} />
|
||||
{!geography.locations.length && (
|
||||
<p>
|
||||
{cluster
|
||||
? 'A área própria de abrangência do cluster não está documentada em referências territoriais. As localizações dos membros abaixo não definem o seu perímetro.'
|
||||
: 'Sem associação territorial estruturada. Consulte a descrição de localização no dossier; os níveis desconhecidos permanecem não documentados.'}
|
||||
</p>
|
||||
)}
|
||||
{cluster && (
|
||||
<p>
|
||||
O mapa apresenta locais documentados dos membros. Não existe
|
||||
um ponto único atribuído ao cluster.
|
||||
</p>
|
||||
)}
|
||||
<InteractiveInvestmentMap points={points} />
|
||||
{!points.length && (
|
||||
<p>
|
||||
Sem coordenadas documentadas dos locais. Nenhum ponto foi
|
||||
estimado.
|
||||
</p>
|
||||
)}
|
||||
{geography.members.map((member) => (
|
||||
<article key={member.id} className="space-y-3 border-t pt-4">
|
||||
<h3 className="font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/carteira/${member.dossier_id}?from=${dossierId}`}
|
||||
>
|
||||
{member.code} · {member.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<p>
|
||||
Papel: {member.role} · Relação{' '}
|
||||
{member.validation_status === 'validated'
|
||||
? 'validada no cadastro'
|
||||
: 'documental de planeamento; validação pendente'}{' '}
|
||||
· Fonte: {member.source_reference}
|
||||
</p>
|
||||
<LocationList locations={member.locations} />
|
||||
{!member.locations.length && (
|
||||
<p>
|
||||
Localização estruturada do membro não documentada.
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{geography.clusters.map((item) => (
|
||||
<p key={item.id}>
|
||||
Cluster:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/carteira/${item.dossier_id}?from=${dossierId}`}
|
||||
>
|
||||
{item.title}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
{item.validation_status === 'validated'
|
||||
? 'validada no cadastro'
|
||||
: 'relação documental de planeamento; validação pendente'}{' '}
|
||||
· Fonte: {item.source_reference}
|
||||
</p>
|
||||
))}
|
||||
{cluster && (
|
||||
<div>
|
||||
<h3 className="font-bold">
|
||||
Elos da cadeia de valor cadastrados
|
||||
</h3>
|
||||
{geography.chains?.map((chain) => (
|
||||
<p key={chain.id}>
|
||||
{chain.code} · {chain.name} ·{' '}
|
||||
{(
|
||||
{
|
||||
input: 'Insumos',
|
||||
production: 'Produção',
|
||||
processing: 'Transformação',
|
||||
logistics: 'Logística',
|
||||
market: 'Mercado',
|
||||
} as Record<string, string>
|
||||
)[chain.stage] ?? chain.stage}
|
||||
</p>
|
||||
))}
|
||||
{!geography.chains?.length && (
|
||||
<p>
|
||||
Sem elos estruturados cadastrados. As actividades e
|
||||
lacunas descritas no dossier continuam disponíveis.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!!geography.chainLinks.length && (
|
||||
<div>
|
||||
<h3 className="font-bold">
|
||||
Relações entre elos da cadeia de valor
|
||||
</h3>
|
||||
{geography.chainLinks.map((link) => (
|
||||
<p key={link.id}>
|
||||
{link.origin} → {link.destination} ·{' '}
|
||||
{link.link_type}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user