@@ -26,6 +26,9 @@ void createInertiaApp({
|
||||
case name === 'management-access':
|
||||
case name.startsWith('portal/'):
|
||||
case name.startsWith('investment/'):
|
||||
case name.startsWith('portfolio/'):
|
||||
case name.startsWith('land-assistance/'):
|
||||
case name.startsWith('desk/'):
|
||||
return PortalNavigation;
|
||||
case name.startsWith('auth/'):
|
||||
return [PortalNavigation, AuthLayout];
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { AppContent } from '@/components/app-content';
|
||||
import { AppShell } from '@/components/app-shell';
|
||||
import { AppSidebar } from '@/components/app-sidebar';
|
||||
import { AppSidebarHeader } from '@/components/app-sidebar-header';
|
||||
import { JourneyCompanion } from '@/components/journey-companion';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import type { AppLayoutProps } from '@/types';
|
||||
|
||||
export default function AppSidebarLayout({
|
||||
@@ -13,6 +15,8 @@ export default function AppSidebarLayout({
|
||||
<AppSidebar />
|
||||
<AppContent variant="sidebar" className="min-w-0 overflow-x-clip">
|
||||
<AppSidebarHeader breadcrumbs={breadcrumbs} />
|
||||
<PortalMenu primary />
|
||||
<JourneyCompanion />
|
||||
{children}
|
||||
</AppContent>
|
||||
</AppShell>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { useId, useState } from 'react';
|
||||
import { createContext, useContext } from 'react';
|
||||
import { PortalGroupedMenu } from '@/components/portal-grouped-menu';
|
||||
import type { ReactNode } from 'react';
|
||||
import { JourneyCompanion } from '@/components/journey-companion';
|
||||
|
||||
const MenuPlacement = createContext(false);
|
||||
|
||||
export const portalLinks = [
|
||||
['/', 'Início'],
|
||||
@@ -46,7 +50,19 @@ export default function PortalNavigation({
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { url, props } = usePage();
|
||||
const { url, props, component } = usePage();
|
||||
const portalShell =
|
||||
['welcome', 'PortalInvestidor', 'management-access'].includes(
|
||||
component,
|
||||
) ||
|
||||
[
|
||||
'portal/',
|
||||
'investment/',
|
||||
'portfolio/',
|
||||
'desk/',
|
||||
'auth/',
|
||||
'land-assistance/',
|
||||
].some((prefix) => component.startsWith(prefix));
|
||||
const path = url.split('?')[0];
|
||||
const parent = Object.keys(names)
|
||||
.filter((p) => p !== '/' && path.startsWith(`${p}/`))
|
||||
@@ -72,119 +88,55 @@ export default function PortalNavigation({
|
||||
? 'Definições da conta'
|
||||
: 'Detalhes');
|
||||
return (
|
||||
<div className="pb-8 lg:pb-24 [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24">
|
||||
<a
|
||||
href="#portal-content"
|
||||
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
|
||||
>
|
||||
Saltar para o conteúdo
|
||||
</a>
|
||||
<nav
|
||||
aria-label="Caminho de navegação"
|
||||
className="bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm"
|
||||
>
|
||||
{path === '/' ? (
|
||||
<span aria-current="page">Início</span>
|
||||
) : (
|
||||
<>
|
||||
<Link href="/" className="underline">
|
||||
Início
|
||||
</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
{parent && (
|
||||
<>
|
||||
<Link href={parent} className="underline">
|
||||
{names[parent]}
|
||||
</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
</>
|
||||
)}
|
||||
<span aria-current="page">{title}</span>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
<div id="portal-content" tabIndex={-1}>
|
||||
{children}
|
||||
<MenuPlacement.Provider value={true}>
|
||||
<div className="pb-8 lg:pb-24 [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24">
|
||||
{portalShell && <PortalMenu primary />}
|
||||
<a
|
||||
href="#portal-content"
|
||||
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
|
||||
>
|
||||
Saltar para o conteúdo
|
||||
</a>
|
||||
<nav
|
||||
aria-label="Caminho de navegação"
|
||||
className="bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm"
|
||||
>
|
||||
{path === '/' ? (
|
||||
<span aria-current="page">Início</span>
|
||||
) : (
|
||||
<>
|
||||
<Link href="/" className="underline">
|
||||
Início
|
||||
</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
{parent && (
|
||||
<>
|
||||
<Link href={parent} className="underline">
|
||||
{names[parent]}
|
||||
</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
</>
|
||||
)}
|
||||
<span aria-current="page">{title}</span>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
<div id="portal-content" tabIndex={-1}>
|
||||
{portalShell && <JourneyCompanion />}
|
||||
{children}
|
||||
</div>
|
||||
<a
|
||||
href="/apoio"
|
||||
className="mx-3 mt-4 block max-w-[calc(100%-1.5rem)] rounded-xl bg-emerald-800 px-5 py-3 text-center text-sm font-semibold text-white shadow-xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-emerald-600"
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
</a>
|
||||
</div>
|
||||
<a
|
||||
href="/apoio"
|
||||
className="mx-3 mt-4 block max-w-[calc(100%-1.5rem)] rounded-xl bg-emerald-800 px-5 py-3 text-center text-sm font-semibold text-white shadow-xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-emerald-600 lg:fixed lg:right-3 lg:bottom-3 lg:z-50 lg:mx-0 lg:mt-0 lg:max-w-[calc(100vw-1.5rem)]"
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
</a>
|
||||
</div>
|
||||
</MenuPlacement.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function PortalMenu() {
|
||||
const { existingBusinessEnabled } = usePage<{
|
||||
existingBusinessEnabled?: boolean;
|
||||
}>().props;
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const menuId = useId();
|
||||
return (
|
||||
<nav
|
||||
aria-label="Áreas do portal"
|
||||
className="border-b bg-white px-5 py-4 text-sm text-slate-800"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4 md:hidden">
|
||||
<Link href="/" className="font-bold">
|
||||
Portal do Investidor
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-lg border px-3 py-2 font-semibold focus-visible:outline-2 focus-visible:outline-emerald-700"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={menuId}
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
>
|
||||
{expanded ? 'Fechar menu' : 'Abrir menu'}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
id={menuId}
|
||||
className={`${expanded ? 'flex' : 'hidden'} mt-4 flex-wrap gap-x-5 gap-y-3 md:mt-0 md:flex`}
|
||||
>
|
||||
{portalLinks.map(([href, label]) => (
|
||||
<Link
|
||||
key={href}
|
||||
href={href}
|
||||
className="underline underline-offset-4"
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
<details className="relative">
|
||||
<summary className="cursor-pointer underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-emerald-700">
|
||||
Catálogos territoriais e económicos
|
||||
</summary>
|
||||
<ul className="mt-2 grid gap-2 rounded-lg border bg-white p-4 shadow-sm md:absolute md:z-20 md:min-w-64">
|
||||
<li><Link className="underline" href="/carteira?kind=cluster">Clusters</Link></li>
|
||||
<li><Link className="underline" href="/carteira?kind=corridor">Corredores</Link></li>
|
||||
<li><Link className="underline" href="/zonas">ZEE, ZFI e parques industriais</Link></li>
|
||||
<li><Link className="underline" href="/carteira?kind=project">Projectos âncora</Link></li>
|
||||
<li><Link className="underline" href="/oportunidades">Oportunidades publicadas</Link></li>
|
||||
<li><Link className="underline" href="/negocios">Negócios existentes e participações publicadas</Link></li>
|
||||
</ul>
|
||||
</details>
|
||||
{existingBusinessEnabled && (
|
||||
<Link href="/investidor/negocios" className="underline">
|
||||
Os meus negócios
|
||||
</Link>
|
||||
)}
|
||||
<Link href="/parcerias" className="underline">
|
||||
Bolsa de Parcerias
|
||||
</Link>
|
||||
<Link href="/simulador-fiscal" className="underline">
|
||||
Simulador Fiscal
|
||||
</Link>
|
||||
<Link href="/balcao-virtual" className="underline">
|
||||
Balcão Virtual
|
||||
</Link>
|
||||
<Link href="/investidor/manifestacoes" className="underline">
|
||||
Área do investidor
|
||||
</Link>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
export function PortalMenu({ primary = false }: { primary?: boolean }) {
|
||||
const placed = useContext(MenuPlacement);
|
||||
return placed && !primary ? null : <PortalGroupedMenu />;
|
||||
}
|
||||
|
||||
@@ -1349,9 +1349,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
|
||||
const presentationCurrency = input.presentationCurrency || input.currency;
|
||||
if (!validCurrency(presentationCurrency))
|
||||
throw new Error(
|
||||
'Seleccione uma moeda de apresentação ISO suportada.',
|
||||
);
|
||||
throw new Error('Seleccione uma moeda de apresentação ISO suportada.');
|
||||
let fxRate: bigint | null = null;
|
||||
if (presentationCurrency !== input.currency) {
|
||||
if (!input.fxRate || !input.fxDate || !input.fxSource?.trim())
|
||||
@@ -1417,7 +1415,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
product.unitVariableCost,
|
||||
`Custo variável do produto ${index + 1}`,
|
||||
);
|
||||
const productInventoryOpening = useProductInventorySchedule
|
||||
const _productInventoryOpening = useProductInventorySchedule
|
||||
? cents(
|
||||
product.productInventoryOpening ?? '',
|
||||
`Opening inventory for ${product.label}`,
|
||||
@@ -1458,7 +1456,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
),
|
||||
};
|
||||
});
|
||||
const productStockInputs = input.products.map((product, index) => {
|
||||
const productStockInputs = input.products.map((product, _index) => {
|
||||
if (!useProductInventorySchedule)
|
||||
return { opening: null, orders: null };
|
||||
const opening = cents(
|
||||
@@ -1863,7 +1861,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
const periodPayrollPayment = payrollPaymentsByPeriod[month - 1];
|
||||
const revenue = revenueByPeriod[month - 1];
|
||||
const costOfSales = costOfSalesByPeriod[month - 1];
|
||||
const opening = cash;
|
||||
const _opening = cash;
|
||||
const openingInventory = inventoryBalance;
|
||||
let inventoryShortfall: bigint | null = null;
|
||||
let closingInventory: bigint | null = null;
|
||||
@@ -3087,8 +3085,7 @@ export function exportBusinessPlanCsv(
|
||||
row.openingReceivablesBalance ?? '',
|
||||
row.openingPayablesPayments ?? '',
|
||||
row.openingPayablesBalance ?? '',
|
||||
row.otherCollections ??
|
||||
'incluídas nas cobranças manuais',
|
||||
row.otherCollections ?? 'incluídas nas cobranças manuais',
|
||||
row.profitBeforeTax ?? '',
|
||||
row.netCashFlow ?? '',
|
||||
row.closingCash ?? '',
|
||||
|
||||
@@ -12,20 +12,29 @@ export const emptyBusinessLocation = (): BusinessLocationPath => ({
|
||||
locality_id: '',
|
||||
});
|
||||
|
||||
export function decodeBusinessLocations(value?: string): BusinessLocationPath[] {
|
||||
export function decodeBusinessLocations(
|
||||
value?: string,
|
||||
): BusinessLocationPath[] {
|
||||
if (!value) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.slice(0, 20).map((entry) => {
|
||||
const row = entry && typeof entry === 'object'
|
||||
? (entry as Record<string, unknown>)
|
||||
: {};
|
||||
const row =
|
||||
entry && typeof entry === 'object'
|
||||
? (entry as Record<string, unknown>)
|
||||
: {};
|
||||
return {
|
||||
province_id: typeof row.province_id === 'string' ? row.province_id : '',
|
||||
district_id: typeof row.district_id === 'string' ? row.district_id : '',
|
||||
admin_post_id: typeof row.admin_post_id === 'string' ? row.admin_post_id : '',
|
||||
locality_id: typeof row.locality_id === 'string' ? row.locality_id : '',
|
||||
province_id:
|
||||
typeof row.province_id === 'string' ? row.province_id : '',
|
||||
district_id:
|
||||
typeof row.district_id === 'string' ? row.district_id : '',
|
||||
admin_post_id:
|
||||
typeof row.admin_post_id === 'string'
|
||||
? row.admin_post_id
|
||||
: '',
|
||||
locality_id:
|
||||
typeof row.locality_id === 'string' ? row.locality_id : '',
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
@@ -46,7 +55,9 @@ export function updateBusinessLocation(
|
||||
if (!rows[index]) return rows;
|
||||
const next = rows.map((row) => ({ ...row }));
|
||||
next[index][key] = value;
|
||||
const children: Partial<Record<keyof BusinessLocationPath, (keyof BusinessLocationPath)[]>> = {
|
||||
const children: Partial<
|
||||
Record<keyof BusinessLocationPath, (keyof BusinessLocationPath)[]>
|
||||
> = {
|
||||
province_id: ['district_id', 'admin_post_id', 'locality_id'],
|
||||
district_id: ['admin_post_id', 'locality_id'],
|
||||
admin_post_id: ['locality_id'],
|
||||
@@ -55,18 +66,28 @@ export function updateBusinessLocation(
|
||||
return next;
|
||||
}
|
||||
|
||||
export function hasDuplicateBusinessLocationPath(rows: BusinessLocationPath[]): boolean {
|
||||
const paths = rows.map((row) => [
|
||||
row.province_id,
|
||||
row.district_id,
|
||||
row.admin_post_id,
|
||||
row.locality_id,
|
||||
].filter(Boolean));
|
||||
return paths.some((path, index) => path.length > 0 && paths.slice(index + 1).some((other) => {
|
||||
if (other.length === 0) return false;
|
||||
const common = Math.min(path.length, other.length);
|
||||
return path.slice(0, common).every((id, part) => id === other[part]);
|
||||
}));
|
||||
export function hasDuplicateBusinessLocationPath(
|
||||
rows: BusinessLocationPath[],
|
||||
): boolean {
|
||||
const paths = rows.map((row) =>
|
||||
[
|
||||
row.province_id,
|
||||
row.district_id,
|
||||
row.admin_post_id,
|
||||
row.locality_id,
|
||||
].filter(Boolean),
|
||||
);
|
||||
return paths.some(
|
||||
(path, index) =>
|
||||
path.length > 0 &&
|
||||
paths.slice(index + 1).some((other) => {
|
||||
if (other.length === 0) return false;
|
||||
const common = Math.min(path.length, other.length);
|
||||
return path
|
||||
.slice(0, common)
|
||||
.every((id, part) => id === other[part]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function locationPathFromPayload(
|
||||
|
||||
Vendored
+4
-1
@@ -1,2 +1,5 @@
|
||||
export declare function csvCell(value: unknown): string;
|
||||
export declare function csvCellWithDelimiter(value: unknown, delimiter: string): string;
|
||||
export declare function csvCellWithDelimiter(
|
||||
value: unknown,
|
||||
delimiter: string,
|
||||
): string;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
function serializeCell(value, delimiter) {
|
||||
const raw = String(value ?? '');
|
||||
const formulaLike = /^[\u0000-\u0020\uFEFF]*[=+\-@]/.test(raw);
|
||||
let prefix = 0;
|
||||
while (
|
||||
prefix < raw.length &&
|
||||
(raw.charCodeAt(prefix) <= 32 || raw.charCodeAt(prefix) === 0xfeff)
|
||||
)
|
||||
prefix++;
|
||||
const formulaLike = /^[=+\-@]/.test(raw.slice(prefix));
|
||||
const numeric = /^-?\d+(?:\.\d+)?$/.test(raw);
|
||||
const text = formulaLike && !numeric ? `'${raw}` : raw;
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Display only scalar values; an object is not a verified textual value. */
|
||||
export function displayValue(value: unknown, fallback = ''): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' && Number.isFinite(value))
|
||||
return String(value);
|
||||
if (typeof value === 'boolean') return String(value);
|
||||
return fallback;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
/** Estados de preparação usados pelo cadastro de oportunidades (níveis 1–6). */
|
||||
export const MATURITY_LEVELS = [
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
'Ideia identificada',
|
||||
'Pré-estudo disponível',
|
||||
'Estudo de viabilidade em curso',
|
||||
'Projecto estruturado',
|
||||
'Pronto para investimento',
|
||||
'Em negociação ou implementação',
|
||||
] as const;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,53 +9,182 @@ export type RoadmapPhase = {
|
||||
|
||||
export const roadmapPhases: RoadmapPhase[] = [
|
||||
{
|
||||
id: 'concepcao', title: 'Concepção',
|
||||
summary: 'Transformar a ideia numa proposta de valor e identificar o enquadramento da actividade.',
|
||||
id: 'concepcao',
|
||||
title: 'Concepção',
|
||||
summary:
|
||||
'Transformar a ideia numa proposta de valor e identificar o enquadramento da actividade.',
|
||||
steps: [
|
||||
{ title: 'Definir a ideia e a oportunidade', description: 'Identificar o problema, a necessidade do mercado e o objectivo do investimento.', result: 'Conceito definido.' },
|
||||
{ title: 'Estruturar a proposta de valor', description: 'Especificar produto ou serviço, público-alvo, benefícios e diferenciais.', result: 'Proposta de valor definida.' },
|
||||
{
|
||||
title: 'Definir a ideia e a oportunidade',
|
||||
description:
|
||||
'Identificar o problema, a necessidade do mercado e o objectivo do investimento.',
|
||||
result: 'Conceito definido.',
|
||||
},
|
||||
{
|
||||
title: 'Estruturar a proposta de valor',
|
||||
description:
|
||||
'Especificar produto ou serviço, público-alvo, benefícios e diferenciais.',
|
||||
result: 'Proposta de valor definida.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Desenvolver a ideia no dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Explorar sectores económicos', href: '/sectores' },
|
||||
{ label: 'Encontrar oportunidades', href: '/oportunidades' },
|
||||
],
|
||||
links: [{ label: 'Desenvolver a ideia no dossier', href: '/simulador-fiscal' }, { label: 'Explorar sectores económicos', href: '/sectores' }, { label: 'Encontrar oportunidades', href: '/oportunidades' }],
|
||||
},
|
||||
{
|
||||
id: 'analise', title: 'Análise',
|
||||
summary: 'Estudar mercado, requisitos, localização e viabilidade com pressupostos explícitos.',
|
||||
id: 'analise',
|
||||
title: 'Análise',
|
||||
summary:
|
||||
'Estudar mercado, requisitos, localização e viabilidade com pressupostos explícitos.',
|
||||
steps: [
|
||||
{ title: 'Mapear os requisitos', description: 'Identificar exigências legais, fiscais, técnicas, ambientais, de segurança, infra-estrutura e operação aplicáveis ao projecto.', result: 'Matriz de requisitos a confirmar.' },
|
||||
{ title: 'Realizar o estudo de mercado', description: 'Analisar procura, clientes, concorrência, preços, canais e tendências; registar fontes e datas.', result: 'Estudo de mercado.' },
|
||||
{ title: 'Seleccionar a localização', description: 'Comparar custos, clientes, logística, água, energia, mão de obra, incentivos potenciais e riscos nas alternativas de localização.', result: 'Matriz multicritério de localização.' },
|
||||
{ title: 'Avaliar a viabilidade', description: 'Testar viabilidade comercial, técnica, financeira, ambiental e social. Rever proposta, mercado, localização ou modelo quando necessário.', result: 'Estudo de viabilidade e cenários.' },
|
||||
{
|
||||
title: 'Mapear os requisitos',
|
||||
description:
|
||||
'Identificar exigências legais, fiscais, técnicas, ambientais, de segurança, infra-estrutura e operação aplicáveis ao projecto.',
|
||||
result: 'Matriz de requisitos a confirmar.',
|
||||
},
|
||||
{
|
||||
title: 'Realizar o estudo de mercado',
|
||||
description:
|
||||
'Analisar procura, clientes, concorrência, preços, canais e tendências; registar fontes e datas.',
|
||||
result: 'Estudo de mercado.',
|
||||
},
|
||||
{
|
||||
title: 'Seleccionar a localização',
|
||||
description:
|
||||
'Comparar custos, clientes, logística, água, energia, mão de obra, incentivos potenciais e riscos nas alternativas de localização.',
|
||||
result: 'Matriz multicritério de localização.',
|
||||
},
|
||||
{
|
||||
title: 'Avaliar a viabilidade',
|
||||
description:
|
||||
'Testar viabilidade comercial, técnica, financeira, ambiental e social. Rever proposta, mercado, localização ou modelo quando necessário.',
|
||||
result: 'Estudo de viabilidade e cenários.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{ label: 'Explorar locais de investimento', href: '/zonas' },
|
||||
{
|
||||
label: 'Consultar clusters e cadeias de valor',
|
||||
href: '/clusters',
|
||||
},
|
||||
{
|
||||
label: 'Comparar finanças e efeito fiscal',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Consultar terra e DUAT', href: '/terra-duat' },
|
||||
{ label: 'Consultar fontes legais', href: '/legislacao' },
|
||||
],
|
||||
links: [{ label: 'Explorar locais de investimento', href: '/zonas' }, { label: 'Consultar clusters e cadeias de valor', href: '/clusters' }, { label: 'Comparar finanças e efeito fiscal', href: '/simulador-fiscal' }, { label: 'Consultar terra e DUAT', href: '/terra-duat' }, { label: 'Consultar fontes legais', href: '/legislacao' }],
|
||||
},
|
||||
{
|
||||
id: 'planeamento', title: 'Planeamento e Formalização',
|
||||
summary: 'Consolidar o plano, mobilizar recursos e preparar registos, licenças e autorizações aplicáveis.',
|
||||
id: 'planeamento',
|
||||
title: 'Planeamento e Formalização',
|
||||
summary:
|
||||
'Consolidar o plano, mobilizar recursos e preparar registos, licenças e autorizações aplicáveis.',
|
||||
steps: [
|
||||
{ title: 'Elaborar o modelo e o plano de negócios', description: 'Consolidar estratégia, operação, marketing, projecções financeiras, metas e indicadores.', result: 'Plano de negócios para decisão do promotor.' },
|
||||
{ title: 'Mobilizar recursos', description: 'Definir financiamento, recursos materiais, tecnológicos e humanos; identificar lacunas e alternativas.', result: 'Recursos e financiamento planeados ou assegurados, conforme evidência.' },
|
||||
{ title: 'Constituir e registar a empresa', description: 'Preparar forma jurídica, registo, NUIT e obrigações laborais e fiscais conforme a actividade e a fase de execução.', result: 'Formalização e pendências documentadas.' },
|
||||
{ title: 'Obter licenças, autorizações e incentivos', description: 'Confirmar licenciamento económico, sectorial, ambiental e uso do espaço; verificar condições dos benefícios pretendidos.', result: 'Licenças e autorizações aplicáveis identificadas e acompanhadas.' },
|
||||
{
|
||||
title: 'Elaborar o modelo e o plano de negócios',
|
||||
description:
|
||||
'Consolidar estratégia, operação, marketing, projecções financeiras, metas e indicadores.',
|
||||
result: 'Plano de negócios para decisão do promotor.',
|
||||
},
|
||||
{
|
||||
title: 'Mobilizar recursos',
|
||||
description:
|
||||
'Definir financiamento, recursos materiais, tecnológicos e humanos; identificar lacunas e alternativas.',
|
||||
result: 'Recursos e financiamento planeados ou assegurados, conforme evidência.',
|
||||
},
|
||||
{
|
||||
title: 'Constituir e registar a empresa',
|
||||
description:
|
||||
'Preparar forma jurídica, registo, NUIT e obrigações laborais e fiscais conforme a actividade e a fase de execução.',
|
||||
result: 'Formalização e pendências documentadas.',
|
||||
},
|
||||
{
|
||||
title: 'Obter licenças, autorizações e incentivos',
|
||||
description:
|
||||
'Confirmar licenciamento económico, sectorial, ambiental e uso do espaço; verificar condições dos benefícios pretendidos.',
|
||||
result: 'Licenças e autorizações aplicáveis identificadas e acompanhadas.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Continuar o plano financeiro e dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Explorar parcerias', href: '/parcerias' },
|
||||
{
|
||||
label: 'Consultar documentos e formulários',
|
||||
href: '/documentos',
|
||||
},
|
||||
{ label: 'Pedir apoio ao investimento', href: '/apoio' },
|
||||
],
|
||||
links: [{ label: 'Continuar o plano financeiro e dossier', href: '/simulador-fiscal' }, { label: 'Explorar parcerias', href: '/parcerias' }, { label: 'Consultar documentos e formulários', href: '/documentos' }, { label: 'Pedir apoio ao investimento', href: '/apoio' }],
|
||||
},
|
||||
{
|
||||
id: 'preparacao', title: 'Preparação e Teste',
|
||||
summary: 'Preparar equipa, instalações e processos; testar em escala controlada e corrigir resultados.',
|
||||
id: 'preparacao',
|
||||
title: 'Preparação e Teste',
|
||||
summary:
|
||||
'Preparar equipa, instalações e processos; testar em escala controlada e corrigir resultados.',
|
||||
steps: [
|
||||
{ title: 'Preparar a operação', description: 'Contratar e formar a equipa, seleccionar fornecedores, instalar equipamentos e sistemas e estabelecer procedimentos e controlos.', result: 'Plano de prontidão operacional.' },
|
||||
{ title: 'Executar o piloto', description: 'Testar produto ou serviço, processos, capacidade, custos e experiência do cliente. Corrigir oferta, equipa, processos e custos e repetir o teste quando necessário.', result: 'Piloto e evidências de aceitação.' },
|
||||
{
|
||||
title: 'Preparar a operação',
|
||||
description:
|
||||
'Contratar e formar a equipa, seleccionar fornecedores, instalar equipamentos e sistemas e estabelecer procedimentos e controlos.',
|
||||
result: 'Plano de prontidão operacional.',
|
||||
},
|
||||
{
|
||||
title: 'Executar o piloto',
|
||||
description:
|
||||
'Testar produto ou serviço, processos, capacidade, custos e experiência do cliente. Corrigir oferta, equipa, processos e custos e repetir o teste quando necessário.',
|
||||
result: 'Piloto e evidências de aceitação.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Registar equipa, riscos e marcos no dossier',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{ label: 'Encontrar parceiros e negócios', href: '/negocios' },
|
||||
{ label: 'Consultar requisitos documentais', href: '/documentos' },
|
||||
{ label: 'Pedir apoio à preparação', href: '/apoio' },
|
||||
],
|
||||
links: [{ label: 'Registar equipa, riscos e marcos no dossier', href: '/simulador-fiscal' }, { label: 'Encontrar parceiros e negócios', href: '/negocios' }, { label: 'Consultar requisitos documentais', href: '/documentos' }, { label: 'Pedir apoio à preparação', href: '/apoio' }],
|
||||
},
|
||||
{
|
||||
id: 'execucao', title: 'Execução e Controlo',
|
||||
summary: 'Lançar a actividade, acompanhar indicadores e manter um plano de melhoria e conformidade.',
|
||||
id: 'execucao',
|
||||
title: 'Execução e Controlo',
|
||||
summary:
|
||||
'Lançar a actividade, acompanhar indicadores e manter um plano de melhoria e conformidade.',
|
||||
steps: [
|
||||
{ title: 'Lançar a operação', description: 'Iniciar a actividade, activar canais comerciais, acompanhar clientes e estabilizar a produção ou prestação do serviço.', result: 'Operação iniciada e acompanhada.' },
|
||||
{ title: 'Monitorizar e melhorar', description: 'Acompanhar indicadores financeiros, operacionais, comerciais, sociais e ambientais; controlar riscos, validades e acções correctivas.', result: 'Desempenho e continuidade acompanhados.' },
|
||||
{
|
||||
title: 'Lançar a operação',
|
||||
description:
|
||||
'Iniciar a actividade, activar canais comerciais, acompanhar clientes e estabilizar a produção ou prestação do serviço.',
|
||||
result: 'Operação iniciada e acompanhada.',
|
||||
},
|
||||
{
|
||||
title: 'Monitorizar e melhorar',
|
||||
description:
|
||||
'Acompanhar indicadores financeiros, operacionais, comerciais, sociais e ambientais; controlar riscos, validades e acções correctivas.',
|
||||
result: 'Desempenho e continuidade acompanhados.',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
{
|
||||
label: 'Rever cenários e plano financeiro',
|
||||
href: '/simulador-fiscal',
|
||||
},
|
||||
{
|
||||
label: 'Consultar o espaço privado do investidor',
|
||||
href: '/investidor',
|
||||
},
|
||||
{ label: 'Consultar legislação e documentos', href: '/legislacao' },
|
||||
{ label: 'Solicitar apoio', href: '/apoio' },
|
||||
],
|
||||
links: [{ label: 'Rever cenários e plano financeiro', href: '/simulador-fiscal' }, { label: 'Consultar o espaço privado do investidor', href: '/investidor' }, { label: 'Consultar legislação e documentos', href: '/legislacao' }, { label: 'Solicitar apoio', href: '/apoio' }],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -67,7 +196,14 @@ export const investmentLocations: RoadmapLink[] = [
|
||||
{ label: 'Outras localizações e dossiers territoriais', href: '/carteira' },
|
||||
];
|
||||
|
||||
export const correctiveStates = ['Por iniciar', 'Em execução', 'Bloqueada', 'Pendente de evidência', 'Em validação', 'Encerrada'];
|
||||
export const correctiveStates = [
|
||||
'Por iniciar',
|
||||
'Em execução',
|
||||
'Bloqueada',
|
||||
'Pendente de evidência',
|
||||
'Em validação',
|
||||
'Encerrada',
|
||||
];
|
||||
|
||||
/** Bookmarks select a phase without imposing completion or approval requirements. */
|
||||
export function roadmapPhaseIndex(hash: string): number {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
restoreBusinessPlanSnapshot,
|
||||
compareBusinessScenarios,
|
||||
} from './business-financial-plan.ts';
|
||||
import { buildProjectDossierRows } from './project-dossier.ts';
|
||||
import { restoreFinancialToolsSnapshot } from './financial-calculators.ts';
|
||||
|
||||
/** Reuses the dossier's existing report for loan, budget, funding and break-even. */
|
||||
export function guidanceFinancialTools(draft: Record<string, unknown> | null) {
|
||||
const snapshot =
|
||||
typeof draft?.financial_tools_snapshot === 'string'
|
||||
? draft.financial_tools_snapshot
|
||||
: '';
|
||||
const assumptions = restoreFinancialToolsSnapshot(snapshot);
|
||||
if (!assumptions) return null;
|
||||
const input = {
|
||||
financial_tools_snapshot: snapshot,
|
||||
currency: typeof draft?.currency === 'string' ? draft.currency : '',
|
||||
};
|
||||
return {
|
||||
calculator: 'financial-calculators/project-dossier',
|
||||
snapshotVersion: 1,
|
||||
assumptions,
|
||||
rows: buildProjectDossierRows(input).filter(
|
||||
(row) => row[0] === 'Plano financeiro',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** The assistant only presents outputs of the existing calculator. */
|
||||
export function guidanceFinance(draft: Record<string, unknown> | null) {
|
||||
const snapshot =
|
||||
typeof draft?.business_plan_snapshot === 'string'
|
||||
? draft.business_plan_snapshot
|
||||
: '';
|
||||
const plan = restoreBusinessPlanSnapshot(snapshot);
|
||||
if (!plan)
|
||||
return {
|
||||
status: 'indeterminate' as const,
|
||||
reason: 'Sem snapshot financeiro compatível.',
|
||||
result: null,
|
||||
scenarios: null,
|
||||
};
|
||||
try {
|
||||
const result = forecastBusinessPlan(plan);
|
||||
let scenarios: ReturnType<typeof compareBusinessScenarios> | null =
|
||||
null;
|
||||
try {
|
||||
scenarios = compareBusinessScenarios(plan);
|
||||
} catch {
|
||||
/* Missing scenario inputs remain indeterminate. */
|
||||
}
|
||||
return {
|
||||
status: 'calculated' as const,
|
||||
reason: 'Estimativa determinística; pressupostos declarados, sem validação de procura ou financiamento.',
|
||||
result,
|
||||
scenarios,
|
||||
snapshotVersion: (JSON.parse(snapshot) as { version: number })
|
||||
.version,
|
||||
assumptions: plan,
|
||||
calculator: 'business-financial-plan',
|
||||
tax: 'indeterminate' as const,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
status: 'indeterminate' as const,
|
||||
reason:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Pressupostos incompatíveis.',
|
||||
result: null,
|
||||
scenarios: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -93,24 +93,27 @@ export class PortalApiError extends Error {
|
||||
constructor(status: number, errors: Record<string, string[]> = {}) {
|
||||
super(
|
||||
status === 429
|
||||
? "Foram enviados demasiados pedidos. Aguarde um minuto e tente novamente."
|
||||
? 'Foram enviados demasiados pedidos. Aguarde um minuto e tente novamente.'
|
||||
: status === 404
|
||||
? "O registo solicitado já não está disponível."
|
||||
? 'O registo solicitado já não está disponível.'
|
||||
: status === 422
|
||||
? "Verifique os campos assinalados."
|
||||
: "Não foi possível comunicar com o portal. Tente novamente.",
|
||||
? 'Verifique os campos assinalados.'
|
||||
: 'Não foi possível comunicar com o portal. Tente novamente.',
|
||||
);
|
||||
this.status = status;
|
||||
this.errors = errors;
|
||||
}
|
||||
}
|
||||
|
||||
export async function portalRequest<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
export async function portalRequest<T>(
|
||||
url: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const headers = new Headers(options.headers);
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set('Accept', 'application/json');
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
credentials: "same-origin",
|
||||
credentials: 'same-origin',
|
||||
headers,
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
@@ -128,7 +131,7 @@ export function toOpportunity(record: OpportunityRecord): Opportunity {
|
||||
slug: record.slug,
|
||||
reference: record.reference,
|
||||
title: record.title,
|
||||
sectorName: record.sector?.name ?? "Sector não indicado",
|
||||
sectorName: record.sector?.name ?? 'Sector não indicado',
|
||||
province: record.province,
|
||||
maturity: record.maturity_label,
|
||||
amount: record.estimated_investment_amount,
|
||||
@@ -142,13 +145,13 @@ export function toOpportunity(record: OpportunityRecord): Opportunity {
|
||||
}
|
||||
|
||||
export function toFeaturedOpportunity(
|
||||
record: HomeResponse["data"]["featuredOpportunities"][number],
|
||||
record: HomeResponse['data']['featuredOpportunities'][number],
|
||||
): Opportunity {
|
||||
return {
|
||||
slug: record.url.split("/").filter(Boolean).at(-1) ?? "",
|
||||
slug: record.url.split('/').filter(Boolean).at(-1) ?? '',
|
||||
reference: record.reference,
|
||||
title: record.title,
|
||||
sectorName: record.sector ?? "Sector não indicado",
|
||||
sectorName: record.sector ?? 'Sector não indicado',
|
||||
province: record.province,
|
||||
maturity: record.maturity,
|
||||
amount: record.estimatedInvestment.amount,
|
||||
@@ -162,14 +165,14 @@ export function toFeaturedOpportunity(
|
||||
}
|
||||
|
||||
export function searchUrl(filters: Filters, page: number): string {
|
||||
const params = new URLSearchParams({ page: String(page), per_page: "12" });
|
||||
if (filters.query.trim()) params.set("q", filters.query.trim());
|
||||
if (filters.sector) params.set("sector", filters.sector);
|
||||
if (filters.province) params.set("province", filters.province);
|
||||
if (filters.maturity) params.set("maturity_level", filters.maturity);
|
||||
if (filters.minAmount) params.set("min_amount", filters.minAmount);
|
||||
if (filters.maxAmount) params.set("max_amount", filters.maxAmount);
|
||||
if (filters.currency) params.set("currency", filters.currency);
|
||||
const params = new URLSearchParams({ page: String(page), per_page: '12' });
|
||||
if (filters.query.trim()) params.set('q', filters.query.trim());
|
||||
if (filters.sector) params.set('sector', filters.sector);
|
||||
if (filters.province) params.set('province', filters.province);
|
||||
if (filters.maturity) params.set('maturity_level', filters.maturity);
|
||||
if (filters.minAmount) params.set('min_amount', filters.minAmount);
|
||||
if (filters.maxAmount) params.set('max_amount', filters.maxAmount);
|
||||
if (filters.currency) params.set('currency', filters.currency);
|
||||
return `/api/v1/opportunities/search?${params.toString()}`;
|
||||
}
|
||||
|
||||
@@ -183,27 +186,29 @@ export function newSubmissionKey(): string {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
const hex = Array.from(bytes, (byte) =>
|
||||
byte.toString(16).padStart(2, '0'),
|
||||
).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
export function fieldErrors(error: PortalApiError): FormErrors {
|
||||
const result: FormErrors = {};
|
||||
const fields: (keyof InterestFormData)[] = [
|
||||
"name",
|
||||
"email",
|
||||
"phone",
|
||||
"investorType",
|
||||
"country",
|
||||
"sectorInterest",
|
||||
"opportunityReference",
|
||||
"investmentRange",
|
||||
"message",
|
||||
"privacyConsent",
|
||||
'name',
|
||||
'email',
|
||||
'phone',
|
||||
'investorType',
|
||||
'country',
|
||||
'sectorInterest',
|
||||
'opportunityReference',
|
||||
'investmentRange',
|
||||
'message',
|
||||
'privacyConsent',
|
||||
];
|
||||
for (const field of fields) {
|
||||
const messages = error.errors[field === "name" ? "fullName" : field];
|
||||
if (Array.isArray(messages) && typeof messages[0] === "string") {
|
||||
const messages = error.errors[field === 'name' ? 'fullName' : field];
|
||||
if (Array.isArray(messages) && typeof messages[0] === 'string') {
|
||||
result[field] = messages[0];
|
||||
}
|
||||
}
|
||||
@@ -211,11 +216,12 @@ export function fieldErrors(error: PortalApiError): FormErrors {
|
||||
}
|
||||
|
||||
export function money(amount: string | null, currency: string): string {
|
||||
if (amount === null || !/^-?\d+(\.\d+)?$/.test(amount)) return "Por indicar";
|
||||
if (amount === null || !/^-?\d+(\.\d+)?$/.test(amount))
|
||||
return 'Por indicar';
|
||||
try {
|
||||
// Intl accepts decimal strings without converting them to a lossy Number.
|
||||
const formatter = new Intl.NumberFormat("pt-MZ", {
|
||||
style: "currency",
|
||||
const formatter = new Intl.NumberFormat('pt-MZ', {
|
||||
style: 'currency',
|
||||
currency,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
export type PortalNavItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
href?: string;
|
||||
children?: PortalNavItem[];
|
||||
};
|
||||
export type PortalNavAccess = {
|
||||
authenticated: boolean;
|
||||
manager: boolean;
|
||||
businesses?: boolean;
|
||||
education?: boolean;
|
||||
ai?: boolean;
|
||||
};
|
||||
const link = (id: string, label: string, href: string): PortalNavItem => ({
|
||||
id,
|
||||
label,
|
||||
href,
|
||||
});
|
||||
|
||||
/** One route catalogue for the public shell and authenticated pages. */
|
||||
export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
const groups: PortalNavItem[] = [
|
||||
{
|
||||
id: 'explore',
|
||||
label: 'Explorar investimentos',
|
||||
children: [
|
||||
link('opportunities', 'Oportunidades', '/oportunidades'),
|
||||
link('sectors', 'Sectores', '/sectores'),
|
||||
{
|
||||
id: 'structures',
|
||||
label: 'Carteira e estruturas',
|
||||
children: [
|
||||
link(
|
||||
'portfolio',
|
||||
'Carteira de investimento',
|
||||
'/carteira',
|
||||
),
|
||||
link(
|
||||
'projects',
|
||||
'Projectos âncora',
|
||||
'/carteira?kind=project',
|
||||
),
|
||||
link('clusters', 'Clusters', '/carteira?kind=cluster'),
|
||||
link(
|
||||
'corridors',
|
||||
'Corredores',
|
||||
'/carteira?kind=corridor',
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'zones',
|
||||
label: 'Zonas e parques',
|
||||
children: [
|
||||
link('all-zones', 'Todas as zonas', '/zonas'),
|
||||
link('zee', 'ZEE', '/zonas?category=zee'),
|
||||
link('zfi', 'ZFI', '/zonas?category=zfi'),
|
||||
link(
|
||||
'parks',
|
||||
'Parques industriais',
|
||||
'/zonas?physical_category=industrial_park',
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'prepare',
|
||||
label: 'Preparar o projecto',
|
||||
children: [
|
||||
link('roadmap', 'Como investir', '/como-investir'),
|
||||
link('dossier', 'Preparar dossier', '/simulador-fiscal'),
|
||||
link('simulator', 'Simulador', '/simulador-fiscal'),
|
||||
link('land', 'Terra e DUAT', '/terra-duat'),
|
||||
...(access.education
|
||||
? [
|
||||
link(
|
||||
'education',
|
||||
'Educação e competências',
|
||||
'/educacao',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'support',
|
||||
label: 'Serviços e apoio',
|
||||
children: [
|
||||
link('desk', 'Balcão Virtual', '/balcao-virtual'),
|
||||
link('help', 'Apoio ao investidor', '/apoio'),
|
||||
link('documents', 'Documentos e formulários', '/documentos'),
|
||||
link('law', 'Legislação', '/legislacao'),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'partnerships',
|
||||
label: 'Parcerias',
|
||||
children: [
|
||||
link('exchange', 'Bolsa de Parcerias', '/parcerias'),
|
||||
link('businesses', 'Negócios e participações', '/negocios'),
|
||||
...(access.authenticated
|
||||
? [
|
||||
link(
|
||||
'my-partnerships',
|
||||
'As minhas parcerias',
|
||||
'/parcerias/painel',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...(access.authenticated && access.businesses
|
||||
? [
|
||||
link(
|
||||
'my-businesses',
|
||||
'Os meus negócios',
|
||||
'/investidor/negocios',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'account',
|
||||
label: 'A minha área',
|
||||
children: access.authenticated
|
||||
? [
|
||||
link('dashboard', 'Painel', '/investidor'),
|
||||
link(
|
||||
'profile',
|
||||
'Perfil e empresas',
|
||||
'/investidor/profile',
|
||||
),
|
||||
link('dossiers', 'Dossiers e percursos', '/investidor'),
|
||||
link(
|
||||
'requests',
|
||||
'Pedidos e tarefas de acompanhamento',
|
||||
'/balcao-virtual',
|
||||
),
|
||||
link(
|
||||
'interests',
|
||||
'Manifestações e favoritos',
|
||||
'/investidor/manifestacoes',
|
||||
),
|
||||
link(
|
||||
'notifications',
|
||||
'Notificações',
|
||||
'/investidor/notifications',
|
||||
),
|
||||
]
|
||||
: [
|
||||
link('login', 'Entrar', '/login'),
|
||||
link('register', 'Criar conta', '/register'),
|
||||
],
|
||||
},
|
||||
];
|
||||
if (access.manager)
|
||||
groups.push({
|
||||
id: 'management',
|
||||
label: 'Gestão',
|
||||
children: [
|
||||
link(
|
||||
'manage-interests',
|
||||
'Pedidos de interesse',
|
||||
'/management/interests',
|
||||
),
|
||||
link('crm', 'CRM interno', '/management/crm/leads'),
|
||||
{
|
||||
id: 'manage-catalogue',
|
||||
label: 'Catálogo de investimento',
|
||||
children: [
|
||||
link(
|
||||
'manage-sectors',
|
||||
'Sectores',
|
||||
'/management/sectors',
|
||||
),
|
||||
link(
|
||||
'manage-opportunities',
|
||||
'Oportunidades',
|
||||
'/management/opportunities',
|
||||
),
|
||||
link(
|
||||
'manage-projects',
|
||||
'Projectos',
|
||||
'/management/projects',
|
||||
),
|
||||
link(
|
||||
'manage-clusters',
|
||||
'Clusters',
|
||||
'/management/clusters',
|
||||
),
|
||||
],
|
||||
},
|
||||
link(
|
||||
'manage-portfolio',
|
||||
'Carteira e estruturas',
|
||||
'/management/portfolio',
|
||||
),
|
||||
link(
|
||||
'manage-documents',
|
||||
'Acervo documental',
|
||||
'/management/portal-services',
|
||||
),
|
||||
link(
|
||||
'manage-zones',
|
||||
'Zonas e parques',
|
||||
'/management/investment/zones',
|
||||
),
|
||||
link(
|
||||
'manage-territory',
|
||||
'Associações territoriais',
|
||||
'/management/territory-associations',
|
||||
),
|
||||
link(
|
||||
'manage-references',
|
||||
'Referências e formulários',
|
||||
'/management/investment/references',
|
||||
),
|
||||
link(
|
||||
'desk-installation',
|
||||
'Estado do Balcão e orientação',
|
||||
'/management/balcao-install',
|
||||
),
|
||||
link(
|
||||
'exchange-installation',
|
||||
'Estado da Bolsa de Parcerias',
|
||||
'/management/partnerships-install',
|
||||
),
|
||||
...(access.ai
|
||||
? [
|
||||
link(
|
||||
'manage-ai',
|
||||
'Assistência interna',
|
||||
'/management/ai',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...(access.education
|
||||
? [
|
||||
link(
|
||||
'manage-education',
|
||||
'Educação e competências',
|
||||
'/management/education',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function currentNavigationGroup(
|
||||
groups: PortalNavItem[],
|
||||
url: string,
|
||||
): string | null {
|
||||
const current = new URL(url, 'https://portal.invalid');
|
||||
let match: { group: string; score: number } | null = null;
|
||||
const visit = (items: PortalNavItem[], group: string) =>
|
||||
items.forEach((item) => {
|
||||
if (item.children) visit(item.children, group);
|
||||
if (!item.href) return;
|
||||
const target = new URL(item.href, current.origin);
|
||||
if (
|
||||
current.pathname !== target.pathname &&
|
||||
!current.pathname.startsWith(target.pathname + '/')
|
||||
)
|
||||
return;
|
||||
for (const [key, value] of target.searchParams)
|
||||
if (current.searchParams.get(key) !== value) return;
|
||||
const score =
|
||||
target.pathname.length + target.searchParams.size * 100;
|
||||
if (!match || score > match.score) match = { group, score };
|
||||
});
|
||||
for (const group of groups) visit(group.children ?? [], group.id);
|
||||
return (match as { group: string; score: number } | null)?.group ?? null;
|
||||
}
|
||||
|
||||
/** Select one destination, preferring a matching catalogue filter. */
|
||||
export function currentNavigationItem(
|
||||
groups: PortalNavItem[],
|
||||
url: string,
|
||||
): string | null {
|
||||
const current = new URL(url, 'https://portal.invalid');
|
||||
const best = { id: null as string | null, score: -1 };
|
||||
const visit = (items: PortalNavItem[]) => {
|
||||
for (const item of items) {
|
||||
if (item.children) visit(item.children);
|
||||
if (!item.href) continue;
|
||||
const target = new URL(item.href, current.origin);
|
||||
if (current.pathname !== target.pathname) continue;
|
||||
if (
|
||||
[...target.searchParams].some(
|
||||
([key, value]) => current.searchParams.get(key) !== value,
|
||||
)
|
||||
)
|
||||
continue;
|
||||
const score = target.searchParams.size;
|
||||
if (score > best.score) {
|
||||
best.id = item.id;
|
||||
best.score = score;
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const group of groups) visit(group.children ?? []);
|
||||
return best.id;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { csvCellWithDelimiter } from './csv.js';
|
||||
import {
|
||||
calculateFinancialTools,
|
||||
@@ -7,7 +8,10 @@ import {
|
||||
forecastBusinessPlan,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from './business-financial-plan.ts';
|
||||
import { getProjectReadiness, readPlannedRiskResponses } from './project-readiness.ts';
|
||||
import {
|
||||
getProjectReadiness,
|
||||
readPlannedRiskResponses,
|
||||
} from './project-readiness.ts';
|
||||
|
||||
export type TeamNeed = {
|
||||
competency: string;
|
||||
@@ -30,60 +34,259 @@ export function readRows<T>(value: string, allowed: readonly string[]): T[] {
|
||||
const parsed: unknown = JSON.parse(value || '[]');
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((row): row is T =>
|
||||
Boolean(row && typeof row === 'object' && !Array.isArray(row) &&
|
||||
allowed.every((key) => typeof (row as Record<string, unknown>)[key] === 'string')),
|
||||
Boolean(
|
||||
row &&
|
||||
typeof row === 'object' &&
|
||||
!Array.isArray(row) &&
|
||||
allowed.every(
|
||||
(key) =>
|
||||
typeof (row as Record<string, unknown>)[key] ===
|
||||
'string',
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export type ProjectDossierRow = [section: string, field: string, value: string, origin: string];
|
||||
export type ProjectDossierRow = [
|
||||
section: string,
|
||||
field: string,
|
||||
value: string,
|
||||
origin: string,
|
||||
];
|
||||
|
||||
export function buildProjectDossierRows(draft: Record<string, string | string[]>): ProjectDossierRow[] {
|
||||
export function buildProjectDossierRows(
|
||||
draft: Record<string, string | string[]>,
|
||||
): ProjectDossierRow[] {
|
||||
const rows: ProjectDossierRow[] = [
|
||||
['Secção', 'Campo', 'Valor', 'Origem / estado'],
|
||||
['Projecto', 'Título', String(draft.project_title ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Versão do questionário', String(draft.project_questionnaire_version ?? 'legacy-unversioned'), 'Metadado do questionário; não altera resultados guardados'],
|
||||
['Projecto', 'Resumo', String(draft.project_summary ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Problema', String(draft.project_problem ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Clientes/beneficiários', String(draft.target_customers ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Proposta de valor', String(draft.value_proposition ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Tipo de projecto', String(draft.project_type_label ?? draft.project_type ?? ''), 'Declarado/seleccionado pelo utilizador'],
|
||||
['Projecto', 'Sector', String(draft.sector_id_label ?? draft.sector_id ?? ''), 'Selecção declarada pelo utilizador'],
|
||||
['Projecto', 'Actividade económica', String(draft.activity_id_label ?? draft.activity_id ?? ''), 'Selecção declarada pelo utilizador'],
|
||||
['Projecto', 'Produtos e serviços', String(draft.products_services ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Fase de maturidade', String(draft.maturity_stage_label ?? draft.maturity_stage ?? ''), 'Declarada pelo utilizador'],
|
||||
['Projecto', 'Data prevista de início', String(draft.expected_start_date ?? ''), 'Declarada pelo utilizador; data não verificada'],
|
||||
['Projecto', 'Duração prevista', draft.project_duration_years ? `${draft.project_duration_years} anos` : '', 'Declarada pelo utilizador'],
|
||||
['Mercado', 'Hipótese', String(draft.market_assumption ?? ''), 'Informação declarada, não verificada'],
|
||||
['Mercado', 'Fonte e data', String(draft.market_source ?? ''), 'Opcional; não verificada'],
|
||||
['Mercado', 'Concorrência e alternativas', String(draft.competitor_assumption ?? ''), 'Hipótese declarada; não verificada'],
|
||||
['Mercado', 'Canal de venda', String(draft.sales_channel_assumption ?? ''), 'Planeamento declarado; não confirmado'],
|
||||
['Mercado', 'Acções de divulgação', String(draft.marketing_approach ?? ''), 'Planeamento declarado; não confirmado'],
|
||||
['Localização', 'Província', String(draft.province_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Distrito', String(draft.district_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Posto administrativo', String(draft.admin_post_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Localidade', String(draft.locality_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Critérios e pontos a confirmar', String(draft.location_rationale ?? ''), 'Declaração do utilizador; não confirma disponibilidade'],
|
||||
['Plano financeiro', 'Estado do plano detalhado', draft.business_plan_snapshot ? 'Snapshot versionado disponível; usar também a exportação do plano financeiro' : 'Sem plano empresarial detalhado preenchido', 'Pressupostos declarados; não é demonstração contabilística'],
|
||||
['Equipa', 'Nota anterior sobre competências', String(draft.skills_needed ?? ''), 'Texto declarado existente'],
|
||||
['Execução', 'Nota anterior sobre marcos', String(draft.project_milestones ?? ''), 'Texto declarado existente'],
|
||||
['Financiamento', 'Estado de pré-elegibilidade', 'Informação insuficiente', 'Sem catálogo documentado de produtos e critérios'],
|
||||
['Necessidade de negócio', 'Descrição', String(draft.opportunity_description ?? ''), 'Declarado pelo utilizador'],
|
||||
['Necessidade de negócio', 'Infra-estrutura necessária', (Array.isArray(draft.infrastructure_needs) ? draft.infrastructure_needs : []).join(', '), 'Declarado/seleccionado pelo utilizador'],
|
||||
['Financiamento', 'Montante pretendido', String(draft.opportunity_value ?? ''), 'Declarado pelo utilizador; ver moeda separada'],
|
||||
['Financiamento', 'Moeda do montante', String(draft.opportunity_currency_label ?? draft.opportunity_currency ?? ''), 'Declarada/seleccionada; sem avaliação de produto'],
|
||||
[
|
||||
'Projecto',
|
||||
'Título',
|
||||
String(draft.project_title ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Versão do questionário',
|
||||
String(draft.project_questionnaire_version ?? 'legacy-unversioned'),
|
||||
'Metadado do questionário; não altera resultados guardados',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Resumo',
|
||||
String(draft.project_summary ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Problema',
|
||||
String(draft.project_problem ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Clientes/beneficiários',
|
||||
String(draft.target_customers ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Proposta de valor',
|
||||
String(draft.value_proposition ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Tipo de projecto',
|
||||
String(draft.project_type_label ?? draft.project_type ?? ''),
|
||||
'Declarado/seleccionado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Sector',
|
||||
String(draft.sector_id_label ?? draft.sector_id ?? ''),
|
||||
'Selecção declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Actividade económica',
|
||||
String(draft.activity_id_label ?? draft.activity_id ?? ''),
|
||||
'Selecção declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Produtos e serviços',
|
||||
String(draft.products_services ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Fase de maturidade',
|
||||
String(draft.maturity_stage_label ?? draft.maturity_stage ?? ''),
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Data prevista de início',
|
||||
String(draft.expected_start_date ?? ''),
|
||||
'Declarada pelo utilizador; data não verificada',
|
||||
],
|
||||
[
|
||||
'Projecto',
|
||||
'Duração prevista',
|
||||
draft.project_duration_years
|
||||
? `${displayValue(draft.project_duration_years)} anos`
|
||||
: '',
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Hipótese',
|
||||
String(draft.market_assumption ?? ''),
|
||||
'Informação declarada, não verificada',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Fonte e data',
|
||||
String(draft.market_source ?? ''),
|
||||
'Opcional; não verificada',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Concorrência e alternativas',
|
||||
String(draft.competitor_assumption ?? ''),
|
||||
'Hipótese declarada; não verificada',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Canal de venda',
|
||||
String(draft.sales_channel_assumption ?? ''),
|
||||
'Planeamento declarado; não confirmado',
|
||||
],
|
||||
[
|
||||
'Mercado',
|
||||
'Acções de divulgação',
|
||||
String(draft.marketing_approach ?? ''),
|
||||
'Planeamento declarado; não confirmado',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Província',
|
||||
String(draft.province_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Distrito',
|
||||
String(draft.district_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Posto administrativo',
|
||||
String(draft.admin_post_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Localidade',
|
||||
String(draft.locality_id_label ?? ''),
|
||||
'Selecção de catálogo territorial',
|
||||
],
|
||||
[
|
||||
'Localização',
|
||||
'Critérios e pontos a confirmar',
|
||||
String(draft.location_rationale ?? ''),
|
||||
'Declaração do utilizador; não confirma disponibilidade',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Estado do plano detalhado',
|
||||
draft.business_plan_snapshot
|
||||
? 'Snapshot versionado disponível; usar também a exportação do plano financeiro'
|
||||
: 'Sem plano empresarial detalhado preenchido',
|
||||
'Pressupostos declarados; não é demonstração contabilística',
|
||||
],
|
||||
[
|
||||
'Equipa',
|
||||
'Nota anterior sobre competências',
|
||||
String(draft.skills_needed ?? ''),
|
||||
'Texto declarado existente',
|
||||
],
|
||||
[
|
||||
'Execução',
|
||||
'Nota anterior sobre marcos',
|
||||
String(draft.project_milestones ?? ''),
|
||||
'Texto declarado existente',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Estado de pré-elegibilidade',
|
||||
'Informação insuficiente',
|
||||
'Sem catálogo documentado de produtos e critérios',
|
||||
],
|
||||
[
|
||||
'Necessidade de negócio',
|
||||
'Descrição',
|
||||
String(draft.opportunity_description ?? ''),
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Necessidade de negócio',
|
||||
'Infra-estrutura necessária',
|
||||
(Array.isArray(draft.infrastructure_needs)
|
||||
? draft.infrastructure_needs
|
||||
: []
|
||||
).join(', '),
|
||||
'Declarado/seleccionado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Montante pretendido',
|
||||
String(draft.opportunity_value ?? ''),
|
||||
'Declarado pelo utilizador; ver moeda separada',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Moeda do montante',
|
||||
String(
|
||||
draft.opportunity_currency_label ??
|
||||
draft.opportunity_currency ??
|
||||
'',
|
||||
),
|
||||
'Declarada/seleccionada; sem avaliação de produto',
|
||||
],
|
||||
];
|
||||
const plannedResponses = readPlannedRiskResponses(draft);
|
||||
for (const item of getProjectReadiness(draft)) {
|
||||
const response = plannedResponses.find((entry) => entry.risk_id === item.id);
|
||||
const response = plannedResponses.find(
|
||||
(entry) => entry.risk_id === item.id,
|
||||
);
|
||||
const responseText = response
|
||||
? [response.action, response.owner ? `Responsável: ${response.owner}` : '', response.estimated_cost ? `Custo previsto: ${response.estimated_cost} ${String(draft.currency ?? '')}` : '', response.due_date ? `Prazo: ${response.due_date}` : ''].filter(Boolean).join(' · ')
|
||||
? [
|
||||
response.action,
|
||||
response.owner ? `Responsável: ${response.owner}` : '',
|
||||
response.estimated_cost
|
||||
? `Custo previsto: ${response.estimated_cost} ${String(draft.currency ?? '')}`
|
||||
: '',
|
||||
response.due_date ? `Prazo: ${response.due_date}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
: 'Resposta ainda não registada';
|
||||
rows.push(['Risco', item.title, `${item.origin} ${item.affected} Consequência possível: ${item.consequence} Acção: ${item.nextAction} Resposta planeada: ${responseText}`, 'Derivado das respostas e campos em falta; estimativa qualitativa, sem probabilidade ou gravidade atribuída']);
|
||||
rows.push([
|
||||
'Risco',
|
||||
item.title,
|
||||
`${item.origin} ${item.affected} Consequência possível: ${item.consequence} Acção: ${item.nextAction} Resposta planeada: ${responseText}`,
|
||||
'Derivado das respostas e campos em falta; estimativa qualitativa, sem probabilidade ou gravidade atribuída',
|
||||
]);
|
||||
}
|
||||
const finance = restoreFinancialToolsSnapshot(String(draft.financial_tools_snapshot ?? ''));
|
||||
const finance = restoreFinancialToolsSnapshot(
|
||||
String(draft.financial_tools_snapshot ?? ''),
|
||||
);
|
||||
if (finance) {
|
||||
const calculation = calculateFinancialTools({
|
||||
loan: {
|
||||
@@ -109,70 +312,304 @@ export function buildProjectDossierRows(draft: Record<string, string | string[]>
|
||||
expenses: finance.expenses.map((row) => row.amount),
|
||||
});
|
||||
const currency = String(draft.currency ?? '') || 'moeda não indicada';
|
||||
const source = 'Estimativa matemática baseada em pressupostos declarados; não é oferta de crédito nem resultado oficial';
|
||||
const source =
|
||||
'Estimativa matemática baseada em pressupostos declarados; não é oferta de crédito nem resultado oficial';
|
||||
rows.push(
|
||||
['Plano financeiro', 'Periodicidade do orçamento', finance.budgetPeriod, 'Declarada pelo utilizador'],
|
||||
['Empréstimo educativo', 'Capital pressuposto', `${finance.loan.principal} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Empréstimo educativo', 'Taxa anual pressuposta', `${finance.loan.rate}% (${finance.loan.rateType})`, 'Declarada pelo utilizador; não é taxa de produto'],
|
||||
['Empréstimo educativo', 'Prazo pressuposto', `${finance.loan.months} meses`, 'Declarado pelo utilizador'],
|
||||
['Empréstimo educativo', 'Método e pressupostos substituídos', `Saldo decrescente; capital ${finance.loan.principal}; taxa ${finance.loan.rate}% ${finance.loan.rateType}; ${finance.loan.months} meses; período ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods}; comissão inicial ${finance.loan.upfrontFee}; comissão periódica ${finance.loan.recurringFee}`, 'Cronograma do simulador; taxa declarada, sem correspondência a produto'],
|
||||
['Empréstimo educativo', 'Prestação do primeiro período', calculation.loan.value?.schedule[0]?.totalPayment ? `${calculation.loan.value.schedule[0].totalPayment} ${currency}` : 'Indeterminado', source],
|
||||
['Empréstimo educativo', 'Juros totais estimados', calculation.loan.value?.totalInterest ? `${calculation.loan.value.totalInterest} ${currency}` : 'Indeterminado', source],
|
||||
['Empréstimo educativo', 'Estado/erro do cálculo', calculation.loan.error ?? (calculation.loan.value ? 'Calculado pelo cronograma do simulador' : 'Indeterminado'), source],
|
||||
['Ponto de equilíbrio', 'Fórmula e valores substituídos', `${finance.breakEven.fixed} / (${finance.breakEven.price} − ${finance.breakEven.variable}); unidades arredondadas para cima`, 'Custos fixos ÷ margem de contribuição unitária; pressupostos declarados'],
|
||||
['Ponto de equilíbrio', 'Unidades estimadas', calculation.breakEven.value?.breakEvenUnits ?? 'Indeterminado', source],
|
||||
['Ponto de equilíbrio', 'Vendas correspondentes', calculation.breakEven.value?.breakEvenRevenue ? `${calculation.breakEven.value.breakEvenRevenue} ${currency}` : 'Indeterminado', source],
|
||||
['Ponto de equilíbrio', 'Estado/erro do cálculo', calculation.breakEven.error ?? (calculation.breakEven.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
['Financiamento', 'Investimento total pressuposto', `${finance.funding.total} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Financiamento', 'Montante já mobilizado pressuposto', `${finance.funding.secured} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Financiamento', 'Fórmula e valores substituídos', `${finance.funding.total} − ${finance.funding.secured}`, 'Investimento total declarado − financiamento mobilizado declarado'],
|
||||
['Financiamento', 'Diferença por financiar', calculation.funding.value?.gap ? `${calculation.funding.value.gap} ${currency}` : calculation.funding.value?.gap === '0.00' ? `0.00 ${currency}` : 'Indeterminado', source],
|
||||
['Financiamento', 'Estado/erro do cálculo', calculation.funding.error ?? (calculation.funding.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
['Orçamento', 'Fórmula e valores substituídos', `${calculation.budget.value?.incomeTotal ?? 'Não informado'} − ${calculation.budget.value?.expenseTotal ?? 'Não informado'}`, 'Receitas declaradas − despesas declaradas; valores ausentes não são zero'],
|
||||
['Orçamento', 'Receitas declaradas', calculation.budget.value?.incomeTotal ? `${calculation.budget.value.incomeTotal} ${currency}` : 'Indeterminado', 'Declarado pelo utilizador'],
|
||||
['Orçamento', 'Despesas declaradas', calculation.budget.value?.expenseTotal ? `${calculation.budget.value.expenseTotal} ${currency}` : 'Indeterminado', 'Declarado pelo utilizador'],
|
||||
['Orçamento', 'Saldo operacional estimado', calculation.budget.value?.operatingBalance ? `${calculation.budget.value.operatingBalance} ${currency}` : 'Indeterminado', source],
|
||||
['Orçamento', 'Estado/erro do cálculo', calculation.budget.error ?? (calculation.budget.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Periodicidade do orçamento',
|
||||
finance.budgetPeriod,
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Capital pressuposto',
|
||||
`${finance.loan.principal} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Taxa anual pressuposta',
|
||||
`${finance.loan.rate}% (${finance.loan.rateType})`,
|
||||
'Declarada pelo utilizador; não é taxa de produto',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Prazo pressuposto',
|
||||
`${finance.loan.months} meses`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Método e pressupostos substituídos',
|
||||
`Saldo decrescente; capital ${finance.loan.principal}; taxa ${finance.loan.rate}% ${finance.loan.rateType}; ${finance.loan.months} meses; período ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods}; comissão inicial ${finance.loan.upfrontFee}; comissão periódica ${finance.loan.recurringFee}`,
|
||||
'Cronograma do simulador; taxa declarada, sem correspondência a produto',
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Prestação do primeiro período',
|
||||
calculation.loan.value?.schedule[0]?.totalPayment
|
||||
? `${calculation.loan.value.schedule[0].totalPayment} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Juros totais estimados',
|
||||
calculation.loan.value?.totalInterest
|
||||
? `${calculation.loan.value.totalInterest} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Empréstimo educativo',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.loan.error ??
|
||||
(calculation.loan.value
|
||||
? 'Calculado pelo cronograma do simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Fórmula e valores substituídos',
|
||||
`${finance.breakEven.fixed} / (${finance.breakEven.price} − ${finance.breakEven.variable}); unidades arredondadas para cima`,
|
||||
'Custos fixos ÷ margem de contribuição unitária; pressupostos declarados',
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Unidades estimadas',
|
||||
calculation.breakEven.value?.breakEvenUnits ?? 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Vendas correspondentes',
|
||||
calculation.breakEven.value?.breakEvenRevenue
|
||||
? `${calculation.breakEven.value.breakEvenRevenue} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Ponto de equilíbrio',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.breakEven.error ??
|
||||
(calculation.breakEven.value
|
||||
? 'Calculado pelo simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Investimento total pressuposto',
|
||||
`${finance.funding.total} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Montante já mobilizado pressuposto',
|
||||
`${finance.funding.secured} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Fórmula e valores substituídos',
|
||||
`${finance.funding.total} − ${finance.funding.secured}`,
|
||||
'Investimento total declarado − financiamento mobilizado declarado',
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Diferença por financiar',
|
||||
calculation.funding.value?.gap
|
||||
? `${calculation.funding.value.gap} ${currency}`
|
||||
: calculation.funding.value?.gap === '0.00'
|
||||
? `0.00 ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Financiamento',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.funding.error ??
|
||||
(calculation.funding.value
|
||||
? 'Calculado pelo simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Fórmula e valores substituídos',
|
||||
`${calculation.budget.value?.incomeTotal ?? 'Não informado'} − ${calculation.budget.value?.expenseTotal ?? 'Não informado'}`,
|
||||
'Receitas declaradas − despesas declaradas; valores ausentes não são zero',
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Receitas declaradas',
|
||||
calculation.budget.value?.incomeTotal
|
||||
? `${calculation.budget.value.incomeTotal} ${currency}`
|
||||
: 'Indeterminado',
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Despesas declaradas',
|
||||
calculation.budget.value?.expenseTotal
|
||||
? `${calculation.budget.value.expenseTotal} ${currency}`
|
||||
: 'Indeterminado',
|
||||
'Declarado pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Saldo operacional estimado',
|
||||
calculation.budget.value?.operatingBalance
|
||||
? `${calculation.budget.value.operatingBalance} ${currency}`
|
||||
: 'Indeterminado',
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Orçamento',
|
||||
'Estado/erro do cálculo',
|
||||
calculation.budget.error ??
|
||||
(calculation.budget.value
|
||||
? 'Calculado pelo simulador'
|
||||
: 'Indeterminado'),
|
||||
source,
|
||||
],
|
||||
);
|
||||
for (const income of finance.incomes) {
|
||||
rows.push(['Orçamento', `Receita declarada: ${income.label}`, `${income.amount} ${currency}`, 'Declarado pelo utilizador']);
|
||||
rows.push([
|
||||
'Orçamento',
|
||||
`Receita declarada: ${income.label}`,
|
||||
`${income.amount} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
for (const expense of finance.expenses) {
|
||||
rows.push(['Orçamento', `Despesa declarada: ${expense.label}`, `${expense.amount} ${currency}`, 'Declarado pelo utilizador']);
|
||||
rows.push([
|
||||
'Orçamento',
|
||||
`Despesa declarada: ${expense.label}`,
|
||||
`${expense.amount} ${currency}`,
|
||||
'Declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
}
|
||||
const businessPlan = restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot ?? ''));
|
||||
const businessPlan = restoreBusinessPlanSnapshot(
|
||||
String(draft.business_plan_snapshot ?? ''),
|
||||
);
|
||||
if (businessPlan) {
|
||||
try {
|
||||
const forecast = forecastBusinessPlan(businessPlan);
|
||||
const source = 'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
|
||||
const source =
|
||||
'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
|
||||
rows.push(
|
||||
['Plano financeiro', 'Moeda do plano', businessPlan.currency, 'Declarada pelo utilizador'],
|
||||
['Plano financeiro', 'Horizonte', `${businessPlan.periods ?? 12} meses`, 'Pressuposto declarado'],
|
||||
['Plano financeiro', 'Facturação no horizonte', `${forecast.totalRevenue} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Fórmula e valores substituídos', `Facturação: quantidade mensal × preço unitário por produto; caixa final: saldo de abertura + cobranças e fontes − pagamentos. Horizonte: ${businessPlan.periods ?? 12} meses; moeda: ${businessPlan.currency}.`, 'Métodos do plano financeiro; agendas e pressupostos declarados no snapshot'],
|
||||
['Plano financeiro', 'Cobranças no horizonte', `${forecast.totalCashCollections} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Pagamentos no horizonte', `${forecast.totalPayments} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Resultado antes de impostos', `${forecast.totalProfitBeforeTax} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Caixa final projectada', `${forecast.endingCash} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Reconciliação do financiamento', forecast.fundingStatus, 'Comparação calculada entre usos e fontes declarados'],
|
||||
['Plano financeiro', 'Diferença entre usos e fontes', `${forecast.fundingGap} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Taxa de câmbio de apresentação', businessPlan.fxRate ? `${businessPlan.fxRate}; ${businessPlan.fxDate ?? 'data não informada'}; ${businessPlan.fxSource ?? 'fonte não informada'}` : 'Não utilizada', businessPlan.fxRate ? 'Pressuposto de planeamento declarado pelo utilizador; não verificado' : 'Sem conversão'],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Moeda do plano',
|
||||
businessPlan.currency,
|
||||
'Declarada pelo utilizador',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Horizonte',
|
||||
`${businessPlan.periods ?? 12} meses`,
|
||||
'Pressuposto declarado',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Facturação no horizonte',
|
||||
`${forecast.totalRevenue} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Fórmula e valores substituídos',
|
||||
`Facturação: quantidade mensal × preço unitário por produto; caixa final: saldo de abertura + cobranças e fontes − pagamentos. Horizonte: ${businessPlan.periods ?? 12} meses; moeda: ${businessPlan.currency}.`,
|
||||
'Métodos do plano financeiro; agendas e pressupostos declarados no snapshot',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Cobranças no horizonte',
|
||||
`${forecast.totalCashCollections} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Pagamentos no horizonte',
|
||||
`${forecast.totalPayments} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Resultado antes de impostos',
|
||||
`${forecast.totalProfitBeforeTax} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Caixa final projectada',
|
||||
`${forecast.endingCash} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Reconciliação do financiamento',
|
||||
forecast.fundingStatus,
|
||||
'Comparação calculada entre usos e fontes declarados',
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Diferença entre usos e fontes',
|
||||
`${forecast.fundingGap} ${businessPlan.currency}`,
|
||||
source,
|
||||
],
|
||||
[
|
||||
'Plano financeiro',
|
||||
'Taxa de câmbio de apresentação',
|
||||
businessPlan.fxRate
|
||||
? `${businessPlan.fxRate}; ${businessPlan.fxDate ?? 'data não informada'}; ${businessPlan.fxSource ?? 'fonte não informada'}`
|
||||
: 'Não utilizada',
|
||||
businessPlan.fxRate
|
||||
? 'Pressuposto de planeamento declarado pelo utilizador; não verificado'
|
||||
: 'Sem conversão',
|
||||
],
|
||||
);
|
||||
} catch {
|
||||
rows.push(['Plano financeiro', 'Estado do cálculo', 'Indeterminado', 'Snapshot inválido ou pressupostos incompatíveis; reveja o plano antes de exportar']);
|
||||
rows.push([
|
||||
'Plano financeiro',
|
||||
'Estado do cálculo',
|
||||
'Indeterminado',
|
||||
'Snapshot inválido ou pressupostos incompatíveis; reveja o plano antes de exportar',
|
||||
]);
|
||||
}
|
||||
}
|
||||
for (const [index, need] of readRows<TeamNeed>(String(draft.project_team_snapshot ?? ''), ['competency', 'state', 'action', 'estimated_cost', 'due_date']).entries()) {
|
||||
rows.push(['Equipa', `Necessidade ${index + 1}`, `${need.competency}; ${need.state}; resposta: ${need.action}; custo: ${need.estimated_cost}; prazo: ${need.due_date}`, 'Declarado pelo utilizador; sem certificação ou correspondência']);
|
||||
for (const [index, need] of readRows<TeamNeed>(
|
||||
String(draft.project_team_snapshot ?? ''),
|
||||
['competency', 'state', 'action', 'estimated_cost', 'due_date'],
|
||||
).entries()) {
|
||||
rows.push([
|
||||
'Equipa',
|
||||
`Necessidade ${index + 1}`,
|
||||
`${need.competency}; ${need.state}; resposta: ${need.action}; custo: ${need.estimated_cost}; prazo: ${need.due_date}`,
|
||||
'Declarado pelo utilizador; sem certificação ou correspondência',
|
||||
]);
|
||||
}
|
||||
for (const [index, milestone] of readRows<ProjectMilestone>(String(draft.project_execution_snapshot ?? ''), ['title', 'due_date', 'status', 'planned_amount', 'actual_amount']).entries()) {
|
||||
rows.push(['Execução', `Marco ${index + 1}`, `${milestone.title}; ${milestone.status}; prazo: ${milestone.due_date}; planeado: ${milestone.planned_amount}; realizado: ${milestone.actual_amount}`, 'Planeado/realizado declarado pelo utilizador']);
|
||||
for (const [index, milestone] of readRows<ProjectMilestone>(
|
||||
String(draft.project_execution_snapshot ?? ''),
|
||||
['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
|
||||
).entries()) {
|
||||
rows.push([
|
||||
'Execução',
|
||||
`Marco ${index + 1}`,
|
||||
`${milestone.title}; ${milestone.status}; prazo: ${milestone.due_date}; planeado: ${milestone.planned_amount}; realizado: ${milestone.actual_amount}`,
|
||||
'Planeado/realizado declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function exportProjectDossierCsv(draft: Record<string, string | string[]>): string {
|
||||
export function exportProjectDossierCsv(
|
||||
draft: Record<string, string | string[]>,
|
||||
): string {
|
||||
const rows = buildProjectDossierRows(draft);
|
||||
// Semicolon is the active list separator in the target Excel locale (pt-MZ).
|
||||
return `\uFEFF${rows.map((row) => row.map((value) => csvCellWithDelimiter(value, ';')).join(';')).join('\r\n')}`;
|
||||
|
||||
@@ -26,12 +26,17 @@ function value(draft: ReadinessDraft, key: string): string {
|
||||
return typeof current === 'string' ? current.trim() : '';
|
||||
}
|
||||
|
||||
function rows(draft: ReadinessDraft, key: string): Array<Record<string, string>> {
|
||||
function rows(
|
||||
draft: ReadinessDraft,
|
||||
key: string,
|
||||
): Array<Record<string, string>> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value(draft, key) || '[]');
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item): item is Record<string, string> =>
|
||||
Boolean(item && typeof item === 'object' && !Array.isArray(item)),
|
||||
Boolean(
|
||||
item && typeof item === 'object' && !Array.isArray(item),
|
||||
),
|
||||
)
|
||||
: [];
|
||||
} catch {
|
||||
@@ -46,15 +51,22 @@ export function getProjectReadiness(
|
||||
const customers = value(draft, 'target_customers');
|
||||
const market = value(draft, 'market_assumption');
|
||||
const marketSource = value(draft, 'market_source');
|
||||
const costs = value(draft, 'business_plan_snapshot') ||
|
||||
const costs =
|
||||
value(draft, 'business_plan_snapshot') ||
|
||||
value(draft, 'financial_tools_snapshot') ||
|
||||
value(draft, 'annual_operating_costs');
|
||||
const territory = ['province_id', 'district_id', 'locality_id'].some((key) => value(draft, key));
|
||||
const territory = ['province_id', 'district_id', 'locality_id'].some(
|
||||
(key) => value(draft, key),
|
||||
);
|
||||
const locationReason = value(draft, 'location_rationale');
|
||||
const team = rows(draft, 'project_team_snapshot');
|
||||
const identifiedGap = team.some((item) => item.state === 'gap');
|
||||
const sought = Number(value(draft, 'sought_amount') || value(draft, 'opportunity_value') || 0);
|
||||
const secured = Number(value(draft, 'secured_amount') || value(draft, 'own_capital') || 0);
|
||||
const sought = Number(
|
||||
value(draft, 'sought_amount') || value(draft, 'opportunity_value') || 0,
|
||||
);
|
||||
const secured = Number(
|
||||
value(draft, 'secured_amount') || value(draft, 'own_capital') || 0,
|
||||
);
|
||||
const benefits = value(draft, 'claimed_benefits');
|
||||
const customerStatus = value(draft, 'customer_validation_status');
|
||||
const costStatus = value(draft, 'cost_estimate_status');
|
||||
@@ -64,89 +76,156 @@ export function getProjectReadiness(
|
||||
|
||||
if (!customers && customerStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'customers', kind: 'missing', title: 'Clientes ainda pouco definidos',
|
||||
origin: customerStatus ? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.` : 'Não foi indicada uma descrição de clientes ou beneficiários.',
|
||||
id: 'customers',
|
||||
kind: 'missing',
|
||||
title: 'Clientes ainda pouco definidos',
|
||||
origin: customerStatus
|
||||
? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.`
|
||||
: 'Não foi indicada uma descrição de clientes ou beneficiários.',
|
||||
affected: 'Procura e receitas previstas.',
|
||||
consequence: 'As vendas planeadas podem não corresponder à procura real.',
|
||||
nextAction: 'Indique quem poderá comprar, onde está e que necessidade procura resolver.',
|
||||
consequence:
|
||||
'As vendas planeadas podem não corresponder à procura real.',
|
||||
nextAction:
|
||||
'Indique quem poderá comprar, onde está e que necessidade procura resolver.',
|
||||
fieldKey: 'target_customers',
|
||||
});
|
||||
} else if (customers && ((!marketSource && market) || ['no', 'partial', 'unknown'].includes(customerStatus))) {
|
||||
} else if (
|
||||
customers &&
|
||||
((!marketSource && market) ||
|
||||
['no', 'partial', 'unknown'].includes(customerStatus))
|
||||
) {
|
||||
items.push({
|
||||
id: 'market-source', kind: 'unverified', title: 'Hipótese de mercado sem fonte ou data',
|
||||
id: 'market-source',
|
||||
kind: 'unverified',
|
||||
title: 'Hipótese de mercado sem fonte ou data',
|
||||
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${customerStatus}` : ''}.`,
|
||||
affected: 'Procura, preço e projecções de vendas.',
|
||||
consequence: 'A hipótese pode não representar informação actual ou verificável.',
|
||||
nextAction: 'Registe a origem e a data, ou marque-a como uma hipótese ainda por testar.',
|
||||
consequence:
|
||||
'A hipótese pode não representar informação actual ou verificável.',
|
||||
nextAction:
|
||||
'Registe a origem e a data, ou marque-a como uma hipótese ainda por testar.',
|
||||
fieldKey: 'market_source',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!costs || ['no', 'partial', 'unknown'].includes(costStatus)) && costStatus !== 'not_applicable') {
|
||||
if (
|
||||
(!costs || ['no', 'partial', 'unknown'].includes(costStatus)) &&
|
||||
costStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'costs', kind: 'missing', title: 'Custos do projecto por detalhar',
|
||||
origin: costStatus ? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}` : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
|
||||
id: 'costs',
|
||||
kind: 'missing',
|
||||
title: 'Custos do projecto por detalhar',
|
||||
origin: costStatus
|
||||
? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}`
|
||||
: 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
|
||||
affected: 'Investimento necessário, margem e tesouraria.',
|
||||
consequence: 'O capital necessário pode estar subestimado.',
|
||||
nextAction: 'Registe os principais custos, moeda e periodicidade no plano financeiro.',
|
||||
nextAction:
|
||||
'Registe os principais custos, moeda e periodicidade no plano financeiro.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if ((value(draft, 'business_plan_snapshot') || value(draft, 'annual_revenue'))
|
||||
&& ['no', 'partial', 'unknown', ''].includes(collectionStatus)
|
||||
&& collectionStatus !== 'not_applicable') {
|
||||
if (
|
||||
(value(draft, 'business_plan_snapshot') ||
|
||||
value(draft, 'annual_revenue')) &&
|
||||
['no', 'partial', 'unknown', ''].includes(collectionStatus) &&
|
||||
collectionStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'receivables', kind: collectionStatus === 'no' || collectionStatus === 'partial' ? 'risk' : 'missing',
|
||||
id: 'receivables',
|
||||
kind:
|
||||
collectionStatus === 'no' || collectionStatus === 'partial'
|
||||
? 'risk'
|
||||
: 'missing',
|
||||
title: 'Prazo de recebimentos por esclarecer',
|
||||
origin: collectionStatus ? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.` : 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
|
||||
origin: collectionStatus
|
||||
? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.`
|
||||
: 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
|
||||
affected: 'Fluxo de caixa e capital de giro.',
|
||||
consequence: 'A tesouraria pode ficar abaixo do necessário mesmo quando há vendas previstas.',
|
||||
nextAction: 'Registe os prazos previstos de cobrança no plano de fluxo de caixa e confirme-os com os clientes.',
|
||||
consequence:
|
||||
'A tesouraria pode ficar abaixo do necessário mesmo quando há vendas previstas.',
|
||||
nextAction:
|
||||
'Registe os prazos previstos de cobrança no plano de fluxo de caixa e confirme-os com os clientes.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!territory || !locationReason || ['no', 'partial', 'unknown'].includes(locationStatus)) && locationStatus !== 'not_applicable') {
|
||||
if (
|
||||
(!territory ||
|
||||
!locationReason ||
|
||||
['no', 'partial', 'unknown'].includes(locationStatus)) &&
|
||||
locationStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'location', kind: territory && locationReason ? 'unverified' : 'missing', title: 'Adequação da localização por esclarecer',
|
||||
id: 'location',
|
||||
kind: territory && locationReason ? 'unverified' : 'missing',
|
||||
title: 'Adequação da localização por esclarecer',
|
||||
origin: `Estado declarado: ${locationStatus || 'não indicado'}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
|
||||
affected: 'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
||||
consequence: 'Podem existir limitações logísticas ou custos locais ainda não considerados.',
|
||||
nextAction: 'Registe por que escolheu o local e quais recursos precisam de confirmação.',
|
||||
affected:
|
||||
'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
||||
consequence:
|
||||
'Podem existir limitações logísticas ou custos locais ainda não considerados.',
|
||||
nextAction:
|
||||
'Registe por que escolheu o local e quais recursos precisam de confirmação.',
|
||||
fieldKey: 'location_rationale',
|
||||
});
|
||||
}
|
||||
|
||||
if (identifiedGap || team.length === 0) {
|
||||
items.push({
|
||||
id: 'team', kind: identifiedGap ? 'risk' : 'missing', title: identifiedGap ? 'Competência em falta identificada' : 'Equipa e competências por detalhar',
|
||||
origin: identifiedGap ? 'O plano de equipa assinala pelo menos uma competência como lacuna.' : 'Ainda não há necessidades de equipa registadas.',
|
||||
id: 'team',
|
||||
kind: identifiedGap ? 'risk' : 'missing',
|
||||
title: identifiedGap
|
||||
? 'Competência em falta identificada'
|
||||
: 'Equipa e competências por detalhar',
|
||||
origin: identifiedGap
|
||||
? 'O plano de equipa assinala pelo menos uma competência como lacuna.'
|
||||
: 'Ainda não há necessidades de equipa registadas.',
|
||||
affected: 'Preparação e execução das actividades.',
|
||||
consequence: 'A execução pode atrasar ou exigir apoio e custos adicionais.',
|
||||
nextAction: 'Registe a competência, a resposta planeada, o responsável e o prazo.',
|
||||
consequence:
|
||||
'A execução pode atrasar ou exigir apoio e custos adicionais.',
|
||||
nextAction:
|
||||
'Registe a competência, a resposta planeada, o responsável e o prazo.',
|
||||
fieldKey: 'team',
|
||||
});
|
||||
}
|
||||
|
||||
if ((sought > secured || ['in_process', 'not_started', 'unknown'].includes(fundingStatus) || (fundingStatus === 'confirmed' && sought === 0 && secured === 0)) && fundingStatus !== 'not_applicable') {
|
||||
if (
|
||||
(sought > secured ||
|
||||
['in_process', 'not_started', 'unknown'].includes(fundingStatus) ||
|
||||
(fundingStatus === 'confirmed' && sought === 0 && secured === 0)) &&
|
||||
fundingStatus !== 'not_applicable'
|
||||
) {
|
||||
items.push({
|
||||
id: 'funding', kind: 'risk', title: 'Financiamento ainda não confirmado',
|
||||
origin: sought > secured ? 'O montante indicado como necessário excede os recursos declarados como mobilizados.' : `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
|
||||
id: 'funding',
|
||||
kind: 'risk',
|
||||
title: 'Financiamento ainda não confirmado',
|
||||
origin:
|
||||
sought > secured
|
||||
? 'O montante indicado como necessário excede os recursos declarados como mobilizados.'
|
||||
: `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
|
||||
affected: 'Calendário de investimento e implementação.',
|
||||
consequence: 'Os recursos podem não estar disponíveis quando forem necessários.',
|
||||
nextAction: 'Identifique a fonte, o estado, as condições e uma alternativa de financiamento.',
|
||||
consequence:
|
||||
'Os recursos podem não estar disponíveis quando forem necessários.',
|
||||
nextAction:
|
||||
'Identifique a fonte, o estado, as condições e uma alternativa de financiamento.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if (benefits) {
|
||||
items.push({
|
||||
id: 'benefits', kind: 'unverified', title: 'Benefício fiscal carece de validação',
|
||||
id: 'benefits',
|
||||
kind: 'unverified',
|
||||
title: 'Benefício fiscal carece de validação',
|
||||
origin: 'Foram indicados benefícios para validação no dossier.',
|
||||
affected: 'Impostos e retorno financeiro estimado.',
|
||||
consequence: 'O retorno pode estar sobrestimado se as condições não forem satisfeitas.',
|
||||
nextAction: 'Confirme a regra, vigência, regime e documentação numa fonte oficial; mantenha o benefício fora do cenário base até confirmação.',
|
||||
consequence:
|
||||
'O retorno pode estar sobrestimado se as condições não forem satisfeitas.',
|
||||
nextAction:
|
||||
'Confirme a regra, vigência, regime e documentação numa fonte oficial; mantenha o benefício fora do cenário base até confirmação.',
|
||||
fieldKey: 'tax',
|
||||
});
|
||||
}
|
||||
@@ -154,21 +233,33 @@ export function getProjectReadiness(
|
||||
return items;
|
||||
}
|
||||
|
||||
export function readPlannedRiskResponses(draft: ReadinessDraft): PlannedRiskResponse[] {
|
||||
export function readPlannedRiskResponses(
|
||||
draft: ReadinessDraft,
|
||||
): PlannedRiskResponse[] {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value(draft, 'project_risk_responses_snapshot') || '[]');
|
||||
const parsed: unknown = JSON.parse(
|
||||
value(draft, 'project_risk_responses_snapshot') || '[]',
|
||||
);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((item): item is PlannedRiskResponse => Boolean(
|
||||
item && typeof item === 'object' && !Array.isArray(item) &&
|
||||
typeof item.risk_id === 'string' && typeof item.action === 'string' &&
|
||||
typeof item.owner === 'string' && typeof item.estimated_cost === 'string' &&
|
||||
typeof item.due_date === 'string',
|
||||
));
|
||||
return parsed.filter((item): item is PlannedRiskResponse =>
|
||||
Boolean(
|
||||
item &&
|
||||
typeof item === 'object' &&
|
||||
!Array.isArray(item) &&
|
||||
typeof item.risk_id === 'string' &&
|
||||
typeof item.action === 'string' &&
|
||||
typeof item.owner === 'string' &&
|
||||
typeof item.estimated_cost === 'string' &&
|
||||
typeof item.due_date === 'string',
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function serializePlannedRiskResponses(responses: PlannedRiskResponse[]): string {
|
||||
export function serializePlannedRiskResponses(
|
||||
responses: PlannedRiskResponse[],
|
||||
): string {
|
||||
return JSON.stringify(responses.slice(0, 30));
|
||||
}
|
||||
|
||||
@@ -541,24 +541,44 @@ function isApiSimulationDraftV1(value: unknown): value is ApiSimulationDraftV1 {
|
||||
Array.isArray(value.simulation_sources) &&
|
||||
value.simulation_sources.every(isApiSimulationSourceV1) &&
|
||||
(value.updated_at === null || isIsoDateTime(value.updated_at)) &&
|
||||
(value.expires_at === undefined || value.expires_at === null || isIsoDateTime(value.expires_at))
|
||||
(value.expires_at === undefined ||
|
||||
value.expires_at === null ||
|
||||
isIsoDateTime(value.expires_at))
|
||||
);
|
||||
}
|
||||
|
||||
function isApiSimulationDraftSummaryV1(value: unknown): value is ApiSimulationDraftSummaryV1 {
|
||||
return isPlainObject(value) && typeof value.id === 'string' && uuidPattern.test(value.id) &&
|
||||
function isApiSimulationDraftSummaryV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationDraftSummaryV1 {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
typeof value.id === 'string' &&
|
||||
uuidPattern.test(value.id) &&
|
||||
typeof value.title === 'string' &&
|
||||
(value.updated_at === null || isIsoDateTime(value.updated_at)) &&
|
||||
(value.expires_at === null || isIsoDateTime(value.expires_at)) &&
|
||||
Number.isSafeInteger(value.version_no) && Number(value.version_no) > 0;
|
||||
Number.isSafeInteger(value.version_no) &&
|
||||
Number(value.version_no) > 0
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftListResponseV1(value: unknown): value is { data: ApiSimulationDraftSummaryV1[] } {
|
||||
return isPlainObject(value) && Array.isArray(value.data) && value.data.every(isApiSimulationDraftSummaryV1);
|
||||
export function isApiSimulationDraftListResponseV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationDraftSummaryV1[] } {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
Array.isArray(value.data) &&
|
||||
value.data.every(isApiSimulationDraftSummaryV1)
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftClaimPreviewV1(value: unknown): value is { data: ApiSimulationDraftSummaryV1 | null } {
|
||||
return isPlainObject(value) && (value.data === null || isApiSimulationDraftSummaryV1(value.data));
|
||||
export function isApiSimulationDraftClaimPreviewV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationDraftSummaryV1 | null } {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
(value.data === null || isApiSimulationDraftSummaryV1(value.data))
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftReadResponseV1(
|
||||
@@ -579,7 +599,9 @@ export function isApiSimulationDraftWriteResponseV1(value: unknown): value is {
|
||||
uuidPattern.test(data.id) &&
|
||||
Number.isSafeInteger(data.version_no) &&
|
||||
Number(data.version_no) > 0 &&
|
||||
(value.expires_at === undefined || value.expires_at === null || isIsoDateTime(value.expires_at)) &&
|
||||
(value.expires_at === undefined ||
|
||||
value.expires_at === null ||
|
||||
isIsoDateTime(value.expires_at)) &&
|
||||
(data.replayed === undefined || typeof data.replayed === 'boolean')
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@ import { csvCell } from './csv.js';
|
||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||
|
||||
export type SimulationDraft = Record<string, string | string[]>;
|
||||
export const projectQuestionnaireVersion = 'investmoz-project-dossier-2026-10-05.1';
|
||||
export const projectQuestionnaireVersion =
|
||||
'investmoz-project-dossier-2026-10-05.1';
|
||||
|
||||
function isProjectGuidedJourney(draft: SimulationDraft): boolean {
|
||||
return (
|
||||
@@ -12,7 +13,9 @@ function isProjectGuidedJourney(draft: SimulationDraft): boolean {
|
||||
}
|
||||
|
||||
function isInvestorProjectJourney(draft: SimulationDraft): boolean {
|
||||
return draft.purpose === 'simulate_only' && draft.journey_type === 'investor';
|
||||
return (
|
||||
draft.purpose === 'simulate_only' && draft.journey_type === 'investor'
|
||||
);
|
||||
}
|
||||
|
||||
export function getFiscalPeriodRange(
|
||||
@@ -87,7 +90,13 @@ export function getSimulationSections(draft: SimulationDraft) {
|
||||
if (draft.journey_type === 'investor') {
|
||||
return [
|
||||
...simulationSections.filter((section) =>
|
||||
['purpose', 'project', 'location', 'financial', 'tax'].includes(section.id),
|
||||
[
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'tax',
|
||||
].includes(section.id),
|
||||
),
|
||||
{ id: 'scenarios', title: 'Cenários e retorno indicativo' },
|
||||
{ id: 'procedures', title: 'Procedimentos e documentos' },
|
||||
@@ -254,7 +263,13 @@ export const simulationOptions: Record<string, string[]> = {
|
||||
'unknown',
|
||||
],
|
||||
preparedness_status: ['yes', 'no', 'partial', 'unknown', 'not_applicable'],
|
||||
funding_status: ['confirmed', 'in_process', 'not_started', 'unknown', 'not_applicable'],
|
||||
funding_status: [
|
||||
'confirmed',
|
||||
'in_process',
|
||||
'not_started',
|
||||
'unknown',
|
||||
'not_applicable',
|
||||
],
|
||||
fiscal_month: Array.from({ length: 12 }, (_, index) =>
|
||||
String(index + 1).padStart(2, '0'),
|
||||
),
|
||||
@@ -501,19 +516,25 @@ export const simulationFieldGroups: Record<
|
||||
key: 'target_customers',
|
||||
label: 'Quem são os clientes ou beneficiários?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'value_proposition',
|
||||
label: 'Que solução ou proposta de valor oferece?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_assumption',
|
||||
label: 'Hipótese sobre mercado, concorrência ou procura',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_source',
|
||||
@@ -600,42 +621,56 @@ export const simulationFieldGroups: Record<
|
||||
key: 'customer_validation_status',
|
||||
label: 'Já conversou com potenciais clientes sobre esta necessidade?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'target_customers',
|
||||
label: 'Quem são os clientes ou beneficiários? Onde estão e que necessidade têm?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_assumption',
|
||||
label: 'O que sabe ou está a assumir sobre procura, preço e concorrência?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'market_source',
|
||||
label: 'Qual é a origem e a data dessa informação, se as conhecer?',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'competitor_assumption',
|
||||
label: 'Que alternativas ou concorrentes os clientes usam actualmente?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'sales_channel_assumption',
|
||||
label: 'Como pretende chegar aos clientes e receber encomendas?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'marketing_approach',
|
||||
label: 'Que acções de divulgação pretende experimentar?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => d.purpose === 'simulate_only' && ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
d.purpose === 'simulate_only' &&
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
],
|
||||
location: [
|
||||
@@ -643,7 +678,8 @@ export const simulationFieldGroups: Record<
|
||||
key: 'location_assessment_status',
|
||||
label: 'Já avaliou a adequação desta localização?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'province_id',
|
||||
@@ -684,31 +720,36 @@ export const simulationFieldGroups: Record<
|
||||
label: 'Local conhecido?',
|
||||
options: 'yes_no',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'location_rationale',
|
||||
label: 'Porque considera esta localização e o que ainda precisa de confirmar?',
|
||||
type: 'textarea',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'land_status',
|
||||
label: 'Situação do terreno',
|
||||
options: 'land_status',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'area_required',
|
||||
label: 'Área necessária',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'area_unit',
|
||||
label: 'Unidade da área',
|
||||
options: 'area_unit',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'latitude',
|
||||
@@ -725,14 +766,16 @@ export const simulationFieldGroups: Record<
|
||||
{
|
||||
key: 'special_zone_id',
|
||||
label: 'Zona especial ZEE/ZFI',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'infrastructure_needs',
|
||||
label: 'Necessidades de infra-estrutura',
|
||||
options: 'infrastructure',
|
||||
multiple: true,
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
],
|
||||
financial: [
|
||||
@@ -740,86 +783,99 @@ export const simulationFieldGroups: Record<
|
||||
key: 'cost_estimate_status',
|
||||
label: 'Já identificou os principais custos e respectiva periodicidade?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'receivables_timing_status',
|
||||
label: 'Já sabe quando as vendas serão recebidas?',
|
||||
options: 'preparedness_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'funding_status',
|
||||
label: 'Qual é o estado dos recursos de financiamento de que precisa?',
|
||||
options: 'funding_status',
|
||||
showWhen: (d) => ['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
showWhen: (d) =>
|
||||
['small_business', 'investor'].includes(String(d.journey_type)),
|
||||
},
|
||||
{
|
||||
key: 'currency',
|
||||
label: 'Moeda',
|
||||
options: 'currency',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'total_investment',
|
||||
label: 'Investimento total',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'own_capital',
|
||||
label: 'Capital próprio',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'domestic_debt',
|
||||
label: 'Financiamento interno',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'foreign_debt',
|
||||
label: 'Financiamento externo',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'grants',
|
||||
label: 'Subvenções',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'secured_amount',
|
||||
label: 'Montante mobilizado',
|
||||
type: 'number',
|
||||
required: (d) => d.purpose !== 'simulate_only',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'sought_amount',
|
||||
label: 'Montante procurado',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'annual_revenue',
|
||||
label: 'Receitas anuais estimadas',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'annual_operating_costs',
|
||||
label: 'Custos operacionais anuais',
|
||||
type: 'number',
|
||||
showWhen: (d) => d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
showWhen: (d) =>
|
||||
d.purpose !== 'simulate_only' || isInvestorProjectJourney(d),
|
||||
},
|
||||
{
|
||||
key: 'expected_profit',
|
||||
@@ -1232,7 +1288,8 @@ export const simulationFieldGroups: Record<
|
||||
label: 'Documentos de suporte que já possui ou pretende preparar',
|
||||
options: 'document_types',
|
||||
multiple: true,
|
||||
showWhen: (d) => d.journey_type === 'investor' && d.purpose === 'simulate_only',
|
||||
showWhen: (d) =>
|
||||
d.journey_type === 'investor' && d.purpose === 'simulate_only',
|
||||
},
|
||||
],
|
||||
review: [
|
||||
|
||||
@@ -102,7 +102,7 @@ function TopBar({
|
||||
}) {
|
||||
return (
|
||||
<header className="sticky top-0 z-30 border-b border-slate-200 bg-white/95 backdrop-blur">
|
||||
<div className="mx-auto flex max-w-6xl items-center justify-between px-5 py-4">
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-5 py-4">
|
||||
<button
|
||||
onClick={() => onNavigate('home')}
|
||||
className="flex items-baseline gap-1 font-black tracking-tight text-slate-900"
|
||||
@@ -205,7 +205,7 @@ function Hero({
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Ex.: agronegócio, Nampula, energia..."
|
||||
className="w-full rounded-lg px-3 py-2.5 text-sm text-slate-900 ring-2 ring-transparent outline-none focus:ring-amber-400"
|
||||
className="w-full rounded-lg bg-white px-3 py-2.5 text-sm text-slate-900 ring-2 ring-transparent outline-none placeholder:text-slate-500 focus:ring-amber-400"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
|
||||
+284
-141
@@ -1,8 +1,8 @@
|
||||
import { Link, router, useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, control, button } from "../management/shared";
|
||||
import { capabilities, purposes, states } from "./labels";
|
||||
import { ProvinceSelect } from "@/components/investment-territory";
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Management, Field, control, button } from '../management/shared';
|
||||
import { capabilities, purposes, states } from './labels';
|
||||
import { ProvinceSelect } from '@/components/investment-territory';
|
||||
|
||||
type Source = {
|
||||
id: string;
|
||||
@@ -25,49 +25,61 @@ type Props = {
|
||||
}[];
|
||||
today: string;
|
||||
};
|
||||
export default function Index({ controls, sources, documents, runs, today }: Props) {
|
||||
const [language, setLanguage] = useState<"pt" | "en">("pt");
|
||||
const t = (pt: string, en: string) => (language === "pt" ? pt : en);
|
||||
export default function Index({
|
||||
controls,
|
||||
sources,
|
||||
documents,
|
||||
runs,
|
||||
today,
|
||||
}: Props) {
|
||||
const [language, setLanguage] = useState<'pt' | 'en'>('pt');
|
||||
const t = (pt: string, en: string) => (language === 'pt' ? pt : en);
|
||||
const query = useForm({
|
||||
capability: "assistant",
|
||||
language: "pt",
|
||||
purpose: "investment_information",
|
||||
query: "",
|
||||
source_id: "",
|
||||
interest_id: "",
|
||||
province: "",
|
||||
maturity_level: "",
|
||||
capability: 'assistant',
|
||||
language: 'pt',
|
||||
purpose: 'investment_information',
|
||||
query: '',
|
||||
source_id: '',
|
||||
interest_id: '',
|
||||
province: '',
|
||||
maturity_level: '',
|
||||
});
|
||||
const upload = useForm<{ file: File | null; authorised: boolean }>({
|
||||
file: null,
|
||||
authorised: false,
|
||||
});
|
||||
const source = useForm({
|
||||
document_id: "",
|
||||
title: "",
|
||||
language: "pt",
|
||||
nature: "pending",
|
||||
source_url: "",
|
||||
source_owner: "",
|
||||
evidence_reference: "",
|
||||
document_id: '',
|
||||
title: '',
|
||||
language: 'pt',
|
||||
nature: 'pending',
|
||||
source_url: '',
|
||||
source_owner: '',
|
||||
evidence_reference: '',
|
||||
source_date: today,
|
||||
valid_until: "",
|
||||
valid_until: '',
|
||||
authorised: false,
|
||||
});
|
||||
const [actionError, setActionError] = useState("");
|
||||
const [actionError, setActionError] = useState('');
|
||||
const post = (url: string, data: Record<string, string | boolean>) => {
|
||||
setActionError("");
|
||||
setActionError('');
|
||||
router.post(url, data, {
|
||||
onError: (errors) => setActionError(Object.values(errors).join(" ")),
|
||||
onError: (errors) =>
|
||||
setActionError(Object.values(errors).join(' ')),
|
||||
});
|
||||
};
|
||||
return (
|
||||
<Management title={t("Assistência, fontes e revisão", "Assistance, sources and review")}>
|
||||
<Management
|
||||
title={t(
|
||||
'Assistência, fontes e revisão',
|
||||
'Assistance, sources and review',
|
||||
)}
|
||||
>
|
||||
<Field label="Idioma / Language">
|
||||
<select
|
||||
className={control}
|
||||
value={language}
|
||||
onChange={(e) => setLanguage(e.target.value as "pt" | "en")}
|
||||
onChange={(e) => setLanguage(e.target.value as 'pt' | 'en')}
|
||||
>
|
||||
<option value="pt">Português</option>
|
||||
<option value="en">English</option>
|
||||
@@ -75,8 +87,8 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
</Field>
|
||||
<p className="rounded border p-4">
|
||||
{t(
|
||||
"Ferramentas assistivas com fontes e regras. Não há modelo generativo activo. Os resultados não são decisões oficiais nem garantias de retorno ou aprovação.",
|
||||
"Assistive tools using sources and rules. No generative model is active. Results are not official decisions or guarantees of return or approval.",
|
||||
'Ferramentas assistivas com fontes e regras. Não há modelo generativo activo. Os resultados não são decisões oficiais nem garantias de retorno ou aprovação.',
|
||||
'Assistive tools using sources and rules. No generative model is active. Results are not official decisions or guarantees of return or approval.',
|
||||
)}
|
||||
</p>
|
||||
<form
|
||||
@@ -86,50 +98,78 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
query.transform((data) => ({
|
||||
...data,
|
||||
language,
|
||||
purpose: purposes[data.capability] ?? "investment_information",
|
||||
purpose:
|
||||
purposes[data.capability] ??
|
||||
'investment_information',
|
||||
}));
|
||||
query.post("/management/ai/runs");
|
||||
query.post('/management/ai/runs');
|
||||
}}
|
||||
>
|
||||
<Field label={t("Capacidade", "Capability")}>
|
||||
<Field label={t('Capacidade', 'Capability')}>
|
||||
<select
|
||||
className={control}
|
||||
value={query.data.capability}
|
||||
onChange={(e) => query.setData("capability", e.target.value)}
|
||||
onChange={(e) =>
|
||||
query.setData('capability', e.target.value)
|
||||
}
|
||||
>
|
||||
{controls.map((c) => (
|
||||
<option key={c.capability} value={c.capability} disabled={c.suspended}>
|
||||
{capabilities[c.capability]?.[language === "pt" ? 0 : 1]}
|
||||
{c.suspended ? t(" (suspensa)", " (suspended)") : ""}
|
||||
<option
|
||||
key={c.capability}
|
||||
value={c.capability}
|
||||
disabled={c.suspended}
|
||||
>
|
||||
{
|
||||
capabilities[c.capability]?.[
|
||||
language === 'pt' ? 0 : 1
|
||||
]
|
||||
}
|
||||
{c.suspended
|
||||
? t(' (suspensa)', ' (suspended)')
|
||||
: ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{["assistant", "search"].includes(query.data.capability) && (
|
||||
<Field label={t("Pergunta ou termos de pesquisa", "Question or search terms")}>
|
||||
{['assistant', 'search'].includes(query.data.capability) && (
|
||||
<Field
|
||||
label={t(
|
||||
'Pergunta ou termos de pesquisa',
|
||||
'Question or search terms',
|
||||
)}
|
||||
>
|
||||
<textarea
|
||||
required
|
||||
maxLength={1000}
|
||||
minLength={3}
|
||||
className={control}
|
||||
value={query.data.query}
|
||||
onChange={(e) => query.setData("query", e.target.value)}
|
||||
onChange={(e) =>
|
||||
query.setData('query', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{["assistant", "search", "summary"].includes(query.data.capability) && (
|
||||
<Field label={t("Fonte autorizada", "Authorised source")}>
|
||||
{['assistant', 'search', 'summary'].includes(
|
||||
query.data.capability,
|
||||
) && (
|
||||
<Field label={t('Fonte autorizada', 'Authorised source')}>
|
||||
<select
|
||||
required={query.data.capability === "summary"}
|
||||
required={query.data.capability === 'summary'}
|
||||
className={control}
|
||||
value={query.data.source_id}
|
||||
onChange={(e) => query.setData("source_id", e.target.value)}
|
||||
onChange={(e) =>
|
||||
query.setData('source_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
{t("Todas as fontes elegíveis", "All eligible sources")}
|
||||
{t(
|
||||
'Todas as fontes elegíveis',
|
||||
'All eligible sources',
|
||||
)}
|
||||
</option>
|
||||
{sources
|
||||
.filter((s) => s.status === "approved")
|
||||
.filter((s) => s.status === 'approved')
|
||||
.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.title}
|
||||
@@ -138,11 +178,11 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{query.data.capability === "classify" && (
|
||||
{query.data.capability === 'classify' && (
|
||||
<Field
|
||||
label={t(
|
||||
"Número interno do pedido (requer consentimento específico)",
|
||||
"Internal request number (specific consent required)",
|
||||
'Número interno do pedido (requer consentimento específico)',
|
||||
'Internal request number (specific consent required)',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
@@ -151,28 +191,55 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
min={1}
|
||||
className={control}
|
||||
value={query.data.interest_id}
|
||||
onChange={(e) => query.setData("interest_id", e.target.value)}
|
||||
onChange={(e) =>
|
||||
query.setData('interest_id', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{query.data.capability === "recommend" && (
|
||||
{query.data.capability === 'recommend' && (
|
||||
<>
|
||||
<Field label={t("Província declarada", "Declared province")}>
|
||||
<Field
|
||||
label={t(
|
||||
'Província declarada',
|
||||
'Declared province',
|
||||
)}
|
||||
>
|
||||
<ProvinceSelect
|
||||
value={query.data.province}
|
||||
onChange={(province) => query.setData("province", province)}
|
||||
onChange={(province) =>
|
||||
query.setData('province', province)
|
||||
}
|
||||
className={control}
|
||||
placeholder={t("Seleccione uma província", "Select a province")}
|
||||
label={t("Província declarada", "Declared province")}
|
||||
placeholder={t(
|
||||
'Seleccione uma província',
|
||||
'Select a province',
|
||||
)}
|
||||
label={t(
|
||||
'Província declarada',
|
||||
'Declared province',
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("Maturidade pretendida", "Desired maturity")}>
|
||||
<Field
|
||||
label={t(
|
||||
'Maturidade pretendida',
|
||||
'Desired maturity',
|
||||
)}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={query.data.maturity_level}
|
||||
onChange={(e) => query.setData("maturity_level", e.target.value)}
|
||||
onChange={(e) =>
|
||||
query.setData(
|
||||
'maturity_level',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">{t("Não indicada", "Not specified")}</option>
|
||||
<option value="">
|
||||
{t('Não indicada', 'Not specified')}
|
||||
</option>
|
||||
{[1, 2, 3, 4, 5, 6].map((n) => (
|
||||
<option key={n}>{n}</option>
|
||||
))}
|
||||
@@ -189,17 +256,19 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
<button
|
||||
disabled={
|
||||
query.processing ||
|
||||
controls.find((c) => c.capability === query.data.capability)?.suspended
|
||||
controls.find(
|
||||
(c) => c.capability === query.data.capability,
|
||||
)?.suspended
|
||||
}
|
||||
className={button}
|
||||
>
|
||||
{t("Consultar", "Run assistance")}
|
||||
{t('Consultar', 'Run assistance')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{t("Suspensão imediata", "Immediate suspension")}
|
||||
{t('Suspensão imediata', 'Immediate suspension')}
|
||||
</h2>
|
||||
{actionError && <p role="alert">{actionError}</p>}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
@@ -208,75 +277,112 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
className={button}
|
||||
key={c.capability}
|
||||
onClick={() =>
|
||||
post(`/management/ai/controls/${c.capability}`, {
|
||||
suspended: !c.suspended,
|
||||
})
|
||||
post(
|
||||
`/management/ai/controls/${c.capability}`,
|
||||
{
|
||||
suspended: !c.suspended,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
{t(
|
||||
c.suspended ? "Retomar" : "Suspender",
|
||||
c.suspended ? "Resume" : "Suspend",
|
||||
)}{" "}
|
||||
· {capabilities[c.capability]?.[language === "pt" ? 0 : 1]}
|
||||
c.suspended ? 'Retomar' : 'Suspender',
|
||||
c.suspended ? 'Resume' : 'Suspend',
|
||||
)}{' '}
|
||||
·{' '}
|
||||
{
|
||||
capabilities[c.capability]?.[
|
||||
language === 'pt' ? 0 : 1
|
||||
]
|
||||
}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{t("Resultados recentes e revisão humana", "Recent results and human review")}
|
||||
{t(
|
||||
'Resultados recentes e revisão humana',
|
||||
'Recent results and human review',
|
||||
)}
|
||||
</h2>
|
||||
{runs.length === 0 && <p>{t("Ainda sem consultas.", "No runs yet.")}</p>}
|
||||
{runs.length === 0 && (
|
||||
<p>{t('Ainda sem consultas.', 'No runs yet.')}</p>
|
||||
)}
|
||||
{runs.map((r) => (
|
||||
<p key={r.id}>
|
||||
<Link className="underline" href={`/management/ai/runs/${r.id}`}>
|
||||
{capabilities[r.capability]?.[language === "pt" ? 0 : 1]} ·{" "}
|
||||
{r.created_at}
|
||||
</Link>{" "}
|
||||
— {language === "pt" ? states[r.review_status] : r.review_status}
|
||||
{r.review_requested && t(" · revisão solicitada", " · review requested")}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/ai/runs/${r.id}`}
|
||||
>
|
||||
{
|
||||
capabilities[r.capability]?.[
|
||||
language === 'pt' ? 0 : 1
|
||||
]
|
||||
}{' '}
|
||||
· {r.created_at}
|
||||
</Link>{' '}
|
||||
—{' '}
|
||||
{language === 'pt'
|
||||
? states[r.review_status]
|
||||
: r.review_status}
|
||||
{r.review_requested &&
|
||||
t(' · revisão solicitada', ' · review requested')}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{t("Fontes documentais", "Document sources")}
|
||||
{t('Fontes documentais', 'Document sources')}
|
||||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
"Apenas ficheiros de texto UTF-8 do cadastro documental privado, activos e não confidenciais. A autorização de uso deve ser confirmada por outra pessoa.",
|
||||
"Only active, non-confidential UTF-8 text files from the private document registry. Another person must confirm permission to use the source.",
|
||||
'Apenas ficheiros de texto UTF-8 do cadastro documental privado, activos e não confidenciais. A autorização de uso deve ser confirmada por outra pessoa.',
|
||||
'Only active, non-confidential UTF-8 text files from the private document registry. Another person must confirm permission to use the source.',
|
||||
)}
|
||||
</p>
|
||||
{sources.map((s) => (
|
||||
<article className="space-y-2 rounded border p-3" key={s.id}>
|
||||
<article
|
||||
className="space-y-2 rounded border p-3"
|
||||
key={s.id}
|
||||
>
|
||||
<p>
|
||||
{s.title} · {s.language.toUpperCase()} ·{" "}
|
||||
{language === "pt" ? states[s.status] : s.status} · {s.valid_until}
|
||||
{s.title} · {s.language.toUpperCase()} ·{' '}
|
||||
{language === 'pt' ? states[s.status] : s.status} ·{' '}
|
||||
{s.valid_until}
|
||||
</p>
|
||||
<p>{language === "pt" ? states[s.nature] : s.nature}</p>
|
||||
<p>{language === 'pt' ? states[s.nature] : s.nature}</p>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
post(`/management/ai/sources/${s.id}/review`, {
|
||||
status: "approved",
|
||||
expected_status: s.status,
|
||||
})
|
||||
post(
|
||||
`/management/ai/sources/${s.id}/review`,
|
||||
{
|
||||
status: 'approved',
|
||||
expected_status: s.status,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("Confirmar autorização", "Confirm authorisation")}
|
||||
{t(
|
||||
'Confirmar autorização',
|
||||
'Confirm authorisation',
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
post(`/management/ai/sources/${s.id}/review`, {
|
||||
status: "revoked",
|
||||
expected_status: s.status,
|
||||
})
|
||||
post(
|
||||
`/management/ai/sources/${s.id}/review`,
|
||||
{
|
||||
status: 'revoked',
|
||||
expected_status: s.status,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("Revogar", "Revoke")}
|
||||
{t('Revogar', 'Revoke')}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
@@ -285,15 +391,15 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
<details className="rounded border p-4">
|
||||
<summary>
|
||||
{t(
|
||||
"Adicionar documento de texto autorizado",
|
||||
"Add an authorised text document",
|
||||
'Adicionar documento de texto autorizado',
|
||||
'Add an authorised text document',
|
||||
)}
|
||||
</summary>
|
||||
<form
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
upload.post("/management/ai/documents", {
|
||||
upload.post('/management/ai/documents', {
|
||||
forceFormData: true,
|
||||
onSuccess: () => upload.reset(),
|
||||
});
|
||||
@@ -301,8 +407,8 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
>
|
||||
<Field
|
||||
label={t(
|
||||
"Ficheiro .txt UTF-8 (até 195 KiB)",
|
||||
"UTF-8 .txt file (up to 195 KiB)",
|
||||
'Ficheiro .txt UTF-8 (até 195 KiB)',
|
||||
'UTF-8 .txt file (up to 195 KiB)',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
@@ -310,7 +416,12 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
type="file"
|
||||
accept=".txt,text/plain"
|
||||
className={control}
|
||||
onChange={(e) => upload.setData("file", e.target.files?.[0] ?? null)}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<label className="flex gap-2">
|
||||
@@ -318,11 +429,13 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
required
|
||||
type="checkbox"
|
||||
checked={upload.data.authorised}
|
||||
onChange={(e) => upload.setData("authorised", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
upload.setData('authorised', e.target.checked)
|
||||
}
|
||||
/>
|
||||
{t(
|
||||
"Tenho autorização e confirmei a ausência de dados confidenciais ou pessoais desnecessários.",
|
||||
"I am authorised and have confirmed there is no confidential or unnecessary personal data.",
|
||||
'Tenho autorização e confirmei a ausência de dados confidenciais ou pessoais desnecessários.',
|
||||
'I am authorised and have confirmed there is no confidential or unnecessary personal data.',
|
||||
)}
|
||||
</label>
|
||||
{Object.entries(upload.errors).map(([key, value]) => (
|
||||
@@ -331,32 +444,38 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={upload.processing}>
|
||||
{t("Guardar documento", "Save document")}
|
||||
{t('Guardar documento', 'Save document')}
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
<details className="rounded border p-4">
|
||||
<summary>
|
||||
{t(
|
||||
"Registar fonte existente para revisão",
|
||||
"Register an existing source for review",
|
||||
'Registar fonte existente para revisão',
|
||||
'Register an existing source for review',
|
||||
)}
|
||||
</summary>
|
||||
<form
|
||||
className="mt-4 grid gap-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
source.post("/management/ai/sources", { onSuccess: () => source.reset() });
|
||||
source.post('/management/ai/sources', {
|
||||
onSuccess: () => source.reset(),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field label={t("Documento", "Document")}>
|
||||
<Field label={t('Documento', 'Document')}>
|
||||
<select
|
||||
required
|
||||
className={control}
|
||||
value={source.data.document_id}
|
||||
onChange={(e) => source.setData("document_id", e.target.value)}
|
||||
onChange={(e) =>
|
||||
source.setData('document_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">{t("Seleccionar", "Select")}</option>
|
||||
<option value="">
|
||||
{t('Seleccionar', 'Select')}
|
||||
</option>
|
||||
{documents.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.file_name}
|
||||
@@ -366,64 +485,84 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
"title",
|
||||
"source_url",
|
||||
"source_owner",
|
||||
"evidence_reference",
|
||||
"source_date",
|
||||
"valid_until",
|
||||
'title',
|
||||
'source_url',
|
||||
'source_owner',
|
||||
'evidence_reference',
|
||||
'source_date',
|
||||
'valid_until',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
title: t("Título", "Title"),
|
||||
source_url: t("Fonte HTTPS", "HTTPS source"),
|
||||
source_owner: t("Entidade proprietária", "Source owner"),
|
||||
evidence_reference: t(
|
||||
"Referência da evidência e autorização",
|
||||
"Evidence and authorisation reference",
|
||||
title: t('Título', 'Title'),
|
||||
source_url: t(
|
||||
'Fonte HTTPS',
|
||||
'HTTPS source',
|
||||
),
|
||||
source_date: t("Data da fonte", "Source date"),
|
||||
valid_until: t("Válida até", "Valid until"),
|
||||
source_owner: t(
|
||||
'Entidade proprietária',
|
||||
'Source owner',
|
||||
),
|
||||
evidence_reference: t(
|
||||
'Referência da evidência e autorização',
|
||||
'Evidence and authorisation reference',
|
||||
),
|
||||
source_date: t(
|
||||
'Data da fonte',
|
||||
'Source date',
|
||||
),
|
||||
valid_until: t('Válida até', 'Valid until'),
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<input
|
||||
required
|
||||
type={
|
||||
["source_date", "valid_until"].includes(key)
|
||||
? "date"
|
||||
: key === "source_url"
|
||||
? "url"
|
||||
: "text"
|
||||
['source_date', 'valid_until'].includes(key)
|
||||
? 'date'
|
||||
: key === 'source_url'
|
||||
? 'url'
|
||||
: 'text'
|
||||
}
|
||||
className={control}
|
||||
value={source.data[key]}
|
||||
onChange={(e) => source.setData(key, e.target.value)}
|
||||
onChange={(e) =>
|
||||
source.setData(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label={t("Idioma da fonte", "Source language")}>
|
||||
<Field label={t('Idioma da fonte', 'Source language')}>
|
||||
<select
|
||||
className={control}
|
||||
value={source.data.language}
|
||||
onChange={(e) => source.setData("language", e.target.value)}
|
||||
onChange={(e) =>
|
||||
source.setData('language', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="pt">Português</option>
|
||||
<option value="en">English</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label={t("Natureza declarada", "Declared nature")}>
|
||||
<Field label={t('Natureza declarada', 'Declared nature')}>
|
||||
<select
|
||||
className={control}
|
||||
value={source.data.nature}
|
||||
onChange={(e) => source.setData("nature", e.target.value)}
|
||||
onChange={(e) =>
|
||||
source.setData('nature', e.target.value)
|
||||
}
|
||||
>
|
||||
{["pending", "official", "historical", "illustrative"].map((n) => (
|
||||
{[
|
||||
'pending',
|
||||
'official',
|
||||
'historical',
|
||||
'illustrative',
|
||||
].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{language === "pt" ? states[n] : n}
|
||||
{language === 'pt' ? states[n] : n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -433,11 +572,13 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
required
|
||||
type="checkbox"
|
||||
checked={source.data.authorised}
|
||||
onChange={(e) => source.setData("authorised", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
source.setData('authorised', e.target.checked)
|
||||
}
|
||||
/>
|
||||
{t(
|
||||
"Confirmo autorização para consulta interna e ausência de dados confidenciais ou pessoais desnecessários.",
|
||||
"I confirm authorisation for internal use and the absence of confidential or unnecessary personal data.",
|
||||
'Confirmo autorização para consulta interna e ausência de dados confidenciais ou pessoais desnecessários.',
|
||||
'I confirm authorisation for internal use and the absence of confidential or unnecessary personal data.',
|
||||
)}
|
||||
</label>
|
||||
<div>
|
||||
@@ -447,10 +588,12 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
disabled={source.processing || documents.length === 0}
|
||||
disabled={
|
||||
source.processing || documents.length === 0
|
||||
}
|
||||
className={button}
|
||||
>
|
||||
{t("Submeter fonte", "Submit source")}
|
||||
{t('Submeter fonte', 'Submit source')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
export const capabilities: Record<string, [string, string]> = {
|
||||
assistant: ["Assistente com fontes", "Evidence assistant"],
|
||||
search: ["Pesquisa documental", "Document search"],
|
||||
recommend: ["Correspondência de oportunidades", "Opportunity matching"],
|
||||
classify: ["Triagem de pedidos", "Interest triage"],
|
||||
quality: ["Qualidade dos dados", "Data quality"],
|
||||
sla: ["Prazos e tarefas", "Deadlines and tasks"],
|
||||
summary: ["Excertos de documentos", "Document excerpts"],
|
||||
assistant: ['Assistente com fontes', 'Evidence assistant'],
|
||||
search: ['Pesquisa documental', 'Document search'],
|
||||
recommend: ['Correspondência de oportunidades', 'Opportunity matching'],
|
||||
classify: ['Triagem de pedidos', 'Interest triage'],
|
||||
quality: ['Qualidade dos dados', 'Data quality'],
|
||||
sla: ['Prazos e tarefas', 'Deadlines and tasks'],
|
||||
summary: ['Excertos de documentos', 'Document excerpts'],
|
||||
};
|
||||
export const purposes: Record<string, string> = {
|
||||
classify: "interest_triage",
|
||||
quality: "data_quality",
|
||||
sla: "execution_monitoring",
|
||||
classify: 'interest_triage',
|
||||
quality: 'data_quality',
|
||||
sla: 'execution_monitoring',
|
||||
};
|
||||
export const states: Record<string, string> = {
|
||||
pending: "Pendente",
|
||||
approved: "Autorizada para consulta interna",
|
||||
revoked: "Revogada",
|
||||
accepted: "Aceite na revisão interna",
|
||||
rejected: "Rejeitado",
|
||||
official: "Oficial — natureza declarada da fonte",
|
||||
historical: "Histórica",
|
||||
illustrative: "Ilustrativa",
|
||||
pending: 'Pendente',
|
||||
approved: 'Autorizada para consulta interna',
|
||||
revoked: 'Revogada',
|
||||
accepted: 'Aceite na revisão interna',
|
||||
rejected: 'Rejeitado',
|
||||
official: 'Oficial — natureza declarada da fonte',
|
||||
historical: 'Histórica',
|
||||
illustrative: 'Ilustrativa',
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Management, Field, control, button } from "../management/shared";
|
||||
import { capabilities, states } from "./labels";
|
||||
import { displayValue } from '@/lib/display-value';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Management, Field, control, button } from '../management/shared';
|
||||
import { capabilities, states } from './labels';
|
||||
type Item = {
|
||||
[key: string]: unknown;
|
||||
content?: string;
|
||||
@@ -36,43 +37,47 @@ type Props = {
|
||||
result: Result | null;
|
||||
unavailable: boolean;
|
||||
};
|
||||
const safeLink = (value: string) => /^https:\/\//i.test(value) || /^\/(?!\/)/.test(value);
|
||||
const safeLink = (value: string) =>
|
||||
/^https:\/\//i.test(value) || /^\/(?!\/)/.test(value);
|
||||
export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
const en = result?.language === "en";
|
||||
const en = result?.language === 'en';
|
||||
const t = (pt: string, english: string) => (en ? english : pt);
|
||||
const feedback = useForm({ rating: "helpful", review_requested: true });
|
||||
const review = useForm({ status: "accepted", version_no: run.version_no });
|
||||
const feedback = useForm({ rating: 'helpful', review_requested: true });
|
||||
const review = useForm({ status: 'accepted', version_no: run.version_no });
|
||||
return (
|
||||
<Management
|
||||
title={
|
||||
capabilities[run.capability]?.[en ? 1 : 0] ??
|
||||
t("Resultado assistivo", "Assistive result")
|
||||
t('Resultado assistivo', 'Assistive result')
|
||||
}
|
||||
>
|
||||
<Link className="underline" href="/management/ai">
|
||||
{t("Voltar às consultas e fontes", "Back to assistance and sources")}
|
||||
{t(
|
||||
'Voltar às consultas e fontes',
|
||||
'Back to assistance and sources',
|
||||
)}
|
||||
</Link>
|
||||
<p>
|
||||
{t(
|
||||
"Resultado assistivo, sujeito a revisão. Não constitui decisão oficial ou garantia de retorno ou aprovação.",
|
||||
"Assistive result requiring review. Not an official decision or a guarantee of return or approval.",
|
||||
'Resultado assistivo, sujeito a revisão. Não constitui decisão oficial ou garantia de retorno ou aprovação.',
|
||||
'Assistive result requiring review. Not an official decision or a guarantee of return or approval.',
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
{t(
|
||||
"Confiança não calibrada. Não foram produzidas previsões ou afirmações por um modelo generativo.",
|
||||
"Confidence is not calibrated. No forecasts or claims were generated by a generative model.",
|
||||
'Confiança não calibrada. Não foram produzidas previsões ou afirmações por um modelo generativo.',
|
||||
'Confidence is not calibrated. No forecasts or claims were generated by a generative model.',
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
{t("Estado da revisão", "Review status")}:{" "}
|
||||
{t('Estado da revisão', 'Review status')}:{' '}
|
||||
{en ? run.review_status : states[run.review_status]}
|
||||
</p>
|
||||
{unavailable ? (
|
||||
<p role="alert">
|
||||
{t(
|
||||
"Conteúdo indisponível: capacidade suspensa, fonte alterada, expirada, revogada ou sem consentimento vigente.",
|
||||
"Content unavailable: suspended capability, changed, expired or revoked source, or withdrawn consent.",
|
||||
'Conteúdo indisponível: capacidade suspensa, fonte alterada, expirada, revogada ou sem consentimento vigente.',
|
||||
'Content unavailable: suspended capability, changed, expired or revoked source, or withdrawn consent.',
|
||||
)}
|
||||
</p>
|
||||
) : (
|
||||
@@ -80,73 +85,87 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
{result?.items.length === 0 && (
|
||||
<p className="rounded border p-4">
|
||||
{t(
|
||||
"Não há evidência ou correspondências suficientes nesta consulta. Não é possível formular uma conclusão. Pode solicitar revisão humana abaixo.",
|
||||
"No sufficient evidence or matches for this query. A conclusion cannot be provided. You may request human review below.",
|
||||
'Não há evidência ou correspondências suficientes nesta consulta. Não é possível formular uma conclusão. Pode solicitar revisão humana abaixo.',
|
||||
'No sufficient evidence or matches for this query. A conclusion cannot be provided. You may request human review below.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{run.mode === "extractive_preview" && (
|
||||
{run.mode === 'extractive_preview' && (
|
||||
<p>
|
||||
{t(
|
||||
"Pré-visualização dos primeiros excertos; não é um resumo completo do documento.",
|
||||
"Preview of the first excerpts; not a complete document summary.",
|
||||
'Pré-visualização dos primeiros excertos; não é um resumo completo do documento.',
|
||||
'Preview of the first excerpts; not a complete document summary.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{result?.items.map((item, index) => (
|
||||
<article className="space-y-3 rounded border p-4" key={index}>
|
||||
<article
|
||||
className="space-y-3 rounded border p-4"
|
||||
key={index}
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{item.title ??
|
||||
item.rule?.replaceAll("_", " ") ??
|
||||
`${t("Resultado", "Result")} ${index + 1}`}
|
||||
item.rule?.replaceAll('_', ' ') ??
|
||||
`${t('Resultado', 'Result')} ${index + 1}`}
|
||||
</h2>
|
||||
{item.content && (
|
||||
<blockquote className="whitespace-pre-wrap border-l-4 pl-4">
|
||||
<blockquote className="border-l-4 pl-4 whitespace-pre-wrap">
|
||||
{item.content}
|
||||
</blockquote>
|
||||
)}
|
||||
{item.source_url && safeLink(item.source_url) && (
|
||||
<a className="underline" href={item.source_url} rel="noreferrer">
|
||||
<a
|
||||
className="underline"
|
||||
href={item.source_url}
|
||||
rel="noreferrer"
|
||||
>
|
||||
{t(
|
||||
"Consultar fonte / registo original",
|
||||
"View source / original record",
|
||||
'Consultar fonte / registo original',
|
||||
'View source / original record',
|
||||
)}
|
||||
</a>
|
||||
)}
|
||||
{item.source_date && (
|
||||
<p>
|
||||
{t("Data da fonte", "Source date")}: {item.source_date}
|
||||
{t('Data da fonte', 'Source date')}:{' '}
|
||||
{item.source_date}
|
||||
</p>
|
||||
)}
|
||||
{item.nature && (
|
||||
<p>
|
||||
{t("Natureza declarada", "Declared nature")}:{" "}
|
||||
{en ? item.nature : states[item.nature]}
|
||||
{t('Natureza declarada', 'Declared nature')}
|
||||
: {en ? item.nature : states[item.nature]}
|
||||
</p>
|
||||
)}
|
||||
{item.score !== undefined && (
|
||||
<p>
|
||||
{t(
|
||||
"Filtros declarados correspondentes",
|
||||
"Matching declared filters",
|
||||
'Filtros declarados correspondentes',
|
||||
'Matching declared filters',
|
||||
)}
|
||||
: {item.score}/{item.score_max}.{" "}
|
||||
: {item.score}/{item.score_max}.{' '}
|
||||
{t(
|
||||
"Esta pontuação não mede rentabilidade ou probabilidade de aprovação.",
|
||||
"This score does not measure profitability or likelihood of approval.",
|
||||
'Esta pontuação não mede rentabilidade ou probabilidade de aprovação.',
|
||||
'This score does not measure profitability or likelihood of approval.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{item.favourable_factors && (
|
||||
<p>
|
||||
{t("Factores correspondentes", "Matching factors")}:{" "}
|
||||
{item.favourable_factors.join(", ")}
|
||||
{t(
|
||||
'Factores correspondentes',
|
||||
'Matching factors',
|
||||
)}
|
||||
: {item.favourable_factors.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{item.missing_data && (
|
||||
<p>
|
||||
{t("Dados ainda necessários", "Missing information")}:{" "}
|
||||
{item.missing_data.join(", ")}
|
||||
{t(
|
||||
'Dados ainda necessários',
|
||||
'Missing information',
|
||||
)}
|
||||
: {item.missing_data.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{!item.content && (
|
||||
@@ -155,28 +174,31 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
.filter(
|
||||
([key]) =>
|
||||
![
|
||||
"title",
|
||||
"source_url",
|
||||
"source_date",
|
||||
"score",
|
||||
"score_max",
|
||||
"score_meaning",
|
||||
"favourable_factors",
|
||||
"missing_data",
|
||||
"semantic_similarity",
|
||||
'title',
|
||||
'source_url',
|
||||
'source_date',
|
||||
'score',
|
||||
'score_max',
|
||||
'score_meaning',
|
||||
'favourable_factors',
|
||||
'missing_data',
|
||||
'semantic_similarity',
|
||||
].includes(key),
|
||||
)
|
||||
.map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-medium">
|
||||
{key.replaceAll("_", " ")}
|
||||
{key.replaceAll('_', ' ')}
|
||||
</dt>
|
||||
<dd>
|
||||
{Array.isArray(value)
|
||||
? value.join(", ")
|
||||
? value.join(', ')
|
||||
: value === null
|
||||
? t("Não determinado", "Undetermined")
|
||||
: String(value)}
|
||||
? t(
|
||||
'Não determinado',
|
||||
'Undetermined',
|
||||
)
|
||||
: displayValue(value)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -187,8 +209,9 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
</>
|
||||
)}
|
||||
<p>
|
||||
{t("Regras", "Rules")}: {run.rules_version} · {t("Calculado em", "Computed at")}:{" "}
|
||||
{result?.computed_at ?? "—"} · {run.latency_ms} ms
|
||||
{t('Regras', 'Rules')}: {run.rules_version} ·{' '}
|
||||
{t('Calculado em', 'Computed at')}: {result?.computed_at ?? '—'}{' '}
|
||||
· {run.latency_ms} ms
|
||||
</p>
|
||||
<form
|
||||
className="space-y-3 rounded border p-4"
|
||||
@@ -198,20 +221,27 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{t("Feedback e atendimento humano", "Feedback and human review")}
|
||||
{t(
|
||||
'Feedback e atendimento humano',
|
||||
'Feedback and human review',
|
||||
)}
|
||||
</h2>
|
||||
<Field label={t("Avaliação", "Rating")}>
|
||||
<Field label={t('Avaliação', 'Rating')}>
|
||||
<select
|
||||
className={control}
|
||||
value={feedback.data.rating}
|
||||
onChange={(e) => feedback.setData("rating", e.target.value)}
|
||||
onChange={(e) =>
|
||||
feedback.setData('rating', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="helpful">{t("Útil", "Helpful")}</option>
|
||||
<option value="unhelpful">{t("Pouco útil", "Unhelpful")}</option>
|
||||
<option value="helpful">{t('Útil', 'Helpful')}</option>
|
||||
<option value="unhelpful">
|
||||
{t('Pouco útil', 'Unhelpful')}
|
||||
</option>
|
||||
<option value="unsafe">
|
||||
{t(
|
||||
"Risco detectado — suspender capacidade",
|
||||
"Risk detected — suspend capability",
|
||||
'Risco detectado — suspender capacidade',
|
||||
'Risk detected — suspend capability',
|
||||
)}
|
||||
</option>
|
||||
</select>
|
||||
@@ -220,11 +250,16 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={feedback.data.review_requested}
|
||||
onChange={(e) => feedback.setData("review_requested", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
feedback.setData(
|
||||
'review_requested',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
{t(
|
||||
"Solicitar revisão por uma pessoa autorizada",
|
||||
"Request review by an authorised person",
|
||||
'Solicitar revisão por uma pessoa autorizada',
|
||||
'Request review by an authorised person',
|
||||
)}
|
||||
</label>
|
||||
{Object.entries(feedback.errors).map(([k, v]) => (
|
||||
@@ -233,36 +268,46 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
</p>
|
||||
))}
|
||||
<button disabled={feedback.processing} className={button}>
|
||||
{t("Enviar feedback", "Submit feedback")}
|
||||
{t('Enviar feedback', 'Submit feedback')}
|
||||
</button>
|
||||
</form>
|
||||
<form
|
||||
className="space-y-3 rounded border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
review.transform((data) => ({ ...data, version_no: run.version_no }));
|
||||
review.transform((data) => ({
|
||||
...data,
|
||||
version_no: run.version_no,
|
||||
}));
|
||||
review.post(`/management/ai/runs/${run.id}/review`);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{t("Revisão independente", "Independent review")}
|
||||
{t('Revisão independente', 'Independent review')}
|
||||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
"Uma pessoa diferente deve rever o resultado. Aceitar não altera registos oficiais nem envia conteúdo ao CRM.",
|
||||
"A different person must review the result. Acceptance does not change official records or send content to CRM.",
|
||||
'Uma pessoa diferente deve rever o resultado. Aceitar não altera registos oficiais nem envia conteúdo ao CRM.',
|
||||
'A different person must review the result. Acceptance does not change official records or send content to CRM.',
|
||||
)}
|
||||
</p>
|
||||
<Field label={t("Parecer interno", "Internal review")}>
|
||||
<Field label={t('Parecer interno', 'Internal review')}>
|
||||
<select
|
||||
className={control}
|
||||
value={review.data.status}
|
||||
onChange={(e) => review.setData("status", e.target.value)}
|
||||
onChange={(e) =>
|
||||
review.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="accepted">
|
||||
{t("Aceitar para análise interna", "Accept for internal analysis")}
|
||||
{t(
|
||||
'Aceitar para análise interna',
|
||||
'Accept for internal analysis',
|
||||
)}
|
||||
</option>
|
||||
<option value="rejected">
|
||||
{t('Rejeitar', 'Reject')}
|
||||
</option>
|
||||
<option value="rejected">{t("Rejeitar", "Reject")}</option>
|
||||
</select>
|
||||
</Field>
|
||||
{Object.entries(review.errors).map(([k, v]) => (
|
||||
@@ -271,7 +316,7 @@ export default function ResultPage({ run, result, unavailable }: Props) {
|
||||
</p>
|
||||
))}
|
||||
<button disabled={review.processing} className={button}>
|
||||
{t("Registar revisão", "Record review")}
|
||||
{t('Registar revisão', 'Record review')}
|
||||
</button>
|
||||
</form>
|
||||
</Management>
|
||||
|
||||
@@ -27,6 +27,10 @@ export default function Leads({
|
||||
<Link className="underline" href="/management/interests">
|
||||
Consultar pedidos recebidos
|
||||
</Link>
|
||||
<Link className="underline" href="/balcao-virtual/painel">
|
||||
Acompanhamento do investidor — pedidos, tarefas e respostas do
|
||||
Balcão
|
||||
</Link>
|
||||
<form
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(e) => {
|
||||
|
||||
@@ -0,0 +1,626 @@
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
InvestorGuidance,
|
||||
type Guidance,
|
||||
} from '@/components/investor-guidance';
|
||||
import {
|
||||
DocumentReview,
|
||||
type DeskDocument,
|
||||
} from '@/components/desk-internal-operations';
|
||||
|
||||
type Stage = {
|
||||
title: string;
|
||||
requirements: string;
|
||||
status: string;
|
||||
entity: string;
|
||||
dependencies: string[];
|
||||
evidence: string | null;
|
||||
};
|
||||
|
||||
function LinkReview({
|
||||
link,
|
||||
}: {
|
||||
link: { id: string; version: number; url: string; contact: string | null };
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: link.version,
|
||||
available: false,
|
||||
evidence: '',
|
||||
contact: link.contact ?? '',
|
||||
});
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/management/balcao/ligacoes/${link.id}/conferencia`);
|
||||
}}
|
||||
className="space-y-2 border p-3"
|
||||
>
|
||||
<p>
|
||||
Conferência manual de disponibilidade: {link.url}. Não envia
|
||||
dados do dossier nem integra sistemas externos.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.available}
|
||||
onChange={(e) =>
|
||||
form.setData('available', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Verifiquei que a ligação está disponível
|
||||
</label>
|
||||
<label>
|
||||
Evidência e data da consulta
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={10}
|
||||
value={form.data.evidence}
|
||||
onChange={(e) => form.setData('evidence', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Contacto alternativo com fonte
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.contact}
|
||||
onChange={(e) => form.setData('contact', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Registar a minha conferência da ligação
|
||||
</button>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
<p key={key} role="alert">
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
type Event = {
|
||||
id: string;
|
||||
action: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
payload: Record<string, unknown>;
|
||||
};
|
||||
export default function Case({
|
||||
case: dossier,
|
||||
canWrite,
|
||||
manager,
|
||||
requests,
|
||||
services,
|
||||
documents,
|
||||
workflow,
|
||||
stepStates,
|
||||
states,
|
||||
guidance,
|
||||
events,
|
||||
links,
|
||||
legacyRequest,
|
||||
}: {
|
||||
case: {
|
||||
id: string;
|
||||
title: string;
|
||||
version: number;
|
||||
workflow: Record<string, Stage>;
|
||||
investor_id?: string;
|
||||
project_id?: string;
|
||||
journey_id?: string;
|
||||
};
|
||||
canWrite: boolean;
|
||||
manager: boolean;
|
||||
requests: { id: string; status: string; protocol: string | null }[];
|
||||
services: { id: string; title: string; version: number }[];
|
||||
documents: DeskDocument[];
|
||||
links: {
|
||||
id: string;
|
||||
entity: string;
|
||||
purpose: string;
|
||||
contact: string | null;
|
||||
status: string;
|
||||
verified_at: string | null;
|
||||
version: number;
|
||||
url: string;
|
||||
monitor: { available: boolean; reason: string; contact: string };
|
||||
}[];
|
||||
legacyRequest: {
|
||||
id: number;
|
||||
reference: string;
|
||||
status: string;
|
||||
next_action: string | null;
|
||||
next_action_due_at: string | null;
|
||||
responsible_name: string | null;
|
||||
} | null;
|
||||
workflow?: Record<string, Stage>;
|
||||
stepStates: Record<string, string>;
|
||||
states: Record<string, string>;
|
||||
guidance: Guidance | null;
|
||||
events: Event[];
|
||||
}) {
|
||||
const actor = usePage<{ auth: { user: { id: number } } }>().props.auth.user;
|
||||
const requestForm = useForm({
|
||||
service_version_id: services[0]?.id ?? '',
|
||||
client_key: crypto.randomUUID(),
|
||||
});
|
||||
const stageForm = useForm({
|
||||
version: dossier.version,
|
||||
stage: 'E0',
|
||||
status: 'preparing',
|
||||
reason: '',
|
||||
evidence: '',
|
||||
document_id: '',
|
||||
valid_until: '',
|
||||
exception: false,
|
||||
});
|
||||
const upload = useForm<{
|
||||
version: number;
|
||||
file: File | null;
|
||||
document_id: string;
|
||||
category: string;
|
||||
source_reference: string;
|
||||
consent: boolean;
|
||||
}>({
|
||||
version: dossier.version,
|
||||
file: null,
|
||||
document_id: '',
|
||||
category: 'project_evidence',
|
||||
source_reference: '',
|
||||
consent: false,
|
||||
});
|
||||
return (
|
||||
<Frame title={dossier.title}>
|
||||
{legacyRequest && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Pedido anterior associado — sem nova submissão
|
||||
</h2>
|
||||
<p>
|
||||
{legacyRequest.reference} · {legacyRequest.status} ·
|
||||
Responsável:{' '}
|
||||
{legacyRequest.responsible_name ?? 'Por atribuir'}
|
||||
</p>
|
||||
<p>
|
||||
{legacyRequest.next_action ??
|
||||
'A aguardar orientação do responsável'}{' '}
|
||||
· Prazo interno:{' '}
|
||||
{legacyRequest.next_action_due_at ?? 'Não definido'}
|
||||
</p>
|
||||
{manager && (
|
||||
<Link
|
||||
href={`/management/interests/${legacyRequest.id}`}
|
||||
className="underline"
|
||||
>
|
||||
Continuar no registo original do pedido e CRM
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<Link href="/balcao-virtual/painel" className="underline">
|
||||
Voltar ao Balcão Virtual
|
||||
</Link>
|
||||
<p>
|
||||
Um dossier, os mesmos pedidos, documentos, conversas e tarefas.
|
||||
Projecto existente:{' '}
|
||||
{dossier.project_id ? 'associado' : 'ainda não associado'} ·
|
||||
Investidor:{' '}
|
||||
{dossier.investor_id
|
||||
? 'conta existente associada'
|
||||
: 'por associar'}
|
||||
.
|
||||
</p>
|
||||
{guidance ? (
|
||||
<InvestorGuidance
|
||||
caseId={dossier.id}
|
||||
guidance={guidance}
|
||||
manager={manager}
|
||||
actorId={actor.id}
|
||||
requests={requests}
|
||||
/>
|
||||
) : (
|
||||
<p>A extensão de orientação aguarda instalação autenticada.</p>
|
||||
)}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Pedido de apoio no fluxo existente
|
||||
</h2>
|
||||
<p>
|
||||
A recomendação ajuda a preparar. Só a sua submissão cria um
|
||||
pedido recebido; a resposta é assinada pelo responsável.
|
||||
</p>
|
||||
{requests.map((r) => (
|
||||
<Link
|
||||
key={r.id}
|
||||
className={card + ' block'}
|
||||
href={`/balcao-virtual/pedidos/${r.id}`}
|
||||
>
|
||||
{r.protocol ?? 'Continuar rascunho de apoio'} —{' '}
|
||||
{states[r.status]}
|
||||
</Link>
|
||||
))}
|
||||
{canWrite && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
requestForm.post(
|
||||
`/balcao-virtual/dossiers/${dossier.id}/pedidos`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Serviço publicado
|
||||
<select
|
||||
className={input}
|
||||
required
|
||||
value={requestForm.data.service_version_id}
|
||||
onChange={(e) =>
|
||||
requestForm.setData(
|
||||
'service_version_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{services.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.title} — v{s.version}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
requestForm.processing || !services.length
|
||||
}
|
||||
>
|
||||
Preparar rascunho de pedido
|
||||
</button>
|
||||
{!services.length && (
|
||||
<p>
|
||||
Sem serviços publicados. A orientação e os
|
||||
dossiers continuam disponíveis.
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(requestForm.errors).map(([k, v]) => (
|
||||
<p key={k} role="alert">
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Etapas documentais do Balcão
|
||||
</h2>
|
||||
<p>
|
||||
Estes estados descrevem preparação e conferência no portal.
|
||||
A conclusão interna não significa que uma instituição emitiu
|
||||
aprovação, registo ou licença. Os requisitos do plano são
|
||||
afirmações da fonte; a aplicabilidade deve ser documentada
|
||||
no ato específico.
|
||||
</p>
|
||||
{Object.entries(workflow ?? dossier.workflow).map(
|
||||
([code, s]) => (
|
||||
<article className={card} key={code}>
|
||||
<h3 className="font-bold">
|
||||
{code} — {s.title}
|
||||
</h3>
|
||||
<p>
|
||||
{stepStates[s.status]} · Entidade: {s.entity}
|
||||
</p>
|
||||
<p>{s.requirements}</p>
|
||||
<p>
|
||||
Dependências:{' '}
|
||||
{s.dependencies.join(', ') ||
|
||||
'Nenhuma nesta etapa'}{' '}
|
||||
· Evidência: {s.evidence ?? 'Por documentar'}
|
||||
</p>
|
||||
</article>
|
||||
),
|
||||
)}
|
||||
{(canWrite || manager) && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
stageForm.setData('version', dossier.version);
|
||||
stageForm.transform((d) => ({
|
||||
...d,
|
||||
version: dossier.version,
|
||||
}));
|
||||
stageForm.post(
|
||||
`/balcao-virtual/dossiers/${dossier.id}/etapas`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Etapa
|
||||
<select
|
||||
className={input}
|
||||
value={stageForm.data.stage}
|
||||
onChange={(e) =>
|
||||
stageForm.setData('stage', e.target.value)
|
||||
}
|
||||
>
|
||||
{Object.entries(dossier.workflow).map(
|
||||
([c, s]) => (
|
||||
<option key={c} value={c}>
|
||||
{c} — {s.title}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={input}
|
||||
value={stageForm.data.status}
|
||||
onChange={(e) =>
|
||||
stageForm.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
{Object.entries(stepStates)
|
||||
.filter(
|
||||
([s]) =>
|
||||
manager ||
|
||||
![
|
||||
'completed',
|
||||
'not_applicable',
|
||||
].includes(s),
|
||||
)
|
||||
.map(([s, label]) => (
|
||||
<option key={s} value={s}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Motivo
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
value={stageForm.data.reason}
|
||||
onChange={(e) =>
|
||||
stageForm.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Evidência / referência
|
||||
<input
|
||||
className={input}
|
||||
value={stageForm.data.evidence}
|
||||
onChange={(e) =>
|
||||
stageForm.setData(
|
||||
'evidence',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Identificador do documento de suporte
|
||||
<input
|
||||
className={input}
|
||||
value={stageForm.data.document_id}
|
||||
onChange={(e) =>
|
||||
stageForm.setData(
|
||||
'document_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p>
|
||||
Conclusão e não aplicabilidade exigem revisão por
|
||||
outra pessoa autorizada e evidência documental.
|
||||
</p>
|
||||
<button
|
||||
className={button}
|
||||
disabled={stageForm.processing}
|
||||
>
|
||||
Registar etapa
|
||||
</button>
|
||||
{Object.entries(stageForm.errors).map(([k, v]) => (
|
||||
<p key={k} role="alert">
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Documentos privados reutilizados
|
||||
</h2>
|
||||
{documents.map((d) => (
|
||||
<article key={d.id} className={card}>
|
||||
<p>
|
||||
{d.file_name} · {d.category} ·{' '}
|
||||
{d.malware_scan_status}
|
||||
</p>
|
||||
<p>{d.source_reference}</p>
|
||||
{d.status === 'active' &&
|
||||
d.malware_scan_status === 'clean' && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${dossier.id}/documentos/${d.id}`}
|
||||
>
|
||||
Descarregar com verificação de autorização e
|
||||
hash
|
||||
</a>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{canWrite && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
upload.transform((d) => ({
|
||||
...d,
|
||||
version: dossier.version,
|
||||
}));
|
||||
upload.post(
|
||||
`/balcao-virtual/dossiers/${dossier.id}/documentos`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Ficheiro privado
|
||||
<input
|
||||
className={input}
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg,.txt"
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Ou identificador de documento já autorizado
|
||||
<input
|
||||
className={input}
|
||||
value={upload.data.document_id}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'document_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Proveniência e referência
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
value={upload.data.source_reference}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'source_reference',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Assunto da evidência — não equivale a validação
|
||||
<select
|
||||
className={input}
|
||||
value={upload.data.category}
|
||||
onChange={(e) =>
|
||||
upload.setData('category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="project_evidence">
|
||||
Documento geral do projecto
|
||||
</option>
|
||||
<option value="market_evidence">Mercado</option>
|
||||
<option value="location_evidence">
|
||||
Localização
|
||||
</option>
|
||||
<option value="resource_evidence">
|
||||
Recursos
|
||||
</option>
|
||||
<option value="funding_evidence">
|
||||
Financiamento
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={upload.data.consent}
|
||||
onChange={(e) =>
|
||||
upload.setData('consent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Autorizo associar este documento ao dossier privado.
|
||||
</label>
|
||||
<button className={button} disabled={upload.processing}>
|
||||
Associar documento
|
||||
</button>
|
||||
{Object.entries(upload.errors).map(([k, v]) => (
|
||||
<p key={k} role="alert">
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
{manager && !canWrite && (
|
||||
<DocumentReview
|
||||
caseId={dossier.id}
|
||||
version={dossier.version}
|
||||
documents={documents}
|
||||
/>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Ligações institucionais e alternativas
|
||||
</h2>
|
||||
<p>
|
||||
O encaminhamento não transmite o dossier. Ligações
|
||||
indisponíveis não impedem os serviços internos.
|
||||
</p>
|
||||
{links.map((link) => (
|
||||
<article key={link.id}>
|
||||
<p>
|
||||
{link.entity} — {link.purpose} ·{' '}
|
||||
{link.monitor.available
|
||||
? `Disponibilidade conferida internamente em ${link.verified_at}; não valida conteúdo ou decisão oficial`
|
||||
: 'Ligação por verificar ou indisponível'}
|
||||
</p>
|
||||
<p>Contacto alternativo: {link.monitor.contact}</p>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/balcao-virtual/encaminhar/${link.id}?case_id=${dossier.id}`}
|
||||
>
|
||||
Abrir encaminhamento
|
||||
</a>{' '}
|
||||
·{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href={`/balcao-virtual/encaminhar/${link.id}?case_id=${dossier.id}&unavailable=1`}
|
||||
>
|
||||
Ligação indisponível: continuar internamente
|
||||
</a>
|
||||
{manager && <LinkReview link={link} />}
|
||||
</article>
|
||||
))}
|
||||
{!links.length && (
|
||||
<p>
|
||||
Sem ligações verificadas. Prepare os documentos e
|
||||
solicite apoio no pedido existente.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
<details className={card}>
|
||||
<summary>Histórico de autoria, decisões e resultados</summary>
|
||||
{events.map((event) => (
|
||||
<article key={event.id} className="mt-3 border-t pt-3">
|
||||
<p>
|
||||
{event.action} · {event.name} · {event.created_at}
|
||||
</p>
|
||||
<pre className="overflow-auto text-xs break-all whitespace-pre-wrap">
|
||||
{JSON.stringify(event.payload, null, 2)}
|
||||
</pre>
|
||||
</article>
|
||||
))}
|
||||
</details>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card } from '@/pages/investment/shared';
|
||||
export default function Catalogue({
|
||||
installed,
|
||||
services,
|
||||
prepared,
|
||||
}: {
|
||||
installed: boolean;
|
||||
services: {
|
||||
id: string;
|
||||
version: number;
|
||||
definition: { title: string; result: string };
|
||||
}[];
|
||||
prepared: Record<string, { title: string; result: string }>;
|
||||
}) {
|
||||
return (
|
||||
<Frame title="Serviços do Balcão Virtual">
|
||||
<p>
|
||||
Preparação e acompanhamento internos; a decisão oficial pertence
|
||||
à entidade competente.
|
||||
</p>
|
||||
<Link
|
||||
href={installed ? '/balcao-virtual/painel' : '/balcao-virtual'}
|
||||
className="underline"
|
||||
>
|
||||
{installed
|
||||
? 'Abrir o painel e preparar um pedido'
|
||||
: 'Consultar pedidos existentes'}
|
||||
</Link>
|
||||
{!installed && (
|
||||
<p>
|
||||
Melhorias preparadas; a instalação autenticada e a
|
||||
publicação explícita dos serviços continuam pendentes.
|
||||
</p>
|
||||
)}
|
||||
{(installed
|
||||
? services.map((s) => ({ ...s.definition, version: s.version }))
|
||||
: Object.values(prepared).map((s) => ({ ...s, version: null }))
|
||||
).map((s) => (
|
||||
<article className={card} key={s.title}>
|
||||
<h2 className="text-xl font-bold">{s.title}</h2>
|
||||
<p>{s.result}</p>
|
||||
<p>
|
||||
{s.version
|
||||
? `Versão ${s.version}`
|
||||
: 'Preparado, ainda indisponível para novos pedidos'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, button, input } from '@/pages/investment/shared';
|
||||
export default function Install({
|
||||
hash,
|
||||
installed,
|
||||
backupVerified,
|
||||
qaVerified,
|
||||
changes,
|
||||
target,
|
||||
pendingMigrations,
|
||||
compatibilityVerified,
|
||||
backupDate,
|
||||
scanner,
|
||||
rollback,
|
||||
databaseReady,
|
||||
}: {
|
||||
hash: string;
|
||||
installed: boolean;
|
||||
backupVerified: boolean;
|
||||
qaVerified: boolean;
|
||||
changes: string[];
|
||||
target: { database: string; port: number };
|
||||
pendingMigrations: string[];
|
||||
compatibilityVerified: boolean;
|
||||
backupDate: string | null;
|
||||
scanner: { available: boolean; reason_code: string | null };
|
||||
rollback: string;
|
||||
databaseReady: boolean;
|
||||
}) {
|
||||
const form = useForm({ hash, confirm: false });
|
||||
const service = useForm({ code: 'project-preparation', confirm: false });
|
||||
return (
|
||||
<Frame title="Instalação autenticada do Balcão e acompanhamento">
|
||||
<Link href="/balcao-virtual" className="mr-4 underline">
|
||||
Voltar ao Balcão
|
||||
</Link>
|
||||
<Link href="/management/balcao/fontes" className="underline">
|
||||
Consultar inventário privado e exemplares de formulários
|
||||
</Link>
|
||||
<section className={card}>
|
||||
<p>
|
||||
Destino: {target.database}, porta {target.port}.
|
||||
Backup/restauro: {backupDate ?? 'Pendente'}.
|
||||
</p>
|
||||
<h2 className="mt-3 text-lg font-semibold">
|
||||
Alterações de esquema ainda necessárias
|
||||
</h2>
|
||||
<ul>
|
||||
{pendingMigrations.map((name) => (
|
||||
<li key={name}>{name}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Serão criadas as tabelas internas do Balcão; acrescentadas
|
||||
associações opcionais ao dossier e às tarefas existentes.
|
||||
Não se migram ou apagam pedidos anteriores, não se publicam
|
||||
serviços nem se enviam dados externos.
|
||||
</p>
|
||||
<ul>
|
||||
{changes.map((c) => (
|
||||
<li key={c}>{c}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Backup/restauro verificado:{' '}
|
||||
{backupVerified ? 'Sim' : 'Pendente'} · QA desta versão:{' '}
|
||||
{qaVerified ? 'Sim' : 'Pendente'}.
|
||||
</p>
|
||||
<p>
|
||||
Compatibilidade e reversão em cópia restaurada:{' '}
|
||||
{compatibilityVerified ? 'Verificadas' : 'Pendentes'}.
|
||||
</p>
|
||||
<p>
|
||||
Permissões da conexão para criar o esquema e estender
|
||||
tarefas:{' '}
|
||||
{databaseReady
|
||||
? 'Disponíveis'
|
||||
: 'Insuficientes — intervenção autorizada necessária'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
ClamD real:{' '}
|
||||
{scanner.available
|
||||
? 'Disponível'
|
||||
: `Indisponível (${scanner.reason_code ?? 'sem evidência'})`}
|
||||
. Ficheiros sem scan conclusivo continuam pendentes para
|
||||
utilização segura; guardar rascunhos e preparar pedidos
|
||||
mantém-se disponível.
|
||||
</p>
|
||||
<p>{rollback}</p>
|
||||
<p>
|
||||
Confirmação inclui o restauro isolado da base e a
|
||||
integridade dos ficheiros privados. O histórico e os pedidos
|
||||
existentes são preservados.
|
||||
</p>
|
||||
</section>
|
||||
{!installed && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/management/balcao-install');
|
||||
}}
|
||||
>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.confirm}
|
||||
onChange={(e) =>
|
||||
form.setData('confirm', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Confirmo aplicar exactamente as alterações
|
||||
pré-visualizadas.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing ||
|
||||
!form.data.confirm ||
|
||||
!backupVerified ||
|
||||
!qaVerified ||
|
||||
!compatibilityVerified ||
|
||||
!databaseReady
|
||||
}
|
||||
>
|
||||
Aplicar instalação autenticada
|
||||
</button>
|
||||
{Object.entries(form.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{installed && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
service.post('/management/balcao/servicos');
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Publicar serviço de preparação interna
|
||||
</h2>
|
||||
<p>
|
||||
Publicação do catálogo é uma acção separada; não submete
|
||||
pedidos nem homologa um formulário oficial.
|
||||
</p>
|
||||
<label>
|
||||
Serviço
|
||||
<select
|
||||
className={input}
|
||||
value={service.data.code}
|
||||
onChange={(e) =>
|
||||
service.setData('code', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="project-preparation">
|
||||
Preparação de projecto
|
||||
</option>
|
||||
<option value="project-change">
|
||||
Alteração de projecto
|
||||
</option>
|
||||
<option value="project-follow-up">
|
||||
Acompanhamento de investimento
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={service.data.confirm}
|
||||
onChange={(e) =>
|
||||
service.setData('confirm', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Confirmo disponibilizar este serviço de preparação
|
||||
interna.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={service.processing || !service.data.confirm}
|
||||
>
|
||||
Publicar este serviço
|
||||
</button>
|
||||
{Object.entries(service.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { Frame, input, button, card } from '@/pages/investment/shared';
|
||||
type Option = {
|
||||
id: string;
|
||||
status?: string;
|
||||
name?: string;
|
||||
version_no?: number;
|
||||
};
|
||||
export default function Panel({
|
||||
cases,
|
||||
queue,
|
||||
legacyRequests,
|
||||
companies,
|
||||
submissions,
|
||||
organizations,
|
||||
simulationDrafts,
|
||||
journeys,
|
||||
states,
|
||||
manager,
|
||||
guidanceTasks,
|
||||
}: {
|
||||
cases: { id: string; title: string }[];
|
||||
queue: {
|
||||
id: string;
|
||||
title: string;
|
||||
protocol: string;
|
||||
status: string;
|
||||
due_at: string | null;
|
||||
}[];
|
||||
legacyRequests: { id: number; reference: string; status: string }[];
|
||||
companies: Option[];
|
||||
submissions: Option[];
|
||||
organizations: Option[];
|
||||
simulationDrafts: Option[];
|
||||
journeys: Option[];
|
||||
states: Record<string, string>;
|
||||
manager: boolean;
|
||||
guidanceTasks: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
due_at: string;
|
||||
case_id: string;
|
||||
case_title: string;
|
||||
}[];
|
||||
}) {
|
||||
const params = new URLSearchParams(usePage().url.split('?')[1] ?? '');
|
||||
const pending = useRef(false);
|
||||
const [failure, setFailure] = useState<string | null>(null);
|
||||
const form = useForm({
|
||||
title: '',
|
||||
client_key: crypto.randomUUID(),
|
||||
reuse_consent: false,
|
||||
company_id: '',
|
||||
submission_id: params.get('submission_id') ?? '',
|
||||
simulation_id: params.get('simulation_id') ?? '',
|
||||
organization_id: '',
|
||||
journey_id: params.get('journey_id') ?? '',
|
||||
interest_request_id: '',
|
||||
});
|
||||
const groups = {
|
||||
company_id: ['Empresa existente', companies],
|
||||
submission_id: ['Manifestação ou rascunho existente', submissions],
|
||||
simulation_id: ['Dossier do simulador', simulationDrafts],
|
||||
organization_id: ['Organização representada', organizations],
|
||||
journey_id: ['Percurso territorial existente', journeys],
|
||||
} as const;
|
||||
return (
|
||||
<Frame title="Balcão Virtual — acompanhamento">
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link href="/balcao-virtual/servicos" className="underline">
|
||||
Serviços
|
||||
</Link>
|
||||
<Link href="/investidor/manifestacoes" className="underline">
|
||||
Área do investidor
|
||||
</Link>
|
||||
<Link href="/parcerias/painel" className="underline">
|
||||
Parcerias
|
||||
</Link>
|
||||
{manager && (
|
||||
<Link
|
||||
href="/management/balcao-install"
|
||||
className="underline"
|
||||
>
|
||||
Instalação e serviços
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-bold">Dossiers actuais</h2>
|
||||
{cases.map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
className={card + ' block'}
|
||||
href={`/balcao-virtual/dossiers/${c.id}`}
|
||||
>
|
||||
{c.title}
|
||||
</Link>
|
||||
))}
|
||||
{!cases.length && <p>Ainda sem dossier neste fluxo.</p>}
|
||||
</section>
|
||||
<details className={card}>
|
||||
<summary>Preparar acompanhamento de um projecto</summary>
|
||||
<form
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setFailure(null);
|
||||
form.post('/balcao-virtual/dossiers', {
|
||||
preserveState: true,
|
||||
onError: () =>
|
||||
setFailure(
|
||||
'O dossier não foi guardado. Corrija os campos indicados abaixo; os dados preenchidos foram mantidos.',
|
||||
),
|
||||
onHttpException: (response) => {
|
||||
const reasons: Record<number, string> = {
|
||||
403: 'Não tem autorização para a associação selecionada.',
|
||||
404: 'O registo que pretende associar não está disponível.',
|
||||
409: 'Esta operação já foi utilizada com outro conteúdo ou o contexto mudou. Consulte os dossiers atuais antes de repetir.',
|
||||
419: 'A sessão expirou. Inicie sessão novamente antes de repetir.',
|
||||
422: 'Os dados não permitem guardar este dossier. Reveja as associações e o consentimento.',
|
||||
503: 'O servidor está temporariamente indisponível.',
|
||||
};
|
||||
setFailure(
|
||||
`${reasons[response.status] ?? 'O servidor não confirmou a operação.'} Os dados preenchidos foram mantidos.`,
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
setFailure(
|
||||
'A ligação falhou e não foi possível confirmar o resultado. Os dados foram mantidos. Consulte os dossiers atuais antes de repetir; não submeta um pedido para testar.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
pending.current = false;
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Título do projecto
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.title}
|
||||
maxLength={200}
|
||||
required
|
||||
onChange={(e) =>
|
||||
form.setData('title', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{Object.entries(groups).map(([key, [label, options]]) => (
|
||||
<label className="block" key={key}>
|
||||
{label}
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[key as keyof typeof groups]}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
key as keyof typeof groups,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Sem ligação nesta fase</option>
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name ??
|
||||
`${o.id} — ${o.status ?? `versão ${o.version_no ?? ''}`}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
<label>
|
||||
Pedido de apoio anterior
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.interest_request_id}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'interest_request_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Sem associação nesta fase</option>
|
||||
{legacyRequests.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.reference} — {r.status}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.reuse_consent}
|
||||
onChange={(e) =>
|
||||
form.setData('reuse_consent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Autorizo reutilizar os dados seleccionados para preparar
|
||||
e acompanhar o projecto internamente.
|
||||
</label>
|
||||
<p>
|
||||
O dossier não submete pedidos, não publica documentos e
|
||||
não transmite dados para serviços externos.
|
||||
</p>
|
||||
{Object.entries(form.errors).map(([key, v]) => (
|
||||
<p role="alert" key={key}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
{failure && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-red-700 bg-red-50 p-3"
|
||||
>
|
||||
{failure}
|
||||
</p>
|
||||
)}
|
||||
{form.processing && (
|
||||
<p role="status">
|
||||
A guardar o dossier no servidor. Aguarde a
|
||||
confirmação.
|
||||
</p>
|
||||
)}
|
||||
<button className={button} disabled={form.processing}>
|
||||
{form.processing ? 'A guardar…' : 'Preparar dossier'}
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-bold">
|
||||
Pedidos em acompanhamento{' '}
|
||||
{manager ? '— equipa / CRM interno' : ''}
|
||||
</h2>
|
||||
{queue.map((r) => (
|
||||
<article className={card} key={r.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/pedidos/${r.id}`}
|
||||
>
|
||||
{r.protocol} — {r.title}
|
||||
</Link>
|
||||
<p>
|
||||
{states[r.status]} · Prazo interno:{' '}
|
||||
{r.due_at ?? 'Não atribuído'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{!queue.length && <p>Sem pedidos atribuídos neste fluxo.</p>}
|
||||
</section>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-bold">
|
||||
Tarefas assumidas no CRM interno
|
||||
</h2>
|
||||
{guidanceTasks.map((t) => (
|
||||
<article className={card} key={t.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${t.case_id}`}
|
||||
>
|
||||
{t.case_title} ? {t.title}
|
||||
</Link>
|
||||
<p>
|
||||
{t.status} ? Prazo interno: {t.due_at}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<section>
|
||||
<h2 className="text-xl font-bold">
|
||||
Pedidos anteriores preservados
|
||||
</h2>
|
||||
{legacyRequests.map((r) => (
|
||||
<p key={r.reference}>
|
||||
{r.reference} — {r.status}
|
||||
</p>
|
||||
))}
|
||||
{!legacyRequests.length && (
|
||||
<p>Sem pedidos anteriores associados à conta.</p>
|
||||
)}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
DocumentReview,
|
||||
RequestOperations,
|
||||
type DeskDocument,
|
||||
type DeskPayment,
|
||||
} from '@/components/desk-internal-operations';
|
||||
|
||||
type Field = {
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
options?: Record<string, string>;
|
||||
when?: { field: string; equals: string };
|
||||
};
|
||||
export default function RequestPage({
|
||||
request,
|
||||
case: dossier,
|
||||
definition,
|
||||
owner,
|
||||
manager,
|
||||
analyst,
|
||||
fieldsEditable,
|
||||
states,
|
||||
transitions,
|
||||
findings,
|
||||
messages,
|
||||
analysts,
|
||||
territories,
|
||||
events,
|
||||
documents,
|
||||
payments,
|
||||
caseVersion,
|
||||
}: {
|
||||
request: {
|
||||
id: string;
|
||||
version: number;
|
||||
status: string;
|
||||
payload: Record<string, string>;
|
||||
protocol: string | null;
|
||||
editable_fields: string[];
|
||||
analyst_id: number | null;
|
||||
due_at: string | null;
|
||||
};
|
||||
case: { id: string; title: string };
|
||||
definition: {
|
||||
title: string;
|
||||
fields: Record<string, Field>;
|
||||
result: string;
|
||||
};
|
||||
owner: boolean;
|
||||
manager: boolean;
|
||||
analyst: boolean;
|
||||
fieldsEditable: boolean;
|
||||
states: Record<string, string>;
|
||||
transitions: string[];
|
||||
findings: {
|
||||
code: string;
|
||||
explanation: string;
|
||||
recommendation: string;
|
||||
severity: string;
|
||||
}[];
|
||||
messages: {
|
||||
id: string;
|
||||
body: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
created_at: string;
|
||||
}[];
|
||||
analysts: { id: number; name: string }[];
|
||||
territories: { id: string; name: string }[];
|
||||
documents: DeskDocument[];
|
||||
payments: DeskPayment[];
|
||||
caseVersion: number;
|
||||
events: {
|
||||
id: string;
|
||||
action: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
payload: Record<string, unknown>;
|
||||
}[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: request.version,
|
||||
payload: request.payload,
|
||||
consent: false,
|
||||
reason: '',
|
||||
submit: false,
|
||||
});
|
||||
const decision = useForm({
|
||||
version: request.version,
|
||||
status: transitions[0] ?? '',
|
||||
reason: '',
|
||||
editable_fields: [] as string[],
|
||||
});
|
||||
const assignment = useForm({
|
||||
version: request.version,
|
||||
analyst_id: String(request.analyst_id ?? ''),
|
||||
reason: '',
|
||||
due_at: '',
|
||||
});
|
||||
const message = useForm({ body: '', client_key: crypto.randomUUID() });
|
||||
const canEdit = owner && fieldsEditable;
|
||||
return (
|
||||
<Frame title={definition.title}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${dossier.id}`}
|
||||
>
|
||||
Voltar ao dossier {dossier.title}
|
||||
</Link>
|
||||
<p>{definition.result}</p>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
{request.protocol
|
||||
? 'Pedido submetido pelo investidor'
|
||||
: 'Rascunho — ainda não submetido'}
|
||||
</h2>
|
||||
<p>
|
||||
{states[request.status]} · Protocolo:{' '}
|
||||
{request.protocol ?? 'Ainda sem protocolo'}
|
||||
</p>
|
||||
<p>
|
||||
Responsável real:{' '}
|
||||
{request.analyst_id ?? 'A aguardar atribuição'} · Prazo
|
||||
interno: {request.due_at ?? 'Não definido'}
|
||||
</p>
|
||||
{request.protocol && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/balcao-virtual/pedidos/${request.id}/recibo`}
|
||||
>
|
||||
Descarregar recibo interno e snapshot
|
||||
</a>
|
||||
)}
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Verificações automáticas de preparação
|
||||
</h2>
|
||||
{findings.map((f) => (
|
||||
<p key={f.code}>
|
||||
{f.explanation} {f.recommendation} (
|
||||
{f.severity === 'error'
|
||||
? 'Contradição nos valores declarados'
|
||||
: 'Informação / evidência pendente'}
|
||||
)
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
A análise automática não é uma resposta do responsável nem
|
||||
uma aprovação oficial.
|
||||
</p>
|
||||
</section>
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
submit: false,
|
||||
}));
|
||||
form.put(`/balcao-virtual/pedidos/${request.id}`);
|
||||
}}
|
||||
>
|
||||
{Object.entries(definition.fields)
|
||||
.filter(
|
||||
([, f]) =>
|
||||
!f.when ||
|
||||
form.data.payload[f.when.field] === f.when.equals,
|
||||
)
|
||||
.map(([key, f]) => (
|
||||
<label className="block" key={key}>
|
||||
{f.label}
|
||||
{f.required ? ' *' : ''}
|
||||
{f.type === 'select' || f.type === 'territory' ? (
|
||||
<select
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por preencher</option>
|
||||
{(f.type === 'territory'
|
||||
? territories.map((t) => [t.id, t.name])
|
||||
: Object.entries(f.options ?? {})
|
||||
).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : f.type === 'textarea' ? (
|
||||
<textarea
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type={
|
||||
f.type === 'date'
|
||||
? 'date'
|
||||
: f.type === 'number'
|
||||
? 'number'
|
||||
: 'text'
|
||||
}
|
||||
step={
|
||||
f.type === 'number' ? '0.01' : undefined
|
||||
}
|
||||
className={input}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
{canEdit && (
|
||||
<>
|
||||
<label>
|
||||
Justificação de correcção
|
||||
<textarea
|
||||
className={input}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.consent}
|
||||
onChange={(e) =>
|
||||
form.setData('consent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Revi o conteúdo e autorizo a submissão para análise
|
||||
interna.
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.consent}
|
||||
onClick={() => {
|
||||
form.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
submit: true,
|
||||
}));
|
||||
form.put(
|
||||
`/balcao-virtual/pedidos/${request.id}`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
Submeter este pedido
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{Object.entries(form.errors).map(([k, v]) => (
|
||||
<p key={k} role="alert">
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
{!owner && (manager || analyst) && transitions.length > 0 && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
decision.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
}));
|
||||
decision.post(
|
||||
`/balcao-virtual/pedidos/${request.id}/estado`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Resposta / análise do responsável
|
||||
</h2>
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={input}
|
||||
value={decision.data.status}
|
||||
onChange={(e) =>
|
||||
decision.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
{transitions
|
||||
.filter(
|
||||
(s) =>
|
||||
manager ||
|
||||
![
|
||||
'accepted',
|
||||
'rejected',
|
||||
'closed',
|
||||
].includes(s),
|
||||
)
|
||||
.map((s) => (
|
||||
<option value={s} key={s}>
|
||||
{states[s]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Fundamento da resposta
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
value={decision.data.reason}
|
||||
onChange={(e) =>
|
||||
decision.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{decision.data.status === 'returned' && (
|
||||
<fieldset>
|
||||
<legend>Campos autorizados para correcção</legend>
|
||||
{Object.entries(definition.fields).map(([k, f]) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={decision.data.editable_fields.includes(
|
||||
k,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
decision.setData(
|
||||
'editable_fields',
|
||||
e.target.checked
|
||||
? [
|
||||
...decision.data
|
||||
.editable_fields,
|
||||
k,
|
||||
]
|
||||
: decision.data.editable_fields.filter(
|
||||
(v) => v !== k,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{f.label}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<button className={button} disabled={decision.processing}>
|
||||
Registar resposta fundamentada
|
||||
</button>
|
||||
{Object.entries(decision.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{manager &&
|
||||
!['draft', 'closed', 'cancelled'].includes(request.status) && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
assignment.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
}));
|
||||
assignment.post(
|
||||
`/balcao-virtual/pedidos/${request.id}/responsavel`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Atribuir responsável existente
|
||||
</h2>
|
||||
<label>
|
||||
Responsável
|
||||
<select
|
||||
className={input}
|
||||
required
|
||||
value={assignment.data.analyst_id}
|
||||
onChange={(e) =>
|
||||
assignment.setData(
|
||||
'analyst_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{analysts.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Prazo interno
|
||||
<input
|
||||
className={input}
|
||||
type="datetime-local"
|
||||
value={assignment.data.due_at}
|
||||
onChange={(e) =>
|
||||
assignment.setData('due_at', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Motivo
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
value={assignment.data.reason}
|
||||
onChange={(e) =>
|
||||
assignment.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={assignment.processing}
|
||||
>
|
||||
Atribuir acompanhamento
|
||||
</button>
|
||||
{Object.entries(assignment.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Conversa do pedido existente
|
||||
</h2>
|
||||
{messages.map((m) => (
|
||||
<article key={m.id} className="rounded border p-3">
|
||||
<p>
|
||||
{m.kind === 'responsible_response'
|
||||
? 'Resposta de responsável'
|
||||
: m.kind === 'investor_message'
|
||||
? 'Mensagem do investidor'
|
||||
: 'Mensagem histórica — tipo original não registado'}{' '}
|
||||
— {m.name} · {m.created_at}
|
||||
</p>
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
{m.body}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{!['closed', 'cancelled'].includes(request.status) && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
message.post(
|
||||
`/balcao-virtual/pedidos/${request.id}/mensagens`,
|
||||
{
|
||||
onSuccess: () => {
|
||||
message.reset('body');
|
||||
message.setData(
|
||||
'client_key',
|
||||
crypto.randomUUID(),
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Mensagem privada
|
||||
<textarea
|
||||
className={input}
|
||||
value={message.data.body}
|
||||
required
|
||||
onChange={(e) =>
|
||||
message.setData('body', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={message.processing}
|
||||
>
|
||||
Enviar esta mensagem no pedido
|
||||
</button>
|
||||
{Object.entries(message.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
{!owner && (manager || analyst) && (
|
||||
<DocumentReview
|
||||
caseId={dossier.id}
|
||||
version={caseVersion}
|
||||
documents={documents}
|
||||
requestId={request.id}
|
||||
/>
|
||||
)}
|
||||
{!['closed', 'cancelled'].includes(request.status) && (
|
||||
<RequestOperations
|
||||
requestId={request.id}
|
||||
owner={owner}
|
||||
reviewer={!owner && (manager || analyst)}
|
||||
documents={documents}
|
||||
payments={payments}
|
||||
/>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Respostas e histórico</h2>
|
||||
{events.map((e) => (
|
||||
<article className="mt-3 border-t pt-3" key={e.id}>
|
||||
<p>
|
||||
{e.action} · {e.name} · {e.created_at}
|
||||
</p>
|
||||
{typeof e.payload.reason === 'string' && (
|
||||
<p>{e.payload.reason}</p>
|
||||
)}
|
||||
{[
|
||||
'document_reviewed',
|
||||
'payment_reviewed',
|
||||
'manual_communication_recorded',
|
||||
].includes(e.action) && (
|
||||
<pre className="text-xs break-all whitespace-pre-wrap">
|
||||
{JSON.stringify(e.payload, null, 2)}
|
||||
</pre>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card } from '@/pages/investment/shared';
|
||||
|
||||
export default function Sources({
|
||||
total,
|
||||
attachmentCount,
|
||||
forms,
|
||||
}: {
|
||||
total: number;
|
||||
attachmentCount: number;
|
||||
forms: {
|
||||
identifier: string;
|
||||
sha256: string;
|
||||
size: number;
|
||||
edition: string;
|
||||
provenance: string;
|
||||
consultation: string;
|
||||
legal_documentary_status: string;
|
||||
rule_use: string;
|
||||
official_confirmation: string;
|
||||
fields_status: string;
|
||||
}[];
|
||||
}) {
|
||||
return (
|
||||
<Frame title="Acervo e exemplares de formulários">
|
||||
<Link href="/balcao-virtual/painel" className="underline">
|
||||
Voltar ao Balcão
|
||||
</Link>
|
||||
<p>
|
||||
Inventário privado: {total} ficheiros e {attachmentCount} anexos
|
||||
incorporados. O inventário integral foi preservado antes da
|
||||
selecção. Nada foi importado ou publicado automaticamente.
|
||||
</p>
|
||||
<p>
|
||||
Os exemplares abaixo preservam origem, hash e campos no
|
||||
original. Edição, homologação e correspondência a formulários
|
||||
oficiais permanecem por verificar. Esta pendência permite
|
||||
continuar a preparar o dossier.
|
||||
</p>
|
||||
{forms.map((f) => (
|
||||
<article key={f.sha256 + f.identifier} className={card}>
|
||||
<h2 className="font-bold">{f.identifier}</h2>
|
||||
<p>
|
||||
{f.provenance} · {f.size} bytes · edição:{' '}
|
||||
{f.edition === 'not_identified'
|
||||
? 'por identificar'
|
||||
: f.edition}
|
||||
</p>
|
||||
<p className="text-xs break-all">SHA-256: {f.sha256}</p>
|
||||
<p>
|
||||
Consulta: inventário local, sem autorização de
|
||||
publicação. Situação documental: não verificada.
|
||||
Utilização em regras ou cálculos: nenhuma.
|
||||
</p>
|
||||
<p>
|
||||
Confirmação oficial: pendente. Campos: preservados no
|
||||
ficheiro original; correspondência por verificar.
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{!forms.length && (
|
||||
<p>
|
||||
Inventário não disponível nesta instalação. Os serviços de
|
||||
preparação não dependem da sua publicação.
|
||||
</p>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, control, button } from "../management/shared";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Management, Field, control, button } from '../management/shared';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
export default function Analysis({
|
||||
demand,
|
||||
candidates,
|
||||
@@ -43,41 +46,47 @@ export default function Analysis({
|
||||
const [selectedTerritory, setSelectedTerritory] = useState(territoryPath);
|
||||
const form = useForm({
|
||||
demand_version: demand.version_no,
|
||||
sector_id: "",
|
||||
title: "",
|
||||
intervention: "",
|
||||
equipment_needs: "",
|
||||
trainer_needs: "",
|
||||
funding_plan: "",
|
||||
risks: "",
|
||||
source: "",
|
||||
currency: "MZN",
|
||||
province_id: territoryPath[0]?.id ?? "",
|
||||
district_id: territoryPath[1]?.id ?? "",
|
||||
admin_post_id: territoryPath[2]?.id ?? "",
|
||||
locality_id: territoryPath[3]?.id ?? "",
|
||||
sector_id: '',
|
||||
title: '',
|
||||
intervention: '',
|
||||
equipment_needs: '',
|
||||
trainer_needs: '',
|
||||
funding_plan: '',
|
||||
risks: '',
|
||||
source: '',
|
||||
currency: 'MZN',
|
||||
province_id: territoryPath[0]?.id ?? '',
|
||||
district_id: territoryPath[1]?.id ?? '',
|
||||
admin_post_id: territoryPath[2]?.id ?? '',
|
||||
locality_id: territoryPath[3]?.id ?? '',
|
||||
});
|
||||
return (
|
||||
<Management title="Análise assistida de competências">
|
||||
<p>
|
||||
Procura: {demand.quantity} trabalhadores · {demand.qualification}
|
||||
Procura: {demand.quantity} trabalhadores ·{' '}
|
||||
{demand.qualification}
|
||||
</p>
|
||||
<p>
|
||||
Localização da procura: {territoryPath.map((territory) => territory.name).join(" · ") || "Não indicada"}
|
||||
Localização da procura:{' '}
|
||||
{territoryPath.map((territory) => territory.name).join(' · ') ||
|
||||
'Não indicada'}
|
||||
</p>
|
||||
<p className="rounded border p-4">
|
||||
{gap.state === "expired"
|
||||
? "Fonte expirada. Actualize a declaração antes de analisar."
|
||||
{gap.state === 'expired'
|
||||
? 'Fonte expirada. Actualize a declaração antes de analisar.'
|
||||
: !eligible
|
||||
? "A procura exige revisão independente antes da análise."
|
||||
: "Lacuna quantitativa não determinada: falta evidência de trabalhadores qualificados e disponíveis. Vagas em cursos não são trabalhadores disponíveis."}
|
||||
? 'A procura exige revisão independente antes da análise.'
|
||||
: 'Lacuna quantitativa não determinada: falta evidência de trabalhadores qualificados e disponíveis. Vagas em cursos não são trabalhadores disponíveis.'}
|
||||
</p>
|
||||
<h2 className="text-xl font-semibold">Oferta potencialmente compatível</h2>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Oferta potencialmente compatível
|
||||
</h2>
|
||||
<p>
|
||||
Critérios: mesma ocupação, competência principal, território e texto de
|
||||
qualificação; fonte vigente e revisão interna; conclusão até ao início da
|
||||
necessidade. Esta correspondência não comprova equivalência curricular, acreditação,
|
||||
conclusão ou contratação.
|
||||
Critérios: mesma ocupação, competência principal, território e
|
||||
texto de qualificação; fonte vigente e revisão interna;
|
||||
conclusão até ao início da necessidade. Esta correspondência não
|
||||
comprova equivalência curricular, acreditação, conclusão ou
|
||||
contratação.
|
||||
</p>
|
||||
{candidates.map((c) => (
|
||||
<article className="rounded border p-4" key={c.id}>
|
||||
@@ -89,34 +98,47 @@ export default function Analysis({
|
||||
))}
|
||||
{!candidates.length && (
|
||||
<p>
|
||||
Não há oferta que satisfaça estes critérios. Isto não prova ausência de
|
||||
instituições no território.
|
||||
Não há oferta que satisfaça estes critérios. Isto não prova
|
||||
ausência de instituições no território.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
As capacidades não são somadas nem alocadas: podem partilhar formadores, instalações
|
||||
ou equipamentos.
|
||||
As capacidades não são somadas nem alocadas: podem partilhar
|
||||
formadores, instalações ou equipamentos.
|
||||
</p>
|
||||
<section className="space-y-4 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">Preparação do investimento educativo</h2>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Preparação do investimento educativo
|
||||
</h2>
|
||||
<p>
|
||||
A ficha permanece em rascunho até à validação institucional da lacuna e da
|
||||
resposta formativa. Não garante emprego ou financiamento.
|
||||
A ficha permanece em rascunho até à validação institucional
|
||||
da lacuna e da resposta formativa. Não garante emprego ou
|
||||
financiamento.
|
||||
</p>
|
||||
{proposal ? (
|
||||
<>
|
||||
{proposal.demand_version !== demand.version_no && (
|
||||
<p role="alert">
|
||||
A procura foi alterada desde a criação da ficha. É necessária
|
||||
reconciliação.
|
||||
A procura foi alterada desde a criação da ficha.
|
||||
É necessária reconciliação.
|
||||
</p>
|
||||
)}
|
||||
<p>{proposal.intervention}</p>
|
||||
<p>
|
||||
Equipamentos: {proposal.equipment_needs || "Pendente de levantamento"}
|
||||
Equipamentos:{' '}
|
||||
{proposal.equipment_needs ||
|
||||
'Pendente de levantamento'}
|
||||
</p>
|
||||
<p>
|
||||
Formadores:{' '}
|
||||
{proposal.trainer_needs ||
|
||||
'Pendente de levantamento'}
|
||||
</p>
|
||||
<p>
|
||||
Financiamento:{' '}
|
||||
{proposal.funding_plan ||
|
||||
'Pendente de levantamento'}
|
||||
</p>
|
||||
<p>Formadores: {proposal.trainer_needs || "Pendente de levantamento"}</p>
|
||||
<p>Financiamento: {proposal.funding_plan || "Pendente de levantamento"}</p>
|
||||
<p>Riscos: {proposal.risks}</p>
|
||||
<p>Fonte: {proposal.source}</p>
|
||||
<Link
|
||||
@@ -135,13 +157,19 @@ export default function Analysis({
|
||||
...data,
|
||||
demand_version: demand.version_no,
|
||||
}));
|
||||
form.post(`/management/education/demands/${demand.id}/investment`);
|
||||
form.post(
|
||||
`/management/education/demands/${demand.id}/investment`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<p className="font-medium">Localização da oportunidade educativa</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Inicialmente preenchida com a localização da procura. Confirme ou ajuste cada nível territorial.
|
||||
<p className="font-medium">
|
||||
Localização da oportunidade educativa
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Inicialmente preenchida com a localização da
|
||||
procura. Confirme ou ajuste cada nível
|
||||
territorial.
|
||||
</p>
|
||||
<TerritoryFields
|
||||
initial={selectedTerritory}
|
||||
@@ -150,15 +178,15 @@ export default function Analysis({
|
||||
setSelectedTerritory(path);
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
province_id: path[0]?.id ?? "",
|
||||
district_id: path[1]?.id ?? "",
|
||||
admin_post_id: path[2]?.id ?? "",
|
||||
locality_id: path[3]?.id ?? "",
|
||||
province_id: path[0]?.id ?? '',
|
||||
district_id: path[1]?.id ?? '',
|
||||
admin_post_id: path[2]?.id ?? '',
|
||||
locality_id: path[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
{Object.entries(form.errors)
|
||||
.filter(([key]) => key.endsWith("_id"))
|
||||
.filter(([key]) => key.endsWith('_id'))
|
||||
.map(([key, error]) => (
|
||||
<p role="alert" key={key}>
|
||||
{error}
|
||||
@@ -170,7 +198,9 @@ export default function Analysis({
|
||||
required
|
||||
className={control}
|
||||
value={form.data.sector_id}
|
||||
onChange={(e) => form.setData("sector_id", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar sector</option>
|
||||
{sectors.map((s) => (
|
||||
@@ -186,37 +216,49 @@ export default function Analysis({
|
||||
maxLength={200}
|
||||
className={control}
|
||||
value={form.data.title}
|
||||
onChange={(e) => form.setData("title", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('title', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
"intervention",
|
||||
"equipment_needs",
|
||||
"trainer_needs",
|
||||
"funding_plan",
|
||||
"risks",
|
||||
"source",
|
||||
'intervention',
|
||||
'equipment_needs',
|
||||
'trainer_needs',
|
||||
'funding_plan',
|
||||
'risks',
|
||||
'source',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
intervention: "Resposta formativa proposta",
|
||||
equipment_needs: "Necessidades de equipamentos (opcional)",
|
||||
trainer_needs: "Necessidades de formadores (opcional)",
|
||||
funding_plan: "Financiamento e sustentabilidade (opcional)",
|
||||
risks: "Riscos e limitações",
|
||||
source: "Fonte e responsável pela proposta",
|
||||
intervention:
|
||||
'Resposta formativa proposta',
|
||||
equipment_needs:
|
||||
'Necessidades de equipamentos (opcional)',
|
||||
trainer_needs:
|
||||
'Necessidades de formadores (opcional)',
|
||||
funding_plan:
|
||||
'Financiamento e sustentabilidade (opcional)',
|
||||
risks: 'Riscos e limitações',
|
||||
source: 'Fonte e responsável pela proposta',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
required={["intervention", "risks", "source"].includes(key)}
|
||||
required={[
|
||||
'intervention',
|
||||
'risks',
|
||||
'source',
|
||||
].includes(key)}
|
||||
className={control}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
@@ -224,9 +266,11 @@ export default function Analysis({
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.currency}
|
||||
onChange={(e) => form.setData("currency", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('currency', e.target.value)
|
||||
}
|
||||
>
|
||||
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -237,13 +281,19 @@ export default function Analysis({
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={form.processing}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing}
|
||||
>
|
||||
Guardar ficha em rascunho
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<p>Reveja a procura e a validade da fonte antes de preparar a ficha.</p>
|
||||
<p>
|
||||
Reveja a procura e a validade da fonte antes de preparar
|
||||
a ficha.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</Management>
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, control, button, Pagination } from "../management/shared";
|
||||
import type { Paginated } from "../management/shared";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Management,
|
||||
Field,
|
||||
control,
|
||||
button,
|
||||
Pagination,
|
||||
} from '../management/shared';
|
||||
import type { Paginated } from '../management/shared';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
type Option = { id: string; name?: string; title?: string; code?: string };
|
||||
type RecordRow = {
|
||||
id: string;
|
||||
@@ -33,14 +42,20 @@ type Props = {
|
||||
pending_demands: number;
|
||||
};
|
||||
};
|
||||
const territoryLevels = ["province", "district", "admin_post", "locality"];
|
||||
const territoryLevels = ['province', 'district', 'admin_post', 'locality'];
|
||||
|
||||
function territoryPath(id: string, territories: TerritoryOption[]): TerritoryOption[] {
|
||||
const byId = new Map(territories.map((territory) => [territory.id, territory]));
|
||||
function territoryPath(
|
||||
id: string,
|
||||
territories: TerritoryOption[],
|
||||
): TerritoryOption[] {
|
||||
const byId = new Map(
|
||||
territories.map((territory) => [territory.id, territory]),
|
||||
);
|
||||
const path: TerritoryOption[] = [];
|
||||
let current = byId.get(id);
|
||||
while (current && path.length < territoryLevels.length) {
|
||||
if (territoryLevels.includes(current.location_type)) path.unshift(current);
|
||||
if (territoryLevels.includes(current.location_type))
|
||||
path.unshift(current);
|
||||
current = current.parent_id ? byId.get(current.parent_id) : undefined;
|
||||
}
|
||||
return path;
|
||||
@@ -79,7 +94,7 @@ function Select({
|
||||
<option value="">Seleccione</option>
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.code ? `${o.code} — ` : ""}
|
||||
{o.code ? `${o.code} — ` : ''}
|
||||
{o.name ?? o.title}
|
||||
</option>
|
||||
))}
|
||||
@@ -87,8 +102,16 @@ function Select({
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
function Catalog({ kind, title, providers }: { kind: string; title: string; providers: Option[] }) {
|
||||
const form = useForm({ name: "", title: "", code: "", provider_id: "" });
|
||||
function Catalog({
|
||||
kind,
|
||||
title,
|
||||
providers,
|
||||
}: {
|
||||
kind: string;
|
||||
title: string;
|
||||
providers: Option[];
|
||||
}) {
|
||||
const form = useForm({ name: '', title: '', code: '', provider_id: '' });
|
||||
return (
|
||||
<details className="rounded border p-4">
|
||||
<summary className="cursor-pointer font-semibold">{title}</summary>
|
||||
@@ -105,28 +128,37 @@ function Catalog({ kind, title, providers }: { kind: string; title: string; prov
|
||||
<input
|
||||
className={control}
|
||||
required
|
||||
value={kind === "courses" ? form.data.title : form.data.name}
|
||||
value={
|
||||
kind === 'courses'
|
||||
? form.data.title
|
||||
: form.data.name
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData(kind === "courses" ? "title" : "name", e.target.value)
|
||||
form.setData(
|
||||
kind === 'courses' ? 'title' : 'name',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{kind !== "providers" && (
|
||||
{kind !== 'providers' && (
|
||||
<Field label="Código">
|
||||
<input
|
||||
className={control}
|
||||
required
|
||||
value={form.data.code}
|
||||
onChange={(e) => form.setData("code", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('code', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{kind === "courses" && (
|
||||
{kind === 'courses' && (
|
||||
<Select
|
||||
label="Instituição"
|
||||
value={form.data.provider_id}
|
||||
options={providers}
|
||||
onChange={(v) => form.setData("provider_id", v)}
|
||||
onChange={(v) => form.setData('provider_id', v)}
|
||||
/>
|
||||
)}
|
||||
<Errors errors={form.errors} />
|
||||
@@ -137,28 +169,36 @@ function Catalog({ kind, title, providers }: { kind: string; title: string; prov
|
||||
</details>
|
||||
);
|
||||
}
|
||||
function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props }) {
|
||||
const demand = kind === "demands";
|
||||
function Intake({
|
||||
kind,
|
||||
props,
|
||||
}: {
|
||||
kind: 'demands' | 'capacities';
|
||||
props: Props;
|
||||
}) {
|
||||
const demand = kind === 'demands';
|
||||
const [territoryResetKey, setTerritoryResetKey] = useState(0);
|
||||
const form = useForm({
|
||||
project_id: "",
|
||||
course_id: "",
|
||||
occupation_id: "",
|
||||
skill_id: "",
|
||||
geo_location_id: "",
|
||||
employer: "",
|
||||
qualification: "",
|
||||
quantity: "",
|
||||
period_start: "",
|
||||
period_end: "",
|
||||
source: "",
|
||||
project_id: '',
|
||||
course_id: '',
|
||||
occupation_id: '',
|
||||
skill_id: '',
|
||||
geo_location_id: '',
|
||||
employer: '',
|
||||
qualification: '',
|
||||
quantity: '',
|
||||
period_start: '',
|
||||
period_end: '',
|
||||
source: '',
|
||||
reference_date: props.today,
|
||||
valid_until: "",
|
||||
valid_until: '',
|
||||
});
|
||||
return (
|
||||
<details className="rounded border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
{demand ? "Declarar procura de trabalhadores" : "Declarar vagas de formação"}
|
||||
{demand
|
||||
? 'Declarar procura de trabalhadores'
|
||||
: 'Declarar vagas de formação'}
|
||||
</summary>
|
||||
<form
|
||||
className="mt-4 grid gap-4 md:grid-cols-2"
|
||||
@@ -173,29 +213,34 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
label={demand ? "Projecto" : "Curso"}
|
||||
label={demand ? 'Projecto' : 'Curso'}
|
||||
options={demand ? props.projects : props.courses}
|
||||
value={demand ? form.data.project_id : form.data.course_id}
|
||||
onChange={(v) => form.setData(demand ? "project_id" : "course_id", v)}
|
||||
onChange={(v) =>
|
||||
form.setData(demand ? 'project_id' : 'course_id', v)
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
label="Ocupação"
|
||||
options={props.occupations}
|
||||
value={form.data.occupation_id}
|
||||
onChange={(v) => form.setData("occupation_id", v)}
|
||||
onChange={(v) => form.setData('occupation_id', v)}
|
||||
/>
|
||||
<Select
|
||||
label="Competência principal"
|
||||
options={props.skills}
|
||||
value={form.data.skill_id}
|
||||
onChange={(v) => form.setData("skill_id", v)}
|
||||
onChange={(v) => form.setData('skill_id', v)}
|
||||
/>
|
||||
<div className="md:col-span-2">
|
||||
<TerritoryFields
|
||||
key={territoryResetKey}
|
||||
endpoint="/management/territory-options"
|
||||
onChange={(path) =>
|
||||
form.setData("geo_location_id", path[path.length - 1]?.id ?? "")
|
||||
form.setData(
|
||||
'geo_location_id',
|
||||
path[path.length - 1]?.id ?? '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
@@ -205,7 +250,9 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
|
||||
className={control}
|
||||
required
|
||||
value={form.data.employer}
|
||||
onChange={(e) => form.setData("employer", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('employer', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
@@ -214,14 +261,16 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
|
||||
className={control}
|
||||
required
|
||||
value={form.data.qualification}
|
||||
onChange={(e) => form.setData("qualification", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('qualification', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={
|
||||
demand
|
||||
? "Trabalhadores necessários"
|
||||
: "Vagas disponíveis (não trabalhadores)"
|
||||
? 'Trabalhadores necessários'
|
||||
: 'Vagas disponíveis (não trabalhadores)'
|
||||
}
|
||||
>
|
||||
<input
|
||||
@@ -230,43 +279,50 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
|
||||
min="1"
|
||||
required
|
||||
value={form.data.quantity}
|
||||
onChange={(e) => form.setData("quantity", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('quantity', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(["period_start", "period_end", "reference_date", "valid_until"] as const).map(
|
||||
(key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
period_start: demand
|
||||
? "Início da necessidade"
|
||||
: "Início da formação",
|
||||
period_end: demand
|
||||
? "Fim da necessidade"
|
||||
: "Conclusão prevista",
|
||||
reference_date: "Data de referência da fonte",
|
||||
valid_until: "Fonte válida até",
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
required
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'period_start',
|
||||
'period_end',
|
||||
'reference_date',
|
||||
'valid_until',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
period_start: demand
|
||||
? 'Início da necessidade'
|
||||
: 'Início da formação',
|
||||
period_end: demand
|
||||
? 'Fim da necessidade'
|
||||
: 'Conclusão prevista',
|
||||
reference_date: 'Data de referência da fonte',
|
||||
valid_until: 'Fonte válida até',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
required
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Fonte, referência da evidência e responsável pelos dados">
|
||||
<textarea
|
||||
className={control}
|
||||
required
|
||||
minLength={10}
|
||||
value={form.data.source}
|
||||
onChange={(e) => form.setData("source", e.target.value)}
|
||||
onChange={(e) => form.setData('source', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<div>
|
||||
@@ -279,32 +335,40 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
|
||||
</details>
|
||||
);
|
||||
}
|
||||
function Review({ row, kind, today }: { row: RecordRow; kind: string; today: string }) {
|
||||
function Review({
|
||||
row,
|
||||
kind,
|
||||
today,
|
||||
}: {
|
||||
row: RecordRow;
|
||||
kind: string;
|
||||
today: string;
|
||||
}) {
|
||||
const form = useForm({
|
||||
version_no: row.version_no,
|
||||
status: "reviewed",
|
||||
review_reason: "",
|
||||
status: 'reviewed',
|
||||
review_reason: '',
|
||||
});
|
||||
return (
|
||||
<article className="space-y-3 rounded border p-4">
|
||||
<p className="font-semibold">
|
||||
{row.qualification} · {row.quantity}{" "}
|
||||
{kind === "demands" ? "trabalhadores" : "vagas formativas"}
|
||||
{row.qualification} · {row.quantity}{' '}
|
||||
{kind === 'demands' ? 'trabalhadores' : 'vagas formativas'}
|
||||
</p>
|
||||
<p>
|
||||
{row.period_start} a {row.period_end} ·{" "}
|
||||
{row.period_start} a {row.period_end} ·{' '}
|
||||
{row.valid_until < today
|
||||
? "Fonte expirada"
|
||||
? 'Fonte expirada'
|
||||
: (
|
||||
{
|
||||
submitted: "Submetido",
|
||||
reviewed: "Revisto internamente",
|
||||
rejected: "Rejeitado",
|
||||
submitted: 'Submetido',
|
||||
reviewed: 'Revisto internamente',
|
||||
rejected: 'Rejeitado',
|
||||
} as Record<string, string>
|
||||
)[row.status]}
|
||||
</p>
|
||||
<p className="break-words">Fonte: {row.source}</p>
|
||||
{kind === "demands" && (
|
||||
{kind === 'demands' && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/education/demands/${row.id}/analysis`}
|
||||
@@ -322,17 +386,23 @@ function Review({ row, kind, today }: { row: RecordRow; kind: string; today: str
|
||||
...data,
|
||||
version_no: row.version_no,
|
||||
}));
|
||||
form.post(`/management/education/${kind}/${row.id}/review`);
|
||||
form.post(
|
||||
`/management/education/${kind}/${row.id}/review`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="Decisão interna">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData("status", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="reviewed">Registar revisão</option>
|
||||
<option value="rejected">Rejeitar declaração</option>
|
||||
<option value="rejected">
|
||||
Rejeitar declaração
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Justificação e evidência da revisão">
|
||||
@@ -341,7 +411,9 @@ function Review({ row, kind, today }: { row: RecordRow; kind: string; today: str
|
||||
minLength={15}
|
||||
required
|
||||
value={form.data.review_reason}
|
||||
onChange={(e) => form.setData("review_reason", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('review_reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Errors errors={form.errors} />
|
||||
@@ -355,39 +427,50 @@ function Review({ row, kind, today }: { row: RecordRow; kind: string; today: str
|
||||
}
|
||||
export default function Index(props: Props) {
|
||||
const search = useForm({
|
||||
q: props.filters.q ?? "",
|
||||
status: props.filters.status ?? "",
|
||||
geo_location_id: props.filters.geo_location_id ?? "",
|
||||
q: props.filters.q ?? '',
|
||||
status: props.filters.status ?? '',
|
||||
geo_location_id: props.filters.geo_location_id ?? '',
|
||||
});
|
||||
return (
|
||||
<Management title="Competências e investimento em educação">
|
||||
<p>
|
||||
Declarações internas de procura e oferta. A revisão não constitui acreditação,
|
||||
certificação ou validação institucional. Não introduza dados pessoais de formandos.
|
||||
Declarações internas de procura e oferta. A revisão não
|
||||
constitui acreditação, certificação ou validação institucional.
|
||||
Não introduza dados pessoais de formandos.
|
||||
</p>
|
||||
<section aria-label="Indicadores internos" className="grid gap-4 md:grid-cols-4">
|
||||
<section
|
||||
aria-label="Indicadores internos"
|
||||
className="grid gap-4 md:grid-cols-4"
|
||||
>
|
||||
<p>
|
||||
Declarações de procura: <strong>{props.indicators.demand_records}</strong>
|
||||
Declarações de procura:{' '}
|
||||
<strong>{props.indicators.demand_records}</strong>
|
||||
</p>
|
||||
<p>
|
||||
Declarações de oferta: <strong>{props.indicators.capacity_records}</strong>
|
||||
Declarações de oferta:{' '}
|
||||
<strong>{props.indicators.capacity_records}</strong>
|
||||
</p>
|
||||
<p>
|
||||
Procuras a rever: <strong>{props.indicators.pending_demands}</strong>
|
||||
Procuras a rever:{' '}
|
||||
<strong>{props.indicators.pending_demands}</strong>
|
||||
</p>
|
||||
<p>
|
||||
Procuras com fonte expirada: <strong>{props.indicators.expired_demands}</strong>
|
||||
Procuras com fonte expirada:{' '}
|
||||
<strong>{props.indicators.expired_demands}</strong>
|
||||
</p>
|
||||
</section>
|
||||
<p>
|
||||
Indicadores globais de registos internos, sem aplicação dos filtros. Não representam
|
||||
totais de trabalhadores, lacunas validadas ou resultados educativos.
|
||||
Indicadores globais de registos internos, sem aplicação dos
|
||||
filtros. Não representam totais de trabalhadores, lacunas
|
||||
validadas ou resultados educativos.
|
||||
</p>
|
||||
<form
|
||||
className="grid gap-4 md:grid-cols-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
search.get("/management/education", { preserveState: true });
|
||||
search.get('/management/education', {
|
||||
preserveState: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field label="Pesquisar qualificação">
|
||||
@@ -395,28 +478,40 @@ export default function Index(props: Props) {
|
||||
className={control}
|
||||
maxLength={150}
|
||||
value={search.data.q}
|
||||
onChange={(e) => search.setData("q", e.target.value)}
|
||||
onChange={(e) => search.setData('q', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={search.data.status}
|
||||
onChange={(e) => search.setData("status", e.target.value)}
|
||||
onChange={(e) =>
|
||||
search.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="submitted">Por rever, fonte vigente</option>
|
||||
<option value="submitted">
|
||||
Por rever, fonte vigente
|
||||
</option>
|
||||
<option value="reviewed">Revisto, fonte vigente</option>
|
||||
<option value="rejected">Rejeitado, fonte vigente</option>
|
||||
<option value="rejected">
|
||||
Rejeitado, fonte vigente
|
||||
</option>
|
||||
<option value="expired">Fonte expirada</option>
|
||||
</select>
|
||||
</Field>
|
||||
<div className="md:col-span-2">
|
||||
<TerritoryFields
|
||||
initial={territoryPath(search.data.geo_location_id, props.territories)}
|
||||
initial={territoryPath(
|
||||
search.data.geo_location_id,
|
||||
props.territories,
|
||||
)}
|
||||
endpoint="/management/territory-options"
|
||||
onChange={(path) =>
|
||||
search.setData("geo_location_id", path[path.length - 1]?.id ?? "")
|
||||
search.setData(
|
||||
'geo_location_id',
|
||||
path[path.length - 1]?.id ?? '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
@@ -424,7 +519,10 @@ export default function Index(props: Props) {
|
||||
<button className={button} disabled={search.processing}>
|
||||
Filtrar
|
||||
</button>
|
||||
<Link className="ml-3 underline" href="/management/education">
|
||||
<Link
|
||||
className="ml-3 underline"
|
||||
href="/management/education"
|
||||
>
|
||||
Limpar
|
||||
</Link>
|
||||
<Errors errors={search.errors} />
|
||||
@@ -432,25 +530,35 @@ export default function Index(props: Props) {
|
||||
</form>
|
||||
<section className="grid gap-3 md:grid-cols-2">
|
||||
{[
|
||||
["skills", "Competências"],
|
||||
["occupations", "Ocupações"],
|
||||
["providers", "Instituições"],
|
||||
["courses", "Cursos"],
|
||||
['skills', 'Competências'],
|
||||
['occupations', 'Ocupações'],
|
||||
['providers', 'Instituições'],
|
||||
['courses', 'Cursos'],
|
||||
].map(([kind, title]) => (
|
||||
<Catalog key={kind} kind={kind} title={title} providers={props.providers} />
|
||||
<Catalog
|
||||
key={kind}
|
||||
kind={kind}
|
||||
title={title}
|
||||
providers={props.providers}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
<Intake kind="demands" props={props} />
|
||||
<Intake kind="capacities" props={props} />
|
||||
{(["demands", "capacities"] as const).map((kind) => (
|
||||
{(['demands', 'capacities'] as const).map((kind) => (
|
||||
<section key={kind} className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{kind === "demands"
|
||||
? "Procura de mão-de-obra"
|
||||
: "Oferta formativa declarada"}
|
||||
{kind === 'demands'
|
||||
? 'Procura de mão-de-obra'
|
||||
: 'Oferta formativa declarada'}
|
||||
</h2>
|
||||
{props[kind].data.map((row) => (
|
||||
<Review key={row.id} row={row} kind={kind} today={props.today} />
|
||||
<Review
|
||||
key={row.id}
|
||||
row={row}
|
||||
kind={kind}
|
||||
today={props.today}
|
||||
/>
|
||||
))}
|
||||
{!props[kind].data.length && <p>Ainda sem declarações.</p>}
|
||||
<Pagination page={props[kind]} />
|
||||
|
||||
@@ -1,61 +1,256 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Link } from "@inertiajs/react";
|
||||
import type { FormEvent } from "react";
|
||||
import { newSubmissionKey } from "@/lib/portal-api";
|
||||
import { Frame, Field, button, card, input } from "./shared";
|
||||
import { useRef, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { FormEvent } from 'react';
|
||||
import { newSubmissionKey } from '@/lib/portal-api';
|
||||
import { Frame, Field, button, card, input } from './shared';
|
||||
|
||||
type Opportunity = { id: string; slug: string; title: string; sector?: { name: string } | null };
|
||||
type Opportunity = {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
sector?: { name: string } | null;
|
||||
};
|
||||
type Props = { record: Opportunity; modalities: string[]; returnUrl?: string };
|
||||
type Form = {
|
||||
fullName: string; email: string; phone: string; investorType: string; country: string;
|
||||
sectorInterest: string; modality: string; investmentRange: string; message: string; privacyConsent: boolean; shareWithProponent: boolean;
|
||||
fullName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
investorType: string;
|
||||
country: string;
|
||||
sectorInterest: string;
|
||||
modality: string;
|
||||
investmentRange: string;
|
||||
message: string;
|
||||
privacyConsent: boolean;
|
||||
shareWithProponent: boolean;
|
||||
};
|
||||
|
||||
export default function BusinessInterest({ record, modalities, returnUrl = "/negocios" }: Props) {
|
||||
const [form, setForm] = useState<Form>({ fullName: "", email: "", phone: "", investorType: "empresa", country: "MZ", sectorInterest: record.sector?.name ?? "", modality: modalities[0] ?? "", investmentRange: "", message: "", privacyConsent: false, shareWithProponent: false });
|
||||
export default function BusinessInterest({
|
||||
record,
|
||||
modalities,
|
||||
returnUrl = '/negocios',
|
||||
}: Props) {
|
||||
const [form, setForm] = useState<Form>({
|
||||
fullName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
investorType: 'empresa',
|
||||
country: 'MZ',
|
||||
sectorInterest: record.sector?.name ?? '',
|
||||
modality: modalities[0] ?? '',
|
||||
investmentRange: '',
|
||||
message: '',
|
||||
privacyConsent: false,
|
||||
shareWithProponent: false,
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [receipt, setReceipt] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [receipt, setReceipt] = useState('');
|
||||
const key = useRef(newSubmissionKey());
|
||||
const update = <K extends keyof Form>(field: K, value: Form[K]) => setForm((current) => ({ ...current, [field]: value }));
|
||||
const update = <K extends keyof Form>(field: K, value: Form[K]) =>
|
||||
setForm((current) => ({ ...current, [field]: value }));
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!form.privacyConsent) { setError("Aceite o tratamento de dados para enviar o pedido."); return; }
|
||||
setBusy(true); setError("");
|
||||
const xsrf = decodeURIComponent(document.cookie.split("; ").find((cookie) => cookie.startsWith("XSRF-TOKEN="))?.slice(11) ?? "");
|
||||
if (!form.privacyConsent) {
|
||||
setError('Aceite o tratamento de dados para enviar o pedido.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const xsrf = decodeURIComponent(
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((cookie) => cookie.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
try {
|
||||
const response = await fetch("/api/v1/interest-requests", {
|
||||
method: "POST", credentials: "same-origin",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-XSRF-TOKEN": xsrf, "Idempotency-Key": key.current },
|
||||
body: JSON.stringify({ ...form, existingBusinessId: record.id }),
|
||||
const response = await fetch('/api/v1/interest-requests', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': xsrf,
|
||||
'Idempotency-Key': key.current,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...form,
|
||||
existingBusinessId: record.id,
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.message ?? "Não foi possível enviar a manifestação.");
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
data.message ?? 'Não foi possível enviar a manifestação.',
|
||||
);
|
||||
setReceipt(data.data.reference);
|
||||
key.current = newSubmissionKey();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Não foi possível enviar a manifestação.");
|
||||
} finally { setBusy(false); }
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Não foi possível enviar a manifestação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Frame title="Manifestar interesse">
|
||||
<Link href={returnUrl} className="underline">Voltar à oportunidade</Link>
|
||||
<p>Oportunidade: <strong>{record.title}</strong></p>
|
||||
{receipt ? <section className={card} role="status"><h2 className="text-xl font-bold">Pedido recebido</h2><p>Referência: {receipt}</p><p>A equipa fará a triagem antes de qualquer partilha com o proponente.</p></section> : (
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar à oportunidade
|
||||
</Link>
|
||||
<p>
|
||||
Oportunidade: <strong>{record.title}</strong>
|
||||
</p>
|
||||
{receipt ? (
|
||||
<section className={card} role="status">
|
||||
<h2 className="text-xl font-bold">Pedido recebido</h2>
|
||||
<p>Referência: {receipt}</p>
|
||||
<p>
|
||||
A equipa fará a triagem antes de qualquer partilha com o
|
||||
proponente.
|
||||
</p>
|
||||
</section>
|
||||
) : (
|
||||
<form className={`${card} space-y-4`} onSubmit={submit}>
|
||||
<Field label="Nome ou denominação"><input className={input} required minLength={3} maxLength={150} value={form.fullName} onChange={(e) => update("fullName", e.target.value)} /></Field>
|
||||
<Field label="Email"><input className={input} type="email" required maxLength={150} value={form.email} onChange={(e) => update("email", e.target.value)} /></Field>
|
||||
<Field label="Telefone"><input className={input} type="tel" maxLength={30} value={form.phone} onChange={(e) => update("phone", e.target.value)} /></Field>
|
||||
<Field label="Tipo de investidor"><select className={input} value={form.investorType} onChange={(e) => update("investorType", e.target.value)}><option value="empresa">Empresa</option><option value="individual">Pessoa singular</option><option value="fundo">Fundo</option><option value="entidade_publica">Entidade pública</option><option value="outro">Outro</option></select></Field>
|
||||
<Field label="País"><input className={input} required maxLength={100} value={form.country} onChange={(e) => update("country", e.target.value)} /></Field>
|
||||
<Field label="Sector de interesse"><input className={input} required maxLength={150} value={form.sectorInterest} onChange={(e) => update("sectorInterest", e.target.value)} /></Field>
|
||||
<Field label="Modalidade pretendida"><select className={input} required value={form.modality} onChange={(e) => update("modality", e.target.value)}>{modalities.map((modality) => <option key={modality} value={modality}>{modality.replaceAll("_", " ")}</option>)}</select></Field>
|
||||
<Field label="Intervalo de investimento"><input className={input} maxLength={80} value={form.investmentRange} onChange={(e) => update("investmentRange", e.target.value)} /></Field>
|
||||
<Field label="Motivação e pedido"><textarea className={input} required minLength={20} maxLength={2000} rows={5} value={form.message} onChange={(e) => update("message", e.target.value)} /></Field>
|
||||
<label className="flex items-start gap-3"><input type="checkbox" required checked={form.privacyConsent} onChange={(e) => update("privacyConsent", e.target.checked)} /><span>Autorizo o tratamento destes dados para responder a esta manifestação. O envio não confirma elegibilidade nem permite partilha automática com o proponente.</span></label>
|
||||
<label className="flex items-start gap-3"><input type="checkbox" checked={form.shareWithProponent} onChange={(e) => update("shareWithProponent", e.target.checked)} /><span>Autorizo, se necessário para avaliar esta manifestação, a partilha do meu nome, email, telefone e mensagem com o proponente. Esta autorização é opcional e pode ser retirada junto da equipa.</span></label>
|
||||
<Field label="Nome ou denominação">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={150}
|
||||
value={form.fullName}
|
||||
onChange={(e) => update('fullName', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Email">
|
||||
<input
|
||||
className={input}
|
||||
type="email"
|
||||
required
|
||||
maxLength={150}
|
||||
value={form.email}
|
||||
onChange={(e) => update('email', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Telefone">
|
||||
<input
|
||||
className={input}
|
||||
type="tel"
|
||||
maxLength={30}
|
||||
value={form.phone}
|
||||
onChange={(e) => update('phone', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Tipo de investidor">
|
||||
<select
|
||||
className={input}
|
||||
value={form.investorType}
|
||||
onChange={(e) =>
|
||||
update('investorType', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="empresa">Empresa</option>
|
||||
<option value="individual">Pessoa singular</option>
|
||||
<option value="fundo">Fundo</option>
|
||||
<option value="entidade_publica">
|
||||
Entidade pública
|
||||
</option>
|
||||
<option value="outro">Outro</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="País">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
maxLength={100}
|
||||
value={form.country}
|
||||
onChange={(e) => update('country', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector de interesse">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
maxLength={150}
|
||||
value={form.sectorInterest}
|
||||
onChange={(e) =>
|
||||
update('sectorInterest', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Modalidade pretendida">
|
||||
<select
|
||||
className={input}
|
||||
required
|
||||
value={form.modality}
|
||||
onChange={(e) => update('modality', e.target.value)}
|
||||
>
|
||||
{modalities.map((modality) => (
|
||||
<option key={modality} value={modality}>
|
||||
{modality.replaceAll('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Intervalo de investimento">
|
||||
<input
|
||||
className={input}
|
||||
maxLength={80}
|
||||
value={form.investmentRange}
|
||||
onChange={(e) =>
|
||||
update('investmentRange', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Motivação e pedido">
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={20}
|
||||
maxLength={2000}
|
||||
rows={5}
|
||||
value={form.message}
|
||||
onChange={(e) => update('message', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<label className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
checked={form.privacyConsent}
|
||||
onChange={(e) =>
|
||||
update('privacyConsent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
Autorizo o tratamento destes dados para responder a
|
||||
esta manifestação. O envio não confirma
|
||||
elegibilidade nem permite partilha automática com o
|
||||
proponente.
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.shareWithProponent}
|
||||
onChange={(e) =>
|
||||
update('shareWithProponent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
Autorizo, se necessário para avaliar esta
|
||||
manifestação, a partilha do meu nome, email,
|
||||
telefone e mensagem com o proponente. Esta
|
||||
autorização é opcional e pode ser retirada junto da
|
||||
equipa.
|
||||
</span>
|
||||
</label>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>{busy ? "A enviar…" : "Enviar manifestação"}</button>
|
||||
<button className={button} disabled={busy}>
|
||||
{busy ? 'A enviar…' : 'Enviar manifestação'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</Frame>
|
||||
|
||||
@@ -1,57 +1,197 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, button, card, input } from "./shared";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { businessModalities } from "./business-types";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, button, card, input } from './shared';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { businessModalities } from './business-types';
|
||||
|
||||
type PublicBusiness = {
|
||||
id: string; slug: string; title: string; modality: string; objective?: string | null; stage?: string | null;
|
||||
amount_min?: string | null; amount_max?: string | null; currency?: string | null;
|
||||
sector?: { name: string; slug: string } | null; province?: string | null;
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
modality: string;
|
||||
objective?: string | null;
|
||||
stage?: string | null;
|
||||
amount_min?: string | null;
|
||||
amount_max?: string | null;
|
||||
currency?: string | null;
|
||||
sector?: { name: string; slug: string } | null;
|
||||
province?: string | null;
|
||||
};
|
||||
type PaginationLink = { url: string | null; label: string; active: boolean };
|
||||
type Props = { results: { data: PublicBusiness[]; links?: PaginationLink[] | { first: string | null; last: string | null; prev: string | null; next: string | null }; meta?: { links?: PaginationLink[]; total?: number } }; filters: { q?: string; modality?: string; province_id?: string; district_id?: string; admin_post_id?: string; locality_id?: string }; territorySelection?: TerritoryOption[] };
|
||||
type Props = {
|
||||
results: {
|
||||
data: PublicBusiness[];
|
||||
links?:
|
||||
| PaginationLink[]
|
||||
| {
|
||||
first: string | null;
|
||||
last: string | null;
|
||||
prev: string | null;
|
||||
next: string | null;
|
||||
};
|
||||
meta?: { links?: PaginationLink[]; total?: number };
|
||||
};
|
||||
filters: {
|
||||
q?: string;
|
||||
modality?: string;
|
||||
province_id?: string;
|
||||
district_id?: string;
|
||||
admin_post_id?: string;
|
||||
locality_id?: string;
|
||||
};
|
||||
territorySelection?: TerritoryOption[];
|
||||
};
|
||||
|
||||
export default function BusinessMarketplace({ results, filters, territorySelection = [] }: Props) {
|
||||
const [query, setQuery] = useState(filters.q ?? "");
|
||||
const [modality, setModality] = useState(filters.modality ?? "");
|
||||
const [territory, setTerritory] = useState<Record<string, string>>({ province_id: filters.province_id ?? "", district_id: filters.district_id ?? "", admin_post_id: filters.admin_post_id ?? "", locality_id: filters.locality_id ?? "" });
|
||||
const returnQuery = new URLSearchParams({ ...(query ? { q: query } : {}), ...(modality ? { modality } : {}), ...territory }).toString();
|
||||
const paginationLinks = results.meta?.links ?? (Array.isArray(results.links) ? results.links : []);
|
||||
export default function BusinessMarketplace({
|
||||
results,
|
||||
filters,
|
||||
territorySelection = [],
|
||||
}: Props) {
|
||||
const [query, setQuery] = useState(filters.q ?? '');
|
||||
const [modality, setModality] = useState(filters.modality ?? '');
|
||||
const [territory, setTerritory] = useState<Record<string, string>>({
|
||||
province_id: filters.province_id ?? '',
|
||||
district_id: filters.district_id ?? '',
|
||||
admin_post_id: filters.admin_post_id ?? '',
|
||||
locality_id: filters.locality_id ?? '',
|
||||
});
|
||||
const returnQuery = new URLSearchParams({
|
||||
...(query ? { q: query } : {}),
|
||||
...(modality ? { modality } : {}),
|
||||
...territory,
|
||||
}).toString();
|
||||
const paginationLinks =
|
||||
results.meta?.links ??
|
||||
(Array.isArray(results.links) ? results.links : []);
|
||||
return (
|
||||
<Frame title="Oportunidades de negócio">
|
||||
<p>Explore oportunidades aprovadas para publicação. A informação está sujeita a diligência independente.</p>
|
||||
<form className="flex flex-wrap gap-3" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
router.get("/negocios", { q: query || undefined, modality: modality || undefined, ...territory }, { preserveState: true, preserveScroll: true });
|
||||
}}>
|
||||
<label className="sr-only" htmlFor="business-search">Pesquisar negócios</label>
|
||||
<input id="business-search" className={input} value={query} maxLength={120} onChange={(event) => setQuery(event.target.value)} />
|
||||
<p>
|
||||
Explore oportunidades aprovadas para publicação. A informação
|
||||
está sujeita a diligência independente.
|
||||
</p>
|
||||
<form
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
router.get(
|
||||
'/negocios',
|
||||
{
|
||||
q: query || undefined,
|
||||
modality: modality || undefined,
|
||||
...territory,
|
||||
},
|
||||
{ preserveState: true, preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label className="sr-only" htmlFor="business-search">
|
||||
Pesquisar negócios
|
||||
</label>
|
||||
<input
|
||||
id="business-search"
|
||||
className={input}
|
||||
value={query}
|
||||
maxLength={120}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
<label className="grid gap-1">
|
||||
<span>Tipo de oportunidade</span>
|
||||
<select className={input} value={modality} onChange={(event) => setModality(event.target.value)}>
|
||||
<select
|
||||
className={input}
|
||||
value={modality}
|
||||
onChange={(event) => setModality(event.target.value)}
|
||||
>
|
||||
<option value="">Todos os tipos</option>
|
||||
{Object.entries(businessModalities).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
|
||||
{Object.entries(businessModalities).map(
|
||||
([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<TerritoryFields initial={territorySelection} onChange={(path) => setTerritory({ province_id: path[0]?.id ?? "", district_id: path[1]?.id ?? "", admin_post_id: path[2]?.id ?? "", locality_id: path[3]?.id ?? "" })} />
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
onChange={(path) =>
|
||||
setTerritory({
|
||||
province_id: path[0]?.id ?? '',
|
||||
district_id: path[1]?.id ?? '',
|
||||
admin_post_id: path[2]?.id ?? '',
|
||||
locality_id: path[3]?.id ?? '',
|
||||
})
|
||||
}
|
||||
/>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<p role="status">{results.meta?.total ?? results.data.length} anúncios de negócios publicados</p>
|
||||
{!results.data.length && <p role="status">Não existem oportunidades publicadas com estes critérios.</p>}
|
||||
<p role="status">
|
||||
{results.meta?.total ?? results.data.length} anúncios de
|
||||
negócios publicados
|
||||
</p>
|
||||
{!results.data.length && (
|
||||
<p role="status">
|
||||
Não existem oportunidades publicadas com estes critérios.
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-4 md:grid-cols-2">
|
||||
{results.data.map((record) => (
|
||||
<li className={card} key={record.id}>
|
||||
<p>{businessModalities[record.modality] ?? record.modality}</p>
|
||||
<h2 className="text-xl font-bold"><Link className="underline" href={`/negocios/${record.slug}${returnQuery ? `?${returnQuery}` : ""}`}>{record.title}</Link></h2>
|
||||
<p>{[record.sector?.name, record.province, record.stage].filter(Boolean).join(" · ")}</p>
|
||||
{(record.amount_min || record.amount_max) && <p>{record.amount_min ?? "—"} – {record.amount_max ?? "—"} {record.currency}</p>}
|
||||
{record.objective && <p className="mt-3 line-clamp-3">{record.objective}</p>}
|
||||
<p>
|
||||
{businessModalities[record.modality] ??
|
||||
record.modality}
|
||||
</p>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/negocios/${record.slug}${returnQuery ? `?${returnQuery}` : ''}`}
|
||||
>
|
||||
{record.title}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{[
|
||||
record.sector?.name,
|
||||
record.province,
|
||||
record.stage,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
{(record.amount_min || record.amount_max) && (
|
||||
<p>
|
||||
{record.amount_min ?? '—'} –{' '}
|
||||
{record.amount_max ?? '—'} {record.currency}
|
||||
</p>
|
||||
)}
|
||||
{record.objective && (
|
||||
<p className="mt-3 line-clamp-3">
|
||||
{record.objective}
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<nav aria-label="Paginação das oportunidades" className="flex flex-wrap gap-3">
|
||||
{paginationLinks.map((link) => link.url ? <Link key={link.label} href={link.url} className={link.active ? "font-bold underline" : "underline"} dangerouslySetInnerHTML={{ __html: link.label }} /> : null)}
|
||||
<nav
|
||||
aria-label="Paginação das oportunidades"
|
||||
className="flex flex-wrap gap-3"
|
||||
>
|
||||
{paginationLinks.map((link) =>
|
||||
link.url ? (
|
||||
<Link
|
||||
key={link.label}
|
||||
href={link.url}
|
||||
className={
|
||||
link.active
|
||||
? 'font-bold underline'
|
||||
: 'underline'
|
||||
}
|
||||
dangerouslySetInnerHTML={{ __html: link.label }}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</nav>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -1,28 +1,79 @@
|
||||
import { Link } from "@inertiajs/react";
|
||||
import { Frame, button, card } from "./shared";
|
||||
import { businessModalities } from "./business-types";
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, button, card } from './shared';
|
||||
import { businessModalities } from './business-types';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
|
||||
type Business = {
|
||||
id: string; slug: string; title: string; modality: string; objective?: string | null; stage?: string | null; activity_code?: string | null;
|
||||
amount_min?: string | null; amount_max?: string | null; available_percentage?: string | null; currency?: string | null;
|
||||
province?: string | null; district?: string | null; locality?: string | null; sector?: { name: string; slug: string } | null;
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
modality: string;
|
||||
objective?: string | null;
|
||||
stage?: string | null;
|
||||
activity_code?: string | null;
|
||||
amount_min?: string | null;
|
||||
amount_max?: string | null;
|
||||
available_percentage?: string | null;
|
||||
currency?: string | null;
|
||||
province?: string | null;
|
||||
district?: string | null;
|
||||
locality?: string | null;
|
||||
sector?: { name: string; slug: string } | null;
|
||||
};
|
||||
|
||||
export default function BusinessOpportunity({ record, returnUrl = "/negocios", interestUrl = `/negocios/${record.slug}/manifestar-interesse` }: { record: Business; returnUrl?: string; interestUrl?: string }) {
|
||||
export default function BusinessOpportunity({
|
||||
record,
|
||||
returnUrl = '/negocios',
|
||||
interestUrl = `/negocios/${record.slug}/manifestar-interesse`,
|
||||
}: {
|
||||
record: Business;
|
||||
returnUrl?: string;
|
||||
interestUrl?: string;
|
||||
}) {
|
||||
return (
|
||||
<Frame title={record.title}>
|
||||
<PartnershipSourceLinks type="business" id={record.id}/>
|
||||
<Link href={returnUrl} className="underline">Voltar às oportunidades</Link>
|
||||
<PartnershipSourceLinks type="business" id={record.id} />
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar às oportunidades
|
||||
</Link>
|
||||
<section className={`${card} space-y-4`}>
|
||||
<p>{businessModalities[record.modality] ?? record.modality}</p>
|
||||
<p>{[record.sector?.name, record.stage, record.activity_code].filter(Boolean).join(" · ")}</p>
|
||||
{(record.province || record.district || record.locality) && <p>{[record.locality, record.district, record.province].filter(Boolean).join(", ")}</p>}
|
||||
{(record.amount_min || record.amount_max) && <p>Montante indicativo: {record.amount_min ?? "—"} – {record.amount_max ?? "—"} {record.currency}</p>}
|
||||
{record.available_percentage && <p>Participação indicada: {record.available_percentage}%</p>}
|
||||
{record.objective && <div><h2 className="font-bold">Objectivo</h2><p className="whitespace-pre-wrap">{record.objective}</p></div>}
|
||||
<p className="text-sm">A publicação não constitui garantia de titularidade, avaliação, transmissibilidade ou retorno.</p>
|
||||
<Link className={button} href={interestUrl}>Manifestar interesse</Link>
|
||||
<p>
|
||||
{[record.sector?.name, record.stage, record.activity_code]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
{(record.province || record.district || record.locality) && (
|
||||
<p>
|
||||
{[record.locality, record.district, record.province]
|
||||
.filter(Boolean)
|
||||
.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{(record.amount_min || record.amount_max) && (
|
||||
<p>
|
||||
Montante indicativo: {record.amount_min ?? '—'} –{' '}
|
||||
{record.amount_max ?? '—'} {record.currency}
|
||||
</p>
|
||||
)}
|
||||
{record.available_percentage && (
|
||||
<p>Participação indicada: {record.available_percentage}%</p>
|
||||
)}
|
||||
{record.objective && (
|
||||
<div>
|
||||
<h2 className="font-bold">Objectivo</h2>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{record.objective}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
A publicação não constitui garantia de titularidade,
|
||||
avaliação, transmissibilidade ou retorno.
|
||||
</p>
|
||||
<Link className={button} href={interestUrl}>
|
||||
Manifestar interesse
|
||||
</Link>
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { api, button, card, Field, input } from "./shared";
|
||||
import type { BusinessObject } from "./business-objects";
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { api, button, card, Field, input } from './shared';
|
||||
import type { BusinessObject } from './business-objects';
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
identity: "Identidade",
|
||||
representation: "Representação",
|
||||
declared_ownership: "Titularidade declarada",
|
||||
documentary_ownership: "Titularidade documental",
|
||||
document_received: "Documento recebido",
|
||||
document_validated: "Documento validado",
|
||||
independent_valuation: "Avaliação independente",
|
||||
land_right_documented: "Direito fundiário documentado",
|
||||
license_confirmed: "Licença confirmada",
|
||||
validity: "Validade",
|
||||
legal_transfer: "Transmissibilidade jurídica",
|
||||
prior_authorization: "Autorização prévia",
|
||||
confirmed: "Confirmado pelo revisor",
|
||||
rejected: "Não confirmado",
|
||||
inconclusive: "Inconclusivo",
|
||||
revoked: "Revogado",
|
||||
stale: "Rever após alteração dos dados",
|
||||
expired: "Expirado",
|
||||
identity: 'Identidade',
|
||||
representation: 'Representação',
|
||||
declared_ownership: 'Titularidade declarada',
|
||||
documentary_ownership: 'Titularidade documental',
|
||||
document_received: 'Documento recebido',
|
||||
document_validated: 'Documento validado',
|
||||
independent_valuation: 'Avaliação independente',
|
||||
land_right_documented: 'Direito fundiário documentado',
|
||||
license_confirmed: 'Licença confirmada',
|
||||
validity: 'Validade',
|
||||
legal_transfer: 'Transmissibilidade jurídica',
|
||||
prior_authorization: 'Autorização prévia',
|
||||
confirmed: 'Confirmado pelo revisor',
|
||||
rejected: 'Não confirmado',
|
||||
inconclusive: 'Inconclusivo',
|
||||
revoked: 'Revogado',
|
||||
stale: 'Rever após alteração dos dados',
|
||||
expired: 'Expirado',
|
||||
};
|
||||
export type BusinessVerification = {
|
||||
check: string;
|
||||
@@ -49,31 +49,38 @@ export default function BusinessVerifications({
|
||||
objects: BusinessObject[];
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [outcome, setOutcome] = useState("inconclusive");
|
||||
const [error, setError] = useState('');
|
||||
const [outcome, setOutcome] = useState('inconclusive');
|
||||
return (
|
||||
<section className={`${card} space-y-4`}>
|
||||
<h2 className="text-xl font-bold">Verificações e evidências</h2>
|
||||
<p>
|
||||
Cada conclusão corresponde apenas ao aspecto e à versão analisados. Não constitui
|
||||
certificação global, autorização de publicação ou garantia de transmissão.
|
||||
Alterações aos dados exigem nova revisão.
|
||||
Cada conclusão corresponde apenas ao aspecto e à versão
|
||||
analisados. Não constitui certificação global, autorização de
|
||||
publicação ou garantia de transmissão. Alterações aos dados
|
||||
exigem nova revisão.
|
||||
</p>
|
||||
{findings.length === 0 && <p>Ainda não existem verificações registadas.</p>}
|
||||
{findings.length === 0 && (
|
||||
<p>Ainda não existem verificações registadas.</p>
|
||||
)}
|
||||
<ul className="space-y-4">
|
||||
{findings.map((finding) => (
|
||||
<li key={finding.version_no} className="break-words">
|
||||
<strong>
|
||||
{labels[finding.check]} · {labels[finding.effective_outcome]}
|
||||
{labels[finding.check]} ·{' '}
|
||||
{labels[finding.effective_outcome]}
|
||||
</strong>
|
||||
<p>
|
||||
{objects.find((object) => object.id === finding.object_id)?.payload
|
||||
.label ?? "Negócio"}{" "}
|
||||
{objects.find(
|
||||
(object) => object.id === finding.object_id,
|
||||
)?.payload.label ?? 'Negócio'}{' '}
|
||||
· versão {finding.version_no}
|
||||
</p>
|
||||
<p>Evidência: {finding.evidence_reference}</p>
|
||||
<p>{finding.note}</p>
|
||||
{finding.valid_until && <p>Válido até {finding.valid_until}</p>}
|
||||
{finding.valid_until && (
|
||||
<p>Válido até {finding.valid_until}</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -82,20 +89,25 @@ export default function BusinessVerifications({
|
||||
className="space-y-4"
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget));
|
||||
const data = Object.fromEntries(
|
||||
new FormData(event.currentTarget),
|
||||
);
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(`/api/v1/existing-business/listings/${id}/verifications`, {
|
||||
...data,
|
||||
version_no: version,
|
||||
});
|
||||
await api(
|
||||
`/api/v1/existing-business/listings/${id}/verifications`,
|
||||
{
|
||||
...data,
|
||||
version_no: version,
|
||||
},
|
||||
);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: "Não foi possível registar a verificação.",
|
||||
: 'Não foi possível registar a verificação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -127,15 +139,20 @@ export default function BusinessVerifications({
|
||||
className={input}
|
||||
name="outcome"
|
||||
value={outcome}
|
||||
onChange={(event) => setOutcome(event.target.value)}
|
||||
onChange={(event) =>
|
||||
setOutcome(event.target.value)
|
||||
}
|
||||
>
|
||||
{["inconclusive", "confirmed", "rejected", "revoked"].map(
|
||||
(value) => (
|
||||
<option key={value} value={value}>
|
||||
{labels[value]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
{[
|
||||
'inconclusive',
|
||||
'confirmed',
|
||||
'rejected',
|
||||
'revoked',
|
||||
].map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{labels[value]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Referência da evidência consultada">
|
||||
@@ -161,7 +178,7 @@ export default function BusinessVerifications({
|
||||
className={input}
|
||||
type="date"
|
||||
name="valid_until"
|
||||
required={outcome === "confirmed"}
|
||||
required={outcome === 'confirmed'}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={busy}>
|
||||
|
||||
@@ -239,8 +239,12 @@ export default function BusinessWizard({
|
||||
const [sectorId, setSectorId] = useState(record.sector_id ?? null);
|
||||
const [sectorSearch, setSectorSearch] = useState('');
|
||||
const [publicTitle, setPublicTitle] = useState(record.public_title ?? '');
|
||||
const [territoryPaths, setTerritoryPaths] = useState(record.territory_paths ?? []);
|
||||
const [resolvedLocationJson, setResolvedLocationJson] = useState(record.payload.locations_json ?? '');
|
||||
const [territoryPaths, setTerritoryPaths] = useState(
|
||||
record.territory_paths ?? [],
|
||||
);
|
||||
const [resolvedLocationJson, setResolvedLocationJson] = useState(
|
||||
record.payload.locations_json ?? '',
|
||||
);
|
||||
const [version, setVersion] = useState(record.version_no);
|
||||
const versionRef = useRef(record.version_no);
|
||||
const saved = useRef(
|
||||
@@ -358,7 +362,9 @@ export default function BusinessWizard({
|
||||
next.locations_json = encodeBusinessLocations(rows);
|
||||
}
|
||||
if (key === 'geography_scope' && value === 'specific') {
|
||||
const first = decodeBusinessLocations(current.locations_json)[0];
|
||||
const first = decodeBusinessLocations(
|
||||
current.locations_json,
|
||||
)[0];
|
||||
if (first?.province_id) {
|
||||
next.province_id = first.province_id;
|
||||
next.district_id = first.district_id;
|
||||
@@ -396,23 +402,33 @@ export default function BusinessWizard({
|
||||
});
|
||||
};
|
||||
const locationRows = decodeBusinessLocations(payload.locations_json);
|
||||
const saveLocationRows = (rows: ReturnType<typeof decodeBusinessLocations>) => {
|
||||
const saveLocationRows = (
|
||||
rows: ReturnType<typeof decodeBusinessLocations>,
|
||||
) => {
|
||||
update('locations_json', encodeBusinessLocations(rows));
|
||||
};
|
||||
const setLocation = (
|
||||
index: number,
|
||||
key: keyof ReturnType<typeof emptyBusinessLocation>,
|
||||
value: string,
|
||||
) => saveLocationRows(updateBusinessLocation(locationRows, index, key, value));
|
||||
) =>
|
||||
saveLocationRows(
|
||||
updateBusinessLocation(locationRows, index, key, value),
|
||||
);
|
||||
const addLocation = () => {
|
||||
if (locationRows.length >= 20) return;
|
||||
saveLocationRows([...locationRows, emptyBusinessLocation()]);
|
||||
};
|
||||
const removeLocation = (index: number) => {
|
||||
const remaining = locationRows.filter((_, rowIndex) => rowIndex !== index);
|
||||
saveLocationRows(remaining.length ? remaining : [emptyBusinessLocation()]);
|
||||
const remaining = locationRows.filter(
|
||||
(_, rowIndex) => rowIndex !== index,
|
||||
);
|
||||
saveLocationRows(
|
||||
remaining.length ? remaining : [emptyBusinessLocation()],
|
||||
);
|
||||
};
|
||||
const duplicateLocationPath = hasDuplicateBusinessLocationPath(locationRows);
|
||||
const duplicateLocationPath =
|
||||
hasDuplicateBusinessLocationPath(locationRows);
|
||||
const fundingNeedsReconciliation = fundingReconciliationWarning(payload);
|
||||
const submit = async () => {
|
||||
if (
|
||||
@@ -635,8 +651,14 @@ export default function BusinessWizard({
|
||||
field.step === step &&
|
||||
key !== 'locations_json' &&
|
||||
!(
|
||||
payload.geography_scope === 'multiple' &&
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].includes(key)
|
||||
payload.geography_scope ===
|
||||
'multiple' &&
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
].includes(key)
|
||||
) &&
|
||||
Object.entries(field.when ?? {}).every(
|
||||
([dependency, values]) =>
|
||||
@@ -758,61 +780,146 @@ export default function BusinessWizard({
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
{step === 5 && payload.geography_scope === 'multiple' && (
|
||||
<section className="space-y-4" aria-labelledby="multiple-locations-heading">
|
||||
<h3 id="multiple-locations-heading" className="font-medium">
|
||||
{t('Localizações administrativas (várias) *', 'Administrative locations (multiple) *')}
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
{t('Indique pelo menos duas localizações distintas. Não são recolhidas coordenadas neste formulário.', 'Enter at least two distinct locations. This form does not collect coordinates.')}
|
||||
</p>
|
||||
{locationRows.map((row, index) => (
|
||||
<fieldset key={index} className="space-y-3 rounded border p-4">
|
||||
<legend className="px-1 font-medium">
|
||||
{t('Localização', 'Location')} {index + 1}
|
||||
</legend>
|
||||
{(['province_id', 'district_id', 'admin_post_id', 'locality_id'] as const).map((key) => {
|
||||
const configuration = territoryField[key];
|
||||
const parentId = configuration.parent
|
||||
? row[configuration.parent as keyof typeof row]
|
||||
: '';
|
||||
const name = t(
|
||||
key === 'province_id' ? 'Província ou Cidade de Maputo' : key === 'district_id' ? 'Distrito' : key === 'admin_post_id' ? 'Posto administrativo' : 'Localidade',
|
||||
key === 'province_id' ? 'Province or Maputo City' : key === 'district_id' ? 'District' : key === 'admin_post_id' ? 'Administrative post' : 'Locality',
|
||||
);
|
||||
return (
|
||||
<Field key={key} label={`${name}${key === 'province_id' ? ' *' : ''}`}>
|
||||
<TerritoryField
|
||||
name={`${name}, ${t('localização', 'location')} ${index + 1}`}
|
||||
type={configuration.type}
|
||||
parentId={parentId}
|
||||
value={row[key]}
|
||||
required={key === 'province_id'}
|
||||
onChange={(value) => setLocation(index, key, value)}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<button type="button" className="underline" disabled={locationRows.length <= 1} onClick={() => removeLocation(index)}>
|
||||
{t('Remover esta localização', 'Remove this location')}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button type="button" className={button} disabled={locationRows.length >= 20} onClick={addLocation}>
|
||||
{t('Adicionar localização', 'Add location')}
|
||||
</button>
|
||||
{locationRows.length < 2 && (
|
||||
<p role="status">
|
||||
{t('Adicione pelo menos mais uma localização antes de submeter.', 'Add at least one more location before submitting.')}
|
||||
{step === 5 &&
|
||||
payload.geography_scope === 'multiple' && (
|
||||
<section
|
||||
className="space-y-4"
|
||||
aria-labelledby="multiple-locations-heading"
|
||||
>
|
||||
<h3
|
||||
id="multiple-locations-heading"
|
||||
className="font-medium"
|
||||
>
|
||||
{t(
|
||||
'Localizações administrativas (várias) *',
|
||||
'Administrative locations (multiple) *',
|
||||
)}
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
{t(
|
||||
'Indique pelo menos duas localizações distintas. Não são recolhidas coordenadas neste formulário.',
|
||||
'Enter at least two distinct locations. This form does not collect coordinates.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{duplicateLocationPath && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{t('Remova percursos administrativos repetidos ou sobrepostos.', 'Remove repeated or overlapping administrative paths.')}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{locationRows.map((row, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<legend className="px-1 font-medium">
|
||||
{t('Localização', 'Location')}{' '}
|
||||
{index + 1}
|
||||
</legend>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key) => {
|
||||
const configuration =
|
||||
territoryField[key];
|
||||
const parentId =
|
||||
configuration.parent
|
||||
? row[
|
||||
configuration.parent as keyof typeof row
|
||||
]
|
||||
: '';
|
||||
const name = t(
|
||||
key === 'province_id'
|
||||
? 'Província ou Cidade de Maputo'
|
||||
: key === 'district_id'
|
||||
? 'Distrito'
|
||||
: key ===
|
||||
'admin_post_id'
|
||||
? 'Posto administrativo'
|
||||
: 'Localidade',
|
||||
key === 'province_id'
|
||||
? 'Province or Maputo City'
|
||||
: key === 'district_id'
|
||||
? 'District'
|
||||
: key ===
|
||||
'admin_post_id'
|
||||
? 'Administrative post'
|
||||
: 'Locality',
|
||||
);
|
||||
return (
|
||||
<Field
|
||||
key={key}
|
||||
label={`${name}${key === 'province_id' ? ' *' : ''}`}
|
||||
>
|
||||
<TerritoryField
|
||||
name={`${name}, ${t('localização', 'location')} ${index + 1}`}
|
||||
type={
|
||||
configuration.type
|
||||
}
|
||||
parentId={parentId}
|
||||
value={row[key]}
|
||||
required={
|
||||
key ===
|
||||
'province_id'
|
||||
}
|
||||
onChange={(value) =>
|
||||
setLocation(
|
||||
index,
|
||||
key,
|
||||
value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={
|
||||
locationRows.length <= 1
|
||||
}
|
||||
onClick={() =>
|
||||
removeLocation(index)
|
||||
}
|
||||
>
|
||||
{t(
|
||||
'Remover esta localização',
|
||||
'Remove this location',
|
||||
)}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={locationRows.length >= 20}
|
||||
onClick={addLocation}
|
||||
>
|
||||
{t(
|
||||
'Adicionar localização',
|
||||
'Add location',
|
||||
)}
|
||||
</button>
|
||||
{locationRows.length < 2 && (
|
||||
<p role="status">
|
||||
{t(
|
||||
'Adicione pelo menos mais uma localização antes de submeter.',
|
||||
'Add at least one more location before submitting.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{duplicateLocationPath && (
|
||||
<p
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{t(
|
||||
'Remova percursos administrativos repetidos ou sobrepostos.',
|
||||
'Remove repeated or overlapping administrative paths.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{step === 7 && (
|
||||
<p role="note">
|
||||
{t(
|
||||
@@ -868,15 +975,20 @@ export default function BusinessWizard({
|
||||
</dd>
|
||||
</div>
|
||||
{Object.entries(formSchema)
|
||||
.filter(([, field]) =>
|
||||
field.type !== 'location_list' &&
|
||||
Object.entries(
|
||||
field.when ?? {},
|
||||
).every(([dependency, values]) =>
|
||||
values.includes(
|
||||
payload[dependency] ?? '',
|
||||
.filter(
|
||||
([, field]) =>
|
||||
field.type !==
|
||||
'location_list' &&
|
||||
Object.entries(
|
||||
field.when ?? {},
|
||||
).every(
|
||||
([dependency, values]) =>
|
||||
values.includes(
|
||||
payload[
|
||||
dependency
|
||||
] ?? '',
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.map(([key, field]) => (
|
||||
<div key={key}>
|
||||
@@ -893,10 +1005,17 @@ export default function BusinessWizard({
|
||||
{payload.geography_scope === 'multiple' && (
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
{t('Localizações administrativas', 'Administrative locations')}
|
||||
{t(
|
||||
'Localizações administrativas',
|
||||
'Administrative locations',
|
||||
)}
|
||||
</dt>
|
||||
<dd>
|
||||
{locationRows.length} {t('localizações indicadas', 'locations entered')}
|
||||
{locationRows.length}{' '}
|
||||
{t(
|
||||
'localizações indicadas',
|
||||
'locations entered',
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
@@ -905,11 +1024,22 @@ export default function BusinessWizard({
|
||||
<ul className="list-disc space-y-1 pl-6">
|
||||
{locationRows.map((_, index) => (
|
||||
<li key={index}>
|
||||
{payload.locations_json === resolvedLocationJson && territoryPaths[index]?.length
|
||||
? territoryPaths[index].join(' → ')
|
||||
: payload.locations_json !== resolvedLocationJson
|
||||
? t('Os nomes serão apresentados depois de guardar este rascunho.', 'Names will appear after this draft is saved.')
|
||||
: t('Percurso territorial indisponível na referência pública actual.', 'Territorial path unavailable in the current public reference data.')}
|
||||
{payload.locations_json ===
|
||||
resolvedLocationJson &&
|
||||
territoryPaths[index]?.length
|
||||
? territoryPaths[
|
||||
index
|
||||
].join(' → ')
|
||||
: payload.locations_json !==
|
||||
resolvedLocationJson
|
||||
? t(
|
||||
'Os nomes serão apresentados depois de guardar este rascunho.',
|
||||
'Names will appear after this draft is saved.',
|
||||
)
|
||||
: t(
|
||||
'Percurso territorial indisponível na referência pública actual.',
|
||||
'Territorial path unavailable in the current public reference data.',
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import { businessModalities, businessStates } from "./business-types";
|
||||
import type { Business } from "./business-types";
|
||||
import BusinessObjects from "./business-objects";
|
||||
import type { BusinessObject } from "./business-objects";
|
||||
import BusinessVerifications from "./business-verifications";
|
||||
import type { BusinessVerification } from "./business-verifications";
|
||||
import BusinessWizard from "./business-wizard";
|
||||
import type { FormSchema } from "./business-wizard";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
import { businessModalities, businessStates } from './business-types';
|
||||
import type { Business } from './business-types';
|
||||
import BusinessObjects from './business-objects';
|
||||
import type { BusinessObject } from './business-objects';
|
||||
import BusinessVerifications from './business-verifications';
|
||||
import type { BusinessVerification } from './business-verifications';
|
||||
import BusinessWizard from './business-wizard';
|
||||
import type { FormSchema } from './business-wizard';
|
||||
|
||||
type Props = {
|
||||
formSchema: FormSchema;
|
||||
@@ -26,12 +26,27 @@ type Props = {
|
||||
objectKinds: string[];
|
||||
verificationChecks: string[];
|
||||
verifications: BusinessVerification[];
|
||||
history: { version_no: number; action: string; created_at: string; note: string }[];
|
||||
history: {
|
||||
version_no: number;
|
||||
action: string;
|
||||
created_at: string;
|
||||
note: string;
|
||||
}[];
|
||||
};
|
||||
export default function BusinessPage(props: Props) {
|
||||
if (props.canEdit)
|
||||
return <BusinessWizard key={props.record.id + ":" + props.record.version_no} {...props} />;
|
||||
return <Editor key={`${props.record.id}:${props.record.version_no}`} {...props} />;
|
||||
return (
|
||||
<BusinessWizard
|
||||
key={props.record.id + ':' + props.record.version_no}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Editor
|
||||
key={`${props.record.id}:${props.record.version_no}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Editor({
|
||||
record,
|
||||
@@ -53,22 +68,28 @@ function Editor({
|
||||
}: Props) {
|
||||
const [payload, setPayload] = useState(record.payload);
|
||||
const [modality, setModality] = useState(record.modality);
|
||||
const [note, setNote] = useState("");
|
||||
const [note, setNote] = useState('');
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const dirty =
|
||||
JSON.stringify(payload) !== JSON.stringify(record.payload) || modality !== record.modality;
|
||||
JSON.stringify(payload) !== JSON.stringify(record.payload) ||
|
||||
modality !== record.modality;
|
||||
const run = async (action?: string) => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(
|
||||
`/api/v1/existing-business/listings/${record.id}${action ? "/transitions" : ""}`,
|
||||
`/api/v1/existing-business/listings/${record.id}${action ? '/transitions' : ''}`,
|
||||
action
|
||||
? { action, version_no: record.version_no, note, review_consent: consent }
|
||||
? {
|
||||
action,
|
||||
version_no: record.version_no,
|
||||
note,
|
||||
review_consent: consent,
|
||||
}
|
||||
: {
|
||||
_method: "PUT",
|
||||
_method: 'PUT',
|
||||
modality,
|
||||
classification: record.classification,
|
||||
payload,
|
||||
@@ -81,7 +102,7 @@ function Editor({
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Não foi possível guardar. Recarregue se a versão mudou.",
|
||||
: 'Não foi possível guardar. Recarregue se a versão mudou.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -91,41 +112,45 @@ function Editor({
|
||||
<Frame title={record.payload.title}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={owner ? "/investidor/negocios" : "/management/negocios"}
|
||||
href={owner ? '/investidor/negocios' : '/management/negocios'}
|
||||
>
|
||||
Voltar à lista
|
||||
</Link>
|
||||
<p>
|
||||
{businessStates[record.status]} · versão {record.version_no} · informação reservada
|
||||
{businessStates[record.status]} · versão {record.version_no} ·
|
||||
informação reservada
|
||||
</p>
|
||||
<p>
|
||||
Informação declarada, pendente de validação. Não constitui anúncio público,
|
||||
certificação, avaliação ou autorização de transmissão.
|
||||
Informação declarada, pendente de validação. Não constitui
|
||||
anúncio público, certificação, avaliação ou autorização de
|
||||
transmissão.
|
||||
</p>
|
||||
{!canEdit && (
|
||||
<dl className={`${card} space-y-3 break-words`}>
|
||||
<div>
|
||||
<dt className="font-bold">Sector</dt>
|
||||
<dd>
|
||||
{sectors.find((sector) => sector.id === record.sector_id)?.name ?? "—"}
|
||||
{sectors.find(
|
||||
(sector) => sector.id === record.sector_id,
|
||||
)?.name ?? '—'}
|
||||
</dd>
|
||||
</div>
|
||||
{Object.entries(formSchema)
|
||||
.filter(
|
||||
([key]) =>
|
||||
![
|
||||
"title",
|
||||
"description",
|
||||
"declared_reason",
|
||||
"source_reference",
|
||||
"valid_until",
|
||||
'title',
|
||||
'description',
|
||||
'declared_reason',
|
||||
'source_reference',
|
||||
'valid_until',
|
||||
].includes(key),
|
||||
)
|
||||
.map(([key, field]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-bold">{field.pt}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{record.payload[key] || "—"}
|
||||
{record.payload[key] || '—'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -154,32 +179,40 @@ function Editor({
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
["title", "Título privado"],
|
||||
["description", "Descrição reservada"],
|
||||
["declared_reason", "Motivo declarado"],
|
||||
["source_reference", "Referência da fonte"],
|
||||
["valid_until", "Validade declarada"],
|
||||
['title', 'Título privado'],
|
||||
['description', 'Descrição reservada'],
|
||||
['declared_reason', 'Motivo declarado'],
|
||||
['source_reference', 'Referência da fonte'],
|
||||
['valid_until', 'Validade declarada'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<Field key={key} label={label}>
|
||||
{key === "description" ? (
|
||||
{key === 'description' ? (
|
||||
<textarea
|
||||
className={input}
|
||||
rows={5}
|
||||
maxLength={10000}
|
||||
value={payload[key] ?? ""}
|
||||
value={payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, [key]: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
type={key === "valid_until" ? "date" : "text"}
|
||||
maxLength={key === "title" ? 200 : 2000}
|
||||
value={payload[key] ?? ""}
|
||||
type={
|
||||
key === 'valid_until' ? 'date' : 'text'
|
||||
}
|
||||
maxLength={key === 'title' ? 200 : 2000}
|
||||
value={payload[key] ?? ''}
|
||||
onChange={(e) =>
|
||||
setPayload({ ...payload, [key]: e.target.value })
|
||||
setPayload({
|
||||
...payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
@@ -198,11 +231,18 @@ function Editor({
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{canEdit && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
)}
|
||||
{dirty && <p role="status">Guarde as alterações antes de mudar de estado.</p>}
|
||||
{dirty && (
|
||||
<p role="status">
|
||||
Guarde as alterações antes de mudar de estado.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
{owner && canEdit && (
|
||||
<label className="flex gap-3">
|
||||
@@ -211,88 +251,126 @@ function Editor({
|
||||
checked={consent}
|
||||
onChange={(e) => setConsent(e.target.checked)}
|
||||
/>
|
||||
Autorizo a análise interna desta submissão pelos revisores designados. Esta
|
||||
autorização não permite publicação.
|
||||
Autorizo a análise interna desta submissão pelos revisores
|
||||
designados. Esta autorização não permite publicação.
|
||||
</label>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{owner && canEdit && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || dirty || !consent || note.trim().length < 10}
|
||||
onClick={() => void run("submitted")}
|
||||
disabled={
|
||||
busy || dirty || !consent || note.trim().length < 10
|
||||
}
|
||||
onClick={() => void run('submitted')}
|
||||
>
|
||||
Submeter para análise
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "submitted" && (
|
||||
{canReview && record.status === 'submitted' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run("in_review")}
|
||||
onClick={() => void run('in_review')}
|
||||
>
|
||||
Iniciar revisão
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "in_review" && (
|
||||
{canReview && record.status === 'in_review' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run("needs_information")}
|
||||
onClick={() => void run('needs_information')}
|
||||
>
|
||||
Pedir informação
|
||||
</button>
|
||||
)}
|
||||
{canTriage && record.status === "submitted" && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("triage")}>
|
||||
{canTriage && record.status === 'submitted' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('triage')}
|
||||
>
|
||||
Iniciar triagem
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "triage" && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("in_review")}>
|
||||
{canReview && record.status === 'triage' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('in_review')}
|
||||
>
|
||||
Encaminhar para revisão
|
||||
</button>
|
||||
)}
|
||||
{canReview && record.status === "in_review" && (
|
||||
{canReview && record.status === 'in_review' && (
|
||||
<>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approval_l1")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('approval_l1')}
|
||||
>
|
||||
Enviar para aprovação nÃvel 1
|
||||
</button>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('rejected')}
|
||||
>
|
||||
Rejeitar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canApproveLevelOne && record.status === "approval_l1" && (
|
||||
{canApproveLevelOne && record.status === 'approval_l1' && (
|
||||
<>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approval_l2")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('approval_l2')}
|
||||
>
|
||||
Aprovar nÃvel 1 e enviar ao nÃvel 2
|
||||
</button>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('rejected')}
|
||||
>
|
||||
Rejeitar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canApproveLevelTwo && record.status === "approval_l2" && (
|
||||
{canApproveLevelTwo && record.status === 'approval_l2' && (
|
||||
<>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approved")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('approved')}
|
||||
>
|
||||
Aprovar nÃvel 2
|
||||
</button>
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('rejected')}
|
||||
>
|
||||
Rejeitar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canPublish && record.status === "approved" && (
|
||||
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("published")}>
|
||||
{canPublish && record.status === 'approved' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || note.trim().length < 10}
|
||||
onClick={() => void run('published')}
|
||||
>
|
||||
Publicar
|
||||
</button>
|
||||
)}
|
||||
{owner && record.status !== "withdrawn" && (
|
||||
{owner && record.status !== 'withdrawn' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || dirty || note.trim().length < 10}
|
||||
onClick={() => void run("withdrawn")}
|
||||
onClick={() => void run('withdrawn')}
|
||||
>
|
||||
Retirar submissão
|
||||
</button>
|
||||
@@ -308,7 +386,7 @@ function Editor({
|
||||
<BusinessVerifications
|
||||
id={record.id}
|
||||
version={record.version_no}
|
||||
editable={canReview && record.status === "in_review" && !busy}
|
||||
editable={canReview && record.status === 'in_review' && !busy}
|
||||
checks={verificationChecks}
|
||||
findings={verifications}
|
||||
objects={objects}
|
||||
@@ -318,20 +396,22 @@ function Editor({
|
||||
<ol>
|
||||
{history.map((h) => (
|
||||
<li key={h.version_no}>
|
||||
Versão {h.version_no} ·{" "}
|
||||
Versão {h.version_no} ·{' '}
|
||||
{businessStates[h.action] ??
|
||||
(
|
||||
{
|
||||
created: "Criado",
|
||||
updated: "Alterado",
|
||||
archived: "Arquivado",
|
||||
object_added: "Elemento declarado acrescentado",
|
||||
object_updated: "Elemento declarado alterado",
|
||||
verification: "Verificação registada",
|
||||
created: 'Criado',
|
||||
updated: 'Alterado',
|
||||
archived: 'Arquivado',
|
||||
object_added:
|
||||
'Elemento declarado acrescentado',
|
||||
object_updated:
|
||||
'Elemento declarado alterado',
|
||||
verification: 'Verificação registada',
|
||||
} as Record<string, string>
|
||||
)[h.action] ??
|
||||
h.action}{" "}
|
||||
· {new Date(h.created_at).toLocaleString("pt-MZ")}
|
||||
h.action}{' '}
|
||||
· {new Date(h.created_at).toLocaleString('pt-MZ')}
|
||||
<p>{h.note}</p>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import { businessModalities, businessStates } from "./business-types";
|
||||
import type { Business } from "./business-types";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
import { businessModalities, businessStates } from './business-types';
|
||||
import type { Business } from './business-types';
|
||||
|
||||
export default function Businesses({
|
||||
records,
|
||||
management,
|
||||
modalities,
|
||||
}: {
|
||||
records: { data: Business[]; prev_page_url: string | null; next_page_url: string | null };
|
||||
records: {
|
||||
data: Business[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
management: boolean;
|
||||
modalities: string[];
|
||||
}) {
|
||||
const [title, setTitle] = useState("");
|
||||
const [title, setTitle] = useState('');
|
||||
const [modality, setModality] = useState(modalities[0]);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Frame title={management ? "Revisão de negócios" : "Os meus negócios"}>
|
||||
<Frame title={management ? 'Revisão de negócios' : 'Os meus negócios'}>
|
||||
<p>
|
||||
Área privada de preparação e revisão. A submissão não confirma titularidade,
|
||||
validade ou transmissibilidade do negócio, activo ou direito.
|
||||
Área privada de preparação e revisão. A submissão não confirma
|
||||
titularidade, validade ou transmissibilidade do negócio, activo
|
||||
ou direito.
|
||||
</p>
|
||||
{!management && (
|
||||
<form
|
||||
@@ -29,20 +34,27 @@ export default function Businesses({
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const result = await api("/api/v1/existing-business/listings", {
|
||||
modality,
|
||||
classification: "confidential",
|
||||
reason: "Criação de rascunho pelo proprietário",
|
||||
payload: { title, wizard_version: "1", wizard_step: "1" },
|
||||
});
|
||||
const result = await api(
|
||||
'/api/v1/existing-business/listings',
|
||||
{
|
||||
modality,
|
||||
classification: 'confidential',
|
||||
reason: 'Criação de rascunho pelo proprietário',
|
||||
payload: {
|
||||
title,
|
||||
wizard_version: '1',
|
||||
wizard_step: '1',
|
||||
},
|
||||
},
|
||||
);
|
||||
router.visit(`/investidor/negocios/${result.id}`);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Não foi possível criar o rascunho.",
|
||||
: 'Não foi possível criar o rascunho.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -74,25 +86,34 @@ export default function Businesses({
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>
|
||||
{busy ? "A criar…" : "Criar rascunho privado"}
|
||||
{busy ? 'A criar…' : 'Criar rascunho privado'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{!records.data.length && <p role="status">Não existem negócios nesta lista.</p>}
|
||||
{!records.data.length && (
|
||||
<p role="status">Não existem negócios nesta lista.</p>
|
||||
)}
|
||||
{records.data.map((r) => (
|
||||
<article className={card} key={r.id}>
|
||||
<Link className="font-bold underline" href={`/investidor/negocios/${r.id}`}>
|
||||
<Link
|
||||
className="font-bold underline"
|
||||
href={`/investidor/negocios/${r.id}`}
|
||||
>
|
||||
{r.payload.title}
|
||||
</Link>
|
||||
<p>
|
||||
{businessModalities[r.modality]} · {businessStates[r.status]} · versão{" "}
|
||||
{r.version_no}
|
||||
{businessModalities[r.modality]} ·{' '}
|
||||
{businessStates[r.status]} · versão {r.version_no}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação dos negócios" className="flex gap-4">
|
||||
{records.prev_page_url && <Link href={records.prev_page_url}>Anterior</Link>}
|
||||
{records.next_page_url && <Link href={records.next_page_url}>Seguinte</Link>}
|
||||
{records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{records.next_page_url && (
|
||||
<Link href={records.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Management } from "../management/shared";
|
||||
import { Field, input, button, card, groupLabels } from "./shared";
|
||||
import type { Opportunity, Context, References } from "./shared";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Management } from '../management/shared';
|
||||
import { Field, input, button, card, groupLabels } from './shared';
|
||||
import type { Opportunity, Context, References } from './shared';
|
||||
export default function EditContext({
|
||||
record,
|
||||
context,
|
||||
@@ -14,11 +14,11 @@ export default function EditContext({
|
||||
const form = useForm({
|
||||
version: context.profile?.version ?? 0,
|
||||
is_education: context.profile?.is_education ?? false,
|
||||
business_model: context.profile?.business_model ?? "",
|
||||
requirements: context.profile?.requirements ?? "",
|
||||
risks: context.profile?.risks ?? "",
|
||||
target_date: context.profile?.target_date ?? "",
|
||||
source_reference: context.profile?.source_reference ?? "",
|
||||
business_model: context.profile?.business_model ?? '',
|
||||
requirements: context.profile?.requirements ?? '',
|
||||
risks: context.profile?.risks ?? '',
|
||||
target_date: context.profile?.target_date ?? '',
|
||||
source_reference: context.profile?.source_reference ?? '',
|
||||
clusters: context.clusters.map((r) => r.id),
|
||||
corridors: context.corridors.map((r) => r.id),
|
||||
projects: context.projects.map((r) => r.id),
|
||||
@@ -26,12 +26,15 @@ export default function EditContext({
|
||||
facets: context.facets.map((r) => r.id),
|
||||
});
|
||||
return (
|
||||
<Management title={"Contexto: " + record.title}>
|
||||
<Management title={'Contexto: ' + record.title}>
|
||||
<p>
|
||||
As relações e características são parte da ficha publicada. Guardar devolve-a a
|
||||
rascunho para revisão.
|
||||
As relações e características são parte da ficha publicada.
|
||||
Guardar devolve-a a rascunho para revisão.
|
||||
</p>
|
||||
<Link href={`/management/opportunities/${record.id}/edit`} className="underline">
|
||||
<Link
|
||||
href={`/management/opportunities/${record.id}/edit`}
|
||||
className="underline"
|
||||
>
|
||||
Editar e publicar a ficha principal
|
||||
</Link>
|
||||
<form
|
||||
@@ -39,7 +42,8 @@ export default function EditContext({
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.put(`/management/opportunities/${record.id}/context`, {
|
||||
onSuccess: () => form.setData("version", form.data.version + 1),
|
||||
onSuccess: () =>
|
||||
form.setData('version', form.data.version + 1),
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -47,15 +51,36 @@ export default function EditContext({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.is_education}
|
||||
onChange={(e) => form.setData("is_education", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
form.setData('is_education', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Oportunidade na educação
|
||||
</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(["clusters", "corridors", "projects", "locations"] as const).map((key, i) => (
|
||||
<fieldset className={card + " max-h-72 space-y-2 overflow-auto"} key={key}>
|
||||
{(
|
||||
[
|
||||
'clusters',
|
||||
'corridors',
|
||||
'projects',
|
||||
'locations',
|
||||
] as const
|
||||
).map((key, i) => (
|
||||
<fieldset
|
||||
className={
|
||||
card + ' max-h-72 space-y-2 overflow-auto'
|
||||
}
|
||||
key={key}
|
||||
>
|
||||
<legend className="font-bold">
|
||||
{["Clusters", "Corredores", "Projectos âncora", "Localizações"][i]}
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
'Localizações',
|
||||
][i]
|
||||
}
|
||||
</legend>
|
||||
{references[key].map((r) => (
|
||||
<label key={r.id} className="flex gap-2">
|
||||
@@ -67,7 +92,9 @@ export default function EditContext({
|
||||
key,
|
||||
e.target.checked
|
||||
? [...form.data[key], r.id]
|
||||
: form.data[key].filter((id) => id !== r.id),
|
||||
: form.data[key].filter(
|
||||
(id) => id !== r.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
@@ -79,18 +106,20 @@ export default function EditContext({
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{[
|
||||
"subsector",
|
||||
"education",
|
||||
"infrastructure",
|
||||
"labour",
|
||||
"qualification",
|
||||
"support",
|
||||
"impact",
|
||||
"partnership",
|
||||
'subsector',
|
||||
'education',
|
||||
'infrastructure',
|
||||
'labour',
|
||||
'qualification',
|
||||
'support',
|
||||
'impact',
|
||||
'partnership',
|
||||
].map((group) => (
|
||||
<fieldset
|
||||
key={group}
|
||||
className={card + " max-h-64 space-y-2 overflow-auto"}
|
||||
className={
|
||||
card + ' max-h-64 space-y-2 overflow-auto'
|
||||
}
|
||||
>
|
||||
<legend>{groupLabels[group]}</legend>
|
||||
{references.options
|
||||
@@ -99,14 +128,21 @@ export default function EditContext({
|
||||
<label key={o.id} className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.facets.includes(o.id)}
|
||||
checked={form.data.facets.includes(
|
||||
o.id,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
"facets",
|
||||
'facets',
|
||||
e.target.checked
|
||||
? [...form.data.facets, o.id]
|
||||
? [
|
||||
...form.data
|
||||
.facets,
|
||||
o.id,
|
||||
]
|
||||
: form.data.facets.filter(
|
||||
(id) => id !== o.id,
|
||||
(id) =>
|
||||
id !== o.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -117,35 +153,43 @@ export default function EditContext({
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
{(["business_model", "requirements", "risks", "source_reference"] as const).map(
|
||||
(key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
business_model: "Modelo de negócio",
|
||||
requirements: "Requisitos e necessidades",
|
||||
risks: "Riscos",
|
||||
source_reference: "Fonte e referência de autorização",
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={input}
|
||||
required={key === "source_reference"}
|
||||
rows={3}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'business_model',
|
||||
'requirements',
|
||||
'risks',
|
||||
'source_reference',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
business_model: 'Modelo de negócio',
|
||||
requirements: 'Requisitos e necessidades',
|
||||
risks: 'Riscos',
|
||||
source_reference:
|
||||
'Fonte e referência de autorização',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={input}
|
||||
required={key === 'source_reference'}
|
||||
rows={3}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Data-alvo">
|
||||
<input
|
||||
type="date"
|
||||
className={input}
|
||||
value={form.data.target_date}
|
||||
onChange={(e) => form.setData("target_date", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('target_date', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { newSubmissionKey } from "@/lib/portal-api";
|
||||
import { Field, card, input, button, api } from "./shared";
|
||||
export type Message = { id: string; sender_role: string; body: string; created_at: string };
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { newSubmissionKey } from '@/lib/portal-api';
|
||||
import { Field, card, input, button, api } from './shared';
|
||||
export type Message = {
|
||||
id: string;
|
||||
sender_role: string;
|
||||
body: string;
|
||||
created_at: string;
|
||||
};
|
||||
export function Conversation({
|
||||
id,
|
||||
messages,
|
||||
@@ -14,7 +19,7 @@ export function Conversation({
|
||||
submitted: boolean;
|
||||
revisions: { version: number; created_at: string }[];
|
||||
}) {
|
||||
const form = useForm({ client_key: newSubmissionKey(), body: "" });
|
||||
const form = useForm({ client_key: newSubmissionKey(), body: '' });
|
||||
const [revision, setRevision] = useState<{
|
||||
version: number;
|
||||
snapshot: {
|
||||
@@ -28,31 +33,37 @@ export function Conversation({
|
||||
attachment_ids: string[];
|
||||
};
|
||||
} | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
return (
|
||||
<>
|
||||
<section className={card + " space-y-4"}>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">Versões guardadas</h2>
|
||||
<Field label="Consultar versão">
|
||||
<select
|
||||
className={input}
|
||||
defaultValue=""
|
||||
onChange={(e) => {
|
||||
setError("");
|
||||
setError('');
|
||||
if (!e.target.value) {
|
||||
setRevision(null);
|
||||
return;
|
||||
}
|
||||
api(`/api/v1/investment/submissions/${id}/revisions/${e.target.value}`)
|
||||
api(
|
||||
`/api/v1/investment/submissions/${id}/revisions/${e.target.value}`,
|
||||
)
|
||||
.then(setRevision)
|
||||
.catch(() => setError("Não foi possível consultar esta versão."));
|
||||
.catch(() =>
|
||||
setError(
|
||||
'Não foi possível consultar esta versão.',
|
||||
),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccionar versão</option>
|
||||
{revisions.map((r) => (
|
||||
<option value={r.version} key={r.version}>
|
||||
Versão {r.version} —{" "}
|
||||
{new Date(r.created_at).toLocaleString("pt-MZ")}
|
||||
Versão {r.version} —{' '}
|
||||
{new Date(r.created_at).toLocaleString('pt-MZ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -62,49 +73,70 @@ export function Conversation({
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-bold">Versão {revision.version}</h3>
|
||||
<p>Investidor: {revision.snapshot.payload.full_name}</p>
|
||||
<p>Empresa: {revision.snapshot.payload.organisation || "Não indicada"}</p>
|
||||
<p className="whitespace-pre-line">
|
||||
Objectivo: {revision.snapshot.payload.objective || "Não indicado"}
|
||||
<p>
|
||||
Empresa:{' '}
|
||||
{revision.snapshot.payload.organisation ||
|
||||
'Não indicada'}
|
||||
</p>
|
||||
<p className="whitespace-pre-line">
|
||||
Objectivo:{' '}
|
||||
{revision.snapshot.payload.objective ||
|
||||
'Não indicado'}
|
||||
</p>
|
||||
<p>
|
||||
Prazo:{' '}
|
||||
{revision.snapshot.payload.horizon ||
|
||||
'Não indicado'}
|
||||
</p>
|
||||
<p>Prazo: {revision.snapshot.payload.horizon || "Não indicado"}</p>
|
||||
<ul>
|
||||
{revision.snapshot.needs.map((n, i) => (
|
||||
<li key={i}>{n.details.description}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
{revision.snapshot.attachment_ids.length} anexos associados nessa
|
||||
versão.
|
||||
{revision.snapshot.attachment_ids.length} anexos
|
||||
associados nessa versão.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
{submitted && (
|
||||
<section className={card + " space-y-4"}>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">Conversa com o apoio</h2>
|
||||
<p>
|
||||
As mensagens ficam registadas neste pedido e são visíveis ao investidor e à
|
||||
equipa autorizada.
|
||||
As mensagens ficam registadas neste pedido e são
|
||||
visíveis ao investidor e à equipa autorizada.
|
||||
</p>
|
||||
{messages.map((m) => (
|
||||
<article key={m.id} className="rounded-lg border p-4">
|
||||
<p className="font-semibold">
|
||||
{m.sender_role === "support" ? "Apoio ao Investidor" : "Investidor"}{" "}
|
||||
· {new Date(m.created_at).toLocaleString("pt-MZ")}
|
||||
{m.sender_role === 'support'
|
||||
? 'Apoio ao Investidor'
|
||||
: 'Investidor'}{' '}
|
||||
·{' '}
|
||||
{new Date(m.created_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
<p className="mt-2 whitespace-pre-line">{m.body}</p>
|
||||
</article>
|
||||
))}
|
||||
{!messages.length && <p>Ainda não existem mensagens neste pedido.</p>}
|
||||
{!messages.length && (
|
||||
<p>Ainda não existem mensagens neste pedido.</p>
|
||||
)}
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(`/investidor/manifestacoes/${id}/messages`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
form.setData({ client_key: newSubmissionKey(), body: "" }),
|
||||
});
|
||||
form.post(
|
||||
`/investidor/manifestacoes/${id}/messages`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: () =>
|
||||
form.setData({
|
||||
client_key: newSubmissionKey(),
|
||||
body: '',
|
||||
}),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="Mensagem para acompanhamento">
|
||||
@@ -115,7 +147,9 @@ export function Conversation({
|
||||
minLength={3}
|
||||
maxLength={5000}
|
||||
value={form.data.body}
|
||||
onChange={(e) => form.setData("body", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('body', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { Link, router, usePage } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import InvestmentMapPanel from '@/components/investment-map-panel';
|
||||
import StructureGeographyPanel from '@/components/structure-geography';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import { Frame, card, button, money, groupLabels } from "./shared";
|
||||
import type { Opportunity, Context } from "./shared";
|
||||
import { Frame, card, button, money, groupLabels } from './shared';
|
||||
import type { Opportunity, Context } from './shared';
|
||||
export default function Detail({
|
||||
record: r,
|
||||
context: c,
|
||||
zone_origin,
|
||||
returnUrl = "/oportunidades",
|
||||
returnUrl = '/oportunidades',
|
||||
dossierOrigin,
|
||||
}: {
|
||||
record: Opportunity;
|
||||
@@ -19,34 +19,57 @@ export default function Detail({
|
||||
dossierOrigin?: { id: string; title: string } | null;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
const [sharing, setSharing] = useState("");
|
||||
const [sharing, setSharing] = useState('');
|
||||
return (
|
||||
<Frame title={r.title}>
|
||||
<PartnershipSourceLinks type="investment" id={r.id}/>
|
||||
<Link href={returnUrl} className="underline">Voltar à pesquisa</Link>
|
||||
{dossierOrigin && <p><Link className="underline" href={`/carteira/${dossierOrigin.id}`}>Voltar ao dossier: {dossierOrigin.title}</Link></p>}
|
||||
<PartnershipSourceLinks type="investment" id={r.id} />
|
||||
<Link href={returnUrl} className="underline">
|
||||
Voltar à pesquisa
|
||||
</Link>
|
||||
{dossierOrigin && (
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/carteira/${dossierOrigin.id}`}
|
||||
>
|
||||
Voltar ao dossier: {dossierOrigin.title}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
{r.reference} · {r.sector?.name} · {r.province} {r.district}
|
||||
</p>
|
||||
{!r.last_validated_at && (
|
||||
<p className="rounded border border-amber-700 bg-amber-50 p-4">
|
||||
Esta ficha não regista data de validação documental. Confirme a origem e as condições antes de agir. Preparar uma manifestação expressa interesse; não confirma a oferta nem representa aprovação.
|
||||
Esta ficha não regista data de validação documental.
|
||||
Confirme a origem e as condições antes de agir. Preparar uma
|
||||
manifestação expressa interesse; não confirma a oferta nem
|
||||
representa aprovação.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
|
||||
{c.primary_territory_path && c.primary_territory_path.length > 0 && (
|
||||
<p>Localização: {c.primary_territory_path.map((node) => node.name).join(" → ")}</p>
|
||||
)}
|
||||
{c.primary_territory_path &&
|
||||
c.primary_territory_path.length > 0 && (
|
||||
<p>
|
||||
Localização:{' '}
|
||||
{c.primary_territory_path
|
||||
.map((node) => node.name)
|
||||
.join(' → ')}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{auth.user ? (
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post("/investidor/manifestacoes", {
|
||||
router.post('/investidor/manifestacoes', {
|
||||
opportunity_id: r.id,
|
||||
...(zone_origin
|
||||
? { zone_id: zone_origin.id, intent: "interest" }
|
||||
? {
|
||||
zone_id: zone_origin.id,
|
||||
intent: 'interest',
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
@@ -58,21 +81,28 @@ export default function Detail({
|
||||
Entrar para preparar manifestação
|
||||
</Link>
|
||||
)}
|
||||
<Link className="underline" href={`/manifestar-interesse/${r.slug}`}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/manifestar-interesse/${r.slug}`}
|
||||
>
|
||||
Contacto rápido sem rascunho
|
||||
</Link>
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() => {
|
||||
if (!navigator.clipboard) {
|
||||
setSharing("Copie a ligação na barra de endereço do navegador.");
|
||||
setSharing(
|
||||
'Copie a ligação na barra de endereço do navegador.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
navigator.clipboard
|
||||
.writeText(window.location.href)
|
||||
.then(() => setSharing("Ligação copiada."))
|
||||
.then(() => setSharing('Ligação copiada.'))
|
||||
.catch(() =>
|
||||
setSharing("Copie a ligação na barra de endereço do navegador."),
|
||||
setSharing(
|
||||
'Copie a ligação na barra de endereço do navegador.',
|
||||
),
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -82,7 +112,9 @@ export default function Detail({
|
||||
{sharing && <p role="status">{sharing}</p>}
|
||||
{!!c.zones?.length && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">ZEE, ZFI e parques associados</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
ZEE, ZFI e parques associados
|
||||
</h2>
|
||||
{c.zones.map((z) => (
|
||||
<p key={z.id}>
|
||||
<Link
|
||||
@@ -90,50 +122,59 @@ export default function Detail({
|
||||
href={`/zonas?category=${z.category}&q=${encodeURIComponent(z.name)}`}
|
||||
>
|
||||
{z.name}
|
||||
</Link>{" "}
|
||||
·{" "}
|
||||
{z.association_type === "official"
|
||||
? "Associação documental validada"
|
||||
: "Relação " + z.association_type}{" "}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
{z.association_type === 'official'
|
||||
? 'Associação documental validada'
|
||||
: 'Relação ' + z.association_type}{' '}
|
||||
· Fonte: {z.source_reference}
|
||||
</p>
|
||||
))}
|
||||
<p>A associação não atribui automaticamente benefícios ou licenças.</p>
|
||||
<p>
|
||||
A associação não atribui automaticamente benefícios ou
|
||||
licenças.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<section className={card + " whitespace-pre-line lg:col-span-2"}>
|
||||
<section
|
||||
className={card + ' whitespace-pre-line lg:col-span-2'}
|
||||
>
|
||||
<h2 className="mb-3 text-xl font-bold">O investimento</h2>
|
||||
{r.description || "Descrição por completar."}
|
||||
{r.description || 'Descrição por completar.'}
|
||||
</section>
|
||||
<dl className={card + " space-y-4"}>
|
||||
<dl className={card + ' space-y-4'}>
|
||||
{[
|
||||
["Promotor", r.promoter_name],
|
||||
["Investimento", money(r)],
|
||||
["Maturidade", r.maturity_label],
|
||||
["Parceria", r.financing_modality],
|
||||
["Impacto", r.expected_impact],
|
||||
["Calendário", c.profile?.target_date],
|
||||
['Promotor', r.promoter_name],
|
||||
['Investimento', money(r)],
|
||||
['Maturidade', r.maturity_label],
|
||||
['Parceria', r.financing_modality],
|
||||
['Impacto', r.expected_impact],
|
||||
['Calendário', c.profile?.target_date],
|
||||
].map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-bold">{key}</dt>
|
||||
<dd>{value || "Não indicado"}</dd>
|
||||
<dd>{value || 'Não indicado'}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
{c.profile && (
|
||||
<section className={card + " space-y-4"}>
|
||||
<h2 className="text-xl font-bold">Viabilidade e preparação</h2>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Viabilidade e preparação
|
||||
</h2>
|
||||
{[
|
||||
["Modelo de negócio", c.profile.business_model],
|
||||
["Requisitos", c.profile.requirements],
|
||||
["Riscos", c.profile.risks],
|
||||
["Fonte", c.profile.source_reference],
|
||||
['Modelo de negócio', c.profile.business_model],
|
||||
['Requisitos', c.profile.requirements],
|
||||
['Riscos', c.profile.risks],
|
||||
['Fonte', c.profile.source_reference],
|
||||
].map(([label, text]) => (
|
||||
<div key={label}>
|
||||
<h3 className="font-bold">{label}</h3>
|
||||
<p className="whitespace-pre-line">{text || "Não indicado"}</p>
|
||||
<p className="whitespace-pre-line">
|
||||
{text || 'Não indicado'}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
{c.profile.is_education && (
|
||||
@@ -144,25 +185,44 @@ export default function Detail({
|
||||
</section>
|
||||
)}
|
||||
<section className="grid gap-4 md:grid-cols-4">
|
||||
{(["clusters", "corridors", "projects", "locations"] as const).map((key, i) => (
|
||||
{(
|
||||
['clusters', 'corridors', 'projects', 'locations'] as const
|
||||
).map((key, i) => (
|
||||
<div className={card} key={key}>
|
||||
<h2 className="font-bold">
|
||||
{["Clusters", "Corredores", "Projectos âncora", "Territórios"][i]}
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
'Territórios',
|
||||
][i]
|
||||
}
|
||||
</h2>
|
||||
{c[key].map((entity) => (
|
||||
<p key={entity.id}>
|
||||
{entity.dossiers?.map(dossier => <span key={dossier.id}><Link className="underline" href={`/carteira/${dossier.id}`}>Consultar dossier: {dossier.title}</Link><br /></span>)}
|
||||
{entity.dossiers?.map((dossier) => (
|
||||
<span key={dossier.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/carteira/${dossier.id}`}
|
||||
>
|
||||
Consultar dossier: {dossier.title}
|
||||
</Link>
|
||||
<br />
|
||||
</span>
|
||||
))}
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
"/oportunidades?" +
|
||||
'/oportunidades?' +
|
||||
[
|
||||
"cluster_id",
|
||||
"corridor_id",
|
||||
"project_id",
|
||||
"geo_location_id",
|
||||
'cluster_id',
|
||||
'corridor_id',
|
||||
'project_id',
|
||||
'geo_location_id',
|
||||
][i] +
|
||||
"=" +
|
||||
'=' +
|
||||
entity.id
|
||||
}
|
||||
>
|
||||
@@ -174,7 +234,20 @@ export default function Detail({
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
{(['projects','clusters'] as const).flatMap(key => c[key].filter(entity => entity.geography && entity.dossiers?.length).map(entity => <StructureGeographyPanel key={`${key}-${entity.id}`} geography={entity.geography!} cluster={key === 'clusters'} dossierId={entity.dossiers![0].id} />))}
|
||||
{(['projects', 'clusters'] as const).flatMap((key) =>
|
||||
c[key]
|
||||
.filter(
|
||||
(entity) => entity.geography && entity.dossiers?.length,
|
||||
)
|
||||
.map((entity) => (
|
||||
<StructureGeographyPanel
|
||||
key={`${key}-${entity.id}`}
|
||||
geography={entity.geography!}
|
||||
cluster={key === 'clusters'}
|
||||
dossierId={entity.dossiers![0].id}
|
||||
/>
|
||||
)),
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
Infraestruturas, competências, educação e apoios
|
||||
@@ -186,8 +259,9 @@ export default function Detail({
|
||||
))}
|
||||
{!c.facets.length && (
|
||||
<p>
|
||||
Sem características estruturadas publicadas. Pode declarar as suas
|
||||
necessidades na manifestação de interesse.
|
||||
Sem características estruturadas publicadas. Pode
|
||||
declarar as suas necessidades na manifestação de
|
||||
interesse.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { Frame, card, button } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, button } from './shared';
|
||||
export default function Notifications({
|
||||
unread,
|
||||
notifications,
|
||||
@@ -19,10 +19,10 @@ export default function Notifications({
|
||||
};
|
||||
}) {
|
||||
const states: Record<string, string> = {
|
||||
received: "Recebido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
closed: "Encerrado",
|
||||
received: 'Recebido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
closed: 'Encerrado',
|
||||
};
|
||||
return (
|
||||
<Frame title="Notificações e acompanhamento">
|
||||
@@ -31,24 +31,28 @@ export default function Notifications({
|
||||
</Link>
|
||||
<p role="status">{unread} notificações por ler</p>
|
||||
{notifications.data.map((n) => (
|
||||
<article key={n.id} className={card + " space-y-3"}>
|
||||
<article key={n.id} className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
{n.kind === "received"
|
||||
? "Manifestação recebida"
|
||||
: n.kind === "status"
|
||||
? "Estado actualizado"
|
||||
: "Nova mensagem na conversa"}
|
||||
{n.kind === 'received'
|
||||
? 'Manifestação recebida'
|
||||
: n.kind === 'status'
|
||||
? 'Estado actualizado'
|
||||
: 'Nova mensagem na conversa'}
|
||||
</h2>
|
||||
<p>
|
||||
{n.payload.reference ??
|
||||
(n.payload.status
|
||||
? (states[n.payload.status] ?? n.payload.status)
|
||||
: "Consulte o pedido para ler a mensagem.")}
|
||||
: 'Consulte o pedido para ler a mensagem.')}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{new Date(n.created_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
<p className="text-sm">{new Date(n.created_at).toLocaleString("pt-MZ")}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
href={"/investidor/manifestacoes/" + n.submission_id}
|
||||
href={
|
||||
'/investidor/manifestacoes/' + n.submission_id
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
Abrir manifestação
|
||||
@@ -58,7 +62,9 @@ export default function Notifications({
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
"/investidor/notifications/" + n.id + "/read",
|
||||
'/investidor/notifications/' +
|
||||
n.id +
|
||||
'/read',
|
||||
{},
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
@@ -70,7 +76,9 @@ export default function Notifications({
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
{!notifications.data.length && <p>Ainda não existem notificações.</p>}
|
||||
{!notifications.data.length && (
|
||||
<p>Ainda não existem notificações.</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className="flex gap-4">
|
||||
{notifications.prev_page_url && (
|
||||
<Link href={notifications.prev_page_url}>Anterior</Link>
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { Link, router, useForm } from "@inertiajs/react";
|
||||
import { Frame, Field, input, button, card } from "./shared";
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
|
||||
type RecordData = { version: number; payload: Record<string, string> };
|
||||
type Company = RecordData & { id: string };
|
||||
const labels: Record<string, string> = {
|
||||
phone: "Telefone",
|
||||
country: "País",
|
||||
sector: "Sector de interesse",
|
||||
experience: "Experiência relevante",
|
||||
investment_capacity: "Capacidade de investimento declarada",
|
||||
name: "Nome da empresa",
|
||||
registration: "Referência de registo / NUIT",
|
||||
role: "Função ou relação com a empresa",
|
||||
description: "Actividade e observações",
|
||||
phone: 'Telefone',
|
||||
country: 'País',
|
||||
sector: 'Sector de interesse',
|
||||
experience: 'Experiência relevante',
|
||||
investment_capacity: 'Capacidade de investimento declarada',
|
||||
name: 'Nome da empresa',
|
||||
registration: 'Referência de registo / NUIT',
|
||||
role: 'Função ou relação com a empresa',
|
||||
description: 'Actividade e observações',
|
||||
};
|
||||
|
||||
export default function Profile({
|
||||
@@ -29,43 +29,54 @@ export default function Profile({
|
||||
Voltar à área do investidor
|
||||
</Link>
|
||||
<p>
|
||||
Estes dados são privados e servem para preencher novas manifestações. Nome e email
|
||||
são mantidos nas{" "}
|
||||
Estes dados são privados e servem para preencher novas
|
||||
manifestações. Nome e email são mantidos nas{' '}
|
||||
<Link className="underline" href="/settings/profile">
|
||||
definições da conta
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
<Editor
|
||||
key={"account-" + account.version}
|
||||
key={'account-' + account.version}
|
||||
record={account}
|
||||
fields={["phone", "country", "sector", "experience", "investment_capacity"]}
|
||||
fields={[
|
||||
'phone',
|
||||
'country',
|
||||
'sector',
|
||||
'experience',
|
||||
'investment_capacity',
|
||||
]}
|
||||
/>
|
||||
<h2 className="text-2xl font-bold">Empresas declaradas</h2>
|
||||
<p>
|
||||
Declarar uma empresa não comprova representação legal nem concede acesso aos
|
||||
registos de outras pessoas. A equipa pode pedir evidência durante o atendimento.
|
||||
Declarar uma empresa não comprova representação legal nem
|
||||
concede acesso aos registos de outras pessoas. A equipa pode
|
||||
pedir evidência durante o atendimento.
|
||||
</p>
|
||||
{companies.map((company) => (
|
||||
<section key={company.id} className={card}>
|
||||
<PartnershipSourceLinks type="company" id={company.id}/>
|
||||
<h3 className="text-xl font-bold">{company.payload.name}</h3>
|
||||
<PartnershipSourceLinks type="company" id={company.id} />
|
||||
<h3 className="text-xl font-bold">
|
||||
{company.payload.name}
|
||||
</h3>
|
||||
<Editor
|
||||
key={company.version}
|
||||
record={company}
|
||||
fields={[
|
||||
"name",
|
||||
"country",
|
||||
"registration",
|
||||
"sector",
|
||||
"role",
|
||||
"description",
|
||||
'name',
|
||||
'country',
|
||||
'registration',
|
||||
'sector',
|
||||
'role',
|
||||
'description',
|
||||
]}
|
||||
/>
|
||||
<button
|
||||
className={button + " mt-4"}
|
||||
className={button + ' mt-4'}
|
||||
onClick={() =>
|
||||
router.post("/investidor/manifestacoes", { company_id: company.id })
|
||||
router.post('/investidor/manifestacoes', {
|
||||
company_id: company.id,
|
||||
})
|
||||
}
|
||||
>
|
||||
Preparar manifestação desta empresa
|
||||
@@ -76,16 +87,16 @@ export default function Profile({
|
||||
<section className={card}>
|
||||
<h3 className="text-xl font-bold">Acrescentar empresa</h3>
|
||||
<Editor
|
||||
key={"new-" + companies.length}
|
||||
key={'new-' + companies.length}
|
||||
record={{ version: 0, payload: {} }}
|
||||
company
|
||||
fields={[
|
||||
"name",
|
||||
"country",
|
||||
"registration",
|
||||
"sector",
|
||||
"role",
|
||||
"description",
|
||||
'name',
|
||||
'country',
|
||||
'registration',
|
||||
'sector',
|
||||
'role',
|
||||
'description',
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
@@ -105,7 +116,9 @@ function Editor({
|
||||
const isCompany = company || !!record.id;
|
||||
const form = useForm({
|
||||
version: record.version,
|
||||
payload: Object.fromEntries(fields.map((key) => [key, record.payload[key] ?? ""])),
|
||||
payload: Object.fromEntries(
|
||||
fields.map((key) => [key, record.payload[key] ?? '']),
|
||||
),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
@@ -115,10 +128,11 @@ function Editor({
|
||||
const options = { preserveScroll: true };
|
||||
if (isCompany)
|
||||
form.post(
|
||||
"/investidor/companies" + (record.id ? "/" + record.id : ""),
|
||||
'/investidor/companies' +
|
||||
(record.id ? '/' + record.id : ''),
|
||||
options,
|
||||
);
|
||||
else form.put("/investidor/profile", options);
|
||||
else form.put('/investidor/profile', options);
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
@@ -127,16 +141,19 @@ function Editor({
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.payload[key]}
|
||||
required={isCompany && ["name", "country", "role"].includes(key)}
|
||||
required={
|
||||
isCompany &&
|
||||
['name', 'country', 'role'].includes(key)
|
||||
}
|
||||
maxLength={
|
||||
key === "description" || key === "experience"
|
||||
key === 'description' || key === 'experience'
|
||||
? 2000
|
||||
: key === "investment_capacity"
|
||||
: key === 'investment_capacity'
|
||||
? 1000
|
||||
: 200
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
@@ -151,7 +168,9 @@ function Editor({
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={form.processing}>
|
||||
{isCompany ? "Guardar declaração da empresa" : "Guardar perfil de investimento"}
|
||||
{isCompany
|
||||
? 'Guardar declaração da empresa'
|
||||
: 'Guardar perfil de investimento'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { useForm } from "@inertiajs/react";
|
||||
import { Management } from "../management/shared";
|
||||
import { Field, input, button, card, groupLabels } from "./shared";
|
||||
import type { Option } from "./shared";
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { Management } from '../management/shared';
|
||||
import { Field, input, button, card, groupLabels } from './shared';
|
||||
import type { Option } from './shared';
|
||||
export default function References({ options }: { options: Option[] }) {
|
||||
const groups = [...new Set(options.map((o) => o.group))];
|
||||
return (
|
||||
<Management title="Opções dos formulários e filtros">
|
||||
<p>
|
||||
Os códigos são estáveis; pode corrigir etiquetas ou desactivar opções sem eliminar
|
||||
referências históricas. Cada grupo conserva Outro — especificar.
|
||||
Os códigos são estáveis; pode corrigir etiquetas ou desactivar
|
||||
opções sem eliminar referências históricas. Cada grupo conserva
|
||||
Outro — especificar.
|
||||
</p>
|
||||
<OptionForm groups={groups} />
|
||||
<div className="space-y-4">
|
||||
@@ -21,7 +22,11 @@ export default function References({ options }: { options: Option[] }) {
|
||||
{options
|
||||
.filter((o) => o.group === group)
|
||||
.map((o) => (
|
||||
<OptionForm key={o.id} option={o} groups={groups} />
|
||||
<OptionForm
|
||||
key={o.id}
|
||||
option={o}
|
||||
groups={groups}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
@@ -33,8 +38,8 @@ export default function References({ options }: { options: Option[] }) {
|
||||
function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
const form = useForm({
|
||||
group: option?.group ?? groups[0],
|
||||
code: option?.code ?? "",
|
||||
label: option?.label ?? "",
|
||||
code: option?.code ?? '',
|
||||
label: option?.label ?? '',
|
||||
active: option?.active ?? true,
|
||||
requires_description: option?.requires_description ?? false,
|
||||
sort_order: option?.sort_order ?? 0,
|
||||
@@ -44,19 +49,25 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
className="space-y-3 rounded border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post("/management/investment/references" + (option ? "/" + option.id : ""), {
|
||||
preserveScroll: true,
|
||||
});
|
||||
form.post(
|
||||
'/management/investment/references' +
|
||||
(option ? '/' + option.id : ''),
|
||||
{
|
||||
preserveScroll: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="font-semibold">{option ? "Editar opção" : "Criar opção"}</h2>
|
||||
<h2 className="font-semibold">
|
||||
{option ? 'Editar opção' : 'Criar opção'}
|
||||
</h2>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<Field label="Grupo">
|
||||
<select
|
||||
disabled={!!option}
|
||||
className={input}
|
||||
value={form.data.group}
|
||||
onChange={(e) => form.setData("group", e.target.value)}
|
||||
onChange={(e) => form.setData('group', e.target.value)}
|
||||
>
|
||||
{groups.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
@@ -71,7 +82,7 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
required
|
||||
readOnly={!!option}
|
||||
value={form.data.code}
|
||||
onChange={(e) => form.setData("code", e.target.value)}
|
||||
onChange={(e) => form.setData('code', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Etiqueta">
|
||||
@@ -79,7 +90,7 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
className={input}
|
||||
required
|
||||
value={form.data.label}
|
||||
onChange={(e) => form.setData("label", e.target.value)}
|
||||
onChange={(e) => form.setData('label', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
@@ -87,7 +98,7 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.active}
|
||||
onChange={(e) => form.setData("active", e.target.checked)}
|
||||
onChange={(e) => form.setData('active', e.target.checked)}
|
||||
/>
|
||||
Activa
|
||||
</label>
|
||||
@@ -95,7 +106,9 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.requires_description}
|
||||
onChange={(e) => form.setData("requires_description", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
form.setData('requires_description', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Exige especificação
|
||||
</label>
|
||||
@@ -106,7 +119,9 @@ function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
|
||||
max="10000"
|
||||
className={input}
|
||||
value={form.data.sort_order}
|
||||
onChange={(e) => form.setData("sort_order", Number(e.target.value))}
|
||||
onChange={(e) =>
|
||||
form.setData('sort_order', Number(e.target.value))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Head, Link, usePage } from "@inertiajs/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { PortalMenu } from "@/layouts/portal-navigation";
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import type { StructureGeography } from '@/components/structure-geography';
|
||||
|
||||
export type Option = {
|
||||
@@ -12,7 +12,12 @@ export type Option = {
|
||||
requires_description: boolean;
|
||||
sort_order: number;
|
||||
};
|
||||
export type Entity = { id: string; name: string; dossiers?: { id: string; title: string; source: string }[]; geography?: StructureGeography | null };
|
||||
export type Entity = {
|
||||
id: string;
|
||||
name: string;
|
||||
dossiers?: { id: string; title: string; source: string }[];
|
||||
geography?: StructureGeography | null;
|
||||
};
|
||||
export type References = {
|
||||
zones?: { id: string; name: string; category: string }[];
|
||||
options: Option[];
|
||||
@@ -42,7 +47,11 @@ export type Opportunity = {
|
||||
last_validated_at?: string | null;
|
||||
};
|
||||
export type Context = {
|
||||
primary_territory_path?: { id: string; name: string; location_type: string }[];
|
||||
primary_territory_path?: {
|
||||
id: string;
|
||||
name: string;
|
||||
location_type: string;
|
||||
}[];
|
||||
zones?: {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -66,18 +75,34 @@ export type Context = {
|
||||
locations: Entity[];
|
||||
};
|
||||
export const input =
|
||||
"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700";
|
||||
'w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
export const button =
|
||||
"inline-flex items-center justify-center rounded-lg bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700";
|
||||
export const card = "rounded-xl border border-slate-200 bg-white p-5 shadow-sm";
|
||||
export function Frame({ title, children }: { title: string; children: ReactNode }) {
|
||||
const { flash } = usePage<{ flash?: { success?: string } }>().props;
|
||||
'inline-flex items-center justify-center rounded-lg bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
||||
export const card = 'rounded-xl border border-slate-200 bg-white p-5 shadow-sm';
|
||||
export function Frame({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash } = usePage<{
|
||||
flash?: { success?: string; warning?: string };
|
||||
}>().props;
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title={title} />
|
||||
<PortalMenu />
|
||||
<main className="mx-auto max-w-7xl space-y-6 px-5 py-9">
|
||||
<h1 className="text-3xl font-bold">{title}</h1>
|
||||
{flash?.warning && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-amber-600 bg-amber-50 p-4 text-amber-950"
|
||||
>
|
||||
{flash.warning}
|
||||
</p>
|
||||
)}
|
||||
{flash?.success && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -91,8 +116,8 @@ export function Frame({ title, children }: { title: string; children: ReactNode
|
||||
<footer className="border-t p-6 text-center">
|
||||
<Link href="/apoio" className="underline">
|
||||
Apoio ao Investidor
|
||||
</Link>{" "}
|
||||
·{" "}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
<Link href="/documentos" className="underline">
|
||||
Documentos
|
||||
</Link>
|
||||
@@ -100,7 +125,13 @@ export function Frame({ title, children }: { title: string; children: ReactNode
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||
export function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className="block space-y-1 text-sm font-medium">
|
||||
<span>{label}</span>
|
||||
@@ -110,44 +141,50 @@ export function Field({ label, children }: { label: string; children: ReactNode
|
||||
}
|
||||
export function money(r: Opportunity) {
|
||||
return r.estimated_investment_amount === null
|
||||
? "Montante não indicado"
|
||||
: `${new Intl.NumberFormat("pt-MZ", { maximumFractionDigits: 2 }).format(Number(r.estimated_investment_amount))} ${r.estimated_investment_currency}`;
|
||||
? 'Montante não indicado'
|
||||
: `${new Intl.NumberFormat('pt-MZ', { maximumFractionDigits: 2 }).format(Number(r.estimated_investment_amount))} ${r.estimated_investment_currency}`;
|
||||
}
|
||||
export async function api(url: string, body?: unknown) {
|
||||
const token = decodeURIComponent(
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((c) => c.startsWith("XSRF-TOKEN="))
|
||||
?.slice(11) ?? "",
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
const formData = typeof FormData !== "undefined" && body instanceof FormData;
|
||||
const formData =
|
||||
typeof FormData !== 'undefined' && body instanceof FormData;
|
||||
const response = await fetch(url, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
credentials: "same-origin",
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...(formData ? {} : { "Content-Type": "application/json" }),
|
||||
"X-XSRF-TOKEN": token,
|
||||
Accept: 'application/json',
|
||||
...(formData ? {} : { 'Content-Type': 'application/json' }),
|
||||
'X-XSRF-TOKEN': token,
|
||||
},
|
||||
...(body === undefined ? {} : { body: formData ? body : JSON.stringify(body) }),
|
||||
...(body === undefined
|
||||
? {}
|
||||
: { body: formData ? body : JSON.stringify(body) }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.message ?? "Não foi possível concluir a operação.");
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
data.message ?? 'Não foi possível concluir a operação.',
|
||||
);
|
||||
return data;
|
||||
}
|
||||
export const groupLabels: Record<string, string> = {
|
||||
education: "Educação",
|
||||
infrastructure: "Infraestruturas",
|
||||
labour: "Mão de obra",
|
||||
qualification: "Qualificações",
|
||||
support: "Apoios",
|
||||
impact: "Impacto",
|
||||
partnership: "Modelo de parceria",
|
||||
subsector: "Subsector",
|
||||
need_category: "Categoria da necessidade",
|
||||
priority: "Prioridade",
|
||||
unit: "Unidade",
|
||||
participation: "Participação",
|
||||
investor_profile: "Perfil do investidor",
|
||||
need_status: "Estado da necessidade",
|
||||
education: 'Educação',
|
||||
infrastructure: 'Infraestruturas',
|
||||
labour: 'Mão de obra',
|
||||
qualification: 'Qualificações',
|
||||
support: 'Apoios',
|
||||
impact: 'Impacto',
|
||||
partnership: 'Modelo de parceria',
|
||||
subsector: 'Subsector',
|
||||
need_category: 'Categoria da necessidade',
|
||||
priority: 'Prioridade',
|
||||
unit: 'Unidade',
|
||||
participation: 'Participação',
|
||||
investor_profile: 'Perfil do investidor',
|
||||
need_status: 'Estado da necessidade',
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card } from "./shared";
|
||||
import type { References } from "./shared";
|
||||
import { Conversation } from "./conversation";
|
||||
import type { Message } from "./conversation";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
import type { References } from './shared';
|
||||
import { Conversation } from './conversation';
|
||||
import type { Message } from './conversation';
|
||||
type Payload = {
|
||||
full_name: string;
|
||||
email: string;
|
||||
@@ -54,9 +54,14 @@ type Props = {
|
||||
zone_origin?: {
|
||||
zone_id: string;
|
||||
zone_version: number;
|
||||
intent: "interest" | "dossier" | "meeting";
|
||||
intent: 'interest' | 'dossier' | 'meeting';
|
||||
} | null;
|
||||
submission: { id: string; version: number; payload: Partial<Payload>; status: string };
|
||||
submission: {
|
||||
id: string;
|
||||
version: number;
|
||||
payload: Partial<Payload>;
|
||||
status: string;
|
||||
};
|
||||
references: References;
|
||||
needs: Need[];
|
||||
attachments: { id: string; file_name: string }[];
|
||||
@@ -68,30 +73,37 @@ type Props = {
|
||||
revisions: { version: number; created_at: string }[];
|
||||
};
|
||||
const emptyNeed = (): Need => ({
|
||||
category_id: "",
|
||||
option_id: "",
|
||||
unit_id: "",
|
||||
priority_id: "",
|
||||
quantity: "",
|
||||
deadline: "",
|
||||
category_id: '',
|
||||
option_id: '',
|
||||
unit_id: '',
|
||||
priority_id: '',
|
||||
quantity: '',
|
||||
deadline: '',
|
||||
details: {
|
||||
description: "",
|
||||
location: "",
|
||||
observations: "",
|
||||
qualification: "",
|
||||
specialty: "",
|
||||
experience: "",
|
||||
certifications: "",
|
||||
availability: "",
|
||||
institution: "",
|
||||
training_mode: "",
|
||||
duration: "",
|
||||
status: "",
|
||||
description: '',
|
||||
location: '',
|
||||
observations: '',
|
||||
qualification: '',
|
||||
specialty: '',
|
||||
experience: '',
|
||||
certifications: '',
|
||||
availability: '',
|
||||
institution: '',
|
||||
training_mode: '',
|
||||
duration: '',
|
||||
status: '',
|
||||
},
|
||||
});
|
||||
export default function Submission(props: Props) {
|
||||
const [step, setStep] = useState(0);
|
||||
return <Editor key={props.submission.version} {...props} step={step} setStep={setStep} />;
|
||||
return (
|
||||
<Editor
|
||||
key={props.submission.version}
|
||||
{...props}
|
||||
step={step}
|
||||
setStep={setStep}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Editor({
|
||||
zone_origin,
|
||||
@@ -109,24 +121,24 @@ function Editor({
|
||||
setStep,
|
||||
}: Props & { step: number; setStep: (step: number) => void }) {
|
||||
const initial: Payload = {
|
||||
full_name: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
country: "",
|
||||
organisation: "",
|
||||
representative_role: "",
|
||||
experience: "",
|
||||
investment_capacity: "",
|
||||
other_details: "",
|
||||
profile_id: "",
|
||||
sector: "",
|
||||
objective: "",
|
||||
participation_id: "",
|
||||
partnership_id: "",
|
||||
estimated_amount: "",
|
||||
currency: "",
|
||||
horizon: "",
|
||||
location: "",
|
||||
full_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
country: '',
|
||||
organisation: '',
|
||||
representative_role: '',
|
||||
experience: '',
|
||||
investment_capacity: '',
|
||||
other_details: '',
|
||||
profile_id: '',
|
||||
sector: '',
|
||||
objective: '',
|
||||
participation_id: '',
|
||||
partnership_id: '',
|
||||
estimated_amount: '',
|
||||
currency: '',
|
||||
horizon: '',
|
||||
location: '',
|
||||
cluster_ids: [],
|
||||
corridor_ids: [],
|
||||
project_ids: [],
|
||||
@@ -141,13 +153,13 @@ function Editor({
|
||||
...Object.fromEntries(
|
||||
Object.entries(n).filter(([k]) =>
|
||||
[
|
||||
"category_id",
|
||||
"option_id",
|
||||
"unit_id",
|
||||
"priority_id",
|
||||
"quantity",
|
||||
"deadline",
|
||||
"details",
|
||||
'category_id',
|
||||
'option_id',
|
||||
'unit_id',
|
||||
'priority_id',
|
||||
'quantity',
|
||||
'deadline',
|
||||
'details',
|
||||
].includes(k),
|
||||
),
|
||||
),
|
||||
@@ -158,12 +170,17 @@ function Editor({
|
||||
version: s.version,
|
||||
file: null,
|
||||
});
|
||||
const [note, setNote] = useState("");
|
||||
const readonly = s.status !== "draft" || management;
|
||||
const base = "/investidor/manifestacoes/" + s.id;
|
||||
const [note, setNote] = useState('');
|
||||
const readonly = s.status !== 'draft' || management;
|
||||
const base = '/investidor/manifestacoes/' + s.id;
|
||||
const update = <K extends keyof Payload>(key: K, value: Payload[K]) =>
|
||||
form.setData("payload", { ...form.data.payload, [key]: value });
|
||||
const text = (key: keyof Payload, label: string, required = false, type = "text") => (
|
||||
form.setData('payload', { ...form.data.payload, [key]: value });
|
||||
const text = (
|
||||
key: keyof Payload,
|
||||
label: string,
|
||||
required = false,
|
||||
type = 'text',
|
||||
) => (
|
||||
<Field label={label}>
|
||||
<input
|
||||
className={input}
|
||||
@@ -171,21 +188,29 @@ function Editor({
|
||||
required={required}
|
||||
disabled={readonly}
|
||||
name={key}
|
||||
min={type === "number" ? 0 : undefined}
|
||||
minLength={key === "objective" ? 20 : key === "full_name" ? 3 : undefined}
|
||||
min={type === 'number' ? 0 : undefined}
|
||||
minLength={
|
||||
key === 'objective'
|
||||
? 20
|
||||
: key === 'full_name'
|
||||
? 3
|
||||
: undefined
|
||||
}
|
||||
onBlur={(e) => {
|
||||
if (!e.target.validity.valid)
|
||||
setNote(`Verifique o campo ${label}: ${e.target.validationMessage}`);
|
||||
else setNote("");
|
||||
setNote(
|
||||
`Verifique o campo ${label}: ${e.target.validationMessage}`,
|
||||
);
|
||||
else setNote('');
|
||||
}}
|
||||
value={String(form.data.payload[key] ?? "")}
|
||||
value={String(form.data.payload[key] ?? '')}
|
||||
onChange={(e) => update(key, e.target.value as never)}
|
||||
maxLength={key === "objective" ? 5000 : 2000}
|
||||
maxLength={key === 'objective' ? 5000 : 2000}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
const option = (
|
||||
key: "profile_id" | "participation_id" | "partnership_id",
|
||||
key: 'profile_id' | 'participation_id' | 'partnership_id',
|
||||
group: string,
|
||||
label: string,
|
||||
) => (
|
||||
@@ -193,7 +218,7 @@ function Editor({
|
||||
<select
|
||||
className={input}
|
||||
disabled={readonly}
|
||||
value={form.data.payload[key] ?? ""}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
onChange={(e) => update(key, e.target.value)}
|
||||
>
|
||||
<option value="">Seleccionar</option>
|
||||
@@ -201,12 +226,14 @@ function Editor({
|
||||
.filter(
|
||||
(o) =>
|
||||
o.group === group &&
|
||||
(o.active || String(o.id) === String(form.data.payload[key])),
|
||||
(o.active ||
|
||||
String(o.id) ===
|
||||
String(form.data.payload[key])),
|
||||
)
|
||||
.map((o) => (
|
||||
<option value={o.id} key={o.id} disabled={!o.active}>
|
||||
{o.label}
|
||||
{!o.active ? " (inactiva)" : ""}
|
||||
{!o.active ? ' (inactiva)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -214,81 +241,104 @@ function Editor({
|
||||
);
|
||||
const updateNeed = (index: number, value: Need) =>
|
||||
form.setData(
|
||||
"needs",
|
||||
'needs',
|
||||
form.data.needs.map((n, i) => (i === index ? value : n)),
|
||||
);
|
||||
const errorStep = (key: string) =>
|
||||
key.startsWith("needs.")
|
||||
key.startsWith('needs.')
|
||||
? 2
|
||||
: /payload\.(full_name|email|phone|country|profile_id|organisation|representative_role|sector|experience|investment_capacity)/.test(
|
||||
key,
|
||||
)
|
||||
? 0
|
||||
: key === "payload.contact_consent"
|
||||
: key === 'payload.contact_consent'
|
||||
? 4
|
||||
: 1;
|
||||
return (
|
||||
<Frame
|
||||
title={
|
||||
receipt ? "Manifestação " + receipt.reference : "Preparar manifestação de interesse"
|
||||
receipt
|
||||
? 'Manifestação ' + receipt.reference
|
||||
: 'Preparar manifestação de interesse'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
{target ??
|
||||
(zone_origin
|
||||
? "Pedido relativo a zona de investimento"
|
||||
: "Interesse geral")}{" "}
|
||||
· Versão {s.version} · {s.status === "draft" ? "Rascunho privado" : "Submetido"}
|
||||
? 'Pedido relativo a zona de investimento'
|
||||
: 'Interesse geral')}{' '}
|
||||
· Versão {s.version} ·{' '}
|
||||
{s.status === 'draft' ? 'Rascunho privado' : 'Submetido'}
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/painel?submission_id=${s.id}`}
|
||||
>
|
||||
Preparar apoio e acompanhamento deste projecto no Balcão Virtual
|
||||
</Link>
|
||||
{zone_origin && (
|
||||
<p className={card}>
|
||||
<Link className="underline" href={`/zonas/${zone_origin.zone_id}`}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/zonas/${zone_origin.zone_id}`}
|
||||
>
|
||||
Consultar zona de origem
|
||||
</Link>{" "}
|
||||
· Versão da ficha {zone_origin.zone_version} ·{" "}
|
||||
</Link>{' '}
|
||||
· Versão da ficha {zone_origin.zone_version} ·{' '}
|
||||
{
|
||||
{
|
||||
interest: "Manifestação de interesse",
|
||||
dossier: "Pedido de dossier",
|
||||
meeting: "Pedido de reunião",
|
||||
interest: 'Manifestação de interesse',
|
||||
dossier: 'Pedido de dossier',
|
||||
meeting: 'Pedido de reunião',
|
||||
}[zone_origin.intent]
|
||||
}
|
||||
. Atendimento assistido, sem decisão administrativa automática.
|
||||
. Atendimento assistido, sem decisão administrativa
|
||||
automática.
|
||||
</p>
|
||||
)}
|
||||
{receipt && (
|
||||
<p role="status" className={card}>
|
||||
Protocolo: <strong>{receipt.reference}</strong> · Estado:{" "}
|
||||
Protocolo: <strong>{receipt.reference}</strong> · Estado:{' '}
|
||||
{(
|
||||
{
|
||||
received: "Recebido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
closed: "Encerrado",
|
||||
received: 'Recebido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
closed: 'Encerrado',
|
||||
} as Record<string, string>
|
||||
)[receipt.status] ?? receipt.status}
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label="Etapas da manifestação" className="flex flex-wrap gap-2">
|
||||
{["Identificação", "Investimento", "Necessidades", "Anexos", "Rever e enviar"].map(
|
||||
(label, i) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
aria-current={step === i ? "step" : undefined}
|
||||
className={step === i ? button : "rounded border px-4 py-2"}
|
||||
onClick={() => setStep(i)}
|
||||
>
|
||||
{i + 1}. {label}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<nav
|
||||
aria-label="Etapas da manifestação"
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
{[
|
||||
'Identificação',
|
||||
'Investimento',
|
||||
'Necessidades',
|
||||
'Anexos',
|
||||
'Rever e enviar',
|
||||
].map((label, i) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
aria-current={step === i ? 'step' : undefined}
|
||||
className={
|
||||
step === i ? button : 'rounded border px-4 py-2'
|
||||
}
|
||||
onClick={() => setStep(i)}
|
||||
>
|
||||
{i + 1}. {label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<p className="text-sm">
|
||||
Etapa {step + 1} de 5. Guarde antes de sair. A informação declarada não é publicada.
|
||||
Etapa {step + 1} de 5. Guarde antes de sair. A informação
|
||||
declarada não é publicada.
|
||||
</p>
|
||||
<form
|
||||
className={card + " space-y-5"}
|
||||
className={card + ' space-y-5'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.put(base, { preserveScroll: true });
|
||||
@@ -296,44 +346,63 @@ function Editor({
|
||||
>
|
||||
{step === 0 && (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{text("full_name", "Nome completo", true)}
|
||||
{text("email", "Email", true, "email")}
|
||||
{text("phone", "Telefone")}
|
||||
{text("country", "País", true)}
|
||||
{option("profile_id", "investor_profile", "Perfil do investidor")}
|
||||
{text("organisation", "Organização / empresa")}
|
||||
{text("representative_role", "Função do representante")}
|
||||
{text("sector", "Sector de interesse", true)}
|
||||
{text("experience", "Experiência relevante")}
|
||||
{text('full_name', 'Nome completo', true)}
|
||||
{text('email', 'Email', true, 'email')}
|
||||
{text('phone', 'Telefone')}
|
||||
{text('country', 'País', true)}
|
||||
{option(
|
||||
'profile_id',
|
||||
'investor_profile',
|
||||
'Perfil do investidor',
|
||||
)}
|
||||
{text('organisation', 'Organização / empresa')}
|
||||
{text('representative_role', 'Função do representante')}
|
||||
{text('sector', 'Sector de interesse', true)}
|
||||
{text('experience', 'Experiência relevante')}
|
||||
{text(
|
||||
"investment_capacity",
|
||||
"Capacidade de investimento / especificação do perfil",
|
||||
'investment_capacity',
|
||||
'Capacidade de investimento / especificação do perfil',
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{step === 1 && (
|
||||
<div className="space-y-5">
|
||||
{text(
|
||||
"objective",
|
||||
"Objectivo do investimento (mínimo 20 caracteres)",
|
||||
'objective',
|
||||
'Objectivo do investimento (mínimo 20 caracteres)',
|
||||
true,
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{option(
|
||||
"participation_id",
|
||||
"participation",
|
||||
"Modalidade de participação",
|
||||
'participation_id',
|
||||
'participation',
|
||||
'Modalidade de participação',
|
||||
)}
|
||||
{option("partnership_id", "partnership", "Modelo de parceria")}
|
||||
{text("estimated_amount", "Investimento estimado", false, "number")}
|
||||
{text("currency", "Moeda (código de três letras)")}
|
||||
{text("horizon", "Prazo / horizonte", true)}
|
||||
{text("location", "Localização pretendida")}
|
||||
{option(
|
||||
'partnership_id',
|
||||
'partnership',
|
||||
'Modelo de parceria',
|
||||
)}
|
||||
{text(
|
||||
'estimated_amount',
|
||||
'Investimento estimado',
|
||||
false,
|
||||
'number',
|
||||
)}
|
||||
{text('currency', 'Moeda (código de três letras)')}
|
||||
{text('horizon', 'Prazo / horizonte', true)}
|
||||
{text('location', 'Localização pretendida')}
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
|
||||
{(
|
||||
['clusters', 'corridors', 'projects'] as const
|
||||
).map((group, i) => {
|
||||
const key = (
|
||||
["cluster_ids", "corridor_ids", "project_ids"] as const
|
||||
[
|
||||
'cluster_ids',
|
||||
'corridor_ids',
|
||||
'project_ids',
|
||||
] as const
|
||||
)[i];
|
||||
return (
|
||||
<fieldset
|
||||
@@ -341,27 +410,45 @@ function Editor({
|
||||
key={group}
|
||||
>
|
||||
<legend>
|
||||
{["Clusters", "Corredores", "Projectos âncora"][i]}
|
||||
{
|
||||
[
|
||||
'Clusters',
|
||||
'Corredores',
|
||||
'Projectos âncora',
|
||||
][i]
|
||||
}
|
||||
</legend>
|
||||
{r[group].map((entity) => (
|
||||
<label key={entity.id} className="flex gap-2">
|
||||
<label
|
||||
key={entity.id}
|
||||
className="flex gap-2"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={readonly}
|
||||
checked={(
|
||||
form.data.payload[key] ?? []
|
||||
form.data.payload[
|
||||
key
|
||||
] ?? []
|
||||
).includes(entity.id)}
|
||||
onChange={(e) =>
|
||||
update(
|
||||
key,
|
||||
e.target.checked
|
||||
? [
|
||||
...(form.data.payload[key] ??
|
||||
[]),
|
||||
...(form
|
||||
.data
|
||||
.payload[
|
||||
key
|
||||
] ?? []),
|
||||
entity.id,
|
||||
]
|
||||
: form.data.payload[key].filter(
|
||||
(id) => id !== entity.id,
|
||||
: form.data.payload[
|
||||
key
|
||||
].filter(
|
||||
(id) =>
|
||||
id !==
|
||||
entity.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -381,22 +468,30 @@ function Editor({
|
||||
Mão de obra, infraestruturas, formação e apoios
|
||||
</h2>
|
||||
<p>
|
||||
Acrescente o que existe no local e o que necessita. As opções são
|
||||
mantidas pela gestão; use Outro para especificar casos adicionais.
|
||||
Acrescente o que existe no local e o que necessita.
|
||||
As opções são mantidas pela gestão; use Outro para
|
||||
especificar casos adicionais.
|
||||
</p>
|
||||
{form.data.needs.map((need, index) => {
|
||||
const category =
|
||||
r.options.find((o) => String(o.id) === String(need.category_id))
|
||||
?.code ?? "";
|
||||
const group = category.startsWith("labour")
|
||||
? "labour"
|
||||
: category.startsWith("infrastructure")
|
||||
? "infrastructure"
|
||||
: category === "education"
|
||||
? "education"
|
||||
: "support";
|
||||
r.options.find(
|
||||
(o) =>
|
||||
String(o.id) ===
|
||||
String(need.category_id),
|
||||
)?.code ?? '';
|
||||
const group = category.startsWith('labour')
|
||||
? 'labour'
|
||||
: category.startsWith('infrastructure')
|
||||
? 'infrastructure'
|
||||
: category === 'education'
|
||||
? 'education'
|
||||
: 'support';
|
||||
const needSelect = (
|
||||
field: "category_id" | "option_id" | "unit_id" | "priority_id",
|
||||
field:
|
||||
| 'category_id'
|
||||
| 'option_id'
|
||||
| 'unit_id'
|
||||
| 'priority_id',
|
||||
optionGroup: string,
|
||||
label: string,
|
||||
) => (
|
||||
@@ -404,13 +499,13 @@ function Editor({
|
||||
<select
|
||||
className={input}
|
||||
disabled={readonly}
|
||||
value={need[field] ?? ""}
|
||||
value={need[field] ?? ''}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
[field]: e.target.value,
|
||||
...(field === "category_id"
|
||||
? { option_id: "" }
|
||||
...(field === 'category_id'
|
||||
? { option_id: '' }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
@@ -421,7 +516,10 @@ function Editor({
|
||||
(o) =>
|
||||
o.group === optionGroup &&
|
||||
(o.active ||
|
||||
String(o.id) === String(need[field])),
|
||||
String(o.id) ===
|
||||
String(
|
||||
need[field],
|
||||
)),
|
||||
)
|
||||
.map((o) => (
|
||||
<option value={o.id} key={o.id}>
|
||||
@@ -432,13 +530,30 @@ function Editor({
|
||||
</Field>
|
||||
);
|
||||
return (
|
||||
<fieldset key={index} className="space-y-4 rounded-lg border p-4">
|
||||
<legend className="font-bold">Necessidade {index + 1}</legend>
|
||||
<fieldset
|
||||
key={index}
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
>
|
||||
<legend className="font-bold">
|
||||
Necessidade {index + 1}
|
||||
</legend>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{needSelect("category_id", "need_category", "Categoria")}
|
||||
{needSelect("option_id", group, "Tipo")}
|
||||
{needSelect("unit_id", "unit", "Unidade")}
|
||||
{needSelect("priority_id", "priority", "Prioridade")}
|
||||
{needSelect(
|
||||
'category_id',
|
||||
'need_category',
|
||||
'Categoria',
|
||||
)}
|
||||
{needSelect('option_id', group, 'Tipo')}
|
||||
{needSelect(
|
||||
'unit_id',
|
||||
'unit',
|
||||
'Unidade',
|
||||
)}
|
||||
{needSelect(
|
||||
'priority_id',
|
||||
'priority',
|
||||
'Prioridade',
|
||||
)}
|
||||
<Field label="Quantidade">
|
||||
<input
|
||||
className={input}
|
||||
@@ -446,11 +561,12 @@ function Editor({
|
||||
min="0"
|
||||
step="0.01"
|
||||
disabled={readonly}
|
||||
value={need.quantity ?? ""}
|
||||
value={need.quantity ?? ''}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
quantity: e.target.value,
|
||||
quantity:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -460,11 +576,12 @@ function Editor({
|
||||
className={input}
|
||||
type="date"
|
||||
disabled={readonly}
|
||||
value={need.deadline ?? ""}
|
||||
value={need.deadline ?? ''}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
deadline: e.target.value,
|
||||
deadline:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -472,48 +589,54 @@ function Editor({
|
||||
</div>
|
||||
{(
|
||||
[
|
||||
"description",
|
||||
"location",
|
||||
"observations",
|
||||
...(group === "labour"
|
||||
'description',
|
||||
'location',
|
||||
'observations',
|
||||
...(group === 'labour'
|
||||
? [
|
||||
"qualification",
|
||||
"specialty",
|
||||
"experience",
|
||||
"certifications",
|
||||
"availability",
|
||||
"institution",
|
||||
'qualification',
|
||||
'specialty',
|
||||
'experience',
|
||||
'certifications',
|
||||
'availability',
|
||||
'institution',
|
||||
]
|
||||
: []),
|
||||
...(group === "education"
|
||||
...(group === 'education'
|
||||
? [
|
||||
"qualification",
|
||||
"institution",
|
||||
"training_mode",
|
||||
"duration",
|
||||
"certifications",
|
||||
'qualification',
|
||||
'institution',
|
||||
'training_mode',
|
||||
'duration',
|
||||
'certifications',
|
||||
]
|
||||
: []),
|
||||
] as (keyof Need["details"])[]
|
||||
] as (keyof Need['details'])[]
|
||||
).map((field) => (
|
||||
<Field
|
||||
key={field}
|
||||
label={
|
||||
{
|
||||
description: "Descrição / especificação",
|
||||
location: "Localização",
|
||||
description:
|
||||
'Descrição / especificação',
|
||||
location: 'Localização',
|
||||
observations:
|
||||
"Observações e referência dos anexos de suporte",
|
||||
qualification: "Nível de qualificação",
|
||||
specialty: "Profissão / especialidade",
|
||||
experience: "Experiência",
|
||||
certifications: "Certificações",
|
||||
availability: "Disponibilidade",
|
||||
'Observações e referência dos anexos de suporte',
|
||||
qualification:
|
||||
'Nível de qualificação',
|
||||
specialty:
|
||||
'Profissão / especialidade',
|
||||
experience: 'Experiência',
|
||||
certifications:
|
||||
'Certificações',
|
||||
availability:
|
||||
'Disponibilidade',
|
||||
institution:
|
||||
"Instituições ou centros de formação",
|
||||
training_mode: "Modalidade de formação",
|
||||
duration: "Duração",
|
||||
status: "Estado",
|
||||
'Instituições ou centros de formação',
|
||||
training_mode:
|
||||
'Modalidade de formação',
|
||||
duration: 'Duração',
|
||||
status: 'Estado',
|
||||
}[field]
|
||||
}
|
||||
>
|
||||
@@ -521,13 +644,16 @@ function Editor({
|
||||
className={input}
|
||||
rows={2}
|
||||
disabled={readonly}
|
||||
value={need.details[field] ?? ""}
|
||||
value={
|
||||
need.details[field] ?? ''
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateNeed(index, {
|
||||
...need,
|
||||
details: {
|
||||
...need.details,
|
||||
[field]: e.target.value,
|
||||
[field]:
|
||||
e.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -540,8 +666,10 @@ function Editor({
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
"needs",
|
||||
form.data.needs.filter((_, i) => i !== index),
|
||||
'needs',
|
||||
form.data.needs.filter(
|
||||
(_, i) => i !== index,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
@@ -557,7 +685,10 @@ function Editor({
|
||||
className={button}
|
||||
disabled={form.data.needs.length >= 40}
|
||||
onClick={() =>
|
||||
form.setData("needs", [...form.data.needs, emptyNeed()])
|
||||
form.setData('needs', [
|
||||
...form.data.needs,
|
||||
emptyNeed(),
|
||||
])
|
||||
}
|
||||
>
|
||||
Acrescentar necessidade
|
||||
@@ -567,28 +698,33 @@ function Editor({
|
||||
)}
|
||||
{step === 3 && (
|
||||
<p>
|
||||
Guarde primeiro o rascunho e carregue os anexos no formulário abaixo.
|
||||
Identifique o nome do ficheiro nas observações da necessidade a que
|
||||
corresponde.
|
||||
Guarde primeiro o rascunho e carregue os anexos no
|
||||
formulário abaixo. Identifique o nome do ficheiro nas
|
||||
observações da necessidade a que corresponde.
|
||||
</p>
|
||||
)}
|
||||
{step === 4 && (
|
||||
<section className="space-y-5">
|
||||
<h2 className="text-xl font-bold">Rever antes de enviar</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
Rever antes de enviar
|
||||
</h2>
|
||||
<dl className="space-y-3">
|
||||
{[
|
||||
["Investidor", form.data.payload.full_name],
|
||||
["Email", form.data.payload.email],
|
||||
["Organização", form.data.payload.organisation],
|
||||
["Objectivo", form.data.payload.objective],
|
||||
["Prazo", form.data.payload.horizon],
|
||||
["Necessidades", String(form.data.needs.length)],
|
||||
["Anexos", String(attachments.length)],
|
||||
['Investidor', form.data.payload.full_name],
|
||||
['Email', form.data.payload.email],
|
||||
['Organização', form.data.payload.organisation],
|
||||
['Objectivo', form.data.payload.objective],
|
||||
['Prazo', form.data.payload.horizon],
|
||||
[
|
||||
'Necessidades',
|
||||
String(form.data.needs.length),
|
||||
],
|
||||
['Anexos', String(attachments.length)],
|
||||
].map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-line">
|
||||
{value || "Não indicado"}
|
||||
{value || 'Não indicado'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -598,11 +734,14 @@ function Editor({
|
||||
type="checkbox"
|
||||
disabled={readonly}
|
||||
checked={form.data.payload.contact_consent}
|
||||
onChange={(e) => update("contact_consent", e.target.checked)}
|
||||
onChange={(e) =>
|
||||
update('contact_consent', e.target.checked)
|
||||
}
|
||||
/>
|
||||
Autorizo o tratamento destes dados e o contacto pela equipa para
|
||||
analisar e acompanhar esta manifestação. Os anexos são privados. Não
|
||||
constitui consentimento para utilização em IA.
|
||||
Autorizo o tratamento destes dados e o contacto pela
|
||||
equipa para analisar e acompanhar esta manifestação.
|
||||
Os anexos são privados. Não constitui consentimento
|
||||
para utilização em IA.
|
||||
</label>
|
||||
</section>
|
||||
)}
|
||||
@@ -618,8 +757,8 @@ function Editor({
|
||||
.includes(String(o.id)),
|
||||
) &&
|
||||
text(
|
||||
"other_details",
|
||||
"Outro — especifique o perfil, participação ou parceria seleccionados",
|
||||
'other_details',
|
||||
'Outro — especifique o perfil, participação ou parceria seleccionados',
|
||||
true,
|
||||
)}
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
@@ -650,7 +789,7 @@ function Editor({
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setNote("");
|
||||
setNote('');
|
||||
setStep(step + 1);
|
||||
}}
|
||||
>
|
||||
@@ -670,12 +809,19 @@ function Editor({
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.payload.contact_consent}
|
||||
disabled={
|
||||
form.processing ||
|
||||
!form.data.payload.contact_consent
|
||||
}
|
||||
onClick={() =>
|
||||
form.post(base + "/submit", {
|
||||
form.post(base + '/submit', {
|
||||
preserveScroll: true,
|
||||
onError: (errors) =>
|
||||
setStep(errorStep(Object.keys(errors)[0] ?? "")),
|
||||
setStep(
|
||||
errorStep(
|
||||
Object.keys(errors)[0] ?? '',
|
||||
),
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
@@ -685,15 +831,18 @@ function Editor({
|
||||
</div>
|
||||
</form>
|
||||
{step === 3 && (
|
||||
<section className={card + " space-y-4"}>
|
||||
<section className={card + ' space-y-4'}>
|
||||
<h2 className="text-xl font-bold">Anexos privados</h2>
|
||||
<p>
|
||||
PDF ou TXT, até 10 MiB cada, máximo de dez anexos. Guardar um anexo
|
||||
actualiza a versão do rascunho.
|
||||
PDF ou TXT, até 10 MiB cada, máximo de dez anexos.
|
||||
Guardar um anexo actualiza a versão do rascunho.
|
||||
</p>
|
||||
{attachments.map((a) => (
|
||||
<p key={a.id}>
|
||||
<a className="underline" href={base + "/attachments/" + a.id}>
|
||||
<a
|
||||
className="underline"
|
||||
href={base + '/attachments/' + a.id}
|
||||
>
|
||||
{a.file_name}
|
||||
</a>
|
||||
</p>
|
||||
@@ -705,11 +854,11 @@ function Editor({
|
||||
e.preventDefault();
|
||||
if (form.isDirty) {
|
||||
setNote(
|
||||
"Guarde as alterações do formulário antes de carregar o anexo.",
|
||||
'Guarde as alterações do formulário antes de carregar o anexo.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
upload.post(base + "/attachments", {
|
||||
upload.post(base + '/attachments', {
|
||||
forceFormData: true,
|
||||
preserveScroll: true,
|
||||
});
|
||||
@@ -721,16 +870,24 @@ function Editor({
|
||||
accept="application/pdf,text/plain"
|
||||
required
|
||||
onChange={(e) =>
|
||||
upload.setData("file", e.target.files?.[0] ?? null)
|
||||
upload.setData(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(upload.errors).map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={upload.processing}>
|
||||
{Object.entries(upload.errors).map(
|
||||
([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{value}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={upload.processing}
|
||||
>
|
||||
Carregar anexo
|
||||
</button>
|
||||
</form>
|
||||
@@ -738,19 +895,21 @@ function Editor({
|
||||
</section>
|
||||
)}
|
||||
<details className={card}>
|
||||
<summary className="cursor-pointer font-bold">Histórico do pedido</summary>
|
||||
<summary className="cursor-pointer font-bold">
|
||||
Histórico do pedido
|
||||
</summary>
|
||||
<ol className="mt-3 space-y-2">
|
||||
{events.map((e, i) => (
|
||||
<li key={i}>
|
||||
{new Date(e.created_at).toLocaleString("pt-MZ")} —{" "}
|
||||
{new Date(e.created_at).toLocaleString('pt-MZ')} —{' '}
|
||||
{(
|
||||
{
|
||||
draft_created: "Rascunho criado",
|
||||
draft_saved: "Rascunho guardado",
|
||||
attachment_added: "Anexo acrescentado",
|
||||
submitted: "Submetido",
|
||||
draft_created: 'Rascunho criado',
|
||||
draft_saved: 'Rascunho guardado',
|
||||
attachment_added: 'Anexo acrescentado',
|
||||
submitted: 'Submetido',
|
||||
} as Record<string, string>
|
||||
)[e.action] ?? e.action}{" "}
|
||||
)[e.action] ?? e.action}{' '}
|
||||
· versão {e.version}
|
||||
</li>
|
||||
))}
|
||||
@@ -760,7 +919,7 @@ function Editor({
|
||||
id={s.id}
|
||||
messages={messages}
|
||||
revisions={revisions}
|
||||
submitted={s.status === "submitted"}
|
||||
submitted={s.status === 'submitted'}
|
||||
/>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { Frame, card, button } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, button } from './shared';
|
||||
export default function Workspace({
|
||||
submissions,
|
||||
favourites,
|
||||
@@ -18,10 +18,10 @@ export default function Workspace({
|
||||
favourites: { id: number; title: string; slug: string }[];
|
||||
}) {
|
||||
const states: Record<string, string> = {
|
||||
received: "Recebido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
closed: "Encerrado",
|
||||
received: 'Recebido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
closed: 'Encerrado',
|
||||
};
|
||||
return (
|
||||
<Frame title="Área do investidor">
|
||||
@@ -39,28 +39,38 @@ export default function Workspace({
|
||||
Apoio e parcerias
|
||||
</Link>
|
||||
</nav>
|
||||
<button className={button} onClick={() => router.post("/investidor/manifestacoes")}>
|
||||
<button
|
||||
className={button}
|
||||
onClick={() => router.post('/investidor/manifestacoes')}
|
||||
>
|
||||
Preparar nova manifestação
|
||||
</button>
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-2xl font-bold">Rascunhos e manifestações</h2>
|
||||
<h2 className="text-2xl font-bold">
|
||||
Rascunhos e manifestações
|
||||
</h2>
|
||||
{submissions.data.map((s) => (
|
||||
<article className={card} key={s.id}>
|
||||
<Link
|
||||
href={`/investidor/manifestacoes/${s.id}`}
|
||||
className="font-semibold underline"
|
||||
>
|
||||
{s.reference ?? "Continuar rascunho"}
|
||||
{s.reference ?? 'Continuar rascunho'}
|
||||
</Link>
|
||||
<p>
|
||||
{s.status === "draft"
|
||||
? "Rascunho privado"
|
||||
: (states[s.request_status ?? ""] ?? s.request_status)}
|
||||
{s.status === 'draft'
|
||||
? 'Rascunho privado'
|
||||
: (states[s.request_status ?? ''] ??
|
||||
s.request_status)}
|
||||
</p>
|
||||
<p>
|
||||
{new Date(s.created_at).toLocaleDateString('pt-MZ')}
|
||||
</p>
|
||||
<p>{new Date(s.created_at).toLocaleDateString("pt-MZ")}</p>
|
||||
</article>
|
||||
))}
|
||||
{!submissions.data.length && <p>Ainda não existem manifestações neste percurso.</p>}
|
||||
{!submissions.data.length && (
|
||||
<p>Ainda não existem manifestações neste percurso.</p>
|
||||
)}
|
||||
<nav aria-label="Paginação" className="flex gap-4">
|
||||
{submissions.prev_page_url && (
|
||||
<Link href={submissions.prev_page_url}>Anterior</Link>
|
||||
@@ -73,12 +83,19 @@ export default function Workspace({
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-2xl font-bold">Oportunidades favoritas</h2>
|
||||
{favourites.map((f) => (
|
||||
<Link href={`/oportunidades/${f.slug}`} className={card + " block"} key={f.id}>
|
||||
<Link
|
||||
href={`/oportunidades/${f.slug}`}
|
||||
className={card + ' block'}
|
||||
key={f.id}
|
||||
>
|
||||
{f.title}
|
||||
</Link>
|
||||
))}
|
||||
{!favourites.length && (
|
||||
<p>Explore o catálogo e guarde as oportunidades que pretende acompanhar.</p>
|
||||
<p>
|
||||
Explore o catálogo e guarde as oportunidades que
|
||||
pretende acompanhar.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</Frame>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { api, button, card, Field, input } from "./shared";
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { api, button, card, Field, input } from './shared';
|
||||
|
||||
export type ZoneAttachment = {
|
||||
id: string;
|
||||
@@ -18,7 +18,13 @@ export type ZoneAttachment = {
|
||||
file_name?: string;
|
||||
file_status?: string;
|
||||
document_id?: string;
|
||||
malware_scan_status?: 'pending' | 'scanning' | 'clean' | 'infected' | 'inconclusive' | 'failed';
|
||||
malware_scan_status?:
|
||||
| 'pending'
|
||||
| 'scanning'
|
||||
| 'clean'
|
||||
| 'infected'
|
||||
| 'inconclusive'
|
||||
| 'failed';
|
||||
malware_failure_reason?: string | null;
|
||||
media_type: string;
|
||||
size_bytes: number | null;
|
||||
@@ -37,86 +43,438 @@ export default function ZoneAttachments({
|
||||
zonePublished: boolean;
|
||||
}) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [kind, setKind] = useState("legal_instrument");
|
||||
const [caption, setCaption] = useState("");
|
||||
const [source, setSource] = useState("");
|
||||
const [sourceDate, setSourceDate] = useState("");
|
||||
const [rights, setRights] = useState("pending");
|
||||
const [rightsBasis, setRightsBasis] = useState("");
|
||||
const [reviewChoices, setReviewChoices] = useState<Record<string, { rights: string; personal: string }>>({});
|
||||
const [reviewRightsBasis, setReviewRightsBasis] = useState<Record<string, string>>({});
|
||||
const [error, setError] = useState("");
|
||||
const [kind, setKind] = useState('legal_instrument');
|
||||
const [caption, setCaption] = useState('');
|
||||
const [source, setSource] = useState('');
|
||||
const [sourceDate, setSourceDate] = useState('');
|
||||
const [rights, setRights] = useState('pending');
|
||||
const [rightsBasis, setRightsBasis] = useState('');
|
||||
const [reviewChoices, setReviewChoices] = useState<
|
||||
Record<string, { rights: string; personal: string }>
|
||||
>({});
|
||||
const [reviewRightsBasis, setReviewRightsBasis] = useState<
|
||||
Record<string, string>
|
||||
>({});
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function send(url: string, payload: unknown) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api(url, payload);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
setError(failure instanceof Error ? failure.message : "Não foi possível guardar o anexo.");
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível guardar o anexo.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={card + " space-y-4"} aria-label="Anexos documentais da zona">
|
||||
<h2 className="text-xl font-bold">{management ? "Anexos documentais" : "Documentos e materiais publicados"}</h2>
|
||||
{management && <>
|
||||
<p>Os ficheiros ficam privados por defeito. A revisão é administrativa e não equivale a certificação. Só seleccione para divulgação ficheiros sem dados pessoais e com direitos de utilização esclarecidos.</p>
|
||||
<form className="grid gap-3 md:grid-cols-2" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!file) return;
|
||||
const data = new FormData();
|
||||
data.set("file", file);
|
||||
data.set("kind", kind);
|
||||
data.set("caption", caption);
|
||||
data.set("source_reference", source);
|
||||
if (sourceDate) data.set("source_date", sourceDate);
|
||||
data.set("rights_status", rights);
|
||||
if (rightsBasis) data.set("rights_basis", rightsBasis);
|
||||
void send(`/api/v2/investment/admin/zones/${zoneId}/attachments`, data).then(() => setFile(null));
|
||||
}}>
|
||||
<Field label="Ficheiro (PDF, JPEG, PNG ou WebP; máximo 20 MB)">
|
||||
<input className={input} type="file" accept="application/pdf,image/jpeg,image/png,image/webp" required onChange={(event) => setFile(event.target.files?.[0] ?? null)} />
|
||||
</Field>
|
||||
<Field label="Tipo do anexo"><select className={input} value={kind} onChange={(event) => setKind(event.target.value)}><option value="legal_instrument">Diploma</option><option value="map">Mapa</option><option value="photo">Fotografia</option><option value="study">Estudo</option><option value="other">Outro</option></select></Field>
|
||||
<Field label="Legenda ou título"><input className={input} required maxLength={255} value={caption} onChange={(event) => setCaption(event.target.value)} /></Field>
|
||||
<Field label="Origem exacta do ficheiro"><input className={input} required minLength={5} maxLength={2000} value={source} onChange={(event) => setSource(event.target.value)} /></Field>
|
||||
<Field label="Data da fonte, se conhecida"><input className={input} type="date" value={sourceDate} onChange={(event) => setSourceDate(event.target.value)} /></Field>
|
||||
<Field label="Direitos de utilização"><select className={input} value={rights} onChange={(event) => setRights(event.target.value)}><option value="pending">Por confirmar</option><option value="confirmed">Confirmados</option><option value="restricted">Restritos</option></select></Field>
|
||||
<Field label="Fundamento dos direitos (se confirmado)"><input className={input} maxLength={2000} value={rightsBasis} onChange={(event) => setRightsBasis(event.target.value)} /></Field>
|
||||
<button className={button} disabled={busy || !file || !caption.trim() || !source.trim()}>Carregar como privado</button>
|
||||
</form>
|
||||
</>}
|
||||
<section
|
||||
className={card + ' space-y-4'}
|
||||
aria-label="Anexos documentais da zona"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
{management
|
||||
? 'Anexos documentais'
|
||||
: 'Documentos e materiais publicados'}
|
||||
</h2>
|
||||
{management && (
|
||||
<>
|
||||
<p>
|
||||
Os ficheiros ficam privados por defeito. A revisão é
|
||||
administrativa e não equivale a certificação. Só
|
||||
seleccione para divulgação ficheiros sem dados pessoais
|
||||
e com direitos de utilização esclarecidos.
|
||||
</p>
|
||||
<form
|
||||
className="grid gap-3 md:grid-cols-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!file) return;
|
||||
const data = new FormData();
|
||||
data.set('file', file);
|
||||
data.set('kind', kind);
|
||||
data.set('caption', caption);
|
||||
data.set('source_reference', source);
|
||||
if (sourceDate) data.set('source_date', sourceDate);
|
||||
data.set('rights_status', rights);
|
||||
if (rightsBasis)
|
||||
data.set('rights_basis', rightsBasis);
|
||||
void send(
|
||||
`/api/v2/investment/admin/zones/${zoneId}/attachments`,
|
||||
data,
|
||||
).then(() => setFile(null));
|
||||
}}
|
||||
>
|
||||
<Field label="Ficheiro (PDF, JPEG, PNG ou WebP; máximo 20 MB)">
|
||||
<input
|
||||
className={input}
|
||||
type="file"
|
||||
accept="application/pdf,image/jpeg,image/png,image/webp"
|
||||
required
|
||||
onChange={(event) =>
|
||||
setFile(event.target.files?.[0] ?? null)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Tipo do anexo">
|
||||
<select
|
||||
className={input}
|
||||
value={kind}
|
||||
onChange={(event) =>
|
||||
setKind(event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="legal_instrument">
|
||||
Diploma
|
||||
</option>
|
||||
<option value="map">Mapa</option>
|
||||
<option value="photo">Fotografia</option>
|
||||
<option value="study">Estudo</option>
|
||||
<option value="other">Outro</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Legenda ou título">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
maxLength={255}
|
||||
value={caption}
|
||||
onChange={(event) =>
|
||||
setCaption(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Origem exacta do ficheiro">
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
minLength={5}
|
||||
maxLength={2000}
|
||||
value={source}
|
||||
onChange={(event) =>
|
||||
setSource(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Data da fonte, se conhecida">
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
value={sourceDate}
|
||||
onChange={(event) =>
|
||||
setSourceDate(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Direitos de utilização">
|
||||
<select
|
||||
className={input}
|
||||
value={rights}
|
||||
onChange={(event) =>
|
||||
setRights(event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="pending">Por confirmar</option>
|
||||
<option value="confirmed">Confirmados</option>
|
||||
<option value="restricted">Restritos</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fundamento dos direitos (se confirmado)">
|
||||
<input
|
||||
className={input}
|
||||
maxLength={2000}
|
||||
value={rightsBasis}
|
||||
onChange={(event) =>
|
||||
setRightsBasis(event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!file ||
|
||||
!caption.trim() ||
|
||||
!source.trim()
|
||||
}
|
||||
>
|
||||
Carregar como privado
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{attachments.length === 0 && <p>Não existem anexos divulgados nesta zona.</p>}
|
||||
{attachments.length === 0 && (
|
||||
<p>Não existem anexos divulgados nesta zona.</p>
|
||||
)}
|
||||
{attachments.map((item) => {
|
||||
const choice = reviewChoices[item.id] ?? { rights: item.rights_status ?? "pending", personal: item.personal_data_status ?? "unknown" };
|
||||
return <article key={item.id} className="space-y-2 rounded border p-3">
|
||||
<p className="font-semibold">{item.caption} · {item.kind}{management && item.file_name ? ` · ${item.file_name}` : ""}</p>
|
||||
<p className="text-sm">Origem: {item.source_reference}{item.source_date ? ` · ${item.source_date}` : ""}{management ? ` · ${item.review_status}` : ""}</p>
|
||||
{management && item.independent_review === false && <p className="text-sm">Revisão administrativa registada; não independente e não certificadora.</p>}
|
||||
{management && item.malware_scan_status === "pending" && <p role="status">A analisar o ficheiro.</p>}
|
||||
{management && item.malware_scan_status === "scanning" && <p role="status">A analisar o ficheiro.</p>}
|
||||
{management && item.malware_scan_status === "clean" && <p role="status">Análise concluída: nenhuma ameaça detectada. O ficheiro continua privado até à divulgação explícita.</p>}
|
||||
{management && item.malware_scan_status === "infected" && <p role="alert">Ficheiro bloqueado: ameaça detectada. Mantenha-o em quarentena e carregue uma versão substituta.</p>}
|
||||
{management && ["inconclusive", "failed"].includes(item.malware_scan_status ?? "") && <p role="alert">Não foi possível concluir a análise. O ficheiro permanece privado e indisponível para divulgação.{item.malware_failure_reason ? ` Motivo: ${item.malware_failure_reason}.` : ""}</p>}
|
||||
{management && item.document_id && ["pending", "inconclusive", "failed"].includes(item.malware_scan_status ?? "") && <button type="button" className={button} disabled={busy} onClick={() => void send(`/management/documents/${item.document_id}/malware/retry`, {})}>Tentar análise novamente</button>}
|
||||
{management && item.review_status !== "reviewed" && <div className="grid gap-2 md:grid-cols-2">
|
||||
<select className={input} aria-label={`Direitos de ${item.caption}`} value={choice.rights} onChange={(event) => setReviewChoices((current) => ({ ...current, [item.id]: { ...choice, rights: event.target.value } }))}><option value="pending">Direitos por confirmar</option><option value="confirmed">Direitos confirmados</option><option value="restricted">Direitos restritos</option></select>
|
||||
<select className={input} aria-label={`Dados pessoais de ${item.caption}`} value={choice.personal} onChange={(event) => setReviewChoices((current) => ({ ...current, [item.id]: { ...choice, personal: event.target.value } }))}><option value="unknown">Dados pessoais por verificar</option><option value="none">Sem dados pessoais</option><option value="present">Contém dados pessoais</option></select>
|
||||
<input className={input} aria-label={`Fundamento dos direitos de ${item.caption}`} placeholder="Fundamento dos direitos" maxLength={2000} value={reviewRightsBasis[item.id] ?? item.rights_basis ?? ""} onChange={(event) => setReviewRightsBasis((current) => ({ ...current, [item.id]: event.target.value }))} />
|
||||
<button type="button" className={button} disabled={busy || choice.personal === "unknown" || (choice.rights === "confirmed" && !(reviewRightsBasis[item.id] ?? item.rights_basis)?.trim())} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/review`, { version_no: item.version_no, decision: "reviewed", personal_data_status: choice.personal, rights_status: choice.rights, rights_basis: reviewRightsBasis[item.id] ?? item.rights_basis })}>Registar revisão administrativa</button>
|
||||
<button type="button" className={button} disabled={busy} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/review`, { version_no: item.version_no, decision: "rejected", personal_data_status: choice.personal, rights_status: choice.rights, rights_basis: reviewRightsBasis[item.id] ?? item.rights_basis })}>Registar como não divulgável</button>
|
||||
</div>}
|
||||
{item.media_type.startsWith("image/") && (!management || item.malware_scan_status === "clean") && <img className="max-h-96 rounded object-contain" src={item.download_url} alt={item.caption} />}
|
||||
{(!management || item.malware_scan_status === "clean") && <a className="underline" href={item.download_url}>Abrir ficheiro</a>}
|
||||
{management && item.review_status === "reviewed" && !item.publicly_selected && <button type="button" className={button} disabled={busy || !zonePublished || item.file_status !== "active" || item.rights_status !== "confirmed" || item.personal_data_status !== "none"} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/select-public`, { version_no: item.version_no })}>Seleccionar para divulgação</button>}
|
||||
{management && item.publicly_selected && <button type="button" className={button} disabled={busy} onClick={() => void send(`/api/v2/investment/admin/zone-attachments/${item.id}/withdraw-public`, { version_no: item.version_no })}>Retirar da divulgação</button>}
|
||||
</article>;
|
||||
const choice = reviewChoices[item.id] ?? {
|
||||
rights: item.rights_status ?? 'pending',
|
||||
personal: item.personal_data_status ?? 'unknown',
|
||||
};
|
||||
return (
|
||||
<article
|
||||
key={item.id}
|
||||
className="space-y-2 rounded border p-3"
|
||||
>
|
||||
<p className="font-semibold">
|
||||
{item.caption} · {item.kind}
|
||||
{management && item.file_name
|
||||
? ` · ${item.file_name}`
|
||||
: ''}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Origem: {item.source_reference}
|
||||
{item.source_date ? ` · ${item.source_date}` : ''}
|
||||
{management ? ` · ${item.review_status}` : ''}
|
||||
</p>
|
||||
{management && item.independent_review === false && (
|
||||
<p className="text-sm">
|
||||
Revisão administrativa registada; não
|
||||
independente e não certificadora.
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
item.malware_scan_status === 'pending' && (
|
||||
<p role="status">A analisar o ficheiro.</p>
|
||||
)}
|
||||
{management &&
|
||||
item.malware_scan_status === 'scanning' && (
|
||||
<p role="status">A analisar o ficheiro.</p>
|
||||
)}
|
||||
{management && item.malware_scan_status === 'clean' && (
|
||||
<p role="status">
|
||||
Análise concluída: nenhuma ameaça detectada. O
|
||||
ficheiro continua privado até à divulgação
|
||||
explícita.
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
item.malware_scan_status === 'infected' && (
|
||||
<p role="alert">
|
||||
Ficheiro bloqueado: ameaça detectada.
|
||||
Mantenha-o em quarentena e carregue uma
|
||||
versão substituta.
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
['inconclusive', 'failed'].includes(
|
||||
item.malware_scan_status ?? '',
|
||||
) && (
|
||||
<p role="alert">
|
||||
Não foi possível concluir a análise. O
|
||||
ficheiro permanece privado e indisponível
|
||||
para divulgação.
|
||||
{item.malware_failure_reason
|
||||
? ` Motivo: ${item.malware_failure_reason}.`
|
||||
: ''}
|
||||
</p>
|
||||
)}
|
||||
{management &&
|
||||
item.document_id &&
|
||||
['pending', 'inconclusive', 'failed'].includes(
|
||||
item.malware_scan_status ?? '',
|
||||
) && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/management/documents/${item.document_id}/malware/retry`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
>
|
||||
Tentar análise novamente
|
||||
</button>
|
||||
)}
|
||||
{management && item.review_status !== 'reviewed' && (
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<select
|
||||
className={input}
|
||||
aria-label={`Direitos de ${item.caption}`}
|
||||
value={choice.rights}
|
||||
onChange={(event) =>
|
||||
setReviewChoices((current) => ({
|
||||
...current,
|
||||
[item.id]: {
|
||||
...choice,
|
||||
rights: event.target.value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="pending">
|
||||
Direitos por confirmar
|
||||
</option>
|
||||
<option value="confirmed">
|
||||
Direitos confirmados
|
||||
</option>
|
||||
<option value="restricted">
|
||||
Direitos restritos
|
||||
</option>
|
||||
</select>
|
||||
<select
|
||||
className={input}
|
||||
aria-label={`Dados pessoais de ${item.caption}`}
|
||||
value={choice.personal}
|
||||
onChange={(event) =>
|
||||
setReviewChoices((current) => ({
|
||||
...current,
|
||||
[item.id]: {
|
||||
...choice,
|
||||
personal: event.target.value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Dados pessoais por verificar
|
||||
</option>
|
||||
<option value="none">
|
||||
Sem dados pessoais
|
||||
</option>
|
||||
<option value="present">
|
||||
Contém dados pessoais
|
||||
</option>
|
||||
</select>
|
||||
<input
|
||||
className={input}
|
||||
aria-label={`Fundamento dos direitos de ${item.caption}`}
|
||||
placeholder="Fundamento dos direitos"
|
||||
maxLength={2000}
|
||||
value={
|
||||
reviewRightsBasis[item.id] ??
|
||||
item.rights_basis ??
|
||||
''
|
||||
}
|
||||
onChange={(event) =>
|
||||
setReviewRightsBasis((current) => ({
|
||||
...current,
|
||||
[item.id]: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
choice.personal === 'unknown' ||
|
||||
(choice.rights === 'confirmed' &&
|
||||
!(
|
||||
reviewRightsBasis[item.id] ??
|
||||
item.rights_basis
|
||||
)?.trim())
|
||||
}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/review`,
|
||||
{
|
||||
version_no: item.version_no,
|
||||
decision: 'reviewed',
|
||||
personal_data_status:
|
||||
choice.personal,
|
||||
rights_status: choice.rights,
|
||||
rights_basis:
|
||||
reviewRightsBasis[
|
||||
item.id
|
||||
] ?? item.rights_basis,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Registar revisão administrativa
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/review`,
|
||||
{
|
||||
version_no: item.version_no,
|
||||
decision: 'rejected',
|
||||
personal_data_status:
|
||||
choice.personal,
|
||||
rights_status: choice.rights,
|
||||
rights_basis:
|
||||
reviewRightsBasis[
|
||||
item.id
|
||||
] ?? item.rights_basis,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Registar como não divulgável
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{item.media_type.startsWith('image/') &&
|
||||
(!management ||
|
||||
item.malware_scan_status === 'clean') && (
|
||||
<img
|
||||
className="max-h-96 rounded object-contain"
|
||||
src={item.download_url}
|
||||
alt={item.caption}
|
||||
/>
|
||||
)}
|
||||
{(!management ||
|
||||
item.malware_scan_status === 'clean') && (
|
||||
<a className="underline" href={item.download_url}>
|
||||
Abrir ficheiro
|
||||
</a>
|
||||
)}
|
||||
{management &&
|
||||
item.review_status === 'reviewed' &&
|
||||
!item.publicly_selected && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!zonePublished ||
|
||||
item.file_status !== 'active' ||
|
||||
item.rights_status !== 'confirmed' ||
|
||||
item.personal_data_status !== 'none'
|
||||
}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/select-public`,
|
||||
{ version_no: item.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
Seleccionar para divulgação
|
||||
</button>
|
||||
)}
|
||||
{management && item.publicly_selected && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
`/api/v2/investment/admin/zone-attachments/${item.id}/withdraw-public`,
|
||||
{ version_no: item.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar da divulgação
|
||||
</button>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { api, button, card } from "./shared";
|
||||
import { useState } from 'react';
|
||||
import { api, button, card } from './shared';
|
||||
|
||||
type Feature = {
|
||||
id: string;
|
||||
@@ -8,15 +8,18 @@ type Feature = {
|
||||
};
|
||||
function rings(value: unknown): number[][][] {
|
||||
if (!Array.isArray(value) || !value.length) return [];
|
||||
if (typeof value[0] === "number") return [[value as number[]]];
|
||||
if (Array.isArray(value[0]) && typeof value[0][0] === "number") return [value as number[][]];
|
||||
if (typeof value[0] === 'number') return [[value as number[]]];
|
||||
if (Array.isArray(value[0]) && typeof value[0][0] === 'number')
|
||||
return [value as number[][]];
|
||||
return value.flatMap(rings);
|
||||
}
|
||||
export default function ZoneMap({ id }: { id: string }) {
|
||||
const [features, setFeatures] = useState<Feature[] | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const points = (features ?? []).flatMap((f) => rings(f.geometry.coordinates).flat());
|
||||
const points = (features ?? []).flatMap((f) =>
|
||||
rings(f.geometry.coordinates).flat(),
|
||||
);
|
||||
const xs = points.map((p) => p[0]),
|
||||
ys = points.map((p) => p[1]);
|
||||
const west = xs.length ? Math.min(...xs) : 0,
|
||||
@@ -29,37 +32,44 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
];
|
||||
return (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Localização e geometrias autorizadas</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
Localização e geometrias autorizadas
|
||||
</h2>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const data = await api(`/api/v2/investment/zone-map?zone_id=${id}`);
|
||||
const data = await api(
|
||||
`/api/v2/investment/zone-map?zone_id=${id}`,
|
||||
);
|
||||
setFeatures(data.features);
|
||||
if (data.truncated) setError("Exibidas as primeiras 100 geometrias.");
|
||||
if (data.truncated)
|
||||
setError('Exibidas as primeiras 100 geometrias.');
|
||||
} catch {
|
||||
setError(
|
||||
"Mapa indisponível. A ficha, a localização textual e as acções de apoio continuam disponíveis.",
|
||||
'Mapa indisponível. A ficha, a localização textual e as acções de apoio continuam disponíveis.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{busy ? "A carregar…" : "Consultar mapa"}
|
||||
{busy ? 'A carregar…' : 'Consultar mapa'}
|
||||
</button>
|
||||
{error && <p role="status">{error}</p>}
|
||||
{features?.length === 0 && (
|
||||
<p>Não existe geometria autorizada para divulgação nesta ficha.</p>
|
||||
<p>
|
||||
Não existe geometria autorizada para divulgação nesta ficha.
|
||||
</p>
|
||||
)}
|
||||
{!!features?.length && (
|
||||
<>
|
||||
<p>
|
||||
Esquema das geometrias cadastradas, sem mapa-base. Não serve para demarcação
|
||||
ou atribuição de estatuto.
|
||||
Esquema das geometrias cadastradas, sem mapa-base. Não
|
||||
serve para demarcação ou atribuição de estatuto.
|
||||
</p>
|
||||
<svg
|
||||
viewBox="0 0 640 320"
|
||||
@@ -70,7 +80,8 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
{features.map((f) => (
|
||||
<g key={f.id}>
|
||||
<title>
|
||||
{f.properties.purpose} · {f.properties.source}
|
||||
{f.properties.purpose} ·{' '}
|
||||
{f.properties.source}
|
||||
</title>
|
||||
{rings(f.geometry.coordinates).map((ring, i) =>
|
||||
ring.length === 1 ? (
|
||||
@@ -84,7 +95,11 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
) : (
|
||||
<polyline
|
||||
key={i}
|
||||
points={ring.map((p) => project(p).join(",")).join(" ")}
|
||||
points={ring
|
||||
.map((p) =>
|
||||
project(p).join(','),
|
||||
)
|
||||
.join(' ')}
|
||||
fill="none"
|
||||
stroke="#065f46"
|
||||
strokeWidth="2"
|
||||
@@ -97,7 +112,8 @@ export default function ZoneMap({ id }: { id: string }) {
|
||||
<ul>
|
||||
{features.map((f) => (
|
||||
<li key={f.id}>
|
||||
{f.properties.purpose} · Fonte: {f.properties.source} · Data:{" "}
|
||||
{f.properties.purpose} · Fonte:{' '}
|
||||
{f.properties.source} · Data:{' '}
|
||||
{f.properties.observed_at}
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Field, input, button, card } from "./shared";
|
||||
import { Field, input, button, card } from './shared';
|
||||
|
||||
export type ZoneTargets = {
|
||||
opportunities: { id: number; title: string }[];
|
||||
@@ -38,15 +38,17 @@ export default function ZoneRelations({
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className={card + " grid gap-4 md:grid-cols-2"}
|
||||
className={card + ' grid gap-4 md:grid-cols-2'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(e.currentTarget));
|
||||
if (typeof data.target !== "string") return;
|
||||
const [kind, target] = data.target.split(":");
|
||||
const data = Object.fromEntries(
|
||||
new FormData(e.currentTarget),
|
||||
);
|
||||
if (typeof data.target !== 'string') return;
|
||||
const [kind, target] = data.target.split(':');
|
||||
delete data.target;
|
||||
void action(
|
||||
`/api/v2/investment/admin/zones/${id}/${kind === "opportunity_id" ? "links" : "relations"}`,
|
||||
`/api/v2/investment/admin/zones/${id}/${kind === 'opportunity_id' ? 'links' : 'relations'}`,
|
||||
{ ...data, [kind]: target },
|
||||
);
|
||||
}}
|
||||
@@ -64,12 +66,15 @@ export default function ZoneRelations({
|
||||
))}
|
||||
{targets.dossiers.map((d) => {
|
||||
const field = d.project_id
|
||||
? "project_id"
|
||||
? 'project_id'
|
||||
: d.cluster_id
|
||||
? "cluster_id"
|
||||
: "corridor_id";
|
||||
? 'cluster_id'
|
||||
: 'corridor_id';
|
||||
return (
|
||||
<option key={d.id} value={`${field}:${d[field]}`}>
|
||||
<option
|
||||
key={d.id}
|
||||
value={`${field}:${d[field]}`}
|
||||
>
|
||||
{d.title} · ficha territorial
|
||||
</option>
|
||||
);
|
||||
@@ -79,9 +84,13 @@ export default function ZoneRelations({
|
||||
<Field label="Tipo de associação">
|
||||
<select className={input} name="association_type">
|
||||
<option value="potential">Potencial</option>
|
||||
<option value="official">Oficial, com título próprio</option>
|
||||
<option value="official">
|
||||
Oficial, com título próprio
|
||||
</option>
|
||||
<option value="influence">Área de influência</option>
|
||||
<option value="proximity">Proximidade geográfica</option>
|
||||
<option value="proximity">
|
||||
Proximidade geográfica
|
||||
</option>
|
||||
<option value="historical">Histórica</option>
|
||||
</select>
|
||||
</Field>
|
||||
@@ -99,7 +108,9 @@ export default function ZoneRelations({
|
||||
</Field>
|
||||
<Field label="Fonte jurídica, obrigatória para associação oficial">
|
||||
<select name="legal_source_id" className={input}>
|
||||
<option value="">Não aplicável à relação proposta</option>
|
||||
<option value="">
|
||||
Não aplicável à relação proposta
|
||||
</option>
|
||||
{sources.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.title}
|
||||
@@ -126,7 +137,12 @@ export default function ZoneRelations({
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Válida desde">
|
||||
<input name="valid_from" type="date" className={input} required />
|
||||
<input
|
||||
name="valid_from"
|
||||
type="date"
|
||||
className={input}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Válida até">
|
||||
<input name="valid_until" type="date" className={input} />
|
||||
@@ -139,51 +155,61 @@ export default function ZoneRelations({
|
||||
<h2 className="text-xl font-bold">Relações territoriais</h2>
|
||||
{relations.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.association_type} · {r.validation_status}{" "}
|
||||
{r.association_type} · {r.validation_status}{' '}
|
||||
<button
|
||||
disabled={busy || r.validation_status === "revoked"}
|
||||
disabled={busy || r.validation_status === 'revoked'}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
action(
|
||||
`/api/v2/investment/admin/zone-relations/${r.id}/${r.validation_status === "pending" ? "validate" : "revoke"}`,
|
||||
`/api/v2/investment/admin/zone-relations/${r.id}/${r.validation_status === 'pending' ? 'validate' : 'revoke'}`,
|
||||
{ version_no: r.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
{r.validation_status === "pending" ? "Validar" : "Revogar"}
|
||||
{r.validation_status === 'pending'
|
||||
? 'Validar'
|
||||
: 'Revogar'}
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<form
|
||||
className={card + " grid gap-4 md:grid-cols-2"}
|
||||
className={card + ' grid gap-4 md:grid-cols-2'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(e.currentTarget));
|
||||
if (typeof data.geometry !== "string") return;
|
||||
const data = Object.fromEntries(
|
||||
new FormData(e.currentTarget),
|
||||
);
|
||||
if (typeof data.geometry !== 'string') return;
|
||||
const raw = data.geometry;
|
||||
try {
|
||||
data.geometry = JSON.parse(raw);
|
||||
void action(`/api/v2/investment/admin/zones/${id}/geometries`, data);
|
||||
void action(
|
||||
`/api/v2/investment/admin/zones/${id}/geometries`,
|
||||
data,
|
||||
);
|
||||
} catch {
|
||||
const field = e.currentTarget.elements.namedItem(
|
||||
"geometry",
|
||||
'geometry',
|
||||
) as HTMLTextAreaElement;
|
||||
field.setCustomValidity("Introduza GeoJSON válido.");
|
||||
field.setCustomValidity('Introduza GeoJSON válido.');
|
||||
field.reportValidity();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold md:col-span-2">Geometria para revisão GIS</h2>
|
||||
<h2 className="text-xl font-bold md:col-span-2">
|
||||
Geometria para revisão GIS
|
||||
</h2>
|
||||
<p>
|
||||
GeoJSON no SRID 4326, até 200 KB. Não desenhe um perímetro sem fonte autorizada.
|
||||
GeoJSON no SRID 4326, até 200 KB. Não desenhe um perímetro
|
||||
sem fonte autorizada.
|
||||
</p>
|
||||
<Field label="GeoJSON">
|
||||
<textarea
|
||||
name="geometry"
|
||||
className={input}
|
||||
required
|
||||
onChange={(e) => e.currentTarget.setCustomValidity("")}
|
||||
onChange={(e) => e.currentTarget.setCustomValidity('')}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Finalidade">
|
||||
@@ -191,7 +217,9 @@ export default function ZoneRelations({
|
||||
<option value="site">Localização</option>
|
||||
<option value="influence">Área de influência</option>
|
||||
<option value="alternative">Alternativa</option>
|
||||
<option value="official_perimeter">Perímetro oficial</option>
|
||||
<option value="official_perimeter">
|
||||
Perímetro oficial
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fonte jurídica do perímetro">
|
||||
@@ -205,13 +233,27 @@ export default function ZoneRelations({
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Proveniência da geometria">
|
||||
<input className={input} name="source_reference" required minLength={10} />
|
||||
<input
|
||||
className={input}
|
||||
name="source_reference"
|
||||
required
|
||||
minLength={10}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Entidade indicada para validação">
|
||||
<input className={input} name="validating_entity" required />
|
||||
<input
|
||||
className={input}
|
||||
name="validating_entity"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Data da observação">
|
||||
<input className={input} type="date" name="observed_at" required />
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
name="observed_at"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<button disabled={busy} className={button}>
|
||||
Submeter geometria
|
||||
@@ -221,20 +263,20 @@ export default function ZoneRelations({
|
||||
<h2 className="text-xl font-bold">Revisão GIS</h2>
|
||||
{geometries.map((g) => (
|
||||
<p key={g.id}>
|
||||
{g.purpose} · {g.validation_status}{" "}
|
||||
{g.purpose} · {g.validation_status}{' '}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || g.validation_status === "revoked"}
|
||||
disabled={busy || g.validation_status === 'revoked'}
|
||||
onClick={() =>
|
||||
action(
|
||||
`/api/v2/investment/admin/zone-geometries/${g.id}/${g.validation_status === "pending" ? "validate" : "revoke"}`,
|
||||
`/api/v2/investment/admin/zone-geometries/${g.id}/${g.validation_status === 'pending' ? 'validate' : 'revoke'}`,
|
||||
{ version_no: g.version_no },
|
||||
)
|
||||
}
|
||||
>
|
||||
{g.validation_status === "pending"
|
||||
? "Validar e autorizar divulgação"
|
||||
: "Retirar geometria"}
|
||||
{g.validation_status === 'pending'
|
||||
? 'Validar e autorizar divulgação'
|
||||
: 'Retirar geometria'}
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,10 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { Frame, Field, input, button, card, api } from './shared';
|
||||
|
||||
type Zone = {
|
||||
id: string;
|
||||
@@ -19,11 +22,22 @@ type Zone = {
|
||||
operational_status?: string;
|
||||
development_status?: string;
|
||||
availability_status?: string;
|
||||
source_evidence?: { title: string; url: string; source_type: string; supports: string; source_date?: string | null }[];
|
||||
source_evidence?: {
|
||||
title: string;
|
||||
url: string;
|
||||
source_type: string;
|
||||
supports: string;
|
||||
source_date?: string | null;
|
||||
}[];
|
||||
area_value?: string | null;
|
||||
area_unit?: string | null;
|
||||
activities?: { name: string; status: string }[];
|
||||
locations?: { id: string; name: string; location_type: string; scope_type: string }[];
|
||||
locations?: {
|
||||
id: string;
|
||||
name: string;
|
||||
location_type: string;
|
||||
scope_type: string;
|
||||
}[];
|
||||
};
|
||||
export default function Zones({
|
||||
records,
|
||||
@@ -38,79 +52,190 @@ export default function Zones({
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
};
|
||||
filters: { q?: string; category?: string; physical_category?: string; legal_regime?: string; development_status?: string; availability_status?: string; activity?: string };
|
||||
filters: {
|
||||
q?: string;
|
||||
category?: string;
|
||||
physical_category?: string;
|
||||
legal_regime?: string;
|
||||
development_status?: string;
|
||||
availability_status?: string;
|
||||
activity?: string;
|
||||
};
|
||||
management: boolean;
|
||||
zoneExtensionsAvailable?: boolean;
|
||||
territorySelection?: TerritoryOption[];
|
||||
}) {
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const exportParams = new URLSearchParams();
|
||||
for (const key of ["q", "category", "physical_category", "legal_regime", "development_status", "availability_status", "activity"] as const) {
|
||||
for (const key of [
|
||||
'q',
|
||||
'category',
|
||||
'physical_category',
|
||||
'legal_regime',
|
||||
'development_status',
|
||||
'availability_status',
|
||||
'activity',
|
||||
] as const) {
|
||||
const value = filters[key];
|
||||
if (value) exportParams.set(key, value);
|
||||
}
|
||||
const territoryKeys: Record<string, string> = { province: "province_id", district: "district_id", admin_post: "admin_post_id", locality: "locality_id" };
|
||||
territorySelection.forEach((item) => { const key = territoryKeys[item.location_type]; if (key) exportParams.set(key, item.id); });
|
||||
const territoryKeys: Record<string, string> = {
|
||||
province: 'province_id',
|
||||
district: 'district_id',
|
||||
admin_post: 'admin_post_id',
|
||||
locality: 'locality_id',
|
||||
};
|
||||
territorySelection.forEach((item) => {
|
||||
const key = territoryKeys[item.location_type];
|
||||
if (key) exportParams.set(key, item.id);
|
||||
});
|
||||
return (
|
||||
<Frame
|
||||
title={management ? "Gestão de ZEE, ZFI e parques" : "ZEE, ZFI e parques industriais"}
|
||||
title={
|
||||
management
|
||||
? 'Gestão de ZEE, ZFI e parques'
|
||||
: 'ZEE, ZFI e parques industriais'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
A informação territorial não atribui benefícios nem substitui certificados ou
|
||||
decisões das entidades competentes.
|
||||
A informação territorial não atribui benefícios nem substitui
|
||||
certificados ou decisões das entidades competentes.
|
||||
</p>
|
||||
<nav aria-label="Dimensões de investimento" className="flex flex-wrap gap-4 underline">
|
||||
<nav
|
||||
aria-label="Dimensões de investimento"
|
||||
className="flex flex-wrap gap-4 underline"
|
||||
>
|
||||
<Link href="/clusters">Por Cluster</Link>
|
||||
<Link href="/corredores">Por Corredor</Link>
|
||||
<Link href="/zonas?category=zee">Por ZEE</Link>
|
||||
<Link href="/zonas?category=zfi">Por ZFI</Link>
|
||||
<Link href="/zonas?category=industrial_park">Parques industriais</Link>
|
||||
<Link href="/zonas?category=industrial_park">
|
||||
Parques industriais
|
||||
</Link>
|
||||
</nav>
|
||||
<form method="get" className={card + " grid gap-4 md:grid-cols-3"}>
|
||||
<form method="get" className={card + ' grid gap-4 md:grid-cols-3'}>
|
||||
<Field label="Pesquisar por nome ou código">
|
||||
<input className={input} name="q" defaultValue={filters.q} maxLength={120} />
|
||||
<input
|
||||
className={input}
|
||||
name="q"
|
||||
defaultValue={filters.q}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Categoria">
|
||||
<select className={input} name="category" defaultValue={filters.category ?? ""}>
|
||||
<select
|
||||
className={input}
|
||||
name="category"
|
||||
defaultValue={filters.category ?? ''}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Categoria física">
|
||||
<select className={input} name="physical_category" defaultValue={filters.physical_category ?? ""}>
|
||||
<option value="">Todas</option><option value="industrial_park">Parque industrial</option>{zoneExtensionsAvailable && <><option value="agro_industrial_park">Parque agro-industrial</option><option value="industrial_logistics_park">Parque industrial e logístico</option></>}<option value="industrial_free_zone">ZFI</option><option value="economic_zone">ZEE</option>
|
||||
<select
|
||||
className={input}
|
||||
name="physical_category"
|
||||
defaultValue={filters.physical_category ?? ''}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
{zoneExtensionsAvailable && (
|
||||
<>
|
||||
<option value="agro_industrial_park">
|
||||
Parque agro-industrial
|
||||
</option>
|
||||
<option value="industrial_logistics_park">
|
||||
Parque industrial e logístico
|
||||
</option>
|
||||
</>
|
||||
)}
|
||||
<option value="industrial_free_zone">ZFI</option>
|
||||
<option value="economic_zone">ZEE</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Actividade documentada">
|
||||
<input className={input} name="activity" defaultValue={filters.activity} maxLength={120} />
|
||||
<input
|
||||
className={input}
|
||||
name="activity"
|
||||
defaultValue={filters.activity}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Regime jurídico">
|
||||
<select className={input} name="legal_regime" defaultValue={filters.legal_regime ?? ""}>
|
||||
<option value="">Todos</option><option value="zee">ZEE</option><option value="zfi">ZFI</option><option value="general">Regime geral</option><option value="pending">Por confirmar</option>
|
||||
<select
|
||||
className={input}
|
||||
name="legal_regime"
|
||||
defaultValue={filters.legal_regime ?? ''}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="general">Regime geral</option>
|
||||
<option value="pending">Por confirmar</option>
|
||||
</select>
|
||||
</Field>
|
||||
{zoneExtensionsAvailable && <Field label="Desenvolvimento">
|
||||
<select className={input} name="development_status" defaultValue={filters.development_status ?? ""}>
|
||||
<option value="">Todos</option><option value="announced">Anunciado</option><option value="planned">Planeado</option><option value="in_development">Em desenvolvimento</option><option value="partially_operational">Parcialmente operacional</option><option value="operational">Operacional</option><option value="unknown">Por confirmar</option>
|
||||
</select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && <Field label="Disponibilidade">
|
||||
<select className={input} name="availability_status" defaultValue={filters.availability_status ?? ""}>
|
||||
<option value="">Todas</option><option value="confirmed">Confirmada</option><option value="unavailable">Indisponível</option><option value="reported_unverified">Reportada, por verificar</option><option value="not_informed">Não informada</option>
|
||||
</select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Desenvolvimento">
|
||||
<select
|
||||
className={input}
|
||||
name="development_status"
|
||||
defaultValue={filters.development_status ?? ''}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="announced">Anunciado</option>
|
||||
<option value="planned">Planeado</option>
|
||||
<option value="in_development">
|
||||
Em desenvolvimento
|
||||
</option>
|
||||
<option value="partially_operational">
|
||||
Parcialmente operacional
|
||||
</option>
|
||||
<option value="operational">Operacional</option>
|
||||
<option value="unknown">Por confirmar</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Disponibilidade">
|
||||
<select
|
||||
className={input}
|
||||
name="availability_status"
|
||||
defaultValue={filters.availability_status ?? ''}
|
||||
>
|
||||
<option value="">Todas</option>
|
||||
<option value="confirmed">Confirmada</option>
|
||||
<option value="unavailable">Indisponível</option>
|
||||
<option value="reported_unverified">
|
||||
Reportada, por verificar
|
||||
</option>
|
||||
<option value="not_informed">Não informada</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<TerritoryFields initial={territorySelection} />
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<p role="status">{records.total} registos disponíveis</p>
|
||||
{!management && <a className="underline" href={`/api/v2/investment/zones/export.csv?${exportParams.toString()}`}>Exportar resultados filtrados (CSV)</a>}
|
||||
{!management && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/api/v2/investment/zones/export.csv?${exportParams.toString()}`}
|
||||
>
|
||||
Exportar resultados filtrados (CSV)
|
||||
</a>
|
||||
)}
|
||||
{!records.total && (
|
||||
<p className={card}>
|
||||
Sem registos disponíveis para estes filtros. As zonas aguardam cadastro e
|
||||
validação documental.
|
||||
Sem registos disponíveis para estes filtros. As zonas
|
||||
aguardam cadastro e validação documental.
|
||||
</p>
|
||||
)}
|
||||
{records.data.map((zone) => (
|
||||
@@ -118,22 +243,80 @@ export default function Zones({
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${management ? "/management/investment/zones" : "/zonas"}/${zone.id}`}
|
||||
href={`${management ? '/management/investment/zones' : '/zonas'}/${zone.id}`}
|
||||
>
|
||||
{zone.name}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{zone.code} · {zone.category.toUpperCase()} ·{" "}
|
||||
{[zone.district, zone.province].filter(Boolean).join(", ") || "Localização por confirmar"}
|
||||
{zone.code} · {zone.category.toUpperCase()} ·{' '}
|
||||
{[zone.district, zone.province]
|
||||
.filter(Boolean)
|
||||
.join(', ') || 'Localização por confirmar'}
|
||||
</p>
|
||||
{zone.legal_regime && <p>Regime jurídico: {zone.legal_regime.toUpperCase()}</p>}
|
||||
{zoneExtensionsAvailable && zone.development_status && <p>Desenvolvimento: {zone.development_status.replaceAll("_", " ")}</p>}
|
||||
{zoneExtensionsAvailable && zone.availability_status && <p>Disponibilidade para instalação: {zone.availability_status.replaceAll("_", " ")}</p>}
|
||||
{zone.area_value && <p>Área indicada: {zone.area_value} {zone.area_unit}</p>}
|
||||
{zone.locations?.length ? <p>Abrangência: {zone.locations.map((location) => location.name).join(" · ")}</p> : null}
|
||||
{zone.activities?.length ? <p>Actividades: {zone.activities.map((activity) => `${activity.name} (${activity.status})`).join(" · ")}</p> : null}
|
||||
{!!zone.source_evidence?.length && <p>Fonte: {zone.source_evidence.map((source, index) => <span key={source.url}>{index > 0 ? " · " : ""}<a className="underline" href={source.url} target="_blank" rel="noreferrer">{source.title}</a>{source.source_date ? ` (${source.source_date})` : " (data da fonte não informada)"} — {source.supports}</span>)}</p>}
|
||||
{zone.legal_regime && (
|
||||
<p>
|
||||
Regime jurídico: {zone.legal_regime.toUpperCase()}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.development_status && (
|
||||
<p>
|
||||
Desenvolvimento:{' '}
|
||||
{zone.development_status.replaceAll('_', ' ')}
|
||||
</p>
|
||||
)}
|
||||
{zoneExtensionsAvailable && zone.availability_status && (
|
||||
<p>
|
||||
Disponibilidade para instalação:{' '}
|
||||
{zone.availability_status.replaceAll('_', ' ')}
|
||||
</p>
|
||||
)}
|
||||
{zone.area_value && (
|
||||
<p>
|
||||
Área indicada: {zone.area_value} {zone.area_unit}
|
||||
</p>
|
||||
)}
|
||||
{zone.locations?.length ? (
|
||||
<p>
|
||||
Abrangência:{' '}
|
||||
{zone.locations
|
||||
.map((location) => location.name)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{zone.activities?.length ? (
|
||||
<p>
|
||||
Actividades:{' '}
|
||||
{zone.activities
|
||||
.map(
|
||||
(activity) =>
|
||||
`${activity.name} (${activity.status})`,
|
||||
)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
) : null}
|
||||
{!!zone.source_evidence?.length && (
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{zone.source_evidence.map((source, index) => (
|
||||
<span key={source.url}>
|
||||
{index > 0 ? ' · ' : ''}
|
||||
<a
|
||||
className="underline"
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{source.title}
|
||||
</a>
|
||||
{source.source_date
|
||||
? ` (${source.source_date})`
|
||||
: ' (data da fonte não informada)'}{' '}
|
||||
— {source.supports}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
<p>{zone.description}</p>
|
||||
<p>Validação: {zone.validation_status}</p>
|
||||
{management && (
|
||||
@@ -144,25 +327,31 @@ export default function Zones({
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação" className="flex gap-4 underline">
|
||||
{records.prev_page_url && <Link href={records.prev_page_url}>Anterior</Link>}
|
||||
{records.next_page_url && <Link href={records.next_page_url}>Seguinte</Link>}
|
||||
{records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{records.next_page_url && (
|
||||
<Link href={records.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
{management && (
|
||||
<form
|
||||
className={card + " space-y-4"}
|
||||
className={card + ' space-y-4'}
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget));
|
||||
const data = Object.fromEntries(
|
||||
new FormData(event.currentTarget),
|
||||
);
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
await api("/api/v2/investment/admin/zones", data);
|
||||
await api('/api/v2/investment/admin/zones', data);
|
||||
router.reload();
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: "Não foi possível guardar. Tente novamente.",
|
||||
: 'Não foi possível guardar. Tente novamente.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -172,76 +361,205 @@ export default function Zones({
|
||||
<h2 className="text-xl font-bold">Criar rascunho</h2>
|
||||
<TerritoryFields endpoint="/management/territory-options" />
|
||||
<Field label="Código">
|
||||
<input name="code" className={input} required maxLength={80} />
|
||||
<input
|
||||
name="code"
|
||||
className={input}
|
||||
required
|
||||
maxLength={80}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nome">
|
||||
<input name="name" className={input} required maxLength={255} />
|
||||
<input
|
||||
name="name"
|
||||
className={input}
|
||||
required
|
||||
maxLength={255}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Categoria proposta">
|
||||
<select name="category" className={input}>
|
||||
<option value="pending">Pendente de enquadramento</option>
|
||||
<option value="pending">
|
||||
Pendente de enquadramento
|
||||
</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Categoria física">
|
||||
<select name="physical_category" className={input} defaultValue="unknown">
|
||||
<select
|
||||
name="physical_category"
|
||||
className={input}
|
||||
defaultValue="unknown"
|
||||
>
|
||||
<option value="unknown">Por confirmar</option>
|
||||
<option value="economic_zone">Zona económica</option>
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
{zoneExtensionsAvailable && <option value="agro_industrial_park">Parque agro-industrial</option>}
|
||||
{zoneExtensionsAvailable && <option value="industrial_logistics_park">Parque industrial e logístico</option>}
|
||||
<option value="industrial_free_zone">Zona franca industrial</option>
|
||||
<option value="integrated_tourism_area">Área de turismo integrado</option>
|
||||
<option value="economic_zone">
|
||||
Zona económica
|
||||
</option>
|
||||
<option value="industrial_park">
|
||||
Parque industrial
|
||||
</option>
|
||||
{zoneExtensionsAvailable && (
|
||||
<option value="agro_industrial_park">
|
||||
Parque agro-industrial
|
||||
</option>
|
||||
)}
|
||||
{zoneExtensionsAvailable && (
|
||||
<option value="industrial_logistics_park">
|
||||
Parque industrial e logístico
|
||||
</option>
|
||||
)}
|
||||
<option value="industrial_free_zone">
|
||||
Zona franca industrial
|
||||
</option>
|
||||
<option value="integrated_tourism_area">
|
||||
Área de turismo integrado
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
{zoneExtensionsAvailable && <Field label="Estado de desenvolvimento">
|
||||
<select name="development_status" className={input} defaultValue="unknown"><option value="unknown">Por confirmar</option><option value="announced">Anunciado</option><option value="planned">Planeado</option><option value="in_development">Em desenvolvimento</option><option value="partially_operational">Parcialmente operacional</option><option value="operational">Operacional</option><option value="suspended">Suspenso</option></select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && <Field label="Disponibilidade para instalação">
|
||||
<select name="availability_status" className={input} defaultValue="not_informed"><option value="not_informed">Não informada</option><option value="confirmed">Confirmada por fonte</option><option value="unavailable">Indisponível</option><option value="reported_unverified">Reportada, por verificar</option></select>
|
||||
</Field>}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Estado de desenvolvimento">
|
||||
<select
|
||||
name="development_status"
|
||||
className={input}
|
||||
defaultValue="unknown"
|
||||
>
|
||||
<option value="unknown">Por confirmar</option>
|
||||
<option value="announced">Anunciado</option>
|
||||
<option value="planned">Planeado</option>
|
||||
<option value="in_development">
|
||||
Em desenvolvimento
|
||||
</option>
|
||||
<option value="partially_operational">
|
||||
Parcialmente operacional
|
||||
</option>
|
||||
<option value="operational">Operacional</option>
|
||||
<option value="suspended">Suspenso</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
{zoneExtensionsAvailable && (
|
||||
<Field label="Disponibilidade para instalação">
|
||||
<select
|
||||
name="availability_status"
|
||||
className={input}
|
||||
defaultValue="not_informed"
|
||||
>
|
||||
<option value="not_informed">
|
||||
Não informada
|
||||
</option>
|
||||
<option value="confirmed">
|
||||
Confirmada por fonte
|
||||
</option>
|
||||
<option value="unavailable">
|
||||
Indisponível
|
||||
</option>
|
||||
<option value="reported_unverified">
|
||||
Reportada, por verificar
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Regime jurídico">
|
||||
<select name="legal_regime" className={input} defaultValue="pending">
|
||||
<option value="pending">Pendente de confirmação</option>
|
||||
<select
|
||||
name="legal_regime"
|
||||
className={input}
|
||||
defaultValue="pending"
|
||||
>
|
||||
<option value="pending">
|
||||
Pendente de confirmação
|
||||
</option>
|
||||
<option value="zee">ZEE</option>
|
||||
<option value="zfi">ZFI</option>
|
||||
<option value="general">Regime geral</option>
|
||||
<option value="not_applicable">Não aplicável</option>
|
||||
<option value="not_applicable">
|
||||
Não aplicável
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Área (valor) — se documentada">
|
||||
<input name="area_value" className={input} type="number" min="0" step="0.0001" />
|
||||
<input
|
||||
name="area_value"
|
||||
className={input}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.0001"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Unidade da área">
|
||||
<select name="area_unit" className={input} defaultValue="">
|
||||
<option value="">Por confirmar</option><option value="ha">hectares (ha)</option><option value="km2">quilómetros quadrados (km²)</option>
|
||||
<select
|
||||
name="area_unit"
|
||||
className={input}
|
||||
defaultValue=""
|
||||
>
|
||||
<option value="">Por confirmar</option>
|
||||
<option value="ha">hectares (ha)</option>
|
||||
<option value="km2">
|
||||
quilómetros quadrados (km²)
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Actividade documentada (opcional)">
|
||||
<input name="activity_name" className={input} maxLength={300} />
|
||||
<input
|
||||
name="activity_name"
|
||||
className={input}
|
||||
maxLength={300}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado da actividade">
|
||||
<select name="activity_status" className={input} defaultValue="potential">
|
||||
<option value="potential">Potencial referido pela fonte</option><option value="proposed">Proposta</option>
|
||||
<option value="authorized">Autorizada por documento</option><option value="conditional">Condicionada</option><option value="excluded">Excluída</option>
|
||||
<select
|
||||
name="activity_status"
|
||||
className={input}
|
||||
defaultValue="potential"
|
||||
>
|
||||
<option value="potential">
|
||||
Potencial referido pela fonte
|
||||
</option>
|
||||
<option value="proposed">Proposta</option>
|
||||
<option value="authorized">
|
||||
Autorizada por documento
|
||||
</option>
|
||||
<option value="conditional">Condicionada</option>
|
||||
<option value="excluded">Excluída</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Designações alternativas">
|
||||
<textarea name="aliases_text" className={input} rows={2} placeholder="Uma por linha" />
|
||||
<textarea
|
||||
name="aliases_text"
|
||||
className={input}
|
||||
rows={2}
|
||||
placeholder="Uma por linha"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Localização histórica (se diferente da actual)">
|
||||
<input name="historical_name" className={input} maxLength={255} />
|
||||
<input
|
||||
name="historical_name"
|
||||
className={input}
|
||||
maxLength={255}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Distrito histórico">
|
||||
<input name="historical_district" className={input} maxLength={120} />
|
||||
<input
|
||||
name="historical_district"
|
||||
className={input}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Província histórica">
|
||||
<input name="historical_province" className={input} maxLength={120} />
|
||||
<input
|
||||
name="historical_province"
|
||||
className={input}
|
||||
maxLength={120}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Fonte da localização histórica">
|
||||
<input name="historical_source_reference" className={input} maxLength={2000} />
|
||||
<input
|
||||
name="historical_source_reference"
|
||||
className={input}
|
||||
maxLength={2000}
|
||||
/>
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<button className={button} disabled={busy}>
|
||||
|
||||
@@ -1,23 +1,197 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export default function Blank({ disclaimer }: { disclaimer: string }) {
|
||||
return <main className="mx-auto max-w-4xl space-y-6 p-8 print:max-w-none print:p-0">
|
||||
<div className="flex justify-end print:hidden"><button className="rounded border px-4 py-2" onClick={() => window.print()}>Imprimir / guardar como PDF</button></div>
|
||||
<header className="space-y-2 border-b pb-4"><p>InvestMoz · modelo de preparação · versão land-assistance-v1</p><h1 className="text-2xl font-bold">Formulário de orientação e preparação — Terra e DUAT</h1><p>{disclaimer}</p></header>
|
||||
<p>Preencha apenas o que sabe. Use “Não sei” ou “Por confirmar”. Este modelo imprimível não é um PDF electrónico preenchível nem formulário oficial.</p>
|
||||
<Section title="A. Tipo de apoio"><Lines items={['Terra para investimento', 'Habitação', 'Exploração familiar', 'Reconhecimento ou titulação de área ocupada', 'Regularização cadastral', 'Delimitação ou demarcação', 'Alteração de uso/área', 'Transmissão/herança', 'Acompanhamento de processo', 'Conflito/restrição', 'Outro']} /><Line label="Descrição do pedido" /><Line label="Modalidade invocada, se conhecida" /><Line label="Projecto ou oportunidade no InvestMoz" /></Section>
|
||||
<Section title="B. Requerente"><Lines items={['Pessoa singular', 'Pessoa colectiva', 'Comunidade', 'Outra categoria']} /><Line label="Nome ou denominação" /><Line label="Pessoa de contacto" /><Line label="Email" /><Line label="Telefone" /><Line label="Canal preferido de resposta" /><Line label="País/nacionalidade (se aplicável)" /><Line label="Representante, qualidade e fundamento (se aplicável)" /><Line label="NUIT/identificação (apenas se necessário ao acto concreto)" /></Section>
|
||||
<Section title="C. Localização"><Lines items={['Tenho área identificada', 'Procuro localização', 'Preciso de apoio para localizar']} />{['Província','Distrito/município','Posto administrativo','Localidade/bairro/comunidade','Descrição do local','Área e unidade','Referência cadastral (se existente)','Coordenadas/planta (se disponíveis)'].map((label) => <Line key={label} label={label} />)}</Section>
|
||||
<Section title="D. Finalidade e situação conhecida"><Line label="Uso pretendido e actividade, se aplicável" />{['Ocupantes/utilizações conhecidas? Sim / Não segundo informação disponível / Não sei','Descrição','Construções, benfeitorias, machambas, servidões ou usos comunitários?','Título, autorização ou antecedentes?','Conflito, oposição ou possível sobreposição?','Descrição'].map((label) => <Line key={label} label={label} />)}<p>As respostas são declarações do requerente, não conclusões cadastrais.</p></Section>
|
||||
<Section title="E. Processo existente"><Line label="Número oficial, se já atribuído" /><Line label="Entidade receptora e data apresentada" /><Line label="Estado comunicado pela entidade" /><Line label="Pendências e comprovativo disponível" /></Section>
|
||||
<Section title="F. Plano de exploração, se aplicável"><p>Indique períodos livremente; não existe duração obrigatória presumida por este modelo.</p>{['Actividade e período','Área/unidade','Existente ou planeado','Metas e construções','Investimento previsto'].map((label) => <Line key={label} label={label} />)}</Section>
|
||||
<Section title="G. Consulta comunitária e pareceres"><p>Esta secção serve apenas para preparar/registar informação. Não declarar consulta realizada sem evidência.</p>{['Comunidade/local/data','Participantes e funções','Língua/tradução','Intervenções e divergências','Oposição','Acordos e compromissos','Acta, assinaturas e pareceres recebidos'].map((label) => <Line key={label} label={label} />)}</Section>
|
||||
<Section title="H. Documentos opcionais nesta fase"><Lines items={['Planta/esboço','Título ou antecedente','Plano de exploração','Recibo/comunicação oficial','Acta de consulta','Fotografias','Outros']} /><Line label="Informação complementar" /></Section>
|
||||
<footer className="space-y-2 border-t pt-4"><p>Confirmo que os dados correspondem à informação de que disponho e que identifiquei as dúvidas conhecidas.</p><Line label="Data, nome do requerente/representante e assinatura (só na versão impressa, quando aplicável)"/><p className="font-semibold">{disclaimer}</p></footer>
|
||||
<style>{'@media print { button { display: none } section { break-inside: avoid } }'}</style>
|
||||
</main>;
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl space-y-6 p-8 print:max-w-none print:p-0">
|
||||
<div className="flex justify-end print:hidden">
|
||||
<button
|
||||
className="rounded border px-4 py-2"
|
||||
onClick={() => window.print()}
|
||||
>
|
||||
Imprimir / guardar como PDF
|
||||
</button>
|
||||
</div>
|
||||
<header className="space-y-2 border-b pb-4">
|
||||
<p>
|
||||
InvestMoz · modelo de preparação · versão land-assistance-v1
|
||||
</p>
|
||||
<h1 className="text-2xl font-bold">
|
||||
Formulário de orientação e preparação — Terra e DUAT
|
||||
</h1>
|
||||
<p>{disclaimer}</p>
|
||||
</header>
|
||||
<p>
|
||||
Preencha apenas o que sabe. Use “Não sei” ou “Por confirmar”.
|
||||
Este modelo imprimível não é um PDF electrónico preenchível nem
|
||||
formulário oficial.
|
||||
</p>
|
||||
<Section title="A. Tipo de apoio">
|
||||
<Lines
|
||||
items={[
|
||||
'Terra para investimento',
|
||||
'Habitação',
|
||||
'Exploração familiar',
|
||||
'Reconhecimento ou titulação de área ocupada',
|
||||
'Regularização cadastral',
|
||||
'Delimitação ou demarcação',
|
||||
'Alteração de uso/área',
|
||||
'Transmissão/herança',
|
||||
'Acompanhamento de processo',
|
||||
'Conflito/restrição',
|
||||
'Outro',
|
||||
]}
|
||||
/>
|
||||
<Line label="Descrição do pedido" />
|
||||
<Line label="Modalidade invocada, se conhecida" />
|
||||
<Line label="Projecto ou oportunidade no InvestMoz" />
|
||||
</Section>
|
||||
<Section title="B. Requerente">
|
||||
<Lines
|
||||
items={[
|
||||
'Pessoa singular',
|
||||
'Pessoa colectiva',
|
||||
'Comunidade',
|
||||
'Outra categoria',
|
||||
]}
|
||||
/>
|
||||
<Line label="Nome ou denominação" />
|
||||
<Line label="Pessoa de contacto" />
|
||||
<Line label="Email" />
|
||||
<Line label="Telefone" />
|
||||
<Line label="Canal preferido de resposta" />
|
||||
<Line label="País/nacionalidade (se aplicável)" />
|
||||
<Line label="Representante, qualidade e fundamento (se aplicável)" />
|
||||
<Line label="NUIT/identificação (apenas se necessário ao acto concreto)" />
|
||||
</Section>
|
||||
<Section title="C. Localização">
|
||||
<Lines
|
||||
items={[
|
||||
'Tenho área identificada',
|
||||
'Procuro localização',
|
||||
'Preciso de apoio para localizar',
|
||||
]}
|
||||
/>
|
||||
{[
|
||||
'Província',
|
||||
'Distrito/município',
|
||||
'Posto administrativo',
|
||||
'Localidade/bairro/comunidade',
|
||||
'Descrição do local',
|
||||
'Área e unidade',
|
||||
'Referência cadastral (se existente)',
|
||||
'Coordenadas/planta (se disponíveis)',
|
||||
].map((label) => (
|
||||
<Line key={label} label={label} />
|
||||
))}
|
||||
</Section>
|
||||
<Section title="D. Finalidade e situação conhecida">
|
||||
<Line label="Uso pretendido e actividade, se aplicável" />
|
||||
{[
|
||||
'Ocupantes/utilizações conhecidas? Sim / Não segundo informação disponível / Não sei',
|
||||
'Descrição',
|
||||
'Construções, benfeitorias, machambas, servidões ou usos comunitários?',
|
||||
'Título, autorização ou antecedentes?',
|
||||
'Conflito, oposição ou possível sobreposição?',
|
||||
'Descrição',
|
||||
].map((label) => (
|
||||
<Line key={label} label={label} />
|
||||
))}
|
||||
<p>
|
||||
As respostas são declarações do requerente, não conclusões
|
||||
cadastrais.
|
||||
</p>
|
||||
</Section>
|
||||
<Section title="E. Processo existente">
|
||||
<Line label="Número oficial, se já atribuído" />
|
||||
<Line label="Entidade receptora e data apresentada" />
|
||||
<Line label="Estado comunicado pela entidade" />
|
||||
<Line label="Pendências e comprovativo disponível" />
|
||||
</Section>
|
||||
<Section title="F. Plano de exploração, se aplicável">
|
||||
<p>
|
||||
Indique períodos livremente; não existe duração obrigatória
|
||||
presumida por este modelo.
|
||||
</p>
|
||||
{[
|
||||
'Actividade e período',
|
||||
'Área/unidade',
|
||||
'Existente ou planeado',
|
||||
'Metas e construções',
|
||||
'Investimento previsto',
|
||||
].map((label) => (
|
||||
<Line key={label} label={label} />
|
||||
))}
|
||||
</Section>
|
||||
<Section title="G. Consulta comunitária e pareceres">
|
||||
<p>
|
||||
Esta secção serve apenas para preparar/registar informação.
|
||||
Não declarar consulta realizada sem evidência.
|
||||
</p>
|
||||
{[
|
||||
'Comunidade/local/data',
|
||||
'Participantes e funções',
|
||||
'Língua/tradução',
|
||||
'Intervenções e divergências',
|
||||
'Oposição',
|
||||
'Acordos e compromissos',
|
||||
'Acta, assinaturas e pareceres recebidos',
|
||||
].map((label) => (
|
||||
<Line key={label} label={label} />
|
||||
))}
|
||||
</Section>
|
||||
<Section title="H. Documentos opcionais nesta fase">
|
||||
<Lines
|
||||
items={[
|
||||
'Planta/esboço',
|
||||
'Título ou antecedente',
|
||||
'Plano de exploração',
|
||||
'Recibo/comunicação oficial',
|
||||
'Acta de consulta',
|
||||
'Fotografias',
|
||||
'Outros',
|
||||
]}
|
||||
/>
|
||||
<Line label="Informação complementar" />
|
||||
</Section>
|
||||
<footer className="space-y-2 border-t pt-4">
|
||||
<p>
|
||||
Confirmo que os dados correspondem à informação de que
|
||||
disponho e que identifiquei as dúvidas conhecidas.
|
||||
</p>
|
||||
<Line label="Data, nome do requerente/representante e assinatura (só na versão impressa, quando aplicável)" />
|
||||
<p className="font-semibold">{disclaimer}</p>
|
||||
</footer>
|
||||
<style>
|
||||
{
|
||||
'@media print { button { display: none } section { break-inside: avoid } }'
|
||||
}
|
||||
</style>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: ReactNode }) { return <section className="space-y-3 rounded border p-4"><h2 className="text-lg font-bold">{title}</h2>{children}</section>; }
|
||||
function Line({ label }: { label: string }) { return <div className="space-y-1"><span className="text-sm">{label}</span><div className="min-h-8 border-b border-dotted border-slate-500" /></div>; }
|
||||
function Lines({ items }: { items: string[] }) { return <div className="grid gap-2 sm:grid-cols-2">{items.map((item) => <div key={item}>☐ {item}</div>)}</div>; }
|
||||
function Section({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-lg font-bold">{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Line({ label }: { label: string }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<span className="text-sm">{label}</span>
|
||||
<div className="min-h-8 border-b border-dotted border-slate-500" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function Lines({ items }: { items: string[] }) {
|
||||
return (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{items.map((item) => (
|
||||
<div key={item}>☐ {item}</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,34 +2,433 @@ import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
|
||||
type Props = {
|
||||
case: { id: string; reference: string; version: number; status: string; payload: Record<string, any>; updated_at: string };
|
||||
documents: { id: string; category: string; file_name: string; status: 'active'|'quarantined' }[];
|
||||
events: { action: string; version: number; metadata: Record<string, unknown>; created_at: string }[];
|
||||
case: {
|
||||
id: string;
|
||||
reference: string;
|
||||
version: number;
|
||||
status: string;
|
||||
payload: Record<string, any>;
|
||||
updated_at: string;
|
||||
};
|
||||
documents: {
|
||||
id: string;
|
||||
category: string;
|
||||
file_name: string;
|
||||
status: 'active' | 'quarantined';
|
||||
}[];
|
||||
events: {
|
||||
action: string;
|
||||
version: number;
|
||||
metadata: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}[];
|
||||
disclaimer: string;
|
||||
management: boolean;
|
||||
};
|
||||
const statusLabels: Record<string,string> = { draft:'Rascunho privado', support_requested:'Apoio solicitado ao InvestMoz', internal_review:'Análise interna', waiting_applicant:'A aguardar informação do requerente', referral_prepared:'Encaminhamento preparado (não submetido)', closed:'Encerrado no InvestMoz' };
|
||||
const actionLabels: Record<string,string> = { draft_created:'Rascunho criado', draft_updated:'Rascunho actualizado', support_requested:'Pedido de apoio registado', status_changed:'Estado interno actualizado', attachment_added:'Documento anexado', applicant_update_recorded:'Actualização comunicada pelo requerente' };
|
||||
const categoryLabels: Record<string,string> = { sketch:'Planta/esboço', prior_right:'Antecedente de direito', exploration_plan:'Plano de exploração', official_receipt:'Recibo/comunicação oficial', consultation_minutes:'Acta/minuta', photo:'Fotografia', other:'Outro' };
|
||||
const statusLabels: Record<string, string> = {
|
||||
draft: 'Rascunho privado',
|
||||
support_requested: 'Apoio solicitado ao InvestMoz',
|
||||
internal_review: 'Análise interna',
|
||||
waiting_applicant: 'A aguardar informação do requerente',
|
||||
referral_prepared: 'Encaminhamento preparado (não submetido)',
|
||||
closed: 'Encerrado no InvestMoz',
|
||||
};
|
||||
const actionLabels: Record<string, string> = {
|
||||
draft_created: 'Rascunho criado',
|
||||
draft_updated: 'Rascunho actualizado',
|
||||
support_requested: 'Pedido de apoio registado',
|
||||
status_changed: 'Estado interno actualizado',
|
||||
attachment_added: 'Documento anexado',
|
||||
applicant_update_recorded: 'Actualização comunicada pelo requerente',
|
||||
};
|
||||
const categoryLabels: Record<string, string> = {
|
||||
sketch: 'Planta/esboço',
|
||||
prior_right: 'Antecedente de direito',
|
||||
exploration_plan: 'Plano de exploração',
|
||||
official_receipt: 'Recibo/comunicação oficial',
|
||||
consultation_minutes: 'Acta/minuta',
|
||||
photo: 'Fotografia',
|
||||
other: 'Outro',
|
||||
};
|
||||
|
||||
export default function LandCase({case: record, documents, events, disclaimer, management}:Props) {
|
||||
const [file,setFile]=useState<File|null>(null);
|
||||
const [category,setCategory]=useState('other');
|
||||
const [status,setStatus]=useState('internal_review');
|
||||
const upload=useForm({version:record.version,category,file:null as File|null});
|
||||
const report=useForm({version:record.version,reported_status:'',official_reference:'',receiving_entity:'',reported_at:''});
|
||||
const change=useForm({version:record.version,status:'internal_review',evidence_reference:''});
|
||||
const canEdit=['draft','waiting_applicant'].includes(record.status);
|
||||
const payload=record.payload??{};
|
||||
const supportKinds:Record<string,string>={investment:'Terra para investimento',home:'Habitação',family_exploitation:'Exploração familiar',recognition:'Reconhecimento/titulação',regularization:'Regularização cadastral',delimitation:'Delimitação/demarcação',change_of_use:'Alteração de uso/área',transfer:'Transmissão/herança',existing_process:'Processo existente',conflict_guidance:'Orientação sobre conflito/restrição',other:'Outro'};
|
||||
return <main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header className="space-y-2"><Link href="/investidor/terra-duat" className="underline">Os meus pedidos Terra e DUAT</Link><h1 className="text-3xl font-bold">Acompanhamento {record.reference}</h1><p>Referência interna InvestMoz · versão {record.version} · {statusLabels[record.status]??record.status}</p><p className="rounded border border-amber-400 bg-amber-50 p-3">{disclaimer}</p>{record.status==='referral_prepared'&&<p className="rounded bg-amber-50 p-3">O encaminhamento foi preparado internamente. Não há confirmação de submissão nem de recepção por entidade pública.</p>}</header>
|
||||
{!management&&canEdit&&<Link className="inline-block rounded border px-4 py-2" href={`/investidor/terra-duat/${record.id}/editar`}>Continuar preenchimento</Link>}
|
||||
{!management&&<Link className="ml-3 inline-block rounded border px-4 py-2" href={`/investidor/terra-duat/${record.id}/imprimir`}>Imprimir / guardar cópia preenchida como PDF</Link>}
|
||||
<section className="grid gap-4 rounded border p-4 sm:grid-cols-2"><h2 className="sm:col-span-2 text-xl font-semibold">Resumo informado pelo requerente</h2><p><strong>Tipo:</strong> {supportKinds[payload.support_kind]??'Por indicar'}</p><p><strong>Requerente:</strong> {payload.full_name??'Por indicar'}</p><p><strong>Categoria:</strong> {payload.applicant_category??'Por indicar'}</p><p><strong>Contacto preferido:</strong> {payload.preferred_contact??'Por indicar'}</p><p className="sm:col-span-2"><strong>Descrição:</strong> {payload.request_description??'Por indicar'}</p><p className="sm:col-span-2"><strong>Uso pretendido:</strong> {payload.purpose??'Por indicar'}</p><p className="sm:col-span-2"><strong>Localização declarada:</strong> {(payload.parcels??[]).map((parcel:any)=>parcel.place_description).filter(Boolean).join('; ')||'Por localizar/confirmar'}</p><p className="sm:col-span-2 text-sm">Dados e situação geográfica aqui exibidos são declarações do requerente; não confirmam direitos ou disponibilidade cadastral.</p></section>
|
||||
{!management&&<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Comunicar actualização</h2><p className="text-sm">A informação fica identificada como comunicada por si e não é confirmada automaticamente pelo InvestMoz.</p><label className="block space-y-1"><span>Actualização do estado *</span><textarea className="w-full rounded border p-2" value={report.data.reported_status} onChange={e=>report.setData('reported_status',e.target.value)} maxLength={1000}/></label><div className="grid gap-3 sm:grid-cols-3"><label>Referência oficial (se tiver)<input className="mt-1 w-full rounded border p-2" value={report.data.official_reference} onChange={e=>report.setData('official_reference',e.target.value)}/></label><label>Entidade indicada<input className="mt-1 w-full rounded border p-2" value={report.data.receiving_entity} onChange={e=>report.setData('receiving_entity',e.target.value)}/></label><label>Data indicada<input type="date" className="mt-1 w-full rounded border p-2" value={report.data.reported_at} onChange={e=>report.setData('reported_at',e.target.value)}/></label></div><button className="rounded border px-4 py-2" disabled={!report.data.reported_status||report.processing} onClick={()=>router.post(`/investidor/terra-duat/${record.id}/actualizacoes`,report.data,{preserveScroll:true})}>Registar informação comunicada</button></section>}
|
||||
<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Documentos anexados</h2>{documents.map((document)=><p key={document.id}>{document.status==='active'?<a className="underline" href={`/investidor/terra-duat/${record.id}/documentos/${document.id}`}>{categoryLabels[document.category]??document.category}: {document.file_name}</a>:<span>{categoryLabels[document.category]??document.category}: {document.file_name} · em quarentena; leitura/descarga bloqueada até verificação</span>}</p>)}{!documents.length&&<p>Nenhum documento anexado. Anexos são opcionais nesta fase.</p>}{!management&&record.status!=='closed'&&<div className="grid gap-3 sm:grid-cols-3"><label>Categoria<select className="mt-1 w-full rounded border p-2" value={category} onChange={e=>setCategory(e.target.value)}>{Object.entries(categoryLabels).map(([key,label])=><option value={key} key={key}>{label}</option>)}</select></label><label className="sm:col-span-2">Ficheiro PDF/JPG/PNG (até 10 MB)<input className="mt-1 w-full rounded border p-2" type="file" accept=".pdf,.jpg,.jpeg,.png" onChange={e=>setFile(e.target.files?.[0]??null)}/></label><button className="rounded border px-4 py-2" disabled={!file||upload.processing} onClick={()=>router.post(`/investidor/terra-duat/${record.id}/documentos`,{version:record.version,category,file},{forceFormData:true,preserveScroll:true})}>Anexar em espaço privado</button></div>}<p className="text-sm">Os ficheiros são reservados; anexar não equivale a verificação, validação cadastral ou parecer oficial. O ambiente não tem antivírus configurado, por isso os uploads ficam em quarentena e não podem ser descarregados até verificação.</p></section>
|
||||
<section className="space-y-3 rounded border p-4"><h2 className="text-xl font-semibold">Histórico no InvestMoz</h2>{events.map((event,index)=><div className="border-l-2 pl-3" key={`${event.version}-${index}`}><p className="font-medium">{actionLabels[event.action]??event.action}</p><p className="text-sm">{new Date(event.created_at).toLocaleString('pt-MZ')} · versão {event.version}</p>{event.action==='applicant_update_recorded'&&<p className="text-xs">Actualização comunicada pelo requerente; não verificada externamente.</p>}{event.action==='status_changed'&&event.metadata?.external_submission_confirmed===false&&<p className="text-xs">Transição de estado interno; submissão oficial não confirmada.</p>}</div>)}</section>
|
||||
{management&&<section className="space-y-3 rounded border border-slate-400 p-4"><h2 className="text-xl font-semibold">Gestão interna</h2><label className="block">Estado interno<select className="mt-1 w-full rounded border p-2" value={change.data.status} onChange={e=>change.setData('status',e.target.value)}><option value="internal_review">Análise interna</option><option value="waiting_applicant">A aguardar requerente</option><option value="referral_prepared">Encaminhamento preparado (não enviado)</option><option value="closed">Encerrado no InvestMoz</option></select></label>{change.data.status==='referral_prepared'&&<label className="block">Referência interna da preparação<input className="mt-1 w-full rounded border p-2" value={change.data.evidence_reference} onChange={e=>change.setData('evidence_reference',e.target.value)}/></label>}<button className="rounded bg-slate-800 px-4 py-2 text-white" disabled={change.processing} onClick={()=>router.patch(`/management/terra-duat/${record.id}/estado`,{...change.data,version:record.version},{preserveScroll:true})}>Actualizar estado interno</button></section>}
|
||||
</main>;
|
||||
export default function LandCase({
|
||||
case: record,
|
||||
documents,
|
||||
events,
|
||||
disclaimer,
|
||||
management,
|
||||
}: Props) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [category, setCategory] = useState('other');
|
||||
const [_status, _setStatus] = useState('internal_review');
|
||||
const upload = useForm({
|
||||
version: record.version,
|
||||
category,
|
||||
file: null as File | null,
|
||||
});
|
||||
const report = useForm({
|
||||
version: record.version,
|
||||
reported_status: '',
|
||||
official_reference: '',
|
||||
receiving_entity: '',
|
||||
reported_at: '',
|
||||
});
|
||||
const change = useForm({
|
||||
version: record.version,
|
||||
status: 'internal_review',
|
||||
evidence_reference: '',
|
||||
});
|
||||
const canEdit = ['draft', 'waiting_applicant'].includes(record.status);
|
||||
const payload = record.payload ?? {};
|
||||
const supportKinds: Record<string, string> = {
|
||||
investment: 'Terra para investimento',
|
||||
home: 'Habitação',
|
||||
family_exploitation: 'Exploração familiar',
|
||||
recognition: 'Reconhecimento/titulação',
|
||||
regularization: 'Regularização cadastral',
|
||||
delimitation: 'Delimitação/demarcação',
|
||||
change_of_use: 'Alteração de uso/área',
|
||||
transfer: 'Transmissão/herança',
|
||||
existing_process: 'Processo existente',
|
||||
conflict_guidance: 'Orientação sobre conflito/restrição',
|
||||
other: 'Outro',
|
||||
};
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header className="space-y-2">
|
||||
<Link href="/investidor/terra-duat" className="underline">
|
||||
Os meus pedidos Terra e DUAT
|
||||
</Link>
|
||||
<h1 className="text-3xl font-bold">
|
||||
Acompanhamento {record.reference}
|
||||
</h1>
|
||||
<p>
|
||||
Referência interna InvestMoz · versão {record.version} ·{' '}
|
||||
{statusLabels[record.status] ?? record.status}
|
||||
</p>
|
||||
<p className="rounded border border-amber-400 bg-amber-50 p-3">
|
||||
{disclaimer}
|
||||
</p>
|
||||
{record.status === 'referral_prepared' && (
|
||||
<p className="rounded bg-amber-50 p-3">
|
||||
O encaminhamento foi preparado internamente. Não há
|
||||
confirmação de submissão nem de recepção por entidade
|
||||
pública.
|
||||
</p>
|
||||
)}
|
||||
</header>
|
||||
{!management && canEdit && (
|
||||
<Link
|
||||
className="inline-block rounded border px-4 py-2"
|
||||
href={`/investidor/terra-duat/${record.id}/editar`}
|
||||
>
|
||||
Continuar preenchimento
|
||||
</Link>
|
||||
)}
|
||||
{!management && (
|
||||
<Link
|
||||
className="ml-3 inline-block rounded border px-4 py-2"
|
||||
href={`/investidor/terra-duat/${record.id}/imprimir`}
|
||||
>
|
||||
Imprimir / guardar cópia preenchida como PDF
|
||||
</Link>
|
||||
)}
|
||||
<section className="grid gap-4 rounded border p-4 sm:grid-cols-2">
|
||||
<h2 className="text-xl font-semibold sm:col-span-2">
|
||||
Resumo informado pelo requerente
|
||||
</h2>
|
||||
<p>
|
||||
<strong>Tipo:</strong>{' '}
|
||||
{supportKinds[payload.support_kind] ?? 'Por indicar'}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Requerente:</strong>{' '}
|
||||
{payload.full_name ?? 'Por indicar'}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Categoria:</strong>{' '}
|
||||
{payload.applicant_category ?? 'Por indicar'}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Contacto preferido:</strong>{' '}
|
||||
{payload.preferred_contact ?? 'Por indicar'}
|
||||
</p>
|
||||
<p className="sm:col-span-2">
|
||||
<strong>Descrição:</strong>{' '}
|
||||
{payload.request_description ?? 'Por indicar'}
|
||||
</p>
|
||||
<p className="sm:col-span-2">
|
||||
<strong>Uso pretendido:</strong>{' '}
|
||||
{payload.purpose ?? 'Por indicar'}
|
||||
</p>
|
||||
<p className="sm:col-span-2">
|
||||
<strong>Localização declarada:</strong>{' '}
|
||||
{(payload.parcels ?? [])
|
||||
.map((parcel: any) => parcel.place_description)
|
||||
.filter(Boolean)
|
||||
.join('; ') || 'Por localizar/confirmar'}
|
||||
</p>
|
||||
<p className="text-sm sm:col-span-2">
|
||||
Dados e situação geográfica aqui exibidos são declarações do
|
||||
requerente; não confirmam direitos ou disponibilidade
|
||||
cadastral.
|
||||
</p>
|
||||
</section>
|
||||
{!management && (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Comunicar actualização
|
||||
</h2>
|
||||
<p className="text-sm">
|
||||
A informação fica identificada como comunicada por si e
|
||||
não é confirmada automaticamente pelo InvestMoz.
|
||||
</p>
|
||||
<label className="block space-y-1">
|
||||
<span>Actualização do estado *</span>
|
||||
<textarea
|
||||
className="w-full rounded border p-2"
|
||||
value={report.data.reported_status}
|
||||
onChange={(e) =>
|
||||
report.setData(
|
||||
'reported_status',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</label>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<label>
|
||||
Referência oficial (se tiver)
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={report.data.official_reference}
|
||||
onChange={(e) =>
|
||||
report.setData(
|
||||
'official_reference',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Entidade indicada
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={report.data.receiving_entity}
|
||||
onChange={(e) =>
|
||||
report.setData(
|
||||
'receiving_entity',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Data indicada
|
||||
<input
|
||||
type="date"
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={report.data.reported_at}
|
||||
onChange={(e) =>
|
||||
report.setData(
|
||||
'reported_at',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
className="rounded border px-4 py-2"
|
||||
disabled={
|
||||
!report.data.reported_status || report.processing
|
||||
}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/investidor/terra-duat/${record.id}/actualizacoes`,
|
||||
report.data,
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
Registar informação comunicada
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">Documentos anexados</h2>
|
||||
{documents.map((document) => (
|
||||
<p key={document.id}>
|
||||
{document.status === 'active' ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/investidor/terra-duat/${record.id}/documentos/${document.id}`}
|
||||
>
|
||||
{categoryLabels[document.category] ??
|
||||
document.category}
|
||||
: {document.file_name}
|
||||
</a>
|
||||
) : (
|
||||
<span>
|
||||
{categoryLabels[document.category] ??
|
||||
document.category}
|
||||
: {document.file_name} · em quarentena;
|
||||
leitura/descarga bloqueada até verificação
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{!documents.length && (
|
||||
<p>
|
||||
Nenhum documento anexado. Anexos são opcionais nesta
|
||||
fase.
|
||||
</p>
|
||||
)}
|
||||
{!management && record.status !== 'closed' && (
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<label>
|
||||
Categoria
|
||||
<select
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value)}
|
||||
>
|
||||
{Object.entries(categoryLabels).map(
|
||||
([key, label]) => (
|
||||
<option value={key} key={key}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="sm:col-span-2">
|
||||
Ficheiro PDF/JPG/PNG (até 10 MB)
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
type="file"
|
||||
accept=".pdf,.jpg,.jpeg,.png"
|
||||
onChange={(e) =>
|
||||
setFile(e.target.files?.[0] ?? null)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className="rounded border px-4 py-2"
|
||||
disabled={!file || upload.processing}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/investidor/terra-duat/${record.id}/documentos`,
|
||||
{ version: record.version, category, file },
|
||||
{
|
||||
forceFormData: true,
|
||||
preserveScroll: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Anexar em espaço privado
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Os ficheiros são reservados; anexar não equivale a
|
||||
verificação, validação cadastral ou parecer oficial. O
|
||||
ambiente não tem antivírus configurado, por isso os uploads
|
||||
ficam em quarentena e não podem ser descarregados até
|
||||
verificação.
|
||||
</p>
|
||||
</section>
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Histórico no InvestMoz
|
||||
</h2>
|
||||
{events.map((event, index) => (
|
||||
<div
|
||||
className="border-l-2 pl-3"
|
||||
key={`${event.version}-${index}`}
|
||||
>
|
||||
<p className="font-medium">
|
||||
{actionLabels[event.action] ?? event.action}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{new Date(event.created_at).toLocaleString('pt-MZ')}{' '}
|
||||
· versão {event.version}
|
||||
</p>
|
||||
{event.action === 'applicant_update_recorded' && (
|
||||
<p className="text-xs">
|
||||
Actualização comunicada pelo requerente; não
|
||||
verificada externamente.
|
||||
</p>
|
||||
)}
|
||||
{event.action === 'status_changed' &&
|
||||
event.metadata?.external_submission_confirmed ===
|
||||
false && (
|
||||
<p className="text-xs">
|
||||
Transição de estado interno; submissão
|
||||
oficial não confirmada.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
{management && (
|
||||
<section className="space-y-3 rounded border border-slate-400 p-4">
|
||||
<h2 className="text-xl font-semibold">Gestão interna</h2>
|
||||
<label className="block">
|
||||
Estado interno
|
||||
<select
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={change.data.status}
|
||||
onChange={(e) =>
|
||||
change.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="internal_review">
|
||||
Análise interna
|
||||
</option>
|
||||
<option value="waiting_applicant">
|
||||
A aguardar requerente
|
||||
</option>
|
||||
<option value="referral_prepared">
|
||||
Encaminhamento preparado (não enviado)
|
||||
</option>
|
||||
<option value="closed">
|
||||
Encerrado no InvestMoz
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{change.data.status === 'referral_prepared' && (
|
||||
<label className="block">
|
||||
Referência interna da preparação
|
||||
<input
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
value={change.data.evidence_reference}
|
||||
onChange={(e) =>
|
||||
change.setData(
|
||||
'evidence_reference',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
className="rounded bg-slate-800 px-4 py-2 text-white"
|
||||
disabled={change.processing}
|
||||
onClick={() =>
|
||||
router.patch(
|
||||
`/management/terra-duat/${record.id}/estado`,
|
||||
{ ...change.data, version: record.version },
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
Actualizar estado interno
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,24 +1,78 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
|
||||
export default function Guide({ disclaimer }: { disclaimer: string }) {
|
||||
return <main className="mx-auto max-w-5xl space-y-8 p-6 print:p-0">
|
||||
<header className="space-y-3">
|
||||
<p className="text-sm font-semibold uppercase tracking-wide">InvestMoz · orientação informativa</p>
|
||||
<h1 className="text-3xl font-bold">Terra e DUAT</h1>
|
||||
<p>Prepare informação sobre uma área, um pedido ou um processo que já acompanha. Pode indicar dúvidas e dados por confirmar.</p>
|
||||
<p className="rounded border border-amber-400 bg-amber-50 p-4 text-sm">{disclaimer}</p>
|
||||
</header>
|
||||
<section className="grid gap-4 md:grid-cols-3">
|
||||
<article className="rounded border p-4"><h2 className="font-semibold">Preparar informação</h2><p>Identifique a finalidade, o requerente, a localização conhecida e os antecedentes que tiver.</p></article>
|
||||
<article className="rounded border p-4"><h2 className="font-semibold">Organizar documentos</h2><p>Anexos são opcionais nesta fase. A lista não substitui os requisitos confirmados pela entidade competente.</p></article>
|
||||
<article className="rounded border p-4"><h2 className="font-semibold">Acompanhar</h2><p>Guarde uma referência interna e registe separadamente informações comunicadas por si e diligências internas.</p></article>
|
||||
</section>
|
||||
<p className="rounded bg-slate-50 p-4">Não inferimos que uma área está livre, que não existem direitos ou conflitos, nem que um registo ou mapa confirma titularidade. O InvestMoz não atribui DUAT nem substitui a autoridade pública.</p>
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link className="rounded bg-emerald-800 px-4 py-3 text-white" href="/investidor/terra-duat/novo">Preencher no portal</Link>
|
||||
<Link className="rounded border px-4 py-3" href="/terra-duat/formulario-em-branco">Descarregar formulário em branco (imprimir/guardar como PDF)</Link>
|
||||
<Link className="rounded border px-4 py-3" href="/apoio">Solicitar apoio geral</Link>
|
||||
</nav>
|
||||
<details className="rounded border p-4"><summary className="cursor-pointer font-semibold">Estado das fontes e requisitos</summary><p className="mt-3">Os modelos digitalizados estão inventariados como referências reservadas. Conteúdo, actualidade e requisitos legais aguardam OCR, conferência oficial e revisão. Não use esta orientação como checklist oficial.</p></details>
|
||||
</main>;
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-8 p-6 print:p-0">
|
||||
<header className="space-y-3">
|
||||
<p className="text-sm font-semibold tracking-wide uppercase">
|
||||
InvestMoz · orientação informativa
|
||||
</p>
|
||||
<h1 className="text-3xl font-bold">Terra e DUAT</h1>
|
||||
<p>
|
||||
Prepare informação sobre uma área, um pedido ou um processo
|
||||
que já acompanha. Pode indicar dúvidas e dados por
|
||||
confirmar.
|
||||
</p>
|
||||
<p className="rounded border border-amber-400 bg-amber-50 p-4 text-sm">
|
||||
{disclaimer}
|
||||
</p>
|
||||
</header>
|
||||
<section className="grid gap-4 md:grid-cols-3">
|
||||
<article className="rounded border p-4">
|
||||
<h2 className="font-semibold">Preparar informação</h2>
|
||||
<p>
|
||||
Identifique a finalidade, o requerente, a localização
|
||||
conhecida e os antecedentes que tiver.
|
||||
</p>
|
||||
</article>
|
||||
<article className="rounded border p-4">
|
||||
<h2 className="font-semibold">Organizar documentos</h2>
|
||||
<p>
|
||||
Anexos são opcionais nesta fase. A lista não substitui
|
||||
os requisitos confirmados pela entidade competente.
|
||||
</p>
|
||||
</article>
|
||||
<article className="rounded border p-4">
|
||||
<h2 className="font-semibold">Acompanhar</h2>
|
||||
<p>
|
||||
Guarde uma referência interna e registe separadamente
|
||||
informações comunicadas por si e diligências internas.
|
||||
</p>
|
||||
</article>
|
||||
</section>
|
||||
<p className="rounded bg-slate-50 p-4">
|
||||
Não inferimos que uma área está livre, que não existem direitos
|
||||
ou conflitos, nem que um registo ou mapa confirma titularidade.
|
||||
O InvestMoz não atribui DUAT nem substitui a autoridade pública.
|
||||
</p>
|
||||
<nav className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
className="rounded bg-emerald-800 px-4 py-3 text-white"
|
||||
href="/investidor/terra-duat/novo"
|
||||
>
|
||||
Preencher no portal
|
||||
</Link>
|
||||
<Link
|
||||
className="rounded border px-4 py-3"
|
||||
href="/terra-duat/formulario-em-branco"
|
||||
>
|
||||
Descarregar formulário em branco (imprimir/guardar como PDF)
|
||||
</Link>
|
||||
<Link className="rounded border px-4 py-3" href="/apoio">
|
||||
Solicitar apoio geral
|
||||
</Link>
|
||||
</nav>
|
||||
<details className="rounded border p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Estado das fontes e requisitos
|
||||
</summary>
|
||||
<p className="mt-3">
|
||||
Os modelos digitalizados estão inventariados como
|
||||
referências reservadas. Conteúdo, actualidade e requisitos
|
||||
legais aguardam OCR, conferência oficial e revisão. Não use
|
||||
esta orientação como checklist oficial.
|
||||
</p>
|
||||
</details>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,87 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
type Row={id:string;reference:string;status:string;version:number;applicant:string|null;updated_at:string};
|
||||
const labels:Record<string,string>={draft:'Rascunho',support_requested:'Apoio solicitado',internal_review:'Análise interna',waiting_applicant:'A aguardar requerente',referral_prepared:'Encaminhamento preparado (não enviado)',closed:'Encerrado'};
|
||||
export default function Management({cases}:{cases:{data:Row[];prev_page_url:string|null;next_page_url:string|null}}){return <main className="mx-auto max-w-6xl space-y-6 p-6"><header><h1 className="text-3xl font-bold">Gestão — Terra e DUAT</h1><p>Fila interna. Não representa protocolo com autoridade pública.</p></header><div className="overflow-x-auto"><table className="w-full border-collapse text-left"><thead><tr><th className="border p-2">Referência interna</th><th className="border p-2">Requerente</th><th className="border p-2">Estado InvestMoz</th><th className="border p-2">Versão/actualização</th><th className="border p-2">Acção</th></tr></thead><tbody>{cases.data.map(row=><tr key={row.id}><td className="border p-2">{row.reference}</td><td className="border p-2">{row.applicant??'—'}</td><td className="border p-2">{labels[row.status]??row.status}</td><td className="border p-2">{row.version} · {new Date(row.updated_at).toLocaleString('pt-MZ')}</td><td className="border p-2"><Link className="underline" href={`/management/terra-duat/${row.id}`}>Abrir</Link></td></tr>)}</tbody></table></div>{!cases.data.length&&<p>Sem pedidos registados.</p>}<nav className="flex gap-4">{cases.prev_page_url&&<Link href={cases.prev_page_url}>Anterior</Link>}{cases.next_page_url&&<Link href={cases.next_page_url}>Seguinte</Link>}</nav></main>;}
|
||||
type Row = {
|
||||
id: string;
|
||||
reference: string;
|
||||
status: string;
|
||||
version: number;
|
||||
applicant: string | null;
|
||||
updated_at: string;
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
draft: 'Rascunho',
|
||||
support_requested: 'Apoio solicitado',
|
||||
internal_review: 'Análise interna',
|
||||
waiting_applicant: 'A aguardar requerente',
|
||||
referral_prepared: 'Encaminhamento preparado (não enviado)',
|
||||
closed: 'Encerrado',
|
||||
};
|
||||
export default function Management({
|
||||
cases,
|
||||
}: {
|
||||
cases: {
|
||||
data: Row[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
}) {
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl space-y-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-3xl font-bold">Gestão — Terra e DUAT</h1>
|
||||
<p>
|
||||
Fila interna. Não representa protocolo com autoridade
|
||||
pública.
|
||||
</p>
|
||||
</header>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="border p-2">Referência interna</th>
|
||||
<th className="border p-2">Requerente</th>
|
||||
<th className="border p-2">Estado InvestMoz</th>
|
||||
<th className="border p-2">Versão/actualização</th>
|
||||
<th className="border p-2">Acção</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{cases.data.map((row) => (
|
||||
<tr key={row.id}>
|
||||
<td className="border p-2">{row.reference}</td>
|
||||
<td className="border p-2">
|
||||
{row.applicant ?? '—'}
|
||||
</td>
|
||||
<td className="border p-2">
|
||||
{labels[row.status] ?? row.status}
|
||||
</td>
|
||||
<td className="border p-2">
|
||||
{row.version} ·{' '}
|
||||
{new Date(row.updated_at).toLocaleString(
|
||||
'pt-MZ',
|
||||
)}
|
||||
</td>
|
||||
<td className="border p-2">
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/terra-duat/${row.id}`}
|
||||
>
|
||||
Abrir
|
||||
</Link>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!cases.data.length && <p>Sem pedidos registados.</p>}
|
||||
<nav className="flex gap-4">
|
||||
{cases.prev_page_url && (
|
||||
<Link href={cases.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{cases.next_page_url && (
|
||||
<Link href={cases.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,4 +1,81 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
type CaseRow={id:string;reference:string;status:string;version:number;updated_at:string};
|
||||
const labels:Record<string,string>={draft:'Rascunho privado',support_requested:'Apoio solicitado ao InvestMoz',internal_review:'Análise interna',waiting_applicant:'A aguardar informação',referral_prepared:'Encaminhamento preparado (não enviado)',closed:'Encerrado no InvestMoz'};
|
||||
export default function Workspace({cases}:{cases:{data:CaseRow[];prev_page_url:string|null;next_page_url:string|null}}){return <main className="mx-auto max-w-5xl space-y-6 p-6"><header><h1 className="text-3xl font-bold">Os meus pedidos — Terra e DUAT</h1><p>As referências e estados são internos do InvestMoz.</p></header><Link className="inline-block rounded bg-emerald-800 px-4 py-3 text-white" href="/terra-duat">Orientação Terra e DUAT</Link> <Link className="ml-2 inline-block rounded border px-4 py-3" href="/investidor/terra-duat/novo">Preparar novo pedido</Link><section className="space-y-3">{cases.data.map((record)=><article key={record.id} className="rounded border p-4"><Link href={`/investidor/terra-duat/${record.id}`} className="font-semibold underline">{record.reference}</Link><p>{labels[record.status]??record.status} · versão {record.version}</p><p className="text-sm">Actualizado {new Date(record.updated_at).toLocaleString('pt-MZ')}</p></article>)}{!cases.data.length&&<p>Ainda não tem rascunhos ou pedidos de apoio.</p>}</section><nav className="flex gap-4">{cases.prev_page_url&&<Link href={cases.prev_page_url}>Anterior</Link>}{cases.next_page_url&&<Link href={cases.next_page_url}>Seguinte</Link>}</nav></main>;}
|
||||
type CaseRow = {
|
||||
id: string;
|
||||
reference: string;
|
||||
status: string;
|
||||
version: number;
|
||||
updated_at: string;
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
draft: 'Rascunho privado',
|
||||
support_requested: 'Apoio solicitado ao InvestMoz',
|
||||
internal_review: 'Análise interna',
|
||||
waiting_applicant: 'A aguardar informação',
|
||||
referral_prepared: 'Encaminhamento preparado (não enviado)',
|
||||
closed: 'Encerrado no InvestMoz',
|
||||
};
|
||||
export default function Workspace({
|
||||
cases,
|
||||
}: {
|
||||
cases: {
|
||||
data: CaseRow[];
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
}) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-3xl font-bold">
|
||||
Os meus pedidos — Terra e DUAT
|
||||
</h1>
|
||||
<p>As referências e estados são internos do InvestMoz.</p>
|
||||
</header>
|
||||
<Link
|
||||
className="inline-block rounded bg-emerald-800 px-4 py-3 text-white"
|
||||
href="/terra-duat"
|
||||
>
|
||||
Orientação Terra e DUAT
|
||||
</Link>{' '}
|
||||
<Link
|
||||
className="ml-2 inline-block rounded border px-4 py-3"
|
||||
href="/investidor/terra-duat/novo"
|
||||
>
|
||||
Preparar novo pedido
|
||||
</Link>
|
||||
<section className="space-y-3">
|
||||
{cases.data.map((record) => (
|
||||
<article key={record.id} className="rounded border p-4">
|
||||
<Link
|
||||
href={`/investidor/terra-duat/${record.id}`}
|
||||
className="font-semibold underline"
|
||||
>
|
||||
{record.reference}
|
||||
</Link>
|
||||
<p>
|
||||
{labels[record.status] ?? record.status} · versão{' '}
|
||||
{record.version}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Actualizado{' '}
|
||||
{new Date(record.updated_at).toLocaleString(
|
||||
'pt-MZ',
|
||||
)}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{!cases.data.length && (
|
||||
<p>Ainda não tem rascunhos ou pedidos de apoio.</p>
|
||||
)}
|
||||
</section>
|
||||
<nav className="flex gap-4">
|
||||
{cases.prev_page_url && (
|
||||
<Link href={cases.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{cases.next_page_url && (
|
||||
<Link href={cases.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,12 @@ type Record = {
|
||||
is_active?: boolean;
|
||||
status?: string;
|
||||
geography_scope?: string;
|
||||
primary_territory?: { name: string; location_type: string; source_system?: string; source_code?: string | null } | null;
|
||||
primary_territory?: {
|
||||
name: string;
|
||||
location_type: string;
|
||||
source_system?: string;
|
||||
source_code?: string | null;
|
||||
} | null;
|
||||
};
|
||||
export default function Catalog({
|
||||
resource,
|
||||
@@ -22,7 +27,12 @@ export default function Catalog({
|
||||
}: {
|
||||
resource: 'sectors' | 'opportunities';
|
||||
records: Paginated<Record>;
|
||||
filters: { q?: string; status?: string; sector_id?: number | string; geography_scope?: string };
|
||||
filters: {
|
||||
q?: string;
|
||||
status?: string;
|
||||
sector_id?: number | string;
|
||||
geography_scope?: string;
|
||||
};
|
||||
sectors: { id: number; name: string }[];
|
||||
geographyReviewCount?: number;
|
||||
}) {
|
||||
@@ -41,7 +51,9 @@ export default function Catalog({
|
||||
</Link>
|
||||
{resource === 'opportunities' && (
|
||||
<p role="status" className="my-3">
|
||||
{geographyReviewCount} oportunidade(s) aguardam confirmação do âmbito geográfico. A lista não altera localizações; confirme apenas com fontes existentes.
|
||||
{geographyReviewCount} oportunidade(s) aguardam confirmação
|
||||
do âmbito geográfico. A lista não altera localizações;
|
||||
confirme apenas com fontes existentes.
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
@@ -85,34 +97,47 @@ export default function Catalog({
|
||||
</select>
|
||||
{resource === 'opportunities' && (
|
||||
<>
|
||||
<select
|
||||
aria-label="Sector"
|
||||
className={`${control} max-w-xs`}
|
||||
value={form.data.sector_id}
|
||||
onChange={(event) =>
|
||||
form.setData('sector_id', event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos os sectores</option>
|
||||
{sectors.map((sector) => (
|
||||
<option key={sector.id} value={sector.id}>
|
||||
{sector.name}
|
||||
<select
|
||||
aria-label="Sector"
|
||||
className={`${control} max-w-xs`}
|
||||
value={form.data.sector_id}
|
||||
onChange={(event) =>
|
||||
form.setData('sector_id', event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos os sectores</option>
|
||||
{sectors.map((sector) => (
|
||||
<option key={sector.id} value={sector.id}>
|
||||
{sector.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Âmbito geográfico"
|
||||
className={`${control} max-w-xs`}
|
||||
value={form.data.geography_scope}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'geography_scope',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Todos os âmbitos</option>
|
||||
<option value="unspecified">
|
||||
Pendente de confirmação
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Âmbito geográfico"
|
||||
className={`${control} max-w-xs`}
|
||||
value={form.data.geography_scope}
|
||||
onChange={(event) => form.setData('geography_scope', event.target.value)}
|
||||
>
|
||||
<option value="">Todos os âmbitos</option>
|
||||
<option value="unspecified">Pendente de confirmação</option>
|
||||
<option value="specific">Localização específica</option>
|
||||
<option value="multiple">Várias localizações</option>
|
||||
<option value="national">Âmbito nacional</option>
|
||||
<option value="digital">Digital/sem instalação definida</option>
|
||||
</select>
|
||||
<option value="specific">
|
||||
Localização específica
|
||||
</option>
|
||||
<option value="multiple">
|
||||
Várias localizações
|
||||
</option>
|
||||
<option value="national">Âmbito nacional</option>
|
||||
<option value="digital">
|
||||
Digital/sem instalação definida
|
||||
</option>
|
||||
</select>
|
||||
</>
|
||||
)}
|
||||
<button className={button} disabled={form.processing}>
|
||||
@@ -148,11 +173,23 @@ export default function Catalog({
|
||||
: 'Inactivo'
|
||||
: states[record.status ?? 'draft']}
|
||||
</p>
|
||||
{resource === 'opportunities' && record.geography_scope === 'unspecified' && (
|
||||
<p className="mt-1 text-sm">
|
||||
Pendente de confirmação; território já registado: {record.primary_territory?.name ?? 'nenhum'}. Fonte do território: {record.primary_territory?.source_system ?? 'não indicada'}{record.primary_territory?.source_code ? `, código ${record.primary_territory.source_code}` : ''}. A classificação não é alterada automaticamente.
|
||||
</p>
|
||||
)}
|
||||
{resource === 'opportunities' &&
|
||||
record.geography_scope === 'unspecified' && (
|
||||
<p className="mt-1 text-sm">
|
||||
Pendente de confirmação; território já
|
||||
registado:{' '}
|
||||
{record.primary_territory?.name ??
|
||||
'nenhum'}
|
||||
. Fonte do território:{' '}
|
||||
{record.primary_territory
|
||||
?.source_system ?? 'não indicada'}
|
||||
{record.primary_territory?.source_code
|
||||
? `, código ${record.primary_territory.source_code}`
|
||||
: ''}
|
||||
. A classificação não é alterada
|
||||
automaticamente.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
className="underline"
|
||||
|
||||
@@ -1,38 +1,41 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import InvestmentCoordinates from "@/components/investment-coordinates";
|
||||
import { TerritoryLevel, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, button, control, states } from "./shared";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import InvestmentCoordinates from '@/components/investment-coordinates';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { useState } from 'react';
|
||||
import { Management, Field, button, control, states } from './shared';
|
||||
|
||||
type Values = Record<string, string | boolean>;
|
||||
type Entry = Record<string, string | number | boolean | null> & { id: number };
|
||||
const opportunityFields = {
|
||||
reference: "Referência",
|
||||
title: "Título",
|
||||
slug: "Slug (endereço)",
|
||||
summary: "Resumo",
|
||||
description: "Descrição",
|
||||
promoter_name: "Promotor",
|
||||
promoter_type: "Tipo de promotor",
|
||||
estimated_investment_amount: "Investimento estimado",
|
||||
estimated_investment_currency: "Moeda (código de três letras)",
|
||||
financing_modality: "Modalidade de financiamento",
|
||||
expected_impact: "Impacto esperado",
|
||||
reference: 'Referência',
|
||||
title: 'Título',
|
||||
slug: 'Slug (endereço)',
|
||||
summary: 'Resumo',
|
||||
description: 'Descrição',
|
||||
promoter_name: 'Promotor',
|
||||
promoter_type: 'Tipo de promotor',
|
||||
estimated_investment_amount: 'Investimento estimado',
|
||||
estimated_investment_currency: 'Moeda (código de três letras)',
|
||||
financing_modality: 'Modalidade de financiamento',
|
||||
expected_impact: 'Impacto esperado',
|
||||
};
|
||||
const sectorFields = {
|
||||
name: "Nome",
|
||||
slug: "Slug (endereço)",
|
||||
short_description: "Descrição curta",
|
||||
description: "Descrição",
|
||||
sort_order: "Ordem de apresentação",
|
||||
name: 'Nome',
|
||||
slug: 'Slug (endereço)',
|
||||
short_description: 'Descrição curta',
|
||||
description: 'Descrição',
|
||||
sort_order: 'Ordem de apresentação',
|
||||
};
|
||||
const maturities = [
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
'Ideia identificada',
|
||||
'Pré-estudo disponível',
|
||||
'Estudo de viabilidade em curso',
|
||||
'Projecto estruturado',
|
||||
'Pronto para investimento',
|
||||
'Em negociação ou implementação',
|
||||
];
|
||||
|
||||
export default function Editor({
|
||||
@@ -41,54 +44,64 @@ export default function Editor({
|
||||
sectors,
|
||||
territoryPath = [],
|
||||
}: {
|
||||
resource: "sectors" | "opportunities";
|
||||
resource: 'sectors' | 'opportunities';
|
||||
record: Entry | null;
|
||||
sectors: { id: number; name: string }[];
|
||||
territoryPath?: TerritoryOption[];
|
||||
}) {
|
||||
const isSector = resource === "sectors";
|
||||
const isSector = resource === 'sectors';
|
||||
const fields = isSector ? sectorFields : opportunityFields;
|
||||
const initial: Values = Object.fromEntries(
|
||||
Object.keys(fields).map((key) => [
|
||||
key,
|
||||
String(
|
||||
record?.[key] ??
|
||||
(key === "estimated_investment_currency"
|
||||
? "USD"
|
||||
: key === "sort_order"
|
||||
? "0"
|
||||
: ""),
|
||||
(key === 'estimated_investment_currency'
|
||||
? 'USD'
|
||||
: key === 'sort_order'
|
||||
? '0'
|
||||
: ''),
|
||||
),
|
||||
]),
|
||||
);
|
||||
if (isSector) initial.is_active = Boolean(record?.is_active ?? true);
|
||||
else {
|
||||
initial.sector_id = String(record?.sector_id ?? "");
|
||||
initial.maturity_level = String(record?.maturity_level ?? "");
|
||||
initial.status = String(record?.status ?? "draft");
|
||||
initial.sector_id = String(record?.sector_id ?? '');
|
||||
initial.maturity_level = String(record?.maturity_level ?? '');
|
||||
initial.status = String(record?.status ?? 'draft');
|
||||
initial.is_featured = Boolean(record?.is_featured ?? false);
|
||||
initial.geography_scope = String(record?.geography_scope ?? "unspecified");
|
||||
initial.geography_scope = String(
|
||||
record?.geography_scope ?? 'unspecified',
|
||||
);
|
||||
initial.territory_version = String(record?.territory_version ?? 0);
|
||||
["province_id", "district_id", "admin_post_id", "locality_id"].forEach((field, index) => {
|
||||
initial[field] = territoryPath[index]?.id ?? "";
|
||||
});
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].forEach(
|
||||
(field, index) => {
|
||||
initial[field] = territoryPath[index]?.id ?? '';
|
||||
},
|
||||
);
|
||||
}
|
||||
const form = useForm<Values>(initial);
|
||||
const [creationPath, setCreationPath] = useState<TerritoryOption[]>(territoryPath);
|
||||
const [creationPath, setCreationPath] =
|
||||
useState<TerritoryOption[]>(territoryPath);
|
||||
return (
|
||||
<Management
|
||||
title={`${record ? "Editar" : "Criar"} ${isSector ? "sector" : "oportunidade"}`}
|
||||
title={`${record ? 'Editar' : 'Criar'} ${isSector ? 'sector' : 'oportunidade'}`}
|
||||
>
|
||||
{!isSector && record && (
|
||||
<Link className="underline" href={`/management/opportunities/${record.id}/context`}>
|
||||
Gerir clusters, corredores, projectos, educação e necessidades
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/opportunities/${record.id}/context`}
|
||||
>
|
||||
Gerir clusters, corredores, projectos, educação e
|
||||
necessidades
|
||||
</Link>
|
||||
)}
|
||||
<form
|
||||
className="max-w-3xl space-y-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (record) form.put(`/management/${resource}/${record.id}`);
|
||||
if (record)
|
||||
form.put(`/management/${resource}/${record.id}`);
|
||||
else form.post(`/management/${resource}`);
|
||||
}}
|
||||
>
|
||||
@@ -97,16 +110,16 @@ export default function Editor({
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(
|
||||
[
|
||||
"province_id",
|
||||
"district_id",
|
||||
"admin_post_id",
|
||||
"locality_id",
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${creationPath[index - 1]?.id ?? ""}`}
|
||||
key={`${key}-${creationPath[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={creationPath[index - 1]?.id ?? ""}
|
||||
parent={creationPath[index - 1]?.id ?? ''}
|
||||
selected={creationPath[index]}
|
||||
endpoint="/management/territory-options"
|
||||
fieldError={form.errors[key]}
|
||||
@@ -118,10 +131,10 @@ export default function Editor({
|
||||
setCreationPath(path);
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
province_id: path[0]?.id ?? "",
|
||||
district_id: path[1]?.id ?? "",
|
||||
admin_post_id: path[2]?.id ?? "",
|
||||
locality_id: path[3]?.id ?? "",
|
||||
province_id: path[0]?.id ?? '',
|
||||
district_id: path[1]?.id ?? '',
|
||||
admin_post_id: path[2]?.id ?? '',
|
||||
locality_id: path[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
@@ -131,22 +144,26 @@ export default function Editor({
|
||||
{Object.entries(fields).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={form.errors[key]}>
|
||||
{[
|
||||
"description",
|
||||
"summary",
|
||||
"short_description",
|
||||
"expected_impact",
|
||||
'description',
|
||||
'summary',
|
||||
'short_description',
|
||||
'expected_impact',
|
||||
].includes(key) ? (
|
||||
<textarea
|
||||
className={control}
|
||||
rows={key === "description" ? 6 : 3}
|
||||
rows={key === 'description' ? 6 : 3}
|
||||
value={String(form.data[key])}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(form.data[key])}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
@@ -157,21 +174,37 @@ export default function Editor({
|
||||
<select
|
||||
className={control}
|
||||
value={String(form.data.sector_id)}
|
||||
onChange={(e) => form.setData("sector_id", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'sector_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{sectors.map((sector) => (
|
||||
<option key={sector.id} value={sector.id}>
|
||||
<option
|
||||
key={sector.id}
|
||||
value={sector.id}
|
||||
>
|
||||
{sector.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Maturidade" error={form.errors.maturity_level}>
|
||||
<Field
|
||||
label="Maturidade"
|
||||
error={form.errors.maturity_level}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(form.data.maturity_level)}
|
||||
onChange={(e) => form.setData("maturity_level", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'maturity_level',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{maturities.map((label, index) => (
|
||||
@@ -181,47 +214,86 @@ export default function Editor({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Âmbito geográfico" error={form.errors.geography_scope}>
|
||||
<select className={control} value={String(form.data.geography_scope)} onChange={(e) => {
|
||||
form.setData("geography_scope", e.target.value);
|
||||
if (e.target.value === "national" || e.target.value === "digital") {
|
||||
setCreationPath([]);
|
||||
form.setData((data) => ({ ...data, geography_scope: e.target.value,
|
||||
province_id: "", district_id: "", admin_post_id: "", locality_id: "" }));
|
||||
}
|
||||
}}>
|
||||
<option value="unspecified">Não especificado</option>
|
||||
<option value="specific">Localização específica</option>
|
||||
<option value="multiple">Várias localizações</option>
|
||||
<option value="national">Âmbito nacional</option>
|
||||
<option value="digital">Digital/sem instalação definida</option>
|
||||
<Field
|
||||
label="Âmbito geográfico"
|
||||
error={form.errors.geography_scope}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(form.data.geography_scope)}
|
||||
onChange={(e) => {
|
||||
form.setData(
|
||||
'geography_scope',
|
||||
e.target.value,
|
||||
);
|
||||
if (
|
||||
e.target.value === 'national' ||
|
||||
e.target.value === 'digital'
|
||||
) {
|
||||
setCreationPath([]);
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
geography_scope: e.target.value,
|
||||
province_id: '',
|
||||
district_id: '',
|
||||
admin_post_id: '',
|
||||
locality_id: '',
|
||||
}));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="unspecified">
|
||||
Não especificado
|
||||
</option>
|
||||
<option value="specific">
|
||||
Localização específica
|
||||
</option>
|
||||
<option value="multiple">
|
||||
Várias localizações
|
||||
</option>
|
||||
<option value="national">
|
||||
Âmbito nacional
|
||||
</option>
|
||||
<option value="digital">
|
||||
Digital/sem instalação definida
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado" error={form.errors.status}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(form.data.status)}
|
||||
onChange={(e) => form.setData("status", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
{["draft", "published", "archived"].map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{states[key]}
|
||||
</option>
|
||||
))}
|
||||
{['draft', 'published', 'archived'].map(
|
||||
(key) => (
|
||||
<option key={key} value={key}>
|
||||
{states[key]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
<Field
|
||||
label={isSector ? "Activo" : "Em destaque"}
|
||||
error={form.errors[isSector ? "is_active" : "is_featured"]}
|
||||
label={isSector ? 'Activo' : 'Em destaque'}
|
||||
error={
|
||||
form.errors[isSector ? 'is_active' : 'is_featured']
|
||||
}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(form.data[isSector ? "is_active" : "is_featured"])}
|
||||
checked={Boolean(
|
||||
form.data[
|
||||
isSector ? 'is_active' : 'is_featured'
|
||||
],
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
isSector ? "is_active" : "is_featured",
|
||||
isSector ? 'is_active' : 'is_featured',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
@@ -229,9 +301,12 @@ export default function Editor({
|
||||
</Field>
|
||||
<div className="flex gap-4">
|
||||
<button className={button} disabled={form.processing}>
|
||||
{form.processing ? "A guardar…" : "Guardar"}
|
||||
{form.processing ? 'A guardar…' : 'Guardar'}
|
||||
</button>
|
||||
<Link className="p-2 underline" href={`/management/${resource}`}>
|
||||
<Link
|
||||
className="p-2 underline"
|
||||
href={`/management/${resource}`}
|
||||
>
|
||||
Cancelar
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Management, Field, button, control, states } from "./shared";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Management, Field, button, control, states } from './shared';
|
||||
|
||||
type Interest = {
|
||||
id: number;
|
||||
@@ -32,36 +32,64 @@ type Interest = {
|
||||
};
|
||||
};
|
||||
function dateTime(value: string | null) {
|
||||
if (!value) return "—";
|
||||
return new Intl.DateTimeFormat("pt-MZ", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
timeZone: "Africa/Maputo",
|
||||
if (!value) return '—';
|
||||
return new Intl.DateTimeFormat('pt-MZ', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
timeZone: 'Africa/Maputo',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
type Transition = { from_status: string | null; to_status: string; actor_id: number | null; note: string | null; created_at: string };
|
||||
type Transition = {
|
||||
from_status: string | null;
|
||||
to_status: string;
|
||||
actor_id: number | null;
|
||||
note: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
type Assignee = { id: number; name: string };
|
||||
type Consent = { purpose: string; policy_version: string | null; status: string; granted_at: string | null; withdrawn_at: string | null };
|
||||
type Consent = {
|
||||
purpose: string;
|
||||
policy_version: string | null;
|
||||
status: string;
|
||||
granted_at: string | null;
|
||||
withdrawn_at: string | null;
|
||||
};
|
||||
|
||||
export default function InterestDetail({ interest, history = [], assignees = [], consents = [] }: { interest: Interest; history?: Transition[]; assignees?: Assignee[]; consents?: Consent[] }) {
|
||||
const form = useForm({ status: interest.status, note: "", next_action: interest.next_action ?? "", next_action_due_at: interest.next_action_due_at?.slice(0, 10) ?? "", assigned_to: interest.assigned_to?.toString() ?? "" });
|
||||
const contactConsentForm = useForm({ reason: "" });
|
||||
const sharingConsentForm = useForm({ reason: "" });
|
||||
export default function InterestDetail({
|
||||
interest,
|
||||
history = [],
|
||||
assignees = [],
|
||||
consents = [],
|
||||
}: {
|
||||
interest: Interest;
|
||||
history?: Transition[];
|
||||
assignees?: Assignee[];
|
||||
consents?: Consent[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
status: interest.status,
|
||||
note: '',
|
||||
next_action: interest.next_action ?? '',
|
||||
next_action_due_at: interest.next_action_due_at?.slice(0, 10) ?? '',
|
||||
assigned_to: interest.assigned_to?.toString() ?? '',
|
||||
});
|
||||
const contactConsentForm = useForm({ reason: '' });
|
||||
const sharingConsentForm = useForm({ reason: '' });
|
||||
const rows: [string, string | number | null][] = [
|
||||
["Nome", interest.full_name],
|
||||
["Email", interest.email],
|
||||
["Telefone", interest.phone],
|
||||
["Tipo de investidor", interest.investor_type],
|
||||
["País", interest.country],
|
||||
["Sector", interest.sector_interest],
|
||||
["Oportunidade", interest.opportunity_reference],
|
||||
["Negócio publicado", interest.existing_business_id],
|
||||
["Modalidade", interest.modality],
|
||||
["Faixa de investimento", interest.investment_range],
|
||||
["Recebido em (Maputo)", dateTime(interest.created_at)],
|
||||
["Consentimento em (Maputo)", dateTime(interest.consented_at)],
|
||||
["Revisto em (Maputo)", dateTime(interest.reviewed_at)],
|
||||
["Revisto pelo utilizador", interest.reviewed_by],
|
||||
['Nome', interest.full_name],
|
||||
['Email', interest.email],
|
||||
['Telefone', interest.phone],
|
||||
['Tipo de investidor', interest.investor_type],
|
||||
['País', interest.country],
|
||||
['Sector', interest.sector_interest],
|
||||
['Oportunidade', interest.opportunity_reference],
|
||||
['Negócio publicado', interest.existing_business_id],
|
||||
['Modalidade', interest.modality],
|
||||
['Faixa de investimento', interest.investment_range],
|
||||
['Recebido em (Maputo)', dateTime(interest.created_at)],
|
||||
['Consentimento em (Maputo)', dateTime(interest.consented_at)],
|
||||
['Revisto em (Maputo)', dateTime(interest.reviewed_at)],
|
||||
['Revisto pelo utilizador', interest.reviewed_by],
|
||||
];
|
||||
return (
|
||||
<Management title={interest.reference}>
|
||||
@@ -70,7 +98,8 @@ export default function InterestDetail({ interest, history = [], assignees = [],
|
||||
className="underline"
|
||||
href={`/investidor/manifestacoes/${interest.metadata.submission_id}`}
|
||||
>
|
||||
Consultar manifestação completa, necessidades e anexos privados
|
||||
Consultar manifestação completa, necessidades e anexos
|
||||
privados
|
||||
</Link>
|
||||
)}
|
||||
{interest.metadata?.dossier_id && (
|
||||
@@ -84,54 +113,134 @@ export default function InterestDetail({ interest, history = [], assignees = [],
|
||||
</Link>
|
||||
<p>Jornada: {interest.metadata.journey_id}</p>
|
||||
<p>
|
||||
Papel: {interest.metadata.role} · Horizonte: {interest.metadata.horizon}
|
||||
Papel: {interest.metadata.role} · Horizonte:{' '}
|
||||
{interest.metadata.horizon}
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<Link className={button} href={`/management/crm/convert/${interest.id}`}>
|
||||
<Link
|
||||
className={button}
|
||||
href={`/management/crm/convert/${interest.id}`}
|
||||
>
|
||||
Encaminhar para o CRM
|
||||
</Link>
|
||||
<dl className="grid gap-4 sm:grid-cols-2">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt className="text-muted-foreground text-sm">{label}</dt>
|
||||
<dd className="break-words">{value ?? "—"}</dd>
|
||||
<dt className="text-muted-foreground text-sm">
|
||||
{label}
|
||||
</dt>
|
||||
<dd className="break-words">{value ?? '—'}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<section>
|
||||
<h2 className="font-semibold">Mensagem</h2>
|
||||
<p className="mt-2 break-words whitespace-pre-wrap">{interest.message}</p>
|
||||
<p className="mt-2 break-words whitespace-pre-wrap">
|
||||
{interest.message}
|
||||
</p>
|
||||
</section>
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-semibold">Consentimentos e versões</h2>
|
||||
{consents.map((consent, index) => (
|
||||
<article key={`${consent.purpose}-${index}`} className="rounded border p-3">
|
||||
<p>{consent.purpose}: {consent.status}</p>
|
||||
<p className="text-sm">Política {consent.policy_version ?? "—"} · concedido {dateTime(consent.granted_at)}</p>
|
||||
{consent.withdrawn_at && <p className="text-sm">Revogado {dateTime(consent.withdrawn_at)}</p>}
|
||||
<article
|
||||
key={`${consent.purpose}-${index}`}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
{consent.purpose}: {consent.status}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Política {consent.policy_version ?? '—'} · concedido{' '}
|
||||
{dateTime(consent.granted_at)}
|
||||
</p>
|
||||
{consent.withdrawn_at && (
|
||||
<p className="text-sm">
|
||||
Revogado {dateTime(consent.withdrawn_at)}
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{consents.some((consent) => consent.purpose === "respond_to_interest" && consent.status === "granted") && (
|
||||
<form className="max-w-sm space-y-3" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
contactConsentForm.patch(`/management/interests/${interest.id}/consent/contact`);
|
||||
}}>
|
||||
<Field label="Motivo do pedido de revogação" error={contactConsentForm.errors.reason}>
|
||||
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={contactConsentForm.data.reason} onChange={(event) => contactConsentForm.setData("reason", event.target.value)} />
|
||||
{consents.some(
|
||||
(consent) =>
|
||||
consent.purpose === 'respond_to_interest' &&
|
||||
consent.status === 'granted',
|
||||
) && (
|
||||
<form
|
||||
className="max-w-sm space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
contactConsentForm.patch(
|
||||
`/management/interests/${interest.id}/consent/contact`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Motivo do pedido de revogação"
|
||||
error={contactConsentForm.errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
required
|
||||
rows={3}
|
||||
value={contactConsentForm.data.reason}
|
||||
onChange={(event) =>
|
||||
contactConsentForm.setData(
|
||||
'reason',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={contactConsentForm.processing}>Revogar autorização de contacto</button>
|
||||
<button
|
||||
className={button}
|
||||
disabled={contactConsentForm.processing}
|
||||
>
|
||||
Revogar autorização de contacto
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{consents.some((consent) => consent.purpose === "share_contact_with_proponent" && consent.status === "granted") && (
|
||||
<form className="max-w-sm space-y-3" onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
sharingConsentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
|
||||
}}>
|
||||
<Field label="Motivo do pedido de revogação" error={sharingConsentForm.errors.reason}>
|
||||
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={sharingConsentForm.data.reason} onChange={(event) => sharingConsentForm.setData("reason", event.target.value)} />
|
||||
{consents.some(
|
||||
(consent) =>
|
||||
consent.purpose === 'share_contact_with_proponent' &&
|
||||
consent.status === 'granted',
|
||||
) && (
|
||||
<form
|
||||
className="max-w-sm space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
sharingConsentForm.patch(
|
||||
`/management/interests/${interest.id}/consent/proponent`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Motivo do pedido de revogação"
|
||||
error={sharingConsentForm.errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
required
|
||||
rows={3}
|
||||
value={sharingConsentForm.data.reason}
|
||||
onChange={(event) =>
|
||||
sharingConsentForm.setData(
|
||||
'reason',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={sharingConsentForm.processing}>Revogar autorização de partilha</button>
|
||||
<button
|
||||
className={button}
|
||||
disabled={sharingConsentForm.processing}
|
||||
>
|
||||
Revogar autorização de partilha
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
@@ -146,9 +255,26 @@ export default function InterestDetail({ interest, history = [], assignees = [],
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData("status", e.target.value)}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
>
|
||||
{["received", "submitted", "in_review", "reviewed", "qualification", "qualified", "contacted", "contact_accepted", "referred", "due_diligence", "negotiation", "pending", "refused", "converted", "cancelled", "closed"].map((key) => (
|
||||
{[
|
||||
'received',
|
||||
'submitted',
|
||||
'in_review',
|
||||
'reviewed',
|
||||
'qualification',
|
||||
'qualified',
|
||||
'contacted',
|
||||
'contact_accepted',
|
||||
'referred',
|
||||
'due_diligence',
|
||||
'negotiation',
|
||||
'pending',
|
||||
'refused',
|
||||
'converted',
|
||||
'cancelled',
|
||||
'closed',
|
||||
].map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{states[key]}
|
||||
</option>
|
||||
@@ -156,31 +282,75 @@ export default function InterestDetail({ interest, history = [], assignees = [],
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Nota de acompanhamento" error={form.errors.note}>
|
||||
<textarea className={control} rows={3} value={form.data.note} onChange={(e) => form.setData("note", e.target.value)} />
|
||||
<textarea
|
||||
className={control}
|
||||
rows={3}
|
||||
value={form.data.note}
|
||||
onChange={(e) => form.setData('note', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Próxima acção" error={form.errors.next_action}>
|
||||
<input className={control} value={form.data.next_action} onChange={(e) => form.setData("next_action", e.target.value)} />
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.next_action}
|
||||
onChange={(e) =>
|
||||
form.setData('next_action', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Prazo da próxima acção" error={form.errors.next_action_due_at}>
|
||||
<input type="date" className={control} value={form.data.next_action_due_at} onChange={(e) => form.setData("next_action_due_at", e.target.value)} />
|
||||
<Field
|
||||
label="Prazo da próxima acção"
|
||||
error={form.errors.next_action_due_at}
|
||||
>
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={form.data.next_action_due_at}
|
||||
onChange={(e) =>
|
||||
form.setData('next_action_due_at', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Responsável" error={form.errors.assigned_to}>
|
||||
<select className={control} value={form.data.assigned_to} onChange={(e) => form.setData("assigned_to", e.target.value)}>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.assigned_to}
|
||||
onChange={(e) =>
|
||||
form.setData('assigned_to', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem responsável</option>
|
||||
{assignees.map((assignee) => <option key={assignee.id} value={assignee.id}>{assignee.name}</option>)}
|
||||
{assignees.map((assignee) => (
|
||||
<option key={assignee.id} value={assignee.id}>
|
||||
{assignee.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
{form.processing ? "A guardar…" : "Guardar estado"}
|
||||
{form.processing ? 'A guardar…' : 'Guardar estado'}
|
||||
</button>
|
||||
</form>
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-semibold">Histórico do fluxo</h2>
|
||||
{!history.length && <p>Sem alterações de estado registadas.</p>}
|
||||
{history.map((entry, index) => (
|
||||
<article key={`${entry.created_at}-${index}`} className="rounded border p-3">
|
||||
<p>{entry.from_status ? `${states[entry.from_status] ?? entry.from_status} → ` : ""}{states[entry.to_status] ?? entry.to_status} · {dateTime(entry.created_at)}</p>
|
||||
{entry.note && <p className="mt-1 whitespace-pre-wrap">{entry.note}</p>}
|
||||
<article
|
||||
key={`${entry.created_at}-${index}`}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
{entry.from_status
|
||||
? `${states[entry.from_status] ?? entry.from_status} → `
|
||||
: ''}
|
||||
{states[entry.to_status] ?? entry.to_status} ·{' '}
|
||||
{dateTime(entry.created_at)}
|
||||
</p>
|
||||
{entry.note && (
|
||||
<p className="mt-1 whitespace-pre-wrap">
|
||||
{entry.note}
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
|
||||
@@ -32,7 +32,11 @@ export default function Interests({
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
router.get('/management/interests', { q, status, follow_up: followUp });
|
||||
router.get('/management/interests', {
|
||||
q,
|
||||
status,
|
||||
follow_up: followUp,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<input
|
||||
@@ -49,15 +53,39 @@ export default function Interests({
|
||||
onChange={(e) => setStatus(e.target.value)}
|
||||
>
|
||||
<option value="">Todos os estados</option>
|
||||
{Object.keys(states).filter((key) => ['received', 'submitted', 'in_review', 'reviewed', 'qualification', 'qualified', 'contacted', 'contact_accepted', 'referred', 'due_diligence', 'negotiation', 'pending', 'refused', 'converted', 'cancelled', 'closed'].includes(key)).map(
|
||||
(key) => (
|
||||
{Object.keys(states)
|
||||
.filter((key) =>
|
||||
[
|
||||
'received',
|
||||
'submitted',
|
||||
'in_review',
|
||||
'reviewed',
|
||||
'qualification',
|
||||
'qualified',
|
||||
'contacted',
|
||||
'contact_accepted',
|
||||
'referred',
|
||||
'due_diligence',
|
||||
'negotiation',
|
||||
'pending',
|
||||
'refused',
|
||||
'converted',
|
||||
'cancelled',
|
||||
'closed',
|
||||
].includes(key),
|
||||
)
|
||||
.map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{states[key]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
))}
|
||||
</select>
|
||||
<select aria-label="Acompanhamento" className={`${control} max-w-xs`} value={followUp} onChange={(e) => setFollowUp(e.target.value)}>
|
||||
<select
|
||||
aria-label="Acompanhamento"
|
||||
className={`${control} max-w-xs`}
|
||||
value={followUp}
|
||||
onChange={(e) => setFollowUp(e.target.value)}
|
||||
>
|
||||
<option value="">Todos os acompanhamentos</option>
|
||||
<option value="overdue">Acções atrasadas</option>
|
||||
<option value="upcoming">Acções por vencer</option>
|
||||
@@ -105,12 +133,23 @@ export default function Interests({
|
||||
{item.sector_interest}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{item.modality ?? (item.existing_business_id ? 'Negócio' : '—')}
|
||||
{item.modality ??
|
||||
(item.existing_business_id
|
||||
? 'Negócio'
|
||||
: '—')}
|
||||
</td>
|
||||
<td className="border-b p-3">{item.assignee?.name ?? '—'}</td>
|
||||
<td className="border-b p-3">{item.next_action ?? '—'}</td>
|
||||
<td className={`border-b p-3 ${item.next_action_due_at && new Date(item.next_action_due_at) < new Date() ? 'font-semibold text-red-700' : ''}`}>
|
||||
{item.next_action_due_at ? `${new Date(item.next_action_due_at) < new Date() ? 'Atrasada · ' : ''}${new Intl.DateTimeFormat('pt-MZ', { dateStyle: 'medium', timeZone: 'Africa/Maputo' }).format(new Date(item.next_action_due_at))}` : '—'}
|
||||
<td className="border-b p-3">
|
||||
{item.assignee?.name ?? '—'}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{item.next_action ?? '—'}
|
||||
</td>
|
||||
<td
|
||||
className={`border-b p-3 ${item.next_action_due_at && new Date(item.next_action_due_at) < new Date() ? 'font-semibold text-red-700' : ''}`}
|
||||
>
|
||||
{item.next_action_due_at
|
||||
? `${new Date(item.next_action_due_at) < new Date() ? 'Atrasada · ' : ''}${new Intl.DateTimeFormat('pt-MZ', { dateStyle: 'medium', timeZone: 'Africa/Maputo' }).format(new Date(item.next_action_due_at))}`
|
||||
: '—'}
|
||||
</td>
|
||||
<td className="border-b p-3">
|
||||
{states[item.status] ?? item.status}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { Management } from "./shared";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Management } from './shared';
|
||||
|
||||
type Plan = {
|
||||
target: { database: string; port: number };
|
||||
@@ -35,7 +35,7 @@ type Plan = {
|
||||
type Territory = {
|
||||
row_id: string;
|
||||
validation_hash: string;
|
||||
status: "grounded" | "pending" | "contradictory";
|
||||
status: 'grounded' | 'pending' | 'contradictory';
|
||||
applied: boolean;
|
||||
issues: string[];
|
||||
warnings: string[];
|
||||
@@ -71,23 +71,23 @@ type History = {
|
||||
};
|
||||
};
|
||||
const roles: Record<string, string> = {
|
||||
primary: "Principal",
|
||||
secondary: "Secundária",
|
||||
impact: "Área de impacto",
|
||||
primary: 'Principal',
|
||||
secondary: 'Secundária',
|
||||
impact: 'Área de impacto',
|
||||
};
|
||||
const levels: Record<string, string> = {
|
||||
country: "País",
|
||||
province: "Província",
|
||||
district: "Distrito",
|
||||
admin_post: "Posto administrativo",
|
||||
locality: "Localidade",
|
||||
site: "Implantação",
|
||||
country: 'País',
|
||||
province: 'Província',
|
||||
district: 'Distrito',
|
||||
admin_post: 'Posto administrativo',
|
||||
locality: 'Localidade',
|
||||
site: 'Implantação',
|
||||
};
|
||||
function pathText(path: { name: string; type: string }[]) {
|
||||
return (
|
||||
path
|
||||
.map((node) => `${levels[node.type] ?? node.type}: ${node.name}`)
|
||||
.join(" → ") || "Hierarquia não indicada"
|
||||
.join(' → ') || 'Hierarquia não indicada'
|
||||
);
|
||||
}
|
||||
function IndividualAssociation({
|
||||
@@ -111,7 +111,7 @@ function IndividualAssociation({
|
||||
row_id: item.row_id,
|
||||
validation_hash: item.validation_hash,
|
||||
}));
|
||||
form.post("/management/relationship-repair", {
|
||||
form.post('/management/relationship-repair', {
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
@@ -121,12 +121,12 @@ function IndividualAssociation({
|
||||
disabled={
|
||||
form.processing ||
|
||||
item.applied ||
|
||||
item.status !== "grounded"
|
||||
item.status !== 'grounded'
|
||||
}
|
||||
>
|
||||
{item.applied
|
||||
? "Associação aplicada"
|
||||
: "Aplicar esta associação"}
|
||||
? 'Associação aplicada'
|
||||
: 'Aplicar esta associação'}
|
||||
</button>
|
||||
{Object.values(form.errors).map((error) => (
|
||||
<p key={error} role="alert">
|
||||
@@ -172,7 +172,7 @@ export default function RelationshipRepair({
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.post("/management/relationship-repair");
|
||||
form.post('/management/relationship-repair');
|
||||
}}
|
||||
>
|
||||
<button
|
||||
@@ -198,34 +198,34 @@ export default function RelationshipRepair({
|
||||
localização não é deduzida de clusters ou da proximidade a
|
||||
zonas.
|
||||
</p>
|
||||
{(["grounded", "pending", "contradictory"] as const).map(
|
||||
{(['grounded', 'pending', 'contradictory'] as const).map(
|
||||
(status) => (
|
||||
<section
|
||||
key={status}
|
||||
className="space-y-4"
|
||||
aria-label={
|
||||
status === "grounded"
|
||||
? "Associações fundamentadas"
|
||||
: status === "pending"
|
||||
? "Associações pendentes"
|
||||
: "Associações contraditórias"
|
||||
status === 'grounded'
|
||||
? 'Associações fundamentadas'
|
||||
: status === 'pending'
|
||||
? 'Associações pendentes'
|
||||
: 'Associações contraditórias'
|
||||
}
|
||||
>
|
||||
<h3 className="text-lg font-bold">
|
||||
{status === "grounded"
|
||||
? "Fundamentadas"
|
||||
: status === "pending"
|
||||
? "Pendentes"
|
||||
: "Contraditórias"}
|
||||
:{" "}
|
||||
{status === 'grounded'
|
||||
? 'Fundamentadas'
|
||||
: status === 'pending'
|
||||
? 'Pendentes'
|
||||
: 'Contraditórias'}
|
||||
:{' '}
|
||||
{territorial.filter(
|
||||
(item) => item.status === status,
|
||||
).length +
|
||||
(status === "pending"
|
||||
(status === 'pending'
|
||||
? unproposed.length
|
||||
: 0)}
|
||||
</h3>
|
||||
{status === "pending" &&
|
||||
{status === 'pending' &&
|
||||
unproposed.map((item) => (
|
||||
<article
|
||||
key={item.code}
|
||||
@@ -236,23 +236,23 @@ export default function RelationshipRepair({
|
||||
territorial individualizada
|
||||
</h4>
|
||||
<p>
|
||||
Localização atual:{" "}
|
||||
Localização atual:{' '}
|
||||
{item.current
|
||||
.map(
|
||||
(location) =>
|
||||
`${location.name} · ${roles[location.role]}`,
|
||||
)
|
||||
.join("; ") ||
|
||||
"Sem localização cadastrada"}
|
||||
.join('; ') ||
|
||||
'Sem localização cadastrada'}
|
||||
</p>
|
||||
<p>
|
||||
Localização documental proposta:{" "}
|
||||
Localização documental proposta:{' '}
|
||||
{item.location_text ??
|
||||
"Não indicada"}
|
||||
'Não indicada'}
|
||||
</p>
|
||||
<p>
|
||||
Documento de origem:{" "}
|
||||
{item.source ?? "Não indicado"}
|
||||
Documento de origem:{' '}
|
||||
{item.source ?? 'Não indicado'}
|
||||
</p>
|
||||
{item.reasons.map((reason) => (
|
||||
<p key={reason}>{reason}</p>
|
||||
@@ -267,8 +267,8 @@ export default function RelationshipRepair({
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<h4 className="font-bold">
|
||||
{plan.locations[index].code} →{" "}
|
||||
{validation.proposed.name} ·{" "}
|
||||
{plan.locations[index].code} →{' '}
|
||||
{validation.proposed.name} ·{' '}
|
||||
{roles[validation.proposed.role] ??
|
||||
validation.proposed.role}
|
||||
</h4>
|
||||
@@ -279,12 +279,12 @@ export default function RelationshipRepair({
|
||||
{validation.current.map(
|
||||
(current, i) => (
|
||||
<li key={i}>
|
||||
{current.name} ·{" "}
|
||||
{current.name} ·{' '}
|
||||
{roles[
|
||||
current.role
|
||||
] ??
|
||||
current.role}{" "}
|
||||
—{" "}
|
||||
current.role}{' '}
|
||||
—{' '}
|
||||
{pathText(
|
||||
current.path,
|
||||
)}
|
||||
@@ -301,12 +301,12 @@ export default function RelationshipRepair({
|
||||
<p>
|
||||
<strong>
|
||||
Localização proposta:
|
||||
</strong>{" "}
|
||||
{pathText(validation.proposed.path)}{" "}
|
||||
</strong>{' '}
|
||||
{pathText(validation.proposed.path)}{' '}
|
||||
· {roles[validation.proposed.role]}
|
||||
</p>
|
||||
<p>
|
||||
Documento de origem:{" "}
|
||||
Documento de origem:{' '}
|
||||
{
|
||||
plan.locations[index]
|
||||
.source_reference
|
||||
@@ -316,18 +316,18 @@ export default function RelationshipRepair({
|
||||
{plan.locations[index].source_quote}
|
||||
</blockquote>
|
||||
<p>
|
||||
Motivo:{" "}
|
||||
Motivo:{' '}
|
||||
{plan.locations[index].reason}
|
||||
</p>
|
||||
{validation.coordinates.map(
|
||||
(point, i) => (
|
||||
<p key={i}>
|
||||
Coordenadas (longitude,
|
||||
latitude):{" "}
|
||||
latitude):{' '}
|
||||
{point.coordinates.join(
|
||||
", ",
|
||||
)}{" "}
|
||||
· SRID {point.srid} · Fonte:{" "}
|
||||
', ',
|
||||
)}{' '}
|
||||
· SRID {point.srid} · Fonte:{' '}
|
||||
{point.source}
|
||||
</p>
|
||||
),
|
||||
@@ -336,9 +336,9 @@ export default function RelationshipRepair({
|
||||
(check, i) => (
|
||||
<p key={i}>
|
||||
{check.compatible
|
||||
? "Coordenadas compatíveis com o limite territorial"
|
||||
: "Coordenadas incompatíveis com o limite territorial"}{" "}
|
||||
· Fonte cartográfica:{" "}
|
||||
? 'Coordenadas compatíveis com o limite territorial'
|
||||
: 'Coordenadas incompatíveis com o limite territorial'}{' '}
|
||||
· Fonte cartográfica:{' '}
|
||||
{check.source}
|
||||
</p>
|
||||
),
|
||||
@@ -371,12 +371,12 @@ export default function RelationshipRepair({
|
||||
history.map((event) => (
|
||||
<article key={event.id} className="rounded border p-4">
|
||||
<p>
|
||||
Autor: {event.actor ?? "Utilizador"} (ID{" "}
|
||||
Autor: {event.actor ?? 'Utilizador'} (ID{' '}
|
||||
{event.actor_id}) · Data: {event.date}
|
||||
</p>
|
||||
{event.data.sources?.map((source) => (
|
||||
<p key={source.row_id}>
|
||||
Fonte: {source.source_reference} · Motivo:{" "}
|
||||
Fonte: {source.source_reference} · Motivo:{' '}
|
||||
{source.reason}
|
||||
</p>
|
||||
))}
|
||||
@@ -396,9 +396,9 @@ export default function RelationshipRepair({
|
||||
{item.cluster_code} ↔ {item.project_code}
|
||||
</h3>
|
||||
<p>
|
||||
{item.action === "present_existing"
|
||||
? "Relação existente, agora apresentada como proposta documental pendente"
|
||||
: "Relação ausente"}
|
||||
{item.action === 'present_existing'
|
||||
? 'Relação existente, agora apresentada como proposta documental pendente'
|
||||
: 'Relação ausente'}
|
||||
</p>
|
||||
<p>Fonte: {item.source_reference}</p>
|
||||
<blockquote>{item.source_quote}</blockquote>
|
||||
@@ -407,7 +407,7 @@ export default function RelationshipRepair({
|
||||
</section>
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-xl font-bold">
|
||||
Registos de oportunidades preparados:{" "}
|
||||
Registos de oportunidades preparados:{' '}
|
||||
{plan.prepared_opportunities.length}
|
||||
</h2>
|
||||
{plan.prepared_opportunities.map((item, index) => (
|
||||
@@ -416,14 +416,14 @@ export default function RelationshipRepair({
|
||||
{item.reference} · {item.title}
|
||||
</summary>
|
||||
<p>
|
||||
Projecto:{" "}
|
||||
Projecto:{' '}
|
||||
{item.project_code ??
|
||||
"Identidade em conflito; associação pendente"}
|
||||
'Identidade em conflito; associação pendente'}
|
||||
</p>
|
||||
<p>{item.location_text}</p>
|
||||
<p>Fonte: {item.source_reference}</p>
|
||||
<p>{item.reason}</p>
|
||||
<p>Dados por completar: {item.unknown.join(", ")}.</p>
|
||||
<p>Dados por completar: {item.unknown.join(', ')}.</p>
|
||||
</details>
|
||||
))}
|
||||
</section>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Head, Link, usePage } from "@inertiajs/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { cloneElement, isValidElement, useId } from "react";
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cloneElement, isValidElement, useId } from 'react';
|
||||
|
||||
export type Paginated<T> = {
|
||||
data: T[];
|
||||
@@ -10,32 +10,39 @@ export type Paginated<T> = {
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
export const control = "w-full rounded-md border border-input bg-background p-2 text-foreground";
|
||||
export const control =
|
||||
'w-full rounded-md border border-input bg-background p-2 text-foreground';
|
||||
export const button =
|
||||
"inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50";
|
||||
'inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50';
|
||||
export const states: Record<string, string> = {
|
||||
received: "Recebido",
|
||||
submitted: "Submetido",
|
||||
in_review: "Em análise",
|
||||
contacted: "Contactado",
|
||||
reviewed: "Revisto",
|
||||
qualification: "Em qualificação",
|
||||
qualified: "Qualificado",
|
||||
contact_accepted: "Contacto aceite",
|
||||
referred: "Encaminhado",
|
||||
due_diligence: "Diligência devida",
|
||||
negotiation: "Em negociação",
|
||||
pending: "Pendente",
|
||||
refused: "Recusado",
|
||||
converted: "Convertido",
|
||||
cancelled: "Cancelado",
|
||||
closed: "Encerrado",
|
||||
draft: "Rascunho",
|
||||
published: "Publicado",
|
||||
archived: "Arquivado",
|
||||
received: 'Recebido',
|
||||
submitted: 'Submetido',
|
||||
in_review: 'Em análise',
|
||||
contacted: 'Contactado',
|
||||
reviewed: 'Revisto',
|
||||
qualification: 'Em qualificação',
|
||||
qualified: 'Qualificado',
|
||||
contact_accepted: 'Contacto aceite',
|
||||
referred: 'Encaminhado',
|
||||
due_diligence: 'Diligência devida',
|
||||
negotiation: 'Em negociação',
|
||||
pending: 'Pendente',
|
||||
refused: 'Recusado',
|
||||
converted: 'Convertido',
|
||||
cancelled: 'Cancelado',
|
||||
closed: 'Encerrado',
|
||||
draft: 'Rascunho',
|
||||
published: 'Publicado',
|
||||
archived: 'Arquivado',
|
||||
};
|
||||
|
||||
export function Management({ title, children }: { title: string; children: ReactNode }) {
|
||||
export function Management({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash, educationEnabled, aiEnabled } = usePage<{
|
||||
flash?: { success?: string };
|
||||
educationEnabled?: boolean;
|
||||
@@ -44,7 +51,10 @@ export function Management({ title, children }: { title: string; children: React
|
||||
return (
|
||||
<main className="space-y-6 p-4 md:p-8">
|
||||
<Head title={title} />
|
||||
<nav className="flex flex-wrap gap-4 text-sm underline" aria-label="Gestão do portal">
|
||||
<nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
aria-label="Gestão do portal"
|
||||
>
|
||||
<Link href="/management/interests">Pedidos de interesse</Link>
|
||||
<Link href="/management/sectors">Sectores</Link>
|
||||
<Link href="/management/opportunities">Oportunidades</Link>
|
||||
@@ -53,25 +63,44 @@ export function Management({ title, children }: { title: string; children: React
|
||||
<Link href="/management/crm/investors">Investidores</Link>
|
||||
<Link href="/management/projects">Projectos</Link>
|
||||
<Link href="/management/clusters">Clusters</Link>
|
||||
<Link href="/management/relationship-repair">Revisão das associações documentadas</Link>
|
||||
<Link href="/management/partnerships-install">Aplicação da Bolsa de Parcerias</Link>
|
||||
<Link href="/management/relationship-repair">
|
||||
Revisão das associações documentadas
|
||||
</Link>
|
||||
<Link href="/management/partnerships-install">
|
||||
Aplicação da Bolsa de Parcerias
|
||||
</Link>
|
||||
<Link href="/management/corridors">Corredores</Link>
|
||||
<Link href="/management/territory-associations">
|
||||
Localizações dos investimentos
|
||||
</Link>
|
||||
<Link href="/management/investment/zones">ZEE, ZFI e parques</Link>
|
||||
<Link href="/management/investment/zones">
|
||||
ZEE, ZFI e parques
|
||||
</Link>
|
||||
{educationEnabled && (
|
||||
<Link href="/management/education">Competências e formação</Link>
|
||||
<Link href="/management/education">
|
||||
Competências e formação
|
||||
</Link>
|
||||
)}
|
||||
{aiEnabled && <Link href="/management/ai">Assistência e fontes</Link>}
|
||||
<Link href="/management/portfolio">Corredores e matriz de investimento</Link>
|
||||
<Link href="/management/portal-services">Documentos e parcerias</Link>
|
||||
<Link href="/management/investment/references">Referências e formulários</Link>
|
||||
{aiEnabled && (
|
||||
<Link href="/management/ai">Assistência e fontes</Link>
|
||||
)}
|
||||
<Link href="/management/portfolio">
|
||||
Corredores e matriz de investimento
|
||||
</Link>
|
||||
<Link href="/management/portal-services">
|
||||
Documentos e parcerias
|
||||
</Link>
|
||||
<Link href="/management/investment/references">
|
||||
Referências e formulários
|
||||
</Link>
|
||||
<a href="/">Portal público</a>
|
||||
</nav>
|
||||
<h1 className="text-2xl font-semibold break-words">{title}</h1>
|
||||
{flash?.success && (
|
||||
<p role="status" className="rounded border border-emerald-600 p-3">
|
||||
<p
|
||||
role="status"
|
||||
className="rounded border border-emerald-600 p-3"
|
||||
>
|
||||
{flash.success}
|
||||
</p>
|
||||
)}
|
||||
@@ -82,14 +111,18 @@ export function Management({ title, children }: { title: string; children: React
|
||||
|
||||
export function Pagination<T>({ page }: { page: Paginated<T> }) {
|
||||
return (
|
||||
<nav aria-label="Paginação" className="flex flex-wrap items-center gap-4">
|
||||
<nav
|
||||
aria-label="Paginação"
|
||||
className="flex flex-wrap items-center gap-4"
|
||||
>
|
||||
{page.prev_page_url && (
|
||||
<Link className={button} href={page.prev_page_url}>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
<span>
|
||||
{page.total} registos · Página {page.current_page} de {page.last_page}
|
||||
{page.total} registos · Página {page.current_page} de{' '}
|
||||
{page.last_page}
|
||||
</span>
|
||||
{page.next_page_url && (
|
||||
<Link className={button} href={page.next_page_url}>
|
||||
@@ -116,18 +149,22 @@ export function Field({
|
||||
{label}
|
||||
</span>
|
||||
{isValidElement<{
|
||||
"aria-labelledby"?: string;
|
||||
"aria-describedby"?: string;
|
||||
"aria-invalid"?: boolean;
|
||||
'aria-labelledby'?: string;
|
||||
'aria-describedby'?: string;
|
||||
'aria-invalid'?: boolean;
|
||||
}>(children)
|
||||
? cloneElement(children, {
|
||||
"aria-labelledby": id,
|
||||
"aria-describedby": error ? `${id}-error` : undefined,
|
||||
"aria-invalid": Boolean(error),
|
||||
'aria-labelledby': id,
|
||||
'aria-describedby': error ? `${id}-error` : undefined,
|
||||
'aria-invalid': Boolean(error),
|
||||
})
|
||||
: children}
|
||||
{error && (
|
||||
<span id={`${id}-error`} role="alert" className="block text-sm text-red-600">
|
||||
<span
|
||||
id={`${id}-error`}
|
||||
role="alert"
|
||||
className="block text-sm text-red-600"
|
||||
>
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -1,32 +1,44 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import InvestmentTerritory from "@/components/investment-territory";
|
||||
import { Management, Field, control } from "./shared";
|
||||
import { useEffect, useState } from 'react';
|
||||
import InvestmentTerritory from '@/components/investment-territory';
|
||||
import { Management, Field, control } from './shared';
|
||||
|
||||
export default function TerritoryAssociations() {
|
||||
const [kind, setKind] = useState("projects");
|
||||
const [id, setId] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [kind, setKind] = useState('projects');
|
||||
const [id, setId] = useState('');
|
||||
const [q, setQ] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [rows, setRows] = useState<{ id: string; name: string }[]>([]);
|
||||
const [more, setMore] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({ kind, q, page: String(page) });
|
||||
const response = await fetch(`/management/territory-subjects?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
const params = new URLSearchParams({
|
||||
kind,
|
||||
q,
|
||||
page: String(page),
|
||||
});
|
||||
if (!response.ok) throw new Error("Não foi possível carregar os investimentos.");
|
||||
const response = await fetch(
|
||||
`/management/territory-subjects?${params}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
);
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível carregar os investimentos.',
|
||||
);
|
||||
const data = await response.json();
|
||||
setRows(data.data);
|
||||
setMore(Boolean(data.next_page_url));
|
||||
setError("");
|
||||
setError('');
|
||||
} 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.',
|
||||
);
|
||||
}
|
||||
}, 250);
|
||||
return () => {
|
||||
@@ -42,16 +54,20 @@ export default function TerritoryAssociations() {
|
||||
value={kind}
|
||||
onChange={(e) => {
|
||||
setKind(e.target.value);
|
||||
setId("");
|
||||
setId('');
|
||||
setRows([]);
|
||||
setQ("");
|
||||
setQ('');
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<option value="projects">Projectos / projectos âncora</option>
|
||||
<option value="projects">
|
||||
Projectos / projectos âncora
|
||||
</option>
|
||||
<option value="clusters">Clusters</option>
|
||||
<option value="corridors">Corredores</option>
|
||||
<option value="zones">ZEE / ZFI / parques industriais</option>
|
||||
<option value="zones">
|
||||
ZEE / ZFI / parques industriais
|
||||
</option>
|
||||
<option value="opportunities">Oportunidades</option>
|
||||
</select>
|
||||
</Field>
|
||||
@@ -62,12 +78,16 @@ export default function TerritoryAssociations() {
|
||||
onChange={(e) => {
|
||||
setQ(e.target.value);
|
||||
setPage(1);
|
||||
setId("");
|
||||
setId('');
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Investimento">
|
||||
<select className={control} value={id} onChange={(e) => setId(e.target.value)}>
|
||||
<select
|
||||
className={control}
|
||||
value={id}
|
||||
onChange={(e) => setId(e.target.value)}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{rows.map((row) => (
|
||||
<option value={row.id} key={row.id}>
|
||||
@@ -77,13 +97,15 @@ export default function TerritoryAssociations() {
|
||||
</select>
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{!error && rows.length === 0 && <p>Sem registos para esta pesquisa.</p>}
|
||||
{!error && rows.length === 0 && (
|
||||
<p>Sem registos para esta pesquisa.</p>
|
||||
)}
|
||||
<div className="flex gap-4">
|
||||
{page > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setId("");
|
||||
setId('');
|
||||
setPage(page - 1);
|
||||
}}
|
||||
>
|
||||
@@ -94,7 +116,7 @@ export default function TerritoryAssociations() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setId("");
|
||||
setId('');
|
||||
setPage(page + 1);
|
||||
}}
|
||||
>
|
||||
@@ -102,7 +124,13 @@ export default function TerritoryAssociations() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{id && <InvestmentTerritory key={`${kind}-${id}`} kind={kind} id={id} />}
|
||||
{id && (
|
||||
<InvestmentTerritory
|
||||
key={`${kind}-${id}`}
|
||||
kind={kind}
|
||||
id={id}
|
||||
/>
|
||||
)}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapFeature,
|
||||
} from "@/components/interactive-investment-map";
|
||||
} from '@/components/interactive-investment-map';
|
||||
import {
|
||||
Frame,
|
||||
Field,
|
||||
@@ -10,10 +10,10 @@ import {
|
||||
button,
|
||||
type Catalogues,
|
||||
type Partnership,
|
||||
} from "./shared";
|
||||
} from './shared';
|
||||
type Result = Pick<
|
||||
Partnership,
|
||||
"id" | "title" | "kind" | "partnership_type" | "deadline"
|
||||
'id' | 'title' | 'kind' | 'partnership_type' | 'deadline'
|
||||
> & { summary: string | null; province: string; sector: string };
|
||||
export default function Catalogue(
|
||||
p: Catalogues & {
|
||||
@@ -41,22 +41,22 @@ export default function Catalogue(
|
||||
className="grid gap-4 rounded border p-5 md:grid-cols-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
router.get("/parcerias", filters);
|
||||
router.get('/parcerias', filters);
|
||||
}}
|
||||
>
|
||||
<Field label="Pesquisar">
|
||||
<input
|
||||
className={control}
|
||||
value={filters.q ?? ""}
|
||||
onChange={(e) => set("q", e.target.value)}
|
||||
value={filters.q ?? ''}
|
||||
onChange={(e) => set('q', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Tipo de parceria">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.partnership_type ?? ""}
|
||||
value={filters.partnership_type ?? ''}
|
||||
onChange={(e) =>
|
||||
set("partnership_type", e.target.value)
|
||||
set('partnership_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
@@ -70,8 +70,8 @@ export default function Catalogue(
|
||||
<Field label="Oferta ou procura">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.kind ?? ""}
|
||||
onChange={(e) => set("kind", e.target.value)}
|
||||
value={filters.kind ?? ''}
|
||||
onChange={(e) => set('kind', e.target.value)}
|
||||
>
|
||||
<option value="">Ambas</option>
|
||||
<option value="offering">Oferta</option>
|
||||
@@ -81,8 +81,8 @@ export default function Catalogue(
|
||||
<Field label="Setor">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.sector_id ?? ""}
|
||||
onChange={(e) => set("sector_id", e.target.value)}
|
||||
value={filters.sector_id ?? ''}
|
||||
onChange={(e) => set('sector_id', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.sectors.map((x) => (
|
||||
@@ -95,8 +95,8 @@ export default function Catalogue(
|
||||
<Field label="Território">
|
||||
<select
|
||||
className={control}
|
||||
value={filters.territory_id ?? ""}
|
||||
onChange={(e) => set("territory_id", e.target.value)}
|
||||
value={filters.territory_id ?? ''}
|
||||
onChange={(e) => set('territory_id', e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.territories.map((x) => (
|
||||
@@ -118,24 +118,24 @@ export default function Catalogue(
|
||||
className="space-y-3 rounded border p-5"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link href={"/parcerias/" + item.id}>
|
||||
<Link href={'/parcerias/' + item.id}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{item.partnership_type
|
||||
? p.types[item.partnership_type]
|
||||
: "Tipo por completar"}{" "}
|
||||
· {item.kind === "offering" ? "Oferta" : "Procura"}
|
||||
: 'Tipo por completar'}{' '}
|
||||
· {item.kind === 'offering' ? 'Oferta' : 'Procura'}
|
||||
</p>
|
||||
<p>{item.summary}</p>
|
||||
<p>
|
||||
{item.sector || "Setor por completar"} ·{" "}
|
||||
{item.province || "Território na ficha"}
|
||||
{item.sector || 'Setor por completar'} ·{' '}
|
||||
{item.province || 'Território na ficha'}
|
||||
</p>
|
||||
{item.deadline && <p>Prazo: {item.deadline}</p>}
|
||||
<Link
|
||||
href={"/parcerias/" + item.id}
|
||||
href={'/parcerias/' + item.id}
|
||||
className="underline"
|
||||
>
|
||||
Consultar parceria
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { Frame, labels, button, type Partnership } from "./shared";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, labels, button, type Partnership } from './shared';
|
||||
type Props = {
|
||||
mine: Pick<Partnership, "id" | "title" | "status">[];
|
||||
mine: Pick<Partnership, 'id' | 'title' | 'status'>[];
|
||||
interests: {
|
||||
id: number;
|
||||
partnership_id: number;
|
||||
@@ -10,7 +10,7 @@ type Props = {
|
||||
decision_reason: string | null;
|
||||
room_id: number | null;
|
||||
}[];
|
||||
moderation: Pick<Partnership, "id" | "title" | "status">[];
|
||||
moderation: Pick<Partnership, 'id' | 'title' | 'status'>[];
|
||||
notifications: {
|
||||
id: number;
|
||||
title: string;
|
||||
@@ -33,20 +33,20 @@ export default function Dashboard(p: Props) {
|
||||
<article className="mt-4 rounded border p-4" key={x.id}>
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={"/parcerias/" + x.id}
|
||||
href={'/parcerias/' + x.id}
|
||||
>
|
||||
{x.title || "Ideia sem título"}
|
||||
{x.title || 'Ideia sem título'}
|
||||
</Link>
|
||||
<p>{labels[x.status] ?? x.status}</p>
|
||||
<p>
|
||||
Próxima ação:{" "}
|
||||
{["draft", "returned", "rejected"].includes(
|
||||
Próxima ação:{' '}
|
||||
{['draft', 'returned', 'rejected'].includes(
|
||||
x.status,
|
||||
)
|
||||
? "Completar e pré-visualizar para submissão"
|
||||
: x.status === "published"
|
||||
? "Consultar candidatos e esclarecer pendências"
|
||||
: "Acompanhar a decisão"}
|
||||
? 'Completar e pré-visualizar para submissão'
|
||||
: x.status === 'published'
|
||||
? 'Consultar candidatos e esclarecer pendências'
|
||||
: 'Acompanhar a decisão'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
@@ -59,7 +59,7 @@ export default function Dashboard(p: Props) {
|
||||
<article className="my-4 rounded border p-4" key={x.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={"/parcerias/" + x.partnership_id}
|
||||
href={'/parcerias/' + x.partnership_id}
|
||||
>
|
||||
{x.title}
|
||||
</Link>
|
||||
@@ -69,7 +69,7 @@ export default function Dashboard(p: Props) {
|
||||
{x.room_id && (
|
||||
<Link
|
||||
className={button}
|
||||
href={"/parcerias/salas/" + x.room_id}
|
||||
href={'/parcerias/salas/' + x.room_id}
|
||||
>
|
||||
Abrir conexão privada
|
||||
</Link>
|
||||
@@ -84,7 +84,7 @@ export default function Dashboard(p: Props) {
|
||||
<p key={x.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={"/parcerias/" + x.id}
|
||||
href={'/parcerias/' + x.id}
|
||||
>
|
||||
{x.title} · {labels[x.status]}
|
||||
</Link>
|
||||
@@ -106,9 +106,9 @@ export default function Dashboard(p: Props) {
|
||||
className="ml-4 underline"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
"/parcerias/notificacoes/" +
|
||||
'/parcerias/notificacoes/' +
|
||||
n.id +
|
||||
"/ler",
|
||||
'/ler',
|
||||
)
|
||||
}
|
||||
>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Link, useForm, usePage } from "@inertiajs/react";
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import StructureGeographyPanel, {
|
||||
type StructureGeography,
|
||||
} from "@/components/structure-geography";
|
||||
} from '@/components/structure-geography';
|
||||
import {
|
||||
Frame,
|
||||
Errors,
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
type Interest,
|
||||
type Partnership,
|
||||
type Source,
|
||||
} from "./shared";
|
||||
} from './shared';
|
||||
type Props = Catalogues & {
|
||||
record: Partnership;
|
||||
owner: boolean;
|
||||
@@ -36,10 +36,10 @@ type Props = Catalogues & {
|
||||
}[];
|
||||
};
|
||||
function Publication({ p }: { p: Props }) {
|
||||
const form = useForm({ version: p.record.version, action: "", reason: "" });
|
||||
const form = useForm({ version: p.record.version, action: '', reason: '' });
|
||||
const action = (value: string) => {
|
||||
form.transform((data) => ({ ...data, action: value }));
|
||||
form.post("/parcerias/" + p.record.id + "/estado", {
|
||||
form.post('/parcerias/' + p.record.id + '/estado', {
|
||||
preserveScroll: true,
|
||||
});
|
||||
};
|
||||
@@ -55,27 +55,27 @@ function Publication({ p }: { p: Props }) {
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData("reason", e.target.value)}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Errors errors={form.errors} />
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{p.canEdit &&
|
||||
["draft", "returned", "rejected"].includes(
|
||||
['draft', 'returned', 'rejected'].includes(
|
||||
p.record.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action("submit")}
|
||||
onClick={() => action('submit')}
|
||||
>
|
||||
Submeter para publicação
|
||||
</button>
|
||||
)}
|
||||
{p.moderator &&
|
||||
!p.owner &&
|
||||
["submitted", "pending"].includes(p.record.status) &&
|
||||
["publish", "return", "reject"].map((value) => (
|
||||
['submitted', 'pending'].includes(p.record.status) &&
|
||||
['publish', 'return', 'reject'].map((value) => (
|
||||
<button
|
||||
className={button}
|
||||
key={value}
|
||||
@@ -84,33 +84,33 @@ function Publication({ p }: { p: Props }) {
|
||||
>
|
||||
{
|
||||
{
|
||||
publish: "Publicar",
|
||||
return: "Devolver para correção",
|
||||
reject: "Rejeitar com fundamento",
|
||||
publish: 'Publicar',
|
||||
return: 'Devolver para correção',
|
||||
reject: 'Rejeitar com fundamento',
|
||||
}[value]
|
||||
}
|
||||
</button>
|
||||
))}
|
||||
{p.canEdit &&
|
||||
["published", "suspended", "archived"].includes(
|
||||
['published', 'suspended', 'archived'].includes(
|
||||
p.record.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action("renew")}
|
||||
onClick={() => action('renew')}
|
||||
>
|
||||
Renovar em rascunho
|
||||
</button>
|
||||
)}
|
||||
{p.canEdit &&
|
||||
["draft", "published", "suspended", "rejected"].includes(
|
||||
['draft', 'published', 'suspended', 'rejected'].includes(
|
||||
p.record.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action("archive")}
|
||||
onClick={() => action('archive')}
|
||||
>
|
||||
Arquivar publicação
|
||||
</button>
|
||||
@@ -118,7 +118,7 @@ function Publication({ p }: { p: Props }) {
|
||||
{p.canEdit && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={"/parcerias/" + p.record.id + "/editar"}
|
||||
href={'/parcerias/' + p.record.id + '/editar'}
|
||||
>
|
||||
Editar rascunho
|
||||
</Link>
|
||||
@@ -134,17 +134,17 @@ function InterestForm({
|
||||
}: {
|
||||
record: Partnership;
|
||||
interest?: Interest;
|
||||
organizations: Catalogues["organizations"];
|
||||
organizations: Catalogues['organizations'];
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: interest?.version ?? null,
|
||||
organization_id: interest?.organization_id ?? "",
|
||||
proposal: interest?.proposal ?? "",
|
||||
organization_id: interest?.organization_id ?? '',
|
||||
proposal: interest?.proposal ?? '',
|
||||
payload: {
|
||||
capacity: interest?.payload.capacity ?? "",
|
||||
availability: interest?.payload.availability ?? "",
|
||||
contribution: interest?.payload.contribution ?? "",
|
||||
conflicts: interest?.payload.conflicts ?? "",
|
||||
capacity: interest?.payload.capacity ?? '',
|
||||
availability: interest?.payload.availability ?? '',
|
||||
contribution: interest?.payload.contribution ?? '',
|
||||
conflicts: interest?.payload.conflicts ?? '',
|
||||
consent: interest?.payload.consent ?? false,
|
||||
},
|
||||
});
|
||||
@@ -153,15 +153,15 @@ function InterestForm({
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post("/parcerias/" + record.id + "/interesses", {
|
||||
form.post('/parcerias/' + record.id + '/interesses', {
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
{interest
|
||||
? "Atualizar manifestação de interesse"
|
||||
: "Manifestar interesse"}
|
||||
? 'Atualizar manifestação de interesse'
|
||||
: 'Manifestar interesse'}
|
||||
</h2>
|
||||
<p>
|
||||
Declarações são informações comunicadas por si; não atribuem
|
||||
@@ -174,7 +174,7 @@ function InterestForm({
|
||||
className={control}
|
||||
value={form.data.organization_id}
|
||||
onChange={(e) =>
|
||||
form.setData("organization_id", e.target.value)
|
||||
form.setData('organization_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Participação pessoal</option>
|
||||
@@ -189,25 +189,25 @@ function InterestForm({
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.proposal}
|
||||
onChange={(e) => form.setData("proposal", e.target.value)}
|
||||
onChange={(e) => form.setData('proposal', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
"capacity",
|
||||
"availability",
|
||||
"contribution",
|
||||
"conflicts",
|
||||
'capacity',
|
||||
'availability',
|
||||
'contribution',
|
||||
'conflicts',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
capacity: "Capacidade disponível",
|
||||
availability: "Disponibilidade",
|
||||
contribution: "Contribuição proposta",
|
||||
conflicts: "Conflitos de interesse declarados",
|
||||
capacity: 'Capacidade disponível',
|
||||
availability: 'Disponibilidade',
|
||||
contribution: 'Contribuição proposta',
|
||||
conflicts: 'Conflitos de interesse declarados',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
@@ -215,7 +215,7 @@ function InterestForm({
|
||||
className={control}
|
||||
value={form.data.payload[key]}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
@@ -228,12 +228,12 @@ function InterestForm({
|
||||
type="checkbox"
|
||||
checked={form.data.payload.consent}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
consent: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>{" "}
|
||||
/>{' '}
|
||||
Autorizo a partilha desta candidatura com o responsável pela
|
||||
parceria.
|
||||
</label>
|
||||
@@ -254,30 +254,30 @@ function Candidacy({
|
||||
owner: boolean;
|
||||
canEdit: boolean;
|
||||
record: Partnership;
|
||||
organizations: Catalogues["organizations"];
|
||||
organizations: Catalogues['organizations'];
|
||||
}) {
|
||||
const assessment = Object.fromEntries(
|
||||
interest.match.criteria.map((c) => [
|
||||
c.code,
|
||||
{
|
||||
state: interest.assessment[c.code]?.state ?? "unknown",
|
||||
evidence: interest.assessment[c.code]?.evidence ?? "",
|
||||
state: interest.assessment[c.code]?.state ?? 'unknown',
|
||||
evidence: interest.assessment[c.code]?.evidence ?? '',
|
||||
},
|
||||
]),
|
||||
);
|
||||
const form = useForm({
|
||||
version: interest.version,
|
||||
action: "",
|
||||
reason: "",
|
||||
action: '',
|
||||
reason: '',
|
||||
assessment,
|
||||
});
|
||||
const act = (action: string) => {
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
action,
|
||||
assessment: action === "assess" ? data.assessment : {},
|
||||
assessment: action === 'assess' ? data.assessment : {},
|
||||
}));
|
||||
form.post("/parcerias/candidaturas/" + interest.id, {
|
||||
form.post('/parcerias/candidaturas/' + interest.id, {
|
||||
preserveScroll: true,
|
||||
});
|
||||
};
|
||||
@@ -289,23 +289,23 @@ function Candidacy({
|
||||
<p>{interest.proposal}</p>
|
||||
<p>{interest.payload.capacity}</p>
|
||||
<p>
|
||||
Disponibilidade:{" "}
|
||||
{interest.payload.availability || "Por esclarecer"}
|
||||
Disponibilidade:{' '}
|
||||
{interest.payload.availability || 'Por esclarecer'}
|
||||
</p>
|
||||
<p>
|
||||
Contribuição:{" "}
|
||||
{interest.payload.contribution || "Por esclarecer"}
|
||||
Contribuição:{' '}
|
||||
{interest.payload.contribution || 'Por esclarecer'}
|
||||
</p>
|
||||
<p>
|
||||
Conflitos declarados:{" "}
|
||||
{interest.payload.conflicts || "Sem informação"}
|
||||
Conflitos declarados:{' '}
|
||||
{interest.payload.conflicts || 'Sem informação'}
|
||||
</p>
|
||||
{interest.decision_reason && (
|
||||
<p>Última decisão: {interest.decision_reason}</p>
|
||||
)}
|
||||
<p>
|
||||
Correspondência: {interest.match.score_min}–
|
||||
{interest.match.score_max}% · Elegibilidade:{" "}
|
||||
{interest.match.score_max}% · Elegibilidade:{' '}
|
||||
{labels[interest.match.eligibility]}. O intervalo distingue
|
||||
dados desconhecidos de incumprimentos; não é uma aprovação.
|
||||
</p>
|
||||
@@ -313,7 +313,7 @@ function Candidacy({
|
||||
{interest.match.criteria.map((c) => (
|
||||
<li key={c.code}>
|
||||
{c.label} · peso {c.weight} · {labels[c.state]}
|
||||
{c.mandatory ? " · Obrigatório" : ""}
|
||||
{c.mandatory ? ' · Obrigatório' : ''}
|
||||
{c.evidence && <> · Evidência: {c.evidence}</>}
|
||||
<p className="text-sm">{c.explanation}</p>
|
||||
</li>
|
||||
@@ -322,14 +322,14 @@ function Candidacy({
|
||||
{interest.room_id && (
|
||||
<Link
|
||||
className={button}
|
||||
href={"/parcerias/salas/" + interest.room_id}
|
||||
href={'/parcerias/salas/' + interest.room_id}
|
||||
>
|
||||
Abrir conexão privada
|
||||
</Link>
|
||||
)}
|
||||
{owner &&
|
||||
canEdit &&
|
||||
["submitted", "clarification", "shortlisted"].includes(
|
||||
['submitted', 'clarification', 'shortlisted'].includes(
|
||||
interest.status,
|
||||
) && (
|
||||
<>
|
||||
@@ -348,7 +348,7 @@ function Candidacy({
|
||||
.state
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData("assessment", {
|
||||
form.setData('assessment', {
|
||||
...form.data.assessment,
|
||||
[c.code]: {
|
||||
...form.data.assessment[
|
||||
@@ -359,7 +359,7 @@ function Candidacy({
|
||||
})
|
||||
}
|
||||
>
|
||||
{["unknown", "met", "unmet"].map(
|
||||
{['unknown', 'met', 'unmet'].map(
|
||||
(state) => (
|
||||
<option
|
||||
key={state}
|
||||
@@ -379,7 +379,7 @@ function Candidacy({
|
||||
.evidence
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData("assessment", {
|
||||
form.setData('assessment', {
|
||||
...form.data.assessment,
|
||||
[c.code]: {
|
||||
...form.data.assessment[
|
||||
@@ -400,18 +400,18 @@ function Candidacy({
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData("reason", e.target.value)
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{[
|
||||
"assess",
|
||||
"clarify",
|
||||
"shortlist",
|
||||
"reject",
|
||||
...(interest.status === "shortlisted"
|
||||
? ["connect"]
|
||||
'assess',
|
||||
'clarify',
|
||||
'shortlist',
|
||||
'reject',
|
||||
...(interest.status === 'shortlisted'
|
||||
? ['connect']
|
||||
: []),
|
||||
].map((action) => (
|
||||
<button
|
||||
@@ -424,12 +424,12 @@ function Candidacy({
|
||||
>
|
||||
{
|
||||
{
|
||||
assess: "Guardar avaliação",
|
||||
clarify: "Pedir esclarecimento",
|
||||
assess: 'Guardar avaliação',
|
||||
clarify: 'Pedir esclarecimento',
|
||||
shortlist:
|
||||
"Adicionar à lista curta",
|
||||
reject: "Não selecionar",
|
||||
connect: "Abrir negociação",
|
||||
'Adicionar à lista curta',
|
||||
reject: 'Não selecionar',
|
||||
connect: 'Abrir negociação',
|
||||
}[action]
|
||||
}
|
||||
</button>
|
||||
@@ -438,7 +438,7 @@ function Candidacy({
|
||||
</>
|
||||
)}
|
||||
{!owner &&
|
||||
["submitted", "clarification", "shortlisted"].includes(
|
||||
['submitted', 'clarification', 'shortlisted'].includes(
|
||||
interest.status,
|
||||
) && (
|
||||
<>
|
||||
@@ -447,21 +447,21 @@ function Candidacy({
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData("reason", e.target.value)
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => act("withdraw")}
|
||||
onClick={() => act('withdraw')}
|
||||
>
|
||||
Retirar candidatura
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{!owner &&
|
||||
["submitted", "clarification", "withdrawn"].includes(
|
||||
['submitted', 'clarification', 'withdrawn'].includes(
|
||||
interest.status,
|
||||
) && (
|
||||
<InterestForm
|
||||
@@ -477,13 +477,13 @@ function Candidacy({
|
||||
export default function Detail(p: Props) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
return (
|
||||
<Frame title={p.record.title || "Pré-visualização da ideia"}>
|
||||
<Frame title={p.record.title || 'Pré-visualização da ideia'}>
|
||||
<div className="space-y-6">
|
||||
<p>
|
||||
{p.record.partnership_type
|
||||
? p.types[p.record.partnership_type]
|
||||
: "Tipo por completar"}{" "}
|
||||
· {p.record.kind === "offering" ? "Oferta" : "Procura"} ·{" "}
|
||||
: 'Tipo por completar'}{' '}
|
||||
· {p.record.kind === 'offering' ? 'Oferta' : 'Procura'} ·{' '}
|
||||
{labels[p.record.status] ?? p.record.status}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
@@ -500,7 +500,7 @@ export default function Detail(p: Props) {
|
||||
</p>
|
||||
)}
|
||||
<p>{p.record.payload.requirements}</p>
|
||||
<p>Prazo: {p.record.deadline ?? "Por definir"}</p>
|
||||
<p>Prazo: {p.record.deadline ?? 'Por definir'}</p>
|
||||
</section>
|
||||
<section className="space-y-3 rounded border p-5">
|
||||
<h2 className="text-xl font-bold">
|
||||
@@ -509,14 +509,14 @@ export default function Detail(p: Props) {
|
||||
{p.locations.length ? (
|
||||
p.locations.map((l, i) => (
|
||||
<p key={i}>
|
||||
{l.path.map((n) => n.name).join(" → ")} ·{" "}
|
||||
{l.path.map((n) => n.name).join(' → ')} ·{' '}
|
||||
{
|
||||
{
|
||||
primary: "Principal",
|
||||
operating: "Área de atuação",
|
||||
coverage: "Abrangência",
|
||||
primary: 'Principal',
|
||||
operating: 'Área de atuação',
|
||||
coverage: 'Abrangência',
|
||||
}[l.role]
|
||||
}{" "}
|
||||
}{' '}
|
||||
· Fonte: {l.source_reference}. Validação
|
||||
independente pendente.
|
||||
</p>
|
||||
@@ -528,7 +528,7 @@ export default function Detail(p: Props) {
|
||||
{p.origins.map((source, i) => (
|
||||
<section key={i} className="space-y-3 rounded border p-5">
|
||||
<h2 className="text-xl font-bold">
|
||||
Origem:{" "}
|
||||
Origem:{' '}
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>
|
||||
@@ -540,8 +540,8 @@ export default function Detail(p: Props) {
|
||||
{source.geography && (
|
||||
<StructureGeographyPanel
|
||||
geography={source.geography}
|
||||
cluster={source.type === "cluster"}
|
||||
dossierId={"partnership-source-" + i}
|
||||
cluster={source.type === 'cluster'}
|
||||
dossierId={'partnership-source-' + i}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
@@ -576,10 +576,10 @@ export default function Detail(p: Props) {
|
||||
{i.match.criteria
|
||||
.filter(
|
||||
(c) =>
|
||||
c.state === "unknown",
|
||||
c.state === 'unknown',
|
||||
)
|
||||
.map((c) => c.label)
|
||||
.join(", ")}
|
||||
.join(', ')}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -589,7 +589,7 @@ export default function Detail(p: Props) {
|
||||
)}
|
||||
{p.interests.map((i) => (
|
||||
<Candidacy
|
||||
key={i.id + ":" + i.version}
|
||||
key={i.id + ':' + i.version}
|
||||
interest={i}
|
||||
owner={p.owner}
|
||||
canEdit={p.canEdit}
|
||||
@@ -598,7 +598,7 @@ export default function Detail(p: Props) {
|
||||
/>
|
||||
))}
|
||||
{!p.owner &&
|
||||
p.record.status === "published" &&
|
||||
p.record.status === 'published' &&
|
||||
auth.user &&
|
||||
!p.interests.length && (
|
||||
<InterestForm
|
||||
@@ -606,7 +606,7 @@ export default function Detail(p: Props) {
|
||||
organizations={p.organizations}
|
||||
/>
|
||||
)}
|
||||
{!auth.user && p.record.status === "published" && (
|
||||
{!auth.user && p.record.status === 'published' && (
|
||||
<Link className={button} href="/login">
|
||||
Entrar para manifestar interesse
|
||||
</Link>
|
||||
@@ -616,7 +616,7 @@ export default function Detail(p: Props) {
|
||||
<summary>Histórico e decisões</summary>
|
||||
{p.history.map((h, i) => (
|
||||
<p key={i}>
|
||||
{h.occurred_at} · Autor {h.actor_id} ·{" "}
|
||||
{h.occurred_at} · Autor {h.actor_id} ·{' '}
|
||||
{h.event_type}
|
||||
</p>
|
||||
))}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Frame,
|
||||
Field,
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
button,
|
||||
type Partnership,
|
||||
type Catalogues,
|
||||
} from "./shared";
|
||||
} from './shared';
|
||||
type Location = {
|
||||
geo_location_id: string;
|
||||
role: string;
|
||||
@@ -24,19 +24,19 @@ function Editor(p: Props) {
|
||||
const form = useForm({
|
||||
client_key: crypto.randomUUID(),
|
||||
version: p.record?.version ?? null,
|
||||
title: p.record?.title ?? "",
|
||||
offer: p.record?.offer ?? "",
|
||||
seeking: p.record?.seeking ?? "",
|
||||
organization_id: p.record?.organization_id ?? "",
|
||||
sector_id: p.record?.sector_id?.toString() ?? "",
|
||||
kind: p.record?.kind ?? "seeking",
|
||||
partnership_type: p.record?.partnership_type ?? "",
|
||||
deadline: p.record?.deadline ?? "",
|
||||
title: p.record?.title ?? '',
|
||||
offer: p.record?.offer ?? '',
|
||||
seeking: p.record?.seeking ?? '',
|
||||
organization_id: p.record?.organization_id ?? '',
|
||||
sector_id: p.record?.sector_id?.toString() ?? '',
|
||||
kind: p.record?.kind ?? 'seeking',
|
||||
partnership_type: p.record?.partnership_type ?? '',
|
||||
deadline: p.record?.deadline ?? '',
|
||||
payload: {
|
||||
summary: p.record?.payload.summary ?? "",
|
||||
requirements: p.record?.payload.requirements ?? "",
|
||||
summary: p.record?.payload.summary ?? '',
|
||||
requirements: p.record?.payload.requirements ?? '',
|
||||
mandatory: p.record?.payload.mandatory ?? ([] as string[]),
|
||||
confidentiality: p.record?.payload.confidentiality ?? "public",
|
||||
confidentiality: p.record?.payload.confidentiality ?? 'public',
|
||||
consent: p.record?.payload.consent ?? false,
|
||||
},
|
||||
locations: p.locations.map((x) => ({
|
||||
@@ -49,12 +49,12 @@ function Editor(p: Props) {
|
||||
target_id: x.target_id,
|
||||
})),
|
||||
});
|
||||
const [place, setPlace] = useState("");
|
||||
const [role, setRole] = useState("primary");
|
||||
const [source, setSource] = useState("Declaração do proponente");
|
||||
const [origin, setOrigin] = useState("");
|
||||
const [place, setPlace] = useState('');
|
||||
const [role, setRole] = useState('primary');
|
||||
const [source, setSource] = useState('Declaração do proponente');
|
||||
const [origin, setOrigin] = useState('');
|
||||
return (
|
||||
<Frame title={p.record ? "Editar parceria" : "Preparar parceria"}>
|
||||
<Frame title={p.record ? 'Editar parceria' : 'Preparar parceria'}>
|
||||
<p className="mb-5">
|
||||
Guarde uma ideia e retome-a no seu painel. Empresa constituída,
|
||||
NUIT, documentos e verificação não são exigidos para preparar o
|
||||
@@ -64,8 +64,8 @@ function Editor(p: Props) {
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (p.record) form.put("/parcerias/" + p.record.id);
|
||||
else form.post("/parcerias/rascunhos");
|
||||
if (p.record) form.put('/parcerias/' + p.record.id);
|
||||
else form.post('/parcerias/rascunhos');
|
||||
}}
|
||||
>
|
||||
<Errors errors={form.errors} />
|
||||
@@ -73,7 +73,7 @@ function Editor(p: Props) {
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.title}
|
||||
onChange={(e) => form.setData("title", e.target.value)}
|
||||
onChange={(e) => form.setData('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<div className="grid gap-5 md:grid-cols-2">
|
||||
@@ -82,7 +82,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.organization_id}
|
||||
onChange={(e) =>
|
||||
form.setData("organization_id", e.target.value)
|
||||
form.setData('organization_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
@@ -100,7 +100,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.kind}
|
||||
onChange={(e) =>
|
||||
form.setData("kind", e.target.value)
|
||||
form.setData('kind', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="seeking">Procura</option>
|
||||
@@ -112,7 +112,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.partnership_type}
|
||||
onChange={(e) =>
|
||||
form.setData("partnership_type", e.target.value)
|
||||
form.setData('partnership_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por definir</option>
|
||||
@@ -128,7 +128,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.sector_id}
|
||||
onChange={(e) =>
|
||||
form.setData("sector_id", e.target.value)
|
||||
form.setData('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por definir</option>
|
||||
@@ -145,7 +145,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.payload.summary}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
summary: e.target.value,
|
||||
})
|
||||
@@ -156,7 +156,7 @@ function Editor(p: Props) {
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.offer}
|
||||
onChange={(e) => form.setData("offer", e.target.value)}
|
||||
onChange={(e) => form.setData('offer', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="O que procura">
|
||||
@@ -164,7 +164,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.seeking}
|
||||
onChange={(e) =>
|
||||
form.setData("seeking", e.target.value)
|
||||
form.setData('seeking', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
@@ -173,7 +173,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.payload.requirements}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
requirements: e.target.value,
|
||||
})
|
||||
@@ -198,7 +198,7 @@ function Editor(p: Props) {
|
||||
k,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
mandatory: e.target.checked
|
||||
? [
|
||||
@@ -211,7 +211,7 @@ function Editor(p: Props) {
|
||||
),
|
||||
})
|
||||
}
|
||||
/>{" "}
|
||||
/>{' '}
|
||||
{v}
|
||||
</label>
|
||||
))}
|
||||
@@ -223,7 +223,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.deadline}
|
||||
onChange={(e) =>
|
||||
form.setData("deadline", e.target.value)
|
||||
form.setData('deadline', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
@@ -232,7 +232,7 @@ function Editor(p: Props) {
|
||||
className={control}
|
||||
value={form.data.payload.confidentiality}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
confidentiality: e.target.value,
|
||||
})
|
||||
@@ -302,7 +302,7 @@ function Editor(p: Props) {
|
||||
x.role === role,
|
||||
)
|
||||
)
|
||||
form.setData("locations", [
|
||||
form.setData('locations', [
|
||||
...form.data.locations,
|
||||
{
|
||||
geo_location_id: place,
|
||||
@@ -320,14 +320,14 @@ function Editor(p: Props) {
|
||||
p.territories.find(
|
||||
(t) => t.id === l.geo_location_id,
|
||||
)?.name
|
||||
}{" "}
|
||||
· {l.role} · {l.source_reference}{" "}
|
||||
}{' '}
|
||||
· {l.role} · {l.source_reference}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
"locations",
|
||||
'locations',
|
||||
form.data.locations.filter(
|
||||
(_, j) => j !== i,
|
||||
),
|
||||
@@ -353,8 +353,8 @@ function Editor(p: Props) {
|
||||
</option>
|
||||
{p.sources?.map((x) => (
|
||||
<option
|
||||
key={x.type + ":" + x.target_id}
|
||||
value={x.type + ":" + x.target_id}
|
||||
key={x.type + ':' + x.target_id}
|
||||
value={x.type + ':' + x.target_id}
|
||||
>
|
||||
{x.title}
|
||||
</option>
|
||||
@@ -366,7 +366,7 @@ function Editor(p: Props) {
|
||||
className={button}
|
||||
disabled={!origin}
|
||||
onClick={() => {
|
||||
const [type, target_id] = origin.split(":");
|
||||
const [type, target_id] = origin.split(':');
|
||||
if (
|
||||
!form.data.origins.some(
|
||||
(x) =>
|
||||
@@ -374,7 +374,7 @@ function Editor(p: Props) {
|
||||
x.target_id === target_id,
|
||||
)
|
||||
)
|
||||
form.setData("origins", [
|
||||
form.setData('origins', [
|
||||
...form.data.origins,
|
||||
{ type, target_id },
|
||||
]);
|
||||
@@ -388,13 +388,13 @@ function Editor(p: Props) {
|
||||
(x) =>
|
||||
x.type === o.type &&
|
||||
x.target_id === o.target_id,
|
||||
)?.title ?? "Origem documental ligada"}{" "}
|
||||
)?.title ?? 'Origem documental ligada'}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
"origins",
|
||||
'origins',
|
||||
form.data.origins.filter(
|
||||
(_, j) => j !== i,
|
||||
),
|
||||
@@ -411,12 +411,12 @@ function Editor(p: Props) {
|
||||
type="checkbox"
|
||||
checked={form.data.payload.consent}
|
||||
onChange={(e) =>
|
||||
form.setData("payload", {
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
consent: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>{" "}
|
||||
/>{' '}
|
||||
Autorizo submeter o conteúdo indicado para divulgação no
|
||||
âmbito escolhido. Não confirma verificação ou certificação.
|
||||
</label>
|
||||
@@ -427,7 +427,7 @@ function Editor(p: Props) {
|
||||
{p.record && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={"/parcerias/" + p.record.id}
|
||||
href={'/parcerias/' + p.record.id}
|
||||
>
|
||||
Pré-visualizar e submeter
|
||||
</Link>
|
||||
@@ -440,7 +440,7 @@ function Editor(p: Props) {
|
||||
export default function Page(p: Props) {
|
||||
return (
|
||||
<Editor
|
||||
key={`${p.record?.id ?? "new"}:${p.record?.version ?? 0}`}
|
||||
key={`${p.record?.id ?? 'new'}:${p.record?.version ?? 0}`}
|
||||
{...p}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useForm, Link } from "@inertiajs/react";
|
||||
import { Management } from "../management/shared";
|
||||
import { Errors, button, labels } from "./shared";
|
||||
import { useForm, Link } from '@inertiajs/react';
|
||||
import { Management } from '../management/shared';
|
||||
import { Errors, button, labels } from './shared';
|
||||
type Props = {
|
||||
hash: string;
|
||||
installed: boolean;
|
||||
@@ -17,17 +17,17 @@ export default function Installation(p: Props) {
|
||||
<Management title="Aplicação da Bolsa de Parcerias">
|
||||
<div className="space-y-5">
|
||||
<p>
|
||||
Destino: {p.target.database}:{p.target.port}. Estado:{" "}
|
||||
Destino: {p.target.database}:{p.target.port}. Estado:{' '}
|
||||
{p.installed
|
||||
? "Instalada"
|
||||
: "Preparada para aplicação autenticada"}
|
||||
? 'Instalada'
|
||||
: 'Preparada para aplicação autenticada'}
|
||||
.
|
||||
</p>
|
||||
<p>
|
||||
Backup e restauro:{" "}
|
||||
{p.backupVerified ? "Comprovados" : "Pendentes"} ·{" "}
|
||||
{p.backupDate}. QA desta versão:{" "}
|
||||
{p.qaVerified ? "Comprovada" : "Pendente"}.
|
||||
Backup e restauro:{' '}
|
||||
{p.backupVerified ? 'Comprovados' : 'Pendentes'} ·{' '}
|
||||
{p.backupDate}. QA desta versão:{' '}
|
||||
{p.qaVerified ? 'Comprovada' : 'Pendente'}.
|
||||
</p>
|
||||
<ul className="list-disc pl-5">
|
||||
{p.changes.map((change) => (
|
||||
@@ -39,7 +39,7 @@ export default function Installation(p: Props) {
|
||||
</h2>
|
||||
{p.records.map((record) => (
|
||||
<p key={record.id}>
|
||||
{record.id} · {record.title} · Autor {record.user_id} ·{" "}
|
||||
{record.id} · {record.title} · Autor {record.user_id} ·{' '}
|
||||
{labels[record.status] ?? record.status}
|
||||
</p>
|
||||
))}
|
||||
@@ -47,7 +47,7 @@ export default function Installation(p: Props) {
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post("/management/partnerships-install");
|
||||
form.post('/management/partnerships-install');
|
||||
}}
|
||||
>
|
||||
<Errors errors={form.errors} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useForm, usePage, Link, router } from "@inertiajs/react";
|
||||
import { useForm, usePage, Link, router } from '@inertiajs/react';
|
||||
import {
|
||||
Frame,
|
||||
Field,
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
button,
|
||||
labels,
|
||||
type Partnership,
|
||||
} from "./shared";
|
||||
} from './shared';
|
||||
type Room = {
|
||||
id: number;
|
||||
status: string;
|
||||
@@ -52,11 +52,11 @@ type Props = {
|
||||
};
|
||||
function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
const form = useForm({
|
||||
title: item?.title ?? "",
|
||||
title: item?.title ?? '',
|
||||
responsible_id: item?.responsible_id ?? p.partnership.user_id,
|
||||
due_date: item?.due_date ?? "",
|
||||
status: item?.status ?? "pending",
|
||||
evidence: item?.evidence ?? "",
|
||||
due_date: item?.due_date ?? '',
|
||||
status: item?.status ?? 'pending',
|
||||
evidence: item?.evidence ?? '',
|
||||
version: item?.version ?? null,
|
||||
});
|
||||
return (
|
||||
@@ -76,13 +76,13 @@ function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
}}
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
{item ? "Atualizar marco" : "Acrescentar marco"}
|
||||
{item ? 'Atualizar marco' : 'Acrescentar marco'}
|
||||
</h3>
|
||||
<Field label="Entregável">
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.title}
|
||||
onChange={(e) => form.setData("title", e.target.value)}
|
||||
onChange={(e) => form.setData('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Responsável">
|
||||
@@ -90,7 +90,7 @@ function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
className={control}
|
||||
value={form.data.responsible_id}
|
||||
onChange={(e) =>
|
||||
form.setData("responsible_id", Number(e.target.value))
|
||||
form.setData('responsible_id', Number(e.target.value))
|
||||
}
|
||||
>
|
||||
<option value={p.partnership.user_id}>Proponente</option>
|
||||
@@ -102,18 +102,18 @@ function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
className={control}
|
||||
type="date"
|
||||
value={form.data.due_date}
|
||||
onChange={(e) => form.setData("due_date", e.target.value)}
|
||||
onChange={(e) => form.setData('due_date', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData("status", e.target.value)}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
>
|
||||
{["pending", "progress", "completed"].map((x) => (
|
||||
{['pending', 'progress', 'completed'].map((x) => (
|
||||
<option key={x} value={x}>
|
||||
{x === "pending" ? "Pendente" : labels[x]}
|
||||
{x === 'pending' ? 'Pendente' : labels[x]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -122,7 +122,7 @@ function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.evidence}
|
||||
onChange={(e) => form.setData("evidence", e.target.value)}
|
||||
onChange={(e) => form.setData('evidence', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Errors errors={form.errors} />
|
||||
@@ -133,17 +133,17 @@ function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
);
|
||||
}
|
||||
export default function Page(p: Props) {
|
||||
return <RoomPage key={p.room.id + ":" + p.room.version} {...p} />;
|
||||
return <RoomPage key={p.room.id + ':' + p.room.version} {...p} />;
|
||||
}
|
||||
function RoomPage(p: Props) {
|
||||
const { auth } = usePage<{ auth: { user: { id: number } } }>().props;
|
||||
const message = useForm({ body: "", client_key: crypto.randomUUID() });
|
||||
const message = useForm({ body: '', client_key: crypto.randomUUID() });
|
||||
const agreement = useForm({
|
||||
version: p.room.version,
|
||||
action: "record",
|
||||
title: p.room.agreement?.title ?? "",
|
||||
terms: p.room.agreement?.terms ?? "",
|
||||
reason: "",
|
||||
action: 'record',
|
||||
title: p.room.agreement?.title ?? '',
|
||||
terms: p.room.agreement?.terms ?? '',
|
||||
reason: '',
|
||||
});
|
||||
const upload = useForm<{ file: File | null; shared: boolean }>({
|
||||
file: null,
|
||||
@@ -156,13 +156,13 @@ function RoomPage(p: Props) {
|
||||
});
|
||||
};
|
||||
const mutable =
|
||||
p.canWrite && !["closed", "cancelled"].includes(p.room.status);
|
||||
p.canWrite && !['closed', 'cancelled'].includes(p.room.status);
|
||||
return (
|
||||
<Frame title={"Conexão privada — " + p.partnership.title}>
|
||||
<Frame title={'Conexão privada — ' + p.partnership.title}>
|
||||
<div className="space-y-6">
|
||||
<Link
|
||||
className="underline"
|
||||
href={"/parcerias/" + p.partnership.id}
|
||||
href={'/parcerias/' + p.partnership.id}
|
||||
>
|
||||
Regressar à parceria
|
||||
</Link>
|
||||
@@ -176,7 +176,7 @@ function RoomPage(p: Props) {
|
||||
Mensagens e esclarecimentos
|
||||
</h2>
|
||||
{p.messages.map((m) => (
|
||||
<article className="rounded bg-muted p-4" key={m.id}>
|
||||
<article className="bg-muted rounded p-4" key={m.id}>
|
||||
<p className="font-semibold">
|
||||
{m.name} · {m.created_at}
|
||||
</p>
|
||||
@@ -194,7 +194,7 @@ function RoomPage(p: Props) {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
message.setData({
|
||||
body: "",
|
||||
body: '',
|
||||
client_key: crypto.randomUUID(),
|
||||
});
|
||||
},
|
||||
@@ -207,7 +207,7 @@ function RoomPage(p: Props) {
|
||||
className={control}
|
||||
value={message.data.body}
|
||||
onChange={(e) =>
|
||||
message.setData("body", e.target.value)
|
||||
message.setData('body', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
@@ -234,10 +234,10 @@ function RoomPage(p: Props) {
|
||||
{p.documents.map((d) => (
|
||||
<article key={d.id}>
|
||||
<p>
|
||||
{d.file_name} ·{" "}
|
||||
{d.file_name} ·{' '}
|
||||
{d.shared
|
||||
? "Partilhado com a contraparte"
|
||||
: "Privado do autor"}{" "}
|
||||
? 'Partilhado com a contraparte'
|
||||
: 'Privado do autor'}{' '}
|
||||
· Análise: {d.malware_scan_status}
|
||||
</p>
|
||||
{mutable && d.owner_id === auth.user.id && (
|
||||
@@ -252,12 +252,12 @@ function RoomPage(p: Props) {
|
||||
}
|
||||
>
|
||||
{d.shared
|
||||
? "Retirar autorização de partilha"
|
||||
: "Autorizar partilha com a contraparte"}
|
||||
? 'Retirar autorização de partilha'
|
||||
: 'Autorizar partilha com a contraparte'}
|
||||
</button>
|
||||
)}
|
||||
{d.status === "active" &&
|
||||
d.malware_scan_status === "clean" && (
|
||||
{d.status === 'active' &&
|
||||
d.malware_scan_status === 'clean' && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/parcerias/salas/${p.room.id}/documentos/${d.id}`}
|
||||
@@ -284,11 +284,11 @@ function RoomPage(p: Props) {
|
||||
<Field label="Anexar PDF ou imagem">
|
||||
<input
|
||||
type="file"
|
||||
className="w-full min-w-0 max-w-full"
|
||||
className="w-full max-w-full min-w-0"
|
||||
accept=".pdf,.jpg,.jpeg,.png"
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
"file",
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
@@ -300,11 +300,11 @@ function RoomPage(p: Props) {
|
||||
checked={upload.data.shared}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
"shared",
|
||||
'shared',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>{" "}
|
||||
/>{' '}
|
||||
Autorizo a consulta pela contraparte desta sala.
|
||||
</label>
|
||||
<Errors errors={upload.errors} />
|
||||
@@ -339,13 +339,13 @@ function RoomPage(p: Props) {
|
||||
{p.room.agreement.terms}
|
||||
</p>
|
||||
<p>
|
||||
Confirmações:{" "}
|
||||
Confirmações:{' '}
|
||||
{Object.entries(p.room.agreement.confirmations)
|
||||
.map(
|
||||
([party, c]) =>
|
||||
`${party}: autor ${c.actor_id}, ${c.date}`,
|
||||
)
|
||||
.join("; ") || "Pendentes"}
|
||||
.join('; ') || 'Pendentes'}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
@@ -357,13 +357,13 @@ function RoomPage(p: Props) {
|
||||
value={agreement.data.reason}
|
||||
onChange={(e) =>
|
||||
agreement.setData(
|
||||
"reason",
|
||||
'reason',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{["negotiation", "agreement_recorded"].includes(
|
||||
{['negotiation', 'agreement_recorded'].includes(
|
||||
p.room.status,
|
||||
) && (
|
||||
<>
|
||||
@@ -373,7 +373,7 @@ function RoomPage(p: Props) {
|
||||
value={agreement.data.title}
|
||||
onChange={(e) =>
|
||||
agreement.setData(
|
||||
"title",
|
||||
'title',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
@@ -386,7 +386,7 @@ function RoomPage(p: Props) {
|
||||
value={agreement.data.terms}
|
||||
onChange={(e) =>
|
||||
agreement.setData(
|
||||
"terms",
|
||||
'terms',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
@@ -398,50 +398,50 @@ function RoomPage(p: Props) {
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act("record")}
|
||||
onClick={() => act('record')}
|
||||
>
|
||||
Registar versão do acordo
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{p.room.status === "agreement_recorded" && (
|
||||
{p.room.status === 'agreement_recorded' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act("confirm")}
|
||||
onClick={() => act('confirm')}
|
||||
>
|
||||
Confirmar pela minha parte
|
||||
</button>
|
||||
)}
|
||||
{p.room.status === "agreed" && (
|
||||
{p.room.status === 'agreed' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act("start")}
|
||||
onClick={() => act('start')}
|
||||
>
|
||||
Iniciar acompanhamento
|
||||
</button>
|
||||
)}
|
||||
{p.room.status === "execution" && (
|
||||
{p.room.status === 'execution' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act("complete")}
|
||||
onClick={() => act('complete')}
|
||||
>
|
||||
Concluir após os marcos
|
||||
</button>
|
||||
)}
|
||||
{["agreed", "execution"].includes(
|
||||
{['agreed', 'execution'].includes(
|
||||
p.room.status,
|
||||
) && (
|
||||
<button
|
||||
@@ -450,7 +450,7 @@ function RoomPage(p: Props) {
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act("renew")}
|
||||
onClick={() => act('renew')}
|
||||
>
|
||||
Registar renovação
|
||||
</button>
|
||||
@@ -461,7 +461,7 @@ function RoomPage(p: Props) {
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act("cancel")}
|
||||
onClick={() => act('cancel')}
|
||||
>
|
||||
Cancelar conexão com motivo
|
||||
</button>
|
||||
@@ -473,29 +473,32 @@ function RoomPage(p: Props) {
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-xl font-bold">Marcos e responsáveis</h2>
|
||||
<p>
|
||||
Participação atual:{" "}
|
||||
Participação atual:{' '}
|
||||
{auth.user.id === p.partnership.user_id
|
||||
? "Proponente"
|
||||
? 'Proponente'
|
||||
: auth.user.id === p.interest.user_id
|
||||
? "Candidato"
|
||||
: "Representante autorizado"}
|
||||
? 'Candidato'
|
||||
: 'Representante autorizado'}
|
||||
.
|
||||
</p>
|
||||
{p.milestones.map((m) => (
|
||||
<article
|
||||
key={m.id + ":" + m.version}
|
||||
key={m.id + ':' + m.version}
|
||||
className="space-y-3"
|
||||
>
|
||||
<p>
|
||||
{m.title} · {m.status === "pending" ? "Pendente" : labels[m.status]} · Prazo:{" "}
|
||||
{m.due_date ?? "Pendente"} · Responsável ID{" "}
|
||||
{m.responsible_id}
|
||||
{m.title} ·{' '}
|
||||
{m.status === 'pending'
|
||||
? 'Pendente'
|
||||
: labels[m.status]}{' '}
|
||||
· Prazo: {m.due_date ?? 'Pendente'} ·
|
||||
Responsável ID {m.responsible_id}
|
||||
</p>
|
||||
{mutable && <MilestoneForm p={p} item={m} />}
|
||||
</article>
|
||||
))}
|
||||
{mutable &&
|
||||
["agreement_recorded", "agreed", "execution"].includes(
|
||||
['agreement_recorded', 'agreed', 'execution'].includes(
|
||||
p.room.status,
|
||||
) && <MilestoneForm p={p} />}
|
||||
</section>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Link } from "@inertiajs/react";
|
||||
import { cloneElement, isValidElement, useId, type ReactNode } from "react";
|
||||
import { Layout } from "../portfolio/shared";
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { cloneElement, isValidElement, useId, type ReactNode } from 'react';
|
||||
import { Layout } from '../portfolio/shared';
|
||||
|
||||
export type Option = { id: string | number; name: string };
|
||||
export type Territory = {
|
||||
@@ -79,32 +79,32 @@ export type Interest = {
|
||||
room_id: number | null;
|
||||
};
|
||||
export const labels: Record<string, string> = {
|
||||
draft: "Rascunho",
|
||||
pending: "Submetida — legado",
|
||||
submitted: "Submetida",
|
||||
returned: "Devolvida",
|
||||
rejected: "Rejeitada",
|
||||
published: "Publicada",
|
||||
suspended: "Suspensa",
|
||||
archived: "Arquivada",
|
||||
withdrawn: "Retirada",
|
||||
clarification: "Em esclarecimento",
|
||||
shortlisted: "Lista curta",
|
||||
negotiation: "Em negociação",
|
||||
agreement_recorded: "Acordo registado",
|
||||
agreed: "Confirmado pelas partes",
|
||||
execution: "Em execução",
|
||||
closed: "Concluída",
|
||||
cancelled: "Cancelada",
|
||||
progress: "Em curso",
|
||||
completed: "Concluído",
|
||||
met: "Comprovadamente cumprido",
|
||||
unmet: "Comprovadamente incumprido",
|
||||
unknown: "Informação insuficiente",
|
||||
draft: 'Rascunho',
|
||||
pending: 'Submetida — legado',
|
||||
submitted: 'Submetida',
|
||||
returned: 'Devolvida',
|
||||
rejected: 'Rejeitada',
|
||||
published: 'Publicada',
|
||||
suspended: 'Suspensa',
|
||||
archived: 'Arquivada',
|
||||
withdrawn: 'Retirada',
|
||||
clarification: 'Em esclarecimento',
|
||||
shortlisted: 'Lista curta',
|
||||
negotiation: 'Em negociação',
|
||||
agreement_recorded: 'Acordo registado',
|
||||
agreed: 'Confirmado pelas partes',
|
||||
execution: 'Em execução',
|
||||
closed: 'Concluída',
|
||||
cancelled: 'Cancelada',
|
||||
progress: 'Em curso',
|
||||
completed: 'Concluído',
|
||||
met: 'Comprovadamente cumprido',
|
||||
unmet: 'Comprovadamente incumprido',
|
||||
unknown: 'Informação insuficiente',
|
||||
};
|
||||
export const control = "w-full rounded border bg-background p-2";
|
||||
export const control = 'w-full rounded border bg-background p-2';
|
||||
export const button =
|
||||
"inline-flex rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50";
|
||||
'inline-flex rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50';
|
||||
export function Frame({
|
||||
title,
|
||||
children,
|
||||
@@ -151,8 +151,8 @@ export function Field({
|
||||
<span id={id} className="font-medium">
|
||||
{label}
|
||||
</span>
|
||||
{isValidElement<{ "aria-labelledby"?: string }>(children)
|
||||
? cloneElement(children, { "aria-labelledby": id })
|
||||
{isValidElement<{ 'aria-labelledby'?: string }>(children)
|
||||
? cloneElement(children, { 'aria-labelledby': id })
|
||||
: children}
|
||||
</label>
|
||||
);
|
||||
|
||||
@@ -37,20 +37,34 @@ type DocumentResource = {
|
||||
|
||||
const modulePaths: Record<string, { href: string; label: string }> = {
|
||||
simulator: { href: '/Simulador', label: 'Simulador fiscal' },
|
||||
investment: { href: '/oportunidades', label: 'Oportunidades de investimento' },
|
||||
investment: {
|
||||
href: '/oportunidades',
|
||||
label: 'Oportunidades de investimento',
|
||||
},
|
||||
zones: { href: '/zonas', label: 'ZEE, ZFI e parques industriais' },
|
||||
education: { href: '/educacao', label: 'Educação e competências' },
|
||||
business: { href: '/negocios', label: 'Negócios' },
|
||||
land: { href: '/investidor/terra-duat', label: 'Terra e DUAT' },
|
||||
};
|
||||
const documentTypeLabels: Record<string, string> = {
|
||||
legislation: 'Legislação', procedure: 'Procedimento oficial', official_form: 'Formulário oficial',
|
||||
digital_adaptation: 'Adaptação digital de formulário', guidance_template: 'Modelo orientativo',
|
||||
guide: 'Guia', study: 'Estudo', reference_data: 'Dados de referência', unknown: 'Tipo por classificar',
|
||||
legislation: 'Legislação',
|
||||
procedure: 'Procedimento oficial',
|
||||
official_form: 'Formulário oficial',
|
||||
digital_adaptation: 'Adaptação digital de formulário',
|
||||
guidance_template: 'Modelo orientativo',
|
||||
guide: 'Guia',
|
||||
study: 'Estudo',
|
||||
reference_data: 'Dados de referência',
|
||||
unknown: 'Tipo por classificar',
|
||||
};
|
||||
const legalStatusLabels: Record<string, string> = {
|
||||
not_applicable: 'Não aplicável', in_force: 'Vigência indicada; confirme o período', historical: 'Histórico',
|
||||
proposed: 'Proposta; não é norma vigente', repealed: 'Revogada', amended: 'Alterada; consulte alterações posteriores', unknown: 'Por confirmar',
|
||||
not_applicable: 'Não aplicável',
|
||||
in_force: 'Vigência indicada; confirme o período',
|
||||
historical: 'Histórico',
|
||||
proposed: 'Proposta; não é norma vigente',
|
||||
repealed: 'Revogada',
|
||||
amended: 'Alterada; consulte alterações posteriores',
|
||||
unknown: 'Por confirmar',
|
||||
};
|
||||
|
||||
export default function DocumentPage({
|
||||
@@ -67,46 +81,220 @@ export default function DocumentPage({
|
||||
<Head title={resource.title} />
|
||||
<PortalMenu />
|
||||
<main className="mx-auto max-w-4xl space-y-6 px-5 py-10">
|
||||
<Link className="underline" href={backUrl}>← Voltar à pesquisa</Link>
|
||||
<Link className="underline" href={backUrl}>
|
||||
← Voltar à pesquisa
|
||||
</Link>
|
||||
<article className="space-y-5 rounded-xl border bg-white p-5 sm:p-8">
|
||||
<header className="space-y-2">
|
||||
<p className="text-sm text-slate-600">{resource.category} · {resource.topic}</p>
|
||||
<h1 className="break-words text-3xl font-bold">{resource.title}</h1>
|
||||
{resource.description && <p className="whitespace-pre-line">{resource.description}</p>}
|
||||
<p className="text-sm text-slate-600">
|
||||
{resource.category} · {resource.topic}
|
||||
</p>
|
||||
<h1 className="text-3xl font-bold break-words">
|
||||
{resource.title}
|
||||
</h1>
|
||||
{resource.description && (
|
||||
<p className="whitespace-pre-line">
|
||||
{resource.description}
|
||||
</p>
|
||||
)}
|
||||
</header>
|
||||
<dl className="grid gap-4 sm:grid-cols-2">
|
||||
<div><dt className="font-semibold">Tipo documental</dt><dd>{documentTypeLabels[resource.document_type] ?? resource.document_type}</dd></div>
|
||||
<div><dt className="font-semibold">Entidade emitente / autor</dt><dd>{resource.issuer ?? 'Não indicada'}</dd></div>
|
||||
<div><dt className="font-semibold">Número e data</dt><dd>{[resource.document_number, resource.document_date].filter(Boolean).join(' · ') || 'Não indicados'}</dd></div>
|
||||
<div><dt className="font-semibold">Período de aplicação documentado</dt><dd>{resource.applicable_from || resource.applicable_until ? `${resource.applicable_from ?? 'Início não indicado'} — ${resource.applicable_until ?? 'Sem data final indicada'}` : 'Não registado'}</dd></div>
|
||||
<div><dt className="font-semibold">Versão e idioma</dt><dd>{resource.version_label ?? 'Versão não indicada'} · {resource.language}</dd></div>
|
||||
<div><dt className="font-semibold">Âmbito</dt><dd>{resource.territorial_scope === 'national' ? 'Nacional' : resource.territory_name ?? 'Por confirmar'}</dd></div>
|
||||
<div><dt className="font-semibold">Situação documental</dt><dd>{legalStatusLabels[resource.legal_status] ?? resource.legal_status}</dd></div>
|
||||
<div><dt className="font-semibold">Fonte</dt><dd>{resource.source_confirmation === 'official_confirmed' ? 'Fonte oficial confirmada' : resource.source_confirmation === 'identified' ? 'Origem identificada' : 'Por confirmar'}</dd></div>
|
||||
<div>
|
||||
<dt className="font-semibold">Tipo documental</dt>
|
||||
<dd>
|
||||
{documentTypeLabels[resource.document_type] ??
|
||||
resource.document_type}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Entidade emitente / autor
|
||||
</dt>
|
||||
<dd>{resource.issuer ?? 'Não indicada'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Número e data</dt>
|
||||
<dd>
|
||||
{[
|
||||
resource.document_number,
|
||||
resource.document_date,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || 'Não indicados'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Período de aplicação documentado
|
||||
</dt>
|
||||
<dd>
|
||||
{resource.applicable_from ||
|
||||
resource.applicable_until
|
||||
? `${resource.applicable_from ?? 'Início não indicado'} — ${resource.applicable_until ?? 'Sem data final indicada'}`
|
||||
: 'Não registado'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Versão e idioma</dt>
|
||||
<dd>
|
||||
{resource.version_label ??
|
||||
'Versão não indicada'}{' '}
|
||||
· {resource.language}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Âmbito</dt>
|
||||
<dd>
|
||||
{resource.territorial_scope === 'national'
|
||||
? 'Nacional'
|
||||
: (resource.territory_name ??
|
||||
'Por confirmar')}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Situação documental
|
||||
</dt>
|
||||
<dd>
|
||||
{legalStatusLabels[resource.legal_status] ??
|
||||
resource.legal_status}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Fonte</dt>
|
||||
<dd>
|
||||
{resource.source_confirmation ===
|
||||
'official_confirmed'
|
||||
? 'Fonte oficial confirmada'
|
||||
: resource.source_confirmation ===
|
||||
'identified'
|
||||
? 'Origem identificada'
|
||||
: 'Por confirmar'}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{resource.source_confirmation === 'identified' && <p className="rounded border border-amber-300 bg-amber-50 p-3" role="note">A origem está identificada, mas a autenticidade desta cópia não foi confirmada independentemente. Consulte a fonte indicada.</p>}
|
||||
<p className="break-words text-sm">Referência: {resource.source_reference}</p>
|
||||
{resource.links.length > 0 && <section className="space-y-2">
|
||||
<h2 className="text-xl font-semibold">Base legal e documentos relacionados no portal</h2>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
{resource.links.map((link, index) => {
|
||||
const destination = link.target_type === 'module' ? modulePaths[link.target_key] : undefined;
|
||||
return <li key={`${link.target_type}-${link.target_key}-${index}`}>
|
||||
{destination ? <Link className="underline" href={destination.href}>{destination.label}</Link> : <span>{link.target_type === 'requirement' ? `Requisito documental: ${link.target_label ?? link.target_key}` : `${link.target_type}: ${link.target_key}`}</span>}
|
||||
{' · '}{link.applicability === 'evidence' ? 'evidência documental' : link.applicability}
|
||||
{link.condition_text && <span> · Condição: {link.condition_text}</span>}
|
||||
{link.basis_reference && <span> · Referência documental (não é regra fiscal): {link.basis_reference}</span>}
|
||||
{link.review_status === 'confirmed' ? <span> · Citação conferida no ficheiro; aplicação fiscal pendente</span> : <span> · Pendente de conferência; não constitui fundamento confirmado</span>}
|
||||
</li>;
|
||||
})}
|
||||
</ul>
|
||||
</section>}
|
||||
{resource.source_confirmation === 'identified' && (
|
||||
<p
|
||||
className="rounded border border-amber-300 bg-amber-50 p-3"
|
||||
role="note"
|
||||
>
|
||||
A origem está identificada, mas a autenticidade
|
||||
desta cópia não foi confirmada independentemente.
|
||||
Consulte a fonte indicada.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm break-words">
|
||||
Referência: {resource.source_reference}
|
||||
</p>
|
||||
{resource.links.length > 0 && (
|
||||
<section className="space-y-2">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Base legal e documentos relacionados no portal
|
||||
</h2>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
{resource.links.map((link, index) => {
|
||||
const destination =
|
||||
link.target_type === 'module'
|
||||
? modulePaths[link.target_key]
|
||||
: undefined;
|
||||
return (
|
||||
<li
|
||||
key={`${link.target_type}-${link.target_key}-${index}`}
|
||||
>
|
||||
{destination ? (
|
||||
<Link
|
||||
className="underline"
|
||||
href={destination.href}
|
||||
>
|
||||
{destination.label}
|
||||
</Link>
|
||||
) : (
|
||||
<span>
|
||||
{link.target_type ===
|
||||
'requirement'
|
||||
? `Requisito documental: ${link.target_label ?? link.target_key}`
|
||||
: `${link.target_type}: ${link.target_key}`}
|
||||
</span>
|
||||
)}
|
||||
{' · '}
|
||||
{link.applicability === 'evidence'
|
||||
? 'evidência documental'
|
||||
: link.applicability}
|
||||
{link.condition_text && (
|
||||
<span>
|
||||
{' '}
|
||||
· Condição:{' '}
|
||||
{link.condition_text}
|
||||
</span>
|
||||
)}
|
||||
{link.basis_reference && (
|
||||
<span>
|
||||
{' '}
|
||||
· Referência documental (não
|
||||
é regra fiscal):{' '}
|
||||
{link.basis_reference}
|
||||
</span>
|
||||
)}
|
||||
{link.review_status ===
|
||||
'confirmed' ? (
|
||||
<span>
|
||||
{' '}
|
||||
· Citação conferida no
|
||||
ficheiro; aplicação fiscal
|
||||
pendente
|
||||
</span>
|
||||
) : (
|
||||
<span>
|
||||
{' '}
|
||||
· Pendente de conferência;
|
||||
não constitui fundamento
|
||||
confirmado
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3 border-t pt-4">
|
||||
<a className="rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white" href={downloadUrl}>Descarregar ficheiro ({resource.file_name}{resource.size_bytes ? ` · ${Math.ceil(resource.size_bytes / 1024)} KB` : ''})</a>
|
||||
{resource.view_url && <a className="rounded-lg border px-5 py-3 font-semibold underline" href={resource.view_url} target="_blank" rel="noreferrer">Consultar ficheiro</a>}
|
||||
{resource.source_url && <a className="rounded-lg border px-5 py-3 font-semibold underline" href={resource.source_url} target="_blank" rel="noreferrer">Abrir fonte identificada</a>}
|
||||
<a
|
||||
className="rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white"
|
||||
href={downloadUrl}
|
||||
>
|
||||
Descarregar ficheiro ({resource.file_name}
|
||||
{resource.size_bytes
|
||||
? ` · ${Math.ceil(resource.size_bytes / 1024)} KB`
|
||||
: ''}
|
||||
)
|
||||
</a>
|
||||
{resource.view_url && (
|
||||
<a
|
||||
className="rounded-lg border px-5 py-3 font-semibold underline"
|
||||
href={resource.view_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Consultar ficheiro
|
||||
</a>
|
||||
)}
|
||||
{resource.source_url && (
|
||||
<a
|
||||
className="rounded-lg border px-5 py-3 font-semibold underline"
|
||||
href={resource.source_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Abrir fonte identificada
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-slate-600">A disponibilização desta referência não certifica vigência, elegibilidade, viabilidade ou aprovação oficial. Consulte o diploma ou a entidade competente para confirmar a sua aplicação ao caso concreto.</p>
|
||||
<p className="text-sm text-slate-600">
|
||||
A disponibilização desta referência não certifica
|
||||
vigência, elegibilidade, viabilidade ou aprovação
|
||||
oficial. Consulte o diploma ou a entidade competente
|
||||
para confirmar a sua aplicação ao caso concreto.
|
||||
</p>
|
||||
</article>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -24,13 +24,24 @@ const titles: Record<string, string> = {
|
||||
desk: 'Balcão Virtual',
|
||||
};
|
||||
const documentTypeLabels: Record<string, string> = {
|
||||
legislation: 'Legislação', procedure: 'Procedimento oficial', official_form: 'Formulário oficial',
|
||||
digital_adaptation: 'Adaptação digital de formulário', guidance_template: 'Modelo orientativo',
|
||||
guide: 'Guia', study: 'Estudo', reference_data: 'Dados de referência', unknown: 'Tipo por classificar',
|
||||
legislation: 'Legislação',
|
||||
procedure: 'Procedimento oficial',
|
||||
official_form: 'Formulário oficial',
|
||||
digital_adaptation: 'Adaptação digital de formulário',
|
||||
guidance_template: 'Modelo orientativo',
|
||||
guide: 'Guia',
|
||||
study: 'Estudo',
|
||||
reference_data: 'Dados de referência',
|
||||
unknown: 'Tipo por classificar',
|
||||
};
|
||||
const legalStatusLabels: Record<string, string> = {
|
||||
not_applicable: 'Não aplicável', in_force: 'Vigência indicada; confirme o período', historical: 'Histórico',
|
||||
proposed: 'Proposta; não é norma vigente', repealed: 'Revogada', amended: 'Alterada; consulte alterações posteriores', unknown: 'Por confirmar',
|
||||
not_applicable: 'Não aplicável',
|
||||
in_force: 'Vigência indicada; confirme o período',
|
||||
historical: 'Histórico',
|
||||
proposed: 'Proposta; não é norma vigente',
|
||||
repealed: 'Revogada',
|
||||
amended: 'Alterada; consulte alterações posteriores',
|
||||
unknown: 'Por confirmar',
|
||||
};
|
||||
type Resource = {
|
||||
id: number;
|
||||
@@ -410,7 +421,13 @@ function PartnershipForm() {
|
||||
function Simulator() {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<p><Link href="/como-investir" className="underline">Voltar ao roteiro de investimento</Link> para rever mercado, localização, recursos, formalização e execução.</p>
|
||||
<p>
|
||||
<Link href="/como-investir" className="underline">
|
||||
Voltar ao roteiro de investimento
|
||||
</Link>{' '}
|
||||
para rever mercado, localização, recursos, formalização e
|
||||
execução.
|
||||
</p>
|
||||
<SimulationForm />
|
||||
</div>
|
||||
);
|
||||
@@ -455,13 +472,41 @@ export default function Services(p: Props) {
|
||||
});
|
||||
const [selectedPartner, setSelectedPartner] = useState<number>();
|
||||
const title = p.sector?.name ?? titles[p.section];
|
||||
const formTypes = ['official_form', 'digital_adaptation', 'guidance_template'];
|
||||
const firstFormIndex = p.resources?.data.findIndex((resource) => formTypes.includes(resource.document_type)) ?? -1;
|
||||
const activeFilterNames: Record<string, string> = { q: 'Texto', topic: 'Assunto', category: 'Categoria', document_type: 'Tipo', activity: 'Actividade', stage: 'Etapa', module: 'Módulo', issuer: 'Emitente', language: 'Idioma', legal_status: 'Situação', source_confirmation: 'Fonte', territory_id: 'Território' };
|
||||
const activeFilters = Object.entries(filter.data).flatMap(([key, value]) => {
|
||||
const text = Array.isArray(value) ? value.join(', ') : typeof value === 'string' ? value : '';
|
||||
return activeFilterNames[key] && text.trim() ? [`${activeFilterNames[key]}: ${text}`] : [];
|
||||
});
|
||||
const formTypes = [
|
||||
'official_form',
|
||||
'digital_adaptation',
|
||||
'guidance_template',
|
||||
];
|
||||
const firstFormIndex =
|
||||
p.resources?.data.findIndex((resource) =>
|
||||
formTypes.includes(resource.document_type),
|
||||
) ?? -1;
|
||||
const activeFilterNames: Record<string, string> = {
|
||||
q: 'Texto',
|
||||
topic: 'Assunto',
|
||||
category: 'Categoria',
|
||||
document_type: 'Tipo',
|
||||
activity: 'Actividade',
|
||||
stage: 'Etapa',
|
||||
module: 'Módulo',
|
||||
issuer: 'Emitente',
|
||||
language: 'Idioma',
|
||||
legal_status: 'Situação',
|
||||
source_confirmation: 'Fonte',
|
||||
territory_id: 'Território',
|
||||
};
|
||||
const activeFilters = Object.entries(filter.data).flatMap(
|
||||
([key, value]) => {
|
||||
const text = Array.isArray(value)
|
||||
? value.join(', ')
|
||||
: typeof value === 'string'
|
||||
? value
|
||||
: '';
|
||||
return activeFilterNames[key] && text.trim()
|
||||
? [`${activeFilterNames[key]}: ${text}`]
|
||||
: [];
|
||||
},
|
||||
);
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title={title} />
|
||||
@@ -629,24 +674,124 @@ export default function Services(p: Props) {
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!!p.activities?.length && <fieldset className="min-w-0 rounded border p-3">
|
||||
<legend className="px-1">Actividade ou CAE</legend>
|
||||
<div className="max-h-36 space-y-2 overflow-y-auto">
|
||||
{p.activities.map((activity) => <label key={activity} className="flex items-start gap-2 break-words"><input type="checkbox" checked={filter.data.activity.includes(activity)} onChange={(e) => filter.setData('activity', e.target.checked ? [...filter.data.activity, activity] : filter.data.activity.filter((value) => value !== activity))} /><span>{activity}</span></label>)}
|
||||
</div>
|
||||
</fieldset>}
|
||||
{!!p.stages?.length && <fieldset className="min-w-0 rounded border p-3">
|
||||
<legend className="px-1">Etapa do projecto</legend>
|
||||
<div className="max-h-36 space-y-2 overflow-y-auto">
|
||||
{p.stages.map((stage) => <label key={stage} className="flex items-start gap-2 break-words"><input type="checkbox" checked={filter.data.stage.includes(stage)} onChange={(e) => filter.setData('stage', e.target.checked ? [...filter.data.stage, stage] : filter.data.stage.filter((value) => value !== stage))} /><span>{stage}</span></label>)}
|
||||
</div>
|
||||
</fieldset>}
|
||||
{!!p.modules?.length && <fieldset className="min-w-0 rounded border p-3">
|
||||
<legend className="px-1">Módulo</legend>
|
||||
<div className="max-h-36 space-y-2 overflow-y-auto">
|
||||
{p.modules.map((module) => <label key={module} className="flex items-start gap-2 break-words"><input type="checkbox" checked={filter.data.module.includes(module)} onChange={(e) => filter.setData('module', e.target.checked ? [...filter.data.module, module] : filter.data.module.filter((value) => value !== module))} /><span>{module}</span></label>)}
|
||||
</div>
|
||||
</fieldset>}
|
||||
{!!p.activities?.length && (
|
||||
<fieldset className="min-w-0 rounded border p-3">
|
||||
<legend className="px-1">
|
||||
Actividade ou CAE
|
||||
</legend>
|
||||
<div className="max-h-36 space-y-2 overflow-y-auto">
|
||||
{p.activities.map((activity) => (
|
||||
<label
|
||||
key={activity}
|
||||
className="flex items-start gap-2 break-words"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filter.data.activity.includes(
|
||||
activity,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
filter.setData(
|
||||
'activity',
|
||||
e.target.checked
|
||||
? [
|
||||
...filter
|
||||
.data
|
||||
.activity,
|
||||
activity,
|
||||
]
|
||||
: filter.data.activity.filter(
|
||||
(value) =>
|
||||
value !==
|
||||
activity,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{activity}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
{!!p.stages?.length && (
|
||||
<fieldset className="min-w-0 rounded border p-3">
|
||||
<legend className="px-1">
|
||||
Etapa do projecto
|
||||
</legend>
|
||||
<div className="max-h-36 space-y-2 overflow-y-auto">
|
||||
{p.stages.map((stage) => (
|
||||
<label
|
||||
key={stage}
|
||||
className="flex items-start gap-2 break-words"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filter.data.stage.includes(
|
||||
stage,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
filter.setData(
|
||||
'stage',
|
||||
e.target.checked
|
||||
? [
|
||||
...filter
|
||||
.data
|
||||
.stage,
|
||||
stage,
|
||||
]
|
||||
: filter.data.stage.filter(
|
||||
(value) =>
|
||||
value !==
|
||||
stage,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{stage}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
{!!p.modules?.length && (
|
||||
<fieldset className="min-w-0 rounded border p-3">
|
||||
<legend className="px-1">Módulo</legend>
|
||||
<div className="max-h-36 space-y-2 overflow-y-auto">
|
||||
{p.modules.map((module) => (
|
||||
<label
|
||||
key={module}
|
||||
className="flex items-start gap-2 break-words"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filter.data.module.includes(
|
||||
module,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
filter.setData(
|
||||
'module',
|
||||
e.target.checked
|
||||
? [
|
||||
...filter
|
||||
.data
|
||||
.module,
|
||||
module,
|
||||
]
|
||||
: filter.data.module.filter(
|
||||
(value) =>
|
||||
value !==
|
||||
module,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{module}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
<label className="block min-w-0">
|
||||
Entidade emitente
|
||||
<select
|
||||
@@ -763,188 +908,281 @@ export default function Services(p: Props) {
|
||||
Limpar filtros
|
||||
</Link>
|
||||
</form>
|
||||
{activeFilters.length > 0 && <section aria-label="Filtros activos" className="rounded border bg-white p-3">
|
||||
<h2 className="font-semibold">Filtros activos</h2>
|
||||
<ul className="flex flex-wrap gap-2">{activeFilters.map((item) => <li key={item} className="rounded-full bg-slate-100 px-3 py-1 text-sm">{item}</li>)}</ul>
|
||||
</section>}
|
||||
<p role="status" aria-live="polite">{p.resources?.total ?? 0} documentos correspondem aos filtros activos.</p>
|
||||
{!!p.topics?.length && <nav aria-label="Navegar por assunto" className="flex flex-wrap gap-2">
|
||||
<span className="font-semibold">Assuntos:</span>
|
||||
{p.topics.map((topic) => <Link key={topic} className="rounded-full border bg-white px-3 py-1 underline" href={`${p.section === 'documents' ? '/documentos' : '/legislacao'}?${new URLSearchParams({ topic }).toString()}`}>{topic}</Link>)}
|
||||
</nav>}
|
||||
<p className="text-sm">Os documentos nacionais aplicáveis continuam incluídos numa pesquisa territorial e são identificados como nacionais. A localização da entidade emitente não define o âmbito de aplicação.</p>
|
||||
{p.resources?.data.map((r, index) => (
|
||||
<div key={r.id} className="contents">{index === 0 && <h2 className="pt-4 text-xl font-bold">{firstFormIndex === 0 ? 'Formulários e modelos' : 'Documentos de consulta'}</h2>}{index === firstFormIndex && firstFormIndex > 0 && <h2 className="pt-4 text-xl font-bold">Formulários e modelos</h2>}
|
||||
<article
|
||||
key={r.id}
|
||||
className="min-w-0 space-y-2 overflow-hidden rounded-xl border bg-white p-5"
|
||||
{activeFilters.length > 0 && (
|
||||
<section
|
||||
aria-label="Filtros activos"
|
||||
className="rounded border bg-white p-3"
|
||||
>
|
||||
<h2 className="text-xl font-bold break-words">
|
||||
{r.title}
|
||||
{r.essential ? ' · Essencial' : ''}
|
||||
<h2 className="font-semibold">
|
||||
Filtros activos
|
||||
</h2>
|
||||
<p>
|
||||
{documentTypeLabels[r.document_type] ?? r.document_type} · {r.category} · {r.topic}
|
||||
</p>
|
||||
{r.description && <p>{r.description}</p>}
|
||||
<dl className="grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Entidade emitente
|
||||
</dt>
|
||||
<dd>{r.issuer ?? 'Não indicada'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Número e data
|
||||
</dt>
|
||||
<dd>
|
||||
{[
|
||||
r.document_number,
|
||||
r.document_date,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || 'Não indicados'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Versão / idioma
|
||||
</dt>
|
||||
<dd>
|
||||
{r.version_label ??
|
||||
'Versão não indicada'}{' '}
|
||||
· {r.language}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Período de aplicação documentado</dt>
|
||||
<dd>{r.applicable_from || r.applicable_until ? `${r.applicable_from ?? 'Início não indicado'} — ${r.applicable_until ?? 'Sem data final indicada'}` : 'Não registado'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Âmbito
|
||||
</dt>
|
||||
<dd>
|
||||
{r.territorial_scope === 'national'
|
||||
? 'Nacional'
|
||||
: r.territorial_scope ===
|
||||
'unknown'
|
||||
? 'Por confirmar'
|
||||
: r.territorial_scope}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Fonte</dt>
|
||||
<dd>
|
||||
{r.source_confirmation ===
|
||||
'official_confirmed'
|
||||
? 'Fonte oficial confirmada'
|
||||
: r.source_confirmation ===
|
||||
'identified'
|
||||
? 'Origem identificada'
|
||||
: 'Fonte por confirmar'}
|
||||
</dd>
|
||||
</div>
|
||||
{r.source_confirmation === 'identified' && (
|
||||
<div className="sm:col-span-2 rounded border border-amber-300 bg-amber-50 p-3" role="note">
|
||||
A origem está identificada, mas a autenticidade desta cópia não foi confirmada independentemente. Consulte a fonte indicada.
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{activeFilters.map((item) => (
|
||||
<li
|
||||
key={item}
|
||||
className="rounded-full bg-slate-100 px-3 py-1 text-sm"
|
||||
>
|
||||
{item}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
<p role="status" aria-live="polite">
|
||||
{p.resources?.total ?? 0} documentos correspondem
|
||||
aos filtros activos.
|
||||
</p>
|
||||
{!!p.topics?.length && (
|
||||
<nav
|
||||
aria-label="Navegar por assunto"
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
<span className="font-semibold">Assuntos:</span>
|
||||
{p.topics.map((topic) => (
|
||||
<Link
|
||||
key={topic}
|
||||
className="rounded-full border bg-white px-3 py-1 underline"
|
||||
href={`${p.section === 'documents' ? '/documentos' : '/legislacao'}?${new URLSearchParams({ topic }).toString()}`}
|
||||
>
|
||||
{topic}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
Os documentos nacionais aplicáveis continuam
|
||||
incluídos numa pesquisa territorial e são
|
||||
identificados como nacionais. A localização da
|
||||
entidade emitente não define o âmbito de aplicação.
|
||||
</p>
|
||||
{p.resources?.data.map((r, index) => (
|
||||
<div key={r.id} className="contents">
|
||||
{index === 0 && (
|
||||
<h2 className="pt-4 text-xl font-bold">
|
||||
{firstFormIndex === 0
|
||||
? 'Formulários e modelos'
|
||||
: 'Documentos de consulta'}
|
||||
</h2>
|
||||
)}
|
||||
{index === firstFormIndex &&
|
||||
firstFormIndex > 0 && (
|
||||
<h2 className="pt-4 text-xl font-bold">
|
||||
Formulários e modelos
|
||||
</h2>
|
||||
)}
|
||||
<article
|
||||
key={r.id}
|
||||
className="min-w-0 space-y-2 overflow-hidden rounded-xl border bg-white p-5"
|
||||
>
|
||||
<h2 className="text-xl font-bold break-words">
|
||||
{r.title}
|
||||
{r.essential ? ' · Essencial' : ''}
|
||||
</h2>
|
||||
<p>
|
||||
{documentTypeLabels[r.document_type] ??
|
||||
r.document_type}{' '}
|
||||
· {r.category} · {r.topic}
|
||||
</p>
|
||||
{r.description && <p>{r.description}</p>}
|
||||
<dl className="grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Entidade emitente
|
||||
</dt>
|
||||
<dd>
|
||||
{r.issuer ?? 'Não indicada'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Número e data
|
||||
</dt>
|
||||
<dd>
|
||||
{[
|
||||
r.document_number,
|
||||
r.document_date,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ') ||
|
||||
'Não indicados'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Versão / idioma
|
||||
</dt>
|
||||
<dd>
|
||||
{r.version_label ??
|
||||
'Versão não indicada'}{' '}
|
||||
· {r.language}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Período de aplicação documentado
|
||||
</dt>
|
||||
<dd>
|
||||
{r.applicable_from ||
|
||||
r.applicable_until
|
||||
? `${r.applicable_from ?? 'Início não indicado'} — ${r.applicable_until ?? 'Sem data final indicada'}`
|
||||
: 'Não registado'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Âmbito
|
||||
</dt>
|
||||
<dd>
|
||||
{r.territorial_scope ===
|
||||
'national'
|
||||
? 'Nacional'
|
||||
: r.territorial_scope ===
|
||||
'unknown'
|
||||
? 'Por confirmar'
|
||||
: r.territorial_scope}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Fonte
|
||||
</dt>
|
||||
<dd>
|
||||
{r.source_confirmation ===
|
||||
'official_confirmed'
|
||||
? 'Fonte oficial confirmada'
|
||||
: r.source_confirmation ===
|
||||
'identified'
|
||||
? 'Origem identificada'
|
||||
: 'Fonte por confirmar'}
|
||||
</dd>
|
||||
</div>
|
||||
{r.source_confirmation ===
|
||||
'identified' && (
|
||||
<div
|
||||
className="rounded border border-amber-300 bg-amber-50 p-3 sm:col-span-2"
|
||||
role="note"
|
||||
>
|
||||
A origem está identificada, mas
|
||||
a autenticidade desta cópia não
|
||||
foi confirmada
|
||||
independentemente. Consulte a
|
||||
fonte indicada.
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Vigência
|
||||
</dt>
|
||||
<dd>
|
||||
{legalStatusLabels[
|
||||
r.legal_status
|
||||
] ?? r.legal_status}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Revisão
|
||||
</dt>
|
||||
<dd>
|
||||
Revisão administrativa registada{' '}
|
||||
{r.independent_review
|
||||
? 'com revisão independente'
|
||||
: 'sem revisão independente'}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="my-3 text-sm">
|
||||
Fonte: {r.source_reference}
|
||||
</p>
|
||||
<Link
|
||||
className="mr-4 inline-block underline"
|
||||
href={`/documentos/${r.id}?${new URLSearchParams({ back: currentUrl }).toString()}`}
|
||||
>
|
||||
Consultar ficha
|
||||
</Link>
|
||||
{r.view_url && (
|
||||
<a
|
||||
className="mr-4 inline-block underline"
|
||||
href={r.view_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Consultar ficheiro
|
||||
</a>
|
||||
)}
|
||||
{r.links?.length > 0 && (
|
||||
<div className="text-sm">
|
||||
<strong>
|
||||
Onde este documento é utilizado:
|
||||
</strong>
|
||||
<ul className="list-disc pl-6">
|
||||
{r.links.map((link, index) => (
|
||||
<li
|
||||
key={`${link.target_type}-${link.target_key}-${index}`}
|
||||
>
|
||||
{link.target_type ===
|
||||
'module' &&
|
||||
publicModulePaths[
|
||||
link.target_key
|
||||
] ? (
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
publicModulePaths[
|
||||
link
|
||||
.target_key
|
||||
].href
|
||||
}
|
||||
>
|
||||
{
|
||||
publicModulePaths[
|
||||
link
|
||||
.target_key
|
||||
].label
|
||||
}
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
{link.target_type ===
|
||||
'requirement'
|
||||
? `Requisito documental: ${link.target_label ?? link.target_key}`
|
||||
: `${link.target_type}: ${link.target_key}`}
|
||||
</>
|
||||
)}{' '}
|
||||
· {link.relationship} ·{' '}
|
||||
{link.applicability}
|
||||
{link.condition_text
|
||||
? ` · Condição: ${link.condition_text}`
|
||||
: ''}
|
||||
{link.basis_reference
|
||||
? ` · Referência documental: ${link.basis_reference}`
|
||||
: ''}
|
||||
{link.review_status ===
|
||||
'confirmed'
|
||||
? ' · Citação conferida; aplicação fiscal pendente'
|
||||
: ' · Pendente de conferência; não é fundamento confirmado'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Vigência
|
||||
</dt>
|
||||
<dd>
|
||||
{legalStatusLabels[r.legal_status] ?? r.legal_status}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Revisão
|
||||
</dt>
|
||||
<dd>
|
||||
Revisão administrativa registada{' '}
|
||||
{r.independent_review
|
||||
? 'com revisão independente'
|
||||
: 'sem revisão independente'}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="my-3 text-sm">
|
||||
Fonte: {r.source_reference}
|
||||
</p>
|
||||
<Link className="mr-4 inline-block underline" href={`/documentos/${r.id}?${new URLSearchParams({ back: currentUrl }).toString()}`}>
|
||||
Consultar ficha
|
||||
</Link>
|
||||
{r.view_url && <a className="mr-4 inline-block underline" href={r.view_url} target="_blank" rel="noreferrer">Consultar ficheiro</a>}
|
||||
{r.links?.length > 0 && (
|
||||
<div className="text-sm">
|
||||
<strong>
|
||||
Onde este documento é utilizado:
|
||||
</strong>
|
||||
<ul className="list-disc pl-6">
|
||||
{r.links.map((link, index) => (
|
||||
<li
|
||||
key={`${link.target_type}-${link.target_key}-${index}`}
|
||||
>
|
||||
{link.target_type ===
|
||||
'module' &&
|
||||
publicModulePaths[
|
||||
link.target_key
|
||||
] ? (
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
publicModulePaths[
|
||||
link.target_key
|
||||
].href
|
||||
}
|
||||
>
|
||||
{
|
||||
publicModulePaths[
|
||||
link.target_key
|
||||
].label
|
||||
}
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
{link.target_type === 'requirement' ? `Requisito documental: ${link.target_label ?? link.target_key}` : `${link.target_type}: ${link.target_key}`}
|
||||
</>
|
||||
)}{' '}
|
||||
· {link.relationship} ·{' '}
|
||||
{link.applicability}
|
||||
{link.condition_text
|
||||
? ` · Condição: ${link.condition_text}`
|
||||
: ''}
|
||||
{link.basis_reference
|
||||
? ` · Referência documental: ${link.basis_reference}`
|
||||
: ''}
|
||||
{link.review_status === 'confirmed'
|
||||
? ' · Citação conferida; aplicação fiscal pendente'
|
||||
: ' · Pendente de conferência; não é fundamento confirmado'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{r.source_url && (
|
||||
{r.source_url && (
|
||||
<a
|
||||
className="underline"
|
||||
href={r.source_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Abrir fonte identificada
|
||||
</a>
|
||||
)}
|
||||
<a
|
||||
className="underline"
|
||||
href={r.source_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href={r.download_url}
|
||||
className="ml-4 underline"
|
||||
>
|
||||
Abrir fonte identificada
|
||||
Descarregar {r.title}
|
||||
</a>
|
||||
)}
|
||||
<a
|
||||
href={r.download_url}
|
||||
className="ml-4 underline"
|
||||
>
|
||||
Descarregar {r.title}
|
||||
</a>
|
||||
</article>
|
||||
</article>
|
||||
</div>
|
||||
))}
|
||||
{!p.resources?.data.length && (
|
||||
|
||||
@@ -3,7 +3,10 @@ import { Management } from '../management/shared';
|
||||
import type { Paginated } from '../management/shared';
|
||||
import { Layout, Field, control, button, Pagination, kind } from './shared';
|
||||
import type { Dossier } from './shared';
|
||||
import { TerritoryFields, type TerritoryOption } from '@/components/investment-territory';
|
||||
import {
|
||||
TerritoryFields,
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
export default function Index({
|
||||
records,
|
||||
management,
|
||||
@@ -12,10 +15,24 @@ export default function Index({
|
||||
}: {
|
||||
records: Paginated<Dossier>;
|
||||
management: boolean;
|
||||
filters: { q?: string; kind?: string; province_id?: string; district_id?: string; admin_post_id?: string; locality_id?: string };
|
||||
filters: {
|
||||
q?: string;
|
||||
kind?: string;
|
||||
province_id?: string;
|
||||
district_id?: string;
|
||||
admin_post_id?: string;
|
||||
locality_id?: string;
|
||||
};
|
||||
territorySelection?: TerritoryOption[];
|
||||
}) {
|
||||
const form = useForm({ q: filters.q ?? '', kind: filters.kind ?? '', province_id: filters.province_id ?? '', district_id: filters.district_id ?? '', admin_post_id: filters.admin_post_id ?? '', locality_id: filters.locality_id ?? '' });
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
kind: filters.kind ?? '',
|
||||
province_id: filters.province_id ?? '',
|
||||
district_id: filters.district_id ?? '',
|
||||
admin_post_id: filters.admin_post_id ?? '',
|
||||
locality_id: filters.locality_id ?? '',
|
||||
});
|
||||
const base = management ? '/management/portfolio' : '/carteira';
|
||||
const Frame = management ? Management : Layout;
|
||||
return (
|
||||
@@ -57,7 +74,18 @@ export default function Index({
|
||||
<option value="project">Projectos âncora</option>
|
||||
</select>
|
||||
</Field>
|
||||
<TerritoryFields initial={territorySelection} onChange={(path) => form.setData((current) => ({ ...current, province_id: path[0]?.id ?? '', district_id: path[1]?.id ?? '', admin_post_id: path[2]?.id ?? '', locality_id: path[3]?.id ?? '' }))} />
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
onChange={(path) =>
|
||||
form.setData((current) => ({
|
||||
...current,
|
||||
province_id: path[0]?.id ?? '',
|
||||
district_id: path[1]?.id ?? '',
|
||||
admin_post_id: path[2]?.id ?? '',
|
||||
locality_id: path[3]?.id ?? '',
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
@@ -84,7 +112,12 @@ export default function Index({
|
||||
r.content.focus ??
|
||||
r.content.anchors}
|
||||
</p>
|
||||
{(r.content.location || r.content.region) && <p>Localização: {r.content.location ?? r.content.region}</p>}
|
||||
{(r.content.location || r.content.region) && (
|
||||
<p>
|
||||
Localização:{' '}
|
||||
{r.content.location ?? r.content.region}
|
||||
</p>
|
||||
)}
|
||||
{r.content.priority && (
|
||||
<p>
|
||||
{r.content.priority}{' '}
|
||||
@@ -101,12 +134,28 @@ export default function Index({
|
||||
</div>
|
||||
{!records.data.length && (
|
||||
<div className="space-y-3 rounded-xl border p-5" role="status">
|
||||
<p>Ainda não existem fichas publicadas para esta pesquisa. Os filtros activos foram mantidos.</p>
|
||||
<p>Esta lista contém dossiers territoriais documentados; não representa concursos abertos nem confirma disponibilidade de infra-estruturas ou incentivos.</p>
|
||||
<nav aria-label="Alternativas de exploração" className="flex flex-wrap gap-4">
|
||||
<Link className="underline" href="/oportunidades">Ver oportunidades publicadas</Link>
|
||||
<Link className="underline" href="/zonas">Consultar ZEE, ZFI e parques</Link>
|
||||
<Link className="underline" href="/Simulador">Transformar uma ideia num projecto</Link>
|
||||
<p>
|
||||
Ainda não existem fichas publicadas para esta pesquisa.
|
||||
Os filtros activos foram mantidos.
|
||||
</p>
|
||||
<p>
|
||||
Esta lista contém dossiers territoriais documentados;
|
||||
não representa concursos abertos nem confirma
|
||||
disponibilidade de infra-estruturas ou incentivos.
|
||||
</p>
|
||||
<nav
|
||||
aria-label="Alternativas de exploração"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link className="underline" href="/oportunidades">
|
||||
Ver oportunidades publicadas
|
||||
</Link>
|
||||
<Link className="underline" href="/zonas">
|
||||
Consultar ZEE, ZFI e parques
|
||||
</Link>
|
||||
<Link className="underline" href="/Simulador">
|
||||
Transformar uma ideia num projecto
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Head, Link, usePage } from "@inertiajs/react";
|
||||
import type { ReactNode } from "react";
|
||||
export { button, control, Field, Pagination } from "../management/shared";
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
export { button, control, Field, Pagination } from '../management/shared';
|
||||
export type Dossier = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -13,30 +13,41 @@ export type Dossier = {
|
||||
version_no?: number;
|
||||
};
|
||||
export const labels: Record<string, string> = {
|
||||
description: "Visão e proposta de valor",
|
||||
location: "Território",
|
||||
region: "Região",
|
||||
sector: "Sector",
|
||||
promotion: "Promoção",
|
||||
facts: "Dados indicativos da fonte",
|
||||
partners: "Investidores e parceiros",
|
||||
cta: "Próxima acção",
|
||||
anchors: "Projectos âncora e oportunidades",
|
||||
gaps: "Lacunas da cadeia de valor",
|
||||
priority: "Prioridade proposta na matriz",
|
||||
clusters: "Clusters associados",
|
||||
focus: "Investimentos complementares",
|
||||
notice: "Estado de validação",
|
||||
code: "Código",
|
||||
description: 'Visão e proposta de valor',
|
||||
location: 'Território',
|
||||
region: 'Região',
|
||||
sector: 'Sector',
|
||||
promotion: 'Promoção',
|
||||
facts: 'Dados indicativos da fonte',
|
||||
partners: 'Investidores e parceiros',
|
||||
cta: 'Próxima acção',
|
||||
anchors: 'Projectos âncora e oportunidades',
|
||||
gaps: 'Lacunas da cadeia de valor',
|
||||
priority: 'Prioridade proposta na matriz',
|
||||
clusters: 'Clusters associados',
|
||||
focus: 'Investimentos complementares',
|
||||
notice: 'Estado de validação',
|
||||
code: 'Código',
|
||||
};
|
||||
export const kind = (r: Pick<Dossier, "project_id" | "cluster_id" | "corridor_id">) =>
|
||||
r.corridor_id ? "Corredor" : r.cluster_id ? "Cluster" : "Projecto âncora";
|
||||
export function Layout({ title, children }: { title: string; children: ReactNode }) {
|
||||
export const kind = (
|
||||
r: Pick<Dossier, 'project_id' | 'cluster_id' | 'corridor_id'>,
|
||||
) =>
|
||||
r.corridor_id ? 'Corredor' : r.cluster_id ? 'Cluster' : 'Projecto âncora';
|
||||
export function Layout({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash } = usePage<{ flash?: { success?: string } }>().props;
|
||||
return (
|
||||
<main className="mx-auto w-full min-w-0 max-w-6xl space-y-6 break-words p-4 md:p-8">
|
||||
<main className="mx-auto w-full max-w-6xl min-w-0 space-y-6 p-4 break-words md:p-8">
|
||||
<Head title={title} />
|
||||
<nav className="flex flex-wrap gap-5 text-sm underline" aria-label="Investimento">
|
||||
<nav
|
||||
className="flex flex-wrap gap-5 text-sm underline"
|
||||
aria-label="Investimento"
|
||||
>
|
||||
<Link href="/">InvestMoz</Link>
|
||||
<Link href="/carteira?kind=corridor">Corredores</Link>
|
||||
<Link href="/carteira?kind=cluster">Clusters</Link>
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
import { Link, useForm, router, usePage } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import StructureGeographyPanel, { type StructureGeography } from '@/components/structure-geography';
|
||||
import { Link, useForm, router, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import InvestmentMapPanel from '@/components/investment-map-panel';
|
||||
import StructureGeographyPanel, {
|
||||
type StructureGeography,
|
||||
} from '@/components/structure-geography';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import { Management } from "../management/shared";
|
||||
import { Layout, Field, control, button, labels, kind } from "./shared";
|
||||
import type { Dossier } from "./shared";
|
||||
import { Management } from '../management/shared';
|
||||
import { Layout, Field, control, button, labels, kind } from './shared';
|
||||
import type { Dossier } from './shared';
|
||||
export default function Show(props: Props) {
|
||||
return <Editor key={`${props.record.id}:${props.record.version_no ?? 0}`} {...props} />;
|
||||
return (
|
||||
<Editor
|
||||
key={`${props.record.id}:${props.record.version_no ?? 0}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type Props = {
|
||||
geography: StructureGeography;
|
||||
existingSubmissions?: { id: string; version: number; updated_at: string }[];
|
||||
anchorProject?: { code: string; name: string; status: string; budget_amount: string | null; budget_currency: string | null; start_date: string | null; end_date: string | null } | null;
|
||||
anchorProject?: {
|
||||
code: string;
|
||||
name: string;
|
||||
status: string;
|
||||
budget_amount: string | null;
|
||||
budget_currency: string | null;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
} | null;
|
||||
zones?: {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -25,7 +40,12 @@ type Props = {
|
||||
related: Dossier[];
|
||||
management: boolean;
|
||||
origin: { id: string; title: string } | null;
|
||||
opportunities?: { id: number; title: string; slug: string; summary: string }[];
|
||||
opportunities?: {
|
||||
id: number;
|
||||
title: string;
|
||||
slug: string;
|
||||
summary: string;
|
||||
}[];
|
||||
chains?: { id: string; name: string; stage: string }[];
|
||||
};
|
||||
|
||||
@@ -49,53 +69,122 @@ function Editor({
|
||||
content: record.content,
|
||||
version_no: record.version_no,
|
||||
});
|
||||
const approval = useForm({ approval_evidence: "", version_no: record.version_no });
|
||||
const approval = useForm({
|
||||
approval_evidence: '',
|
||||
version_no: record.version_no,
|
||||
});
|
||||
const save = useForm({ origin_id: origin?.id ?? null });
|
||||
const Frame = management ? Management : Layout;
|
||||
const base = management ? "/management/portfolio" : "/carteira";
|
||||
const base = management ? '/management/portfolio' : '/carteira';
|
||||
return (
|
||||
<Frame title={record.title}>
|
||||
<p>
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{(record.project_id||record.cluster_id)&&<PartnershipSourceLinks type={record.project_id?'project':'cluster'} id={record.project_id??record.cluster_id!}/>}
|
||||
{(record.project_id || record.cluster_id) && <StructureGeographyPanel geography={geography} cluster={Boolean(record.cluster_id)} dossierId={record.id} />}
|
||||
{(record.project_id || record.cluster_id) && (
|
||||
<PartnershipSourceLinks
|
||||
type={record.project_id ? 'project' : 'cluster'}
|
||||
id={record.project_id ?? record.cluster_id!}
|
||||
/>
|
||||
)}
|
||||
{(record.project_id || record.cluster_id) && (
|
||||
<StructureGeographyPanel
|
||||
geography={geography}
|
||||
cluster={Boolean(record.cluster_id)}
|
||||
dossierId={record.id}
|
||||
/>
|
||||
)}
|
||||
{anchorProject && (
|
||||
<section className="space-y-2 rounded-xl border p-5" aria-labelledby="anchor-project-heading">
|
||||
<h2 id="anchor-project-heading" className="text-xl font-bold">Referência de projecto âncora</h2>
|
||||
<p>{anchorProject.code} · {anchorProject.name}</p>
|
||||
<p>Estado registado: {{ draft: "rascunho", planned: "previsto", active: "em execução", suspended: "suspenso", completed: "concluído", cancelled: "cancelado" }[anchorProject.status] ?? "por confirmar"}.</p>
|
||||
{anchorProject.budget_amount && <p>Investimento estimado documentado: {anchorProject.budget_amount} {anchorProject.budget_currency}</p>}
|
||||
{(anchorProject.start_date || anchorProject.end_date) && <p>Calendário registado: {anchorProject.start_date ?? "início não indicado"} – {anchorProject.end_date ?? "fim não indicado"}</p>}
|
||||
<p>Esta é uma referência de planeamento. Não significa concurso aberto, disponibilidade imediata ou convite à apresentação de propostas.</p>
|
||||
<section
|
||||
className="space-y-2 rounded-xl border p-5"
|
||||
aria-labelledby="anchor-project-heading"
|
||||
>
|
||||
<h2
|
||||
id="anchor-project-heading"
|
||||
className="text-xl font-bold"
|
||||
>
|
||||
Referência de projecto âncora
|
||||
</h2>
|
||||
<p>
|
||||
{anchorProject.code} · {anchorProject.name}
|
||||
</p>
|
||||
<p>
|
||||
Estado registado:{' '}
|
||||
{{
|
||||
draft: 'rascunho',
|
||||
planned: 'previsto',
|
||||
active: 'em execução',
|
||||
suspended: 'suspenso',
|
||||
completed: 'concluído',
|
||||
cancelled: 'cancelado',
|
||||
}[anchorProject.status] ?? 'por confirmar'}
|
||||
.
|
||||
</p>
|
||||
{anchorProject.budget_amount && (
|
||||
<p>
|
||||
Investimento estimado documentado:{' '}
|
||||
{anchorProject.budget_amount}{' '}
|
||||
{anchorProject.budget_currency}
|
||||
</p>
|
||||
)}
|
||||
{(anchorProject.start_date || anchorProject.end_date) && (
|
||||
<p>
|
||||
Calendário registado:{' '}
|
||||
{anchorProject.start_date ?? 'início não indicado'}{' '}
|
||||
– {anchorProject.end_date ?? 'fim não indicado'}
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Esta é uma referência de planeamento. Não significa
|
||||
concurso aberto, disponibilidade imediata ou convite à
|
||||
apresentação de propostas.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{record.project_id && !anchorProject && (
|
||||
<section className="space-y-2 rounded-xl border p-5" aria-labelledby="anchor-status-pending-heading">
|
||||
<h2 id="anchor-status-pending-heading" className="text-xl font-bold">Referência de projecto âncora</h2>
|
||||
<p>O estado de execução e o investimento não estão confirmados num registo publicável. A referência do dossier não representa concurso aberto nem disponibilidade imediata.</p>
|
||||
<section
|
||||
className="space-y-2 rounded-xl border p-5"
|
||||
aria-labelledby="anchor-status-pending-heading"
|
||||
>
|
||||
<h2
|
||||
id="anchor-status-pending-heading"
|
||||
className="text-xl font-bold"
|
||||
>
|
||||
Referência de projecto âncora
|
||||
</h2>
|
||||
<p>
|
||||
O estado de execução e o investimento não estão
|
||||
confirmados num registo publicável. A referência do
|
||||
dossier não representa concurso aberto nem
|
||||
disponibilidade imediata.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{!management && (record.cluster_id || record.corridor_id || record.project_id) && (
|
||||
<InvestmentMapPanel
|
||||
filters={
|
||||
record.cluster_id
|
||||
? { cluster_id: record.cluster_id }
|
||||
: record.corridor_id
|
||||
? { corridor_id: record.corridor_id }
|
||||
: { project_id: record.project_id! }
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!management &&
|
||||
(record.cluster_id ||
|
||||
record.corridor_id ||
|
||||
record.project_id) && (
|
||||
<InvestmentMapPanel
|
||||
filters={
|
||||
record.cluster_id
|
||||
? { cluster_id: record.cluster_id }
|
||||
: record.corridor_id
|
||||
? { corridor_id: record.corridor_id }
|
||||
: { project_id: record.project_id! }
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{zones.length > 0 && (
|
||||
<section>
|
||||
<h2 className="text-xl font-bold">ZEE, ZFI e parques relacionados</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
ZEE, ZFI e parques relacionados
|
||||
</h2>
|
||||
{zones.map((z) => (
|
||||
<p key={z.id}>
|
||||
<Link className="underline" href={`/zonas/${z.id}`}>
|
||||
{z.name}
|
||||
</Link>{" "}
|
||||
</Link>{' '}
|
||||
· {z.association_type} · Fonte: {z.source_reference}
|
||||
</p>
|
||||
))}
|
||||
@@ -104,12 +193,35 @@ function Editor({
|
||||
{origin && <p>Exploração iniciada em: {origin.title}</p>}
|
||||
{!management && auth.user && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<p>As manifestações ficam privadas até uma submissão separada. A referência não copia nem publica o dossier público no seu nome.</p>
|
||||
<p>
|
||||
As manifestações ficam privadas até uma submissão
|
||||
separada. A referência não copia nem publica o dossier
|
||||
público no seu nome.
|
||||
</p>
|
||||
{existingSubmissions.length > 0 && (
|
||||
<section className="space-y-2" aria-label="Manifestações em rascunho para esta ficha">
|
||||
<h2 className="font-semibold">Continuar um rascunho existente</h2>
|
||||
{existingSubmissions.map((submission) => <Link key={submission.id} className="block underline" href={`/investidor/manifestacoes/${submission.id}`}>Continuar rascunho actualizado em {new Date(submission.updated_at).toLocaleDateString("pt-MZ")}</Link>)}
|
||||
<p>Ou crie outra manifestação privada. Os rascunhos não serão fundidos.</p>
|
||||
<section
|
||||
className="space-y-2"
|
||||
aria-label="Manifestações em rascunho para esta ficha"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
Continuar um rascunho existente
|
||||
</h2>
|
||||
{existingSubmissions.map((submission) => (
|
||||
<Link
|
||||
key={submission.id}
|
||||
className="block underline"
|
||||
href={`/investidor/manifestacoes/${submission.id}`}
|
||||
>
|
||||
Continuar rascunho actualizado em{' '}
|
||||
{new Date(
|
||||
submission.updated_at,
|
||||
).toLocaleDateString('pt-MZ')}
|
||||
</Link>
|
||||
))}
|
||||
<p>
|
||||
Ou crie outra manifestação privada. Os rascunhos
|
||||
não serão fundidos.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<button
|
||||
@@ -117,31 +229,52 @@ function Editor({
|
||||
className={button}
|
||||
disabled={creatingManifestation}
|
||||
onClick={() => {
|
||||
if (!window.confirm(`Criar ${existingSubmissions.length ? "outra" : "uma"} manifestação privada associada a “${record.title}”? Pode continuar a editá-la antes de submeter. Os rascunhos existentes não serão alterados.`)) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Criar ${existingSubmissions.length ? 'outra' : 'uma'} manifestação privada associada a “${record.title}”? Pode continuar a editá-la antes de submeter. Os rascunhos existentes não serão alterados.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
setCreatingManifestation(true);
|
||||
router.post("/investidor/manifestacoes", { dossier_id: record.id }, { onFinish: () => setCreatingManifestation(false) });
|
||||
router.post(
|
||||
'/investidor/manifestacoes',
|
||||
{ dossier_id: record.id },
|
||||
{
|
||||
onFinish: () =>
|
||||
setCreatingManifestation(false),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{creatingManifestation ? "A preparar…" : "Preparar manifestação privada"}
|
||||
{creatingManifestation
|
||||
? 'A preparar…'
|
||||
: 'Preparar manifestação privada'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!management && !auth.user && (
|
||||
<p className="rounded-xl border p-4">Para associar esta referência a uma manifestação privada, entre na sua conta. Esta ficha continuará pública e não será copiada nem publicada no seu nome. <Link className="underline" href="/login">Entrar</Link></p>
|
||||
<p className="rounded-xl border p-4">
|
||||
Para associar esta referência a uma manifestação privada,
|
||||
entre na sua conta. Esta ficha continuará pública e não será
|
||||
copiada nem publicada no seu nome.{' '}
|
||||
<Link className="underline" href="/login">
|
||||
Entrar
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{chains.length > 0 && (
|
||||
<section>
|
||||
<h2 className="text-xl font-bold">Cadeia de valor</h2>
|
||||
{chains.map((chain) => (
|
||||
<p key={chain.id}>
|
||||
{chain.name} —{" "}
|
||||
{chain.name} —{' '}
|
||||
{(
|
||||
{
|
||||
input: "Insumos",
|
||||
production: "Produção",
|
||||
processing: "Transformação",
|
||||
logistics: "Logística",
|
||||
market: "Mercado",
|
||||
input: 'Insumos',
|
||||
production: 'Produção',
|
||||
processing: 'Transformação',
|
||||
logistics: 'Logística',
|
||||
market: 'Mercado',
|
||||
} as Record<string, string>
|
||||
)[chain.stage] ?? chain.stage}
|
||||
</p>
|
||||
@@ -149,7 +282,9 @@ function Editor({
|
||||
</section>
|
||||
)}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-bold">Oportunidades relacionadas</h2>
|
||||
<h2 className="text-xl font-bold">
|
||||
Oportunidades relacionadas
|
||||
</h2>
|
||||
{opportunities.map((opportunity) => (
|
||||
<article key={opportunity.id}>
|
||||
<Link
|
||||
@@ -168,8 +303,8 @@ function Editor({
|
||||
{management ? (
|
||||
<>
|
||||
<p>
|
||||
Versão editorial: {record.version_no}. Guarde as alterações antes de
|
||||
publicar.
|
||||
Versão editorial: {record.version_no}. Guarde as
|
||||
alterações antes de publicar.
|
||||
</p>
|
||||
<form
|
||||
className="space-y-4"
|
||||
@@ -182,30 +317,36 @@ function Editor({
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.title}
|
||||
onChange={(e) => form.setData("title", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('title', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Fonte e versão">
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.source}
|
||||
onChange={(e) => form.setData("source", e.target.value)}
|
||||
onChange={(e) =>
|
||||
form.setData('source', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{Object.entries(form.data.content).map(([key, value]) => (
|
||||
<Field key={key} label={labels[key] ?? key}>
|
||||
<textarea
|
||||
className={control}
|
||||
value={value ?? ""}
|
||||
onChange={(e) =>
|
||||
form.setData("content", {
|
||||
...form.data.content,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
{Object.entries(form.data.content).map(
|
||||
([key, value]) => (
|
||||
<Field key={key} label={labels[key] ?? key}>
|
||||
<textarea
|
||||
className={control}
|
||||
value={value ?? ''}
|
||||
onChange={(e) =>
|
||||
form.setData('content', {
|
||||
...form.data.content,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
),
|
||||
)}
|
||||
{Object.entries(form.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
@@ -223,8 +364,8 @@ function Editor({
|
||||
}}
|
||||
>
|
||||
<p>
|
||||
O gestor autorizado pode aprovar e publicar esta ficha. Registe a
|
||||
referência da sua decisão.
|
||||
O gestor autorizado pode aprovar e publicar esta
|
||||
ficha. Registe a referência da sua decisão.
|
||||
</p>
|
||||
<Field label="Referência da autorização e revisão">
|
||||
<textarea
|
||||
@@ -233,14 +374,22 @@ function Editor({
|
||||
minLength={15}
|
||||
value={approval.data.approval_evidence}
|
||||
onChange={(e) =>
|
||||
approval.setData("approval_evidence", e.target.value)
|
||||
approval.setData(
|
||||
'approval_evidence',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{approval.errors.approval_evidence && (
|
||||
<p role="alert">{approval.errors.approval_evidence}</p>
|
||||
<p role="alert">
|
||||
{approval.errors.approval_evidence}
|
||||
</p>
|
||||
)}
|
||||
<button className={button} disabled={approval.processing || form.isDirty}>
|
||||
<button
|
||||
className={button}
|
||||
disabled={approval.processing || form.isDirty}
|
||||
>
|
||||
Validar e publicar
|
||||
</button>
|
||||
</form>
|
||||
@@ -249,11 +398,15 @@ function Editor({
|
||||
<>
|
||||
<dl className="space-y-5">
|
||||
{Object.entries(record.content)
|
||||
.filter(([k]) => k !== "name" && k !== "code")
|
||||
.filter(([k]) => k !== 'name' && k !== 'code')
|
||||
.map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-semibold">{labels[key] ?? key}</dt>
|
||||
<dd className="mt-1 whitespace-pre-line">{value}</dd>
|
||||
<dt className="font-semibold">
|
||||
{labels[key] ?? key}
|
||||
</dt>
|
||||
<dd className="mt-1 whitespace-pre-line">
|
||||
{value}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
@@ -266,54 +419,73 @@ function Editor({
|
||||
<button className={button} disabled={save.processing}>
|
||||
Guardar no painel e preparar interesse
|
||||
</button>
|
||||
<p className="mt-2 text-sm">Acesso com conta e email verificado.</p>
|
||||
<p className="mt-2 text-sm">
|
||||
Acesso com conta e email verificado.
|
||||
</p>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">Percurso de execução</h2>
|
||||
<ol className="list-decimal space-y-2 pl-6">
|
||||
<li>Explore as relações entre corredor, cluster e projecto âncora.</li>
|
||||
<li>
|
||||
Consulte as componentes, parceiros e oportunidades de participação da ficha.
|
||||
Explore as relações entre corredor, cluster e projecto
|
||||
âncora.
|
||||
</li>
|
||||
<li>
|
||||
Guarde a ficha no painel do investidor e manifeste interesse com o papel e
|
||||
prazo pretendidos.
|
||||
Consulte as componentes, parceiros e oportunidades de
|
||||
participação da ficha.
|
||||
</li>
|
||||
<li>
|
||||
Guarde a ficha no painel do investidor e manifeste
|
||||
interesse com o papel e prazo pretendidos.
|
||||
</li>
|
||||
<li>
|
||||
A equipa acompanha o pedido no CRM, com responsável e
|
||||
próxima acção.
|
||||
</li>
|
||||
<li>A equipa acompanha o pedido no CRM, com responsável e próxima acção.</li>
|
||||
</ol>
|
||||
{management && (
|
||||
<div className="flex flex-wrap gap-4 underline">
|
||||
{record.project_id && (
|
||||
<Link href={`/management/projects/${record.project_id}/edit`}>
|
||||
<Link
|
||||
href={`/management/projects/${record.project_id}/edit`}
|
||||
>
|
||||
Gerir projecto
|
||||
</Link>
|
||||
)}
|
||||
{record.cluster_id && (
|
||||
<Link href={`/management/clusters/${record.cluster_id}/edit`}>
|
||||
<Link
|
||||
href={`/management/clusters/${record.cluster_id}/edit`}
|
||||
>
|
||||
Gerir cadeias e lacunas do cluster
|
||||
</Link>
|
||||
)}
|
||||
<Link href="/management/interests">Acompanhar pedidos</Link>
|
||||
{record.publication_status === "published" && (
|
||||
<Link href={`/carteira/${record.id}`}>Abrir ficha pública</Link>
|
||||
<Link href="/management/interests">
|
||||
Acompanhar pedidos
|
||||
</Link>
|
||||
{record.publication_status === 'published' && (
|
||||
<Link href={`/carteira/${record.id}`}>
|
||||
Abrir ficha pública
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<h2 className="text-xl font-semibold">Relações na carteira</h2>
|
||||
{related.map((r) => (
|
||||
<p key={r.id}>
|
||||
{kind(r)}:{" "}
|
||||
{kind(r)}:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}/${r.id}${management ? "" : `?from=${record.id}`}`}
|
||||
href={`${base}/${r.id}${management ? '' : `?from=${record.id}`}`}
|
||||
>
|
||||
{r.title}
|
||||
</Link>
|
||||
</p>
|
||||
))}
|
||||
{!related.length && <p>Sem relações disponíveis para consulta.</p>}
|
||||
{!related.length && (
|
||||
<p>Sem relações disponíveis para consulta.</p>
|
||||
)}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user