varias alteracoes
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-06 14:50:12 +02:00
parent 4f35313d06
commit e65cb26901
333 changed files with 54656 additions and 2058 deletions
+25 -17
View File
@@ -1,27 +1,35 @@
import { createInertiaApp } from "@inertiajs/react";
import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initializeTheme } from "@/hooks/use-appearance";
import AppLayout from "@/layouts/app-layout";
import AuthLayout from "@/layouts/auth-layout";
import SettingsLayout from "@/layouts/settings/layout";
import PortalNavigation from "@/layouts/portal-navigation";
import { createInertiaApp } from '@inertiajs/react';
import type { ComponentType } from 'react';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import { initializeTheme } from '@/hooks/use-appearance';
import AppLayout from '@/layouts/app-layout';
import AuthLayout from '@/layouts/auth-layout';
import SettingsLayout from '@/layouts/settings/layout';
import PortalNavigation from '@/layouts/portal-navigation';
const appName = import.meta.env.VITE_APP_NAME || "Laravel";
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
const pages = import.meta.glob<{ default: ComponentType }>('./pages/**/*.tsx');
void createInertiaApp({
resolve: async (name) => {
const path = `./pages/${name}.tsx`;
const loadPage = pages[path];
if (!loadPage) throw new Error(`Page not found: ${name}`);
return (await loadPage()).default;
},
title: (title) => (title ? `${title} - ${appName}` : appName),
layout: (name) => {
switch (true) {
case name === "welcome":
case name === "PortalInvestidor":
case name === "management-access":
case name.startsWith("portal/"):
case name.startsWith("investment/"):
case name === 'welcome':
case name === 'PortalInvestidor':
case name === 'management-access':
case name.startsWith('portal/'):
case name.startsWith('investment/'):
return PortalNavigation;
case name.startsWith("auth/"):
case name.startsWith('auth/'):
return [PortalNavigation, AuthLayout];
case name.startsWith("settings/"):
case name.startsWith('settings/'):
return [PortalNavigation, AppLayout, SettingsLayout];
default:
return [PortalNavigation, AppLayout];
@@ -37,7 +45,7 @@ void createInertiaApp({
);
},
progress: {
color: "#4B5563",
color: '#4B5563',
},
});
@@ -0,0 +1,182 @@
import { useMemo, useState } from 'react';
import {
createProjectDossierPrintHtml,
createProjectDossierReport,
dossierReportSections,
generateProjectDossierDocx,
generateProjectDossierPackage,
validateDossierAttachments,
type DossierAttachment,
type DossierReference,
type DossierCurrentCalculation,
type DossierReportSectionId,
} from '@/lib/project-dossier-report';
import { exportProjectDossierCsv } from '@/lib/project-dossier';
import type { SimulationDraft } from '@/lib/simulation-form';
type Props = {
draft: SimulationDraft;
version: string;
references?: DossierReference[];
currentCalculation?: DossierCurrentCalculation | null;
};
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';
}
function download(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.rel = 'noopener';
link.click();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
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]);
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; }
setAttachments((current) => [
...current,
...incoming.map((file) => ({ file, include: true, caption: '' })),
]);
setError('');
}
function toggleSection(id: DossierReportSectionId, checked: boolean): void {
setSelectedSections((current) => {
const next = new Set(current);
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 removeAttachment(index: number): void {
setAttachments((current) => current.filter((_, itemIndex) => itemIndex !== index));
}
function model() {
return createProjectDossierReport(draft, {
selectedSections: selectedSectionSet,
version,
references,
currentCalculation,
});
}
async function exportWord(): Promise<void> {
setBusy('word'); setError('');
try {
const report = model();
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(''); }
}
async function exportPackage(): Promise<void> {
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`);
} catch (cause) {
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('');
try {
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(''); }
}
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 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">
<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>
</div>
<fieldset className="space-y-2">
<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>
))}
</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>}
<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]">
<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>
</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>}
</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>}
<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>
</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>}
</section>
);
}
@@ -0,0 +1,44 @@
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;
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 }) {
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>;
}
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>;
}
@@ -0,0 +1,87 @@
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 };
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 []; }
}
const kindLabels = { missing: 'Informação em falta', unverified: 'Hipótese por verificar', risk: 'Risco identificado' };
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';
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);
next.push({ ...current, ...patch });
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>;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,369 @@
import { useState } from 'react';
import {
exportMonthlyCashflowCsv,
projectMonthlyCashflow,
} from '@/lib/monthly-cashflow';
import {
isSimulationCurrency,
simulationCurrencyOptions,
} from '@/lib/simulation-contract';
export function SimulationCashflowPlanner({
currency,
onCurrencyChange,
}: {
currency: string;
onCurrencyChange: (currency: string) => void;
}) {
const [taxMode, setTaxMode] = useState<'fixed' | 'schedule'>('fixed');
const [inputs, setInputs] = useState({
openingCash: '0',
monthlyRevenue: '200000',
monthlyOperatingCosts: '150000',
monthlyDebtService: '0',
monthlyTaxAssessed: '',
monthlyTaxSchedule: Array.from({ length: 12 }, () => ''),
vatCreditEstimated: '0',
vatRefundRequested: '0',
vatRefundRecognized: '0',
vatRefundExpectedReceipt: '0',
vatRefundExpectedMonth: '',
});
const set = (
key: Exclude<keyof typeof inputs, 'monthlyTaxSchedule'>,
value: string,
) => setInputs((current) => ({ ...current, [key]: value }));
const cashflowInput = {
...inputs,
...(taxMode === 'fixed'
? { monthlyTaxSchedule: undefined }
: {
monthlyTaxAssessed: '',
monthlyTaxSchedule: inputs.monthlyTaxSchedule,
}),
};
let projection;
let error = '';
try {
projection = projectMonthlyCashflow({ ...cashflowInput, currency });
} catch (cause) {
error =
cause instanceof Error
? cause.message
: 'Verifique os valores introduzidos.';
}
return (
<section
className="space-y-4 rounded-lg border border-slate-300 p-4"
aria-labelledby="cashflow-title"
>
<label className="block max-w-xs text-sm font-medium">
Moeda dos valores (código ISO)
<input
list="cashflow-currency-options"
inputMode="text"
maxLength={3}
pattern="[A-Z]{3}"
autoCapitalize="characters"
value={currency}
onChange={(event) =>
onCurrencyChange(event.target.value.toUpperCase())
}
className="mt-1 w-full rounded border p-2"
aria-invalid={
currency !== '' && !isSimulationCurrency(currency)
}
/>
</label>
<datalist id="cashflow-currency-options">
{simulationCurrencyOptions.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</datalist>
<h3 id="cashflow-title" className="text-lg font-semibold">
Projecção de tesouraria — 12 meses
</h3>
<p className="text-sm text-slate-700">
Introduza pressupostos na mesma moeda. O imposto indicado é um
pressuposto do utilizador; esta ferramenta não calcula nem
confirma uma obrigação fiscal. Crédito estimado, pedido e
montante reconhecido são informativos e não contam como caixa.
Apenas o recebimento previsto entra no mês indicado, como
hipótese não garantida.
</p>
<p
role="note"
className="rounded bg-amber-50 p-3 text-sm text-amber-950"
>
Os valores preenchidos ao abrir são exemplos demonstrativos.
Confirme ou altere os pressupostos antes de interpretar os
resultados ou exportar o CSV.
</p>
{projection?.status === 'incomplete' && (
<p
role="note"
className="rounded bg-amber-50 p-3 text-sm text-amber-950"
>
Há pelo menos um mês sem pressuposto de imposto: o saldo
total desde esse ponto é indeterminado. A caixa conhecida
inclui os impostos declarados e omite apenas os meses em
falta; mês vazio não significa imposto zero.
</p>
)}
<fieldset className="space-y-2 rounded border p-3">
<legend className="px-1 text-sm font-semibold">
Pressuposto de imposto para planeamento
</legend>
<label className="mr-4 inline-flex items-center gap-2 text-sm">
<input
type="radio"
name="cashflow-tax-mode"
checked={taxMode === 'fixed'}
onChange={() => setTaxMode('fixed')}
/>
Valor mensal fixo
</label>
<label className="inline-flex items-center gap-2 text-sm">
<input
type="radio"
name="cashflow-tax-mode"
checked={taxMode === 'schedule'}
onChange={() => setTaxMode('schedule')}
/>
Calendário variável por mês
</label>
{taxMode === 'fixed' ? (
<label className="block max-w-xs text-sm font-medium">
Imposto assumido por mês
<input
type="number"
min="0"
step="0.01"
value={inputs.monthlyTaxAssessed}
onChange={(event) =>
set('monthlyTaxAssessed', event.target.value)
}
className="mt-1 w-full rounded border p-2"
/>
<span className="block font-normal text-slate-600">
Repete o pressuposto em cada mês do horizonte.
</span>
</label>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{inputs.monthlyTaxSchedule.map((value, index) => (
<label key={index} className="text-sm font-medium">
Imposto assumido — mês {index + 1}
<input
type="number"
min="0"
step="0.01"
value={value}
onChange={(event) =>
setInputs((current) => ({
...current,
monthlyTaxSchedule:
current.monthlyTaxSchedule.map(
(amount, month) =>
month === index
? event.target.value
: amount,
),
}))
}
className="mt-1 w-full rounded border p-2"
/>
</label>
))}
</div>
)}
</fieldset>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{(
[
['openingCash', 'Saldo inicial'],
['monthlyRevenue', 'Receita mensal'],
[
'monthlyOperatingCosts',
'Custos operacionais mensais',
],
['monthlyDebtService', 'Prestação mensal'],
[
'vatCreditEstimated',
'Crédito de IVA estimado (não caixa)',
],
[
'vatRefundRequested',
'Reembolso de IVA pedido (não caixa)',
],
[
'vatRefundRecognized',
'Reembolso reconhecido (não caixa)',
],
[
'vatRefundExpectedReceipt',
'Recebimento IVA previsto (condicional)',
],
[
'vatRefundExpectedMonth',
'Mês previsto do recebimento (1–12)',
],
] as const
).map(([key, label]) => (
<label key={key} className="text-sm font-medium">
{label}
<input
type="number"
min={key === 'vatRefundExpectedMonth' ? '1' : '0'}
max={
key === 'vatRefundExpectedMonth'
? '12'
: undefined
}
step={
key === 'vatRefundExpectedMonth' ? '1' : '0.01'
}
value={inputs[key]}
onChange={(event) => set(key, event.target.value)}
className="mt-1 w-full rounded border p-2"
/>
</label>
))}
</div>
{error && (
<p role="alert" className="text-sm text-red-800">
{error}
</p>
)}
{projection && isSimulationCurrency(currency) && (
<>
<p aria-live="polite" className="font-semibold">
{projection.endingCash === null
? `Caixa conhecida antes de imposto em falta, ao fim de 12 meses (${currency}):`
: `Saldo projectado ao fim de 12 meses (${currency}):`}{' '}
{projection.endingCash ??
projection.endingCashBeforeUnassessedTax}
</p>
<button
type="button"
className="rounded border px-3 py-2 text-sm focus-visible:outline-2"
onClick={() => {
const blob = new Blob(
[
exportMonthlyCashflowCsv({
...cashflowInput,
currency,
periods: 12,
}),
],
{ type: 'text/csv;charset=utf-8' },
);
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'projecao-tesouraria.csv';
link.click();
URL.revokeObjectURL(url);
}}
>
Descarregar CSV
</button>
{projection.firstDeficitMonth && (
<output className="block rounded bg-amber-50 p-2 text-sm">
O saldo após o imposto declarado fica negativo no
mês {projection.firstDeficitMonth}.
</output>
)}
{!projection.firstDeficitMonth &&
projection.firstDeficitMonthBeforeUnassessedTax && (
<output className="block rounded bg-amber-50 p-2 text-sm">
Os fluxos conhecidos já deixam o caixa negativo,
antes do imposto não informado, no mês{' '}
{
projection.firstDeficitMonthBeforeUnassessedTax
}
.
</output>
)}
<p className="text-sm">
Crédito estimado: {projection.vatCreditEstimated};
pedido: {projection.vatRefundRequested}; reconhecido:{' '}
{projection.vatRefundRecognized}. Estes valores não
foram somados à caixa.
</p>
<div className="overflow-x-auto">
<table className="min-w-full text-sm">
<caption className="sr-only">
Projecção mensal de tesouraria
</caption>
<thead>
<tr>
{[
'Mês',
'Saldo inicial',
'Receitas',
'Custos',
'Dívida',
'Imposto assumido',
'Reembolso previsto',
'Fluxo antes de imposto em falta',
'Caixa antes de imposto em falta',
'Fluxo líquido total',
'Saldo final total',
].map((value) => (
<th
key={value}
scope="col"
className="p-2 text-left"
>
{value}
</th>
))}
</tr>
</thead>
<tbody>
{projection.rows.map((row) => (
<tr key={row.month} className="border-t">
<th scope="row" className="p-2">
{row.month}
</th>
<td className="p-2">
{row.openingCash ?? 'Indeterminado'}
</td>
<td className="p-2">{row.revenue}</td>
<td className="p-2">
{row.operatingCosts}
</td>
<td className="p-2">
{row.debtService}
</td>
<td className="p-2">
{row.taxAssessed ?? 'Indeterminado'}
</td>
<td className="p-2">
{row.vatRefundExpectedReceipt}
</td>
<td className="p-2">
{row.netFlowBeforeUnassessedTax}
</td>
<td className="p-2">
{row.closingCashBeforeUnassessedTax}
</td>
<td className="p-2">
{row.netFlow ?? 'Indeterminado'}
</td>
<td className="p-2">
{row.closingCash ?? 'Indeterminado'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)}
</section>
);
}
@@ -0,0 +1,684 @@
import { useEffect, useState } from 'react';
import {
calculateFinancialTools,
exportFinancialToolsCsv,
restoreFinancialToolsSnapshot,
serializeFinancialToolsSnapshot,
} from '@/lib/financial-calculators';
import {
isSimulationCurrency,
simulationCurrencyOptions,
} from '@/lib/simulation-contract';
function Field({
label,
value,
onChange,
step = '0.01',
}: {
label: string;
value: string;
onChange: (value: string) => void;
step?: string;
}) {
return (
<label className="block text-sm font-medium">
{label}
<input
type="number"
min="0"
step={step}
value={value}
onChange={(event) => onChange(event.target.value)}
className="mt-1 w-full rounded border p-2"
/>
</label>
);
}
export function SimulationFinancialTools({
currency,
snapshot,
onSnapshotChange,
onCurrencyChange,
}: {
currency: string;
snapshot?: string;
onSnapshotChange: (snapshot: string) => void;
onCurrencyChange: (currency: string) => void;
}) {
const initial = restoreFinancialToolsSnapshot(snapshot);
const [loan, setLoan] = useState(
initial?.loan ?? {
principal: '100000',
rate: '18',
months: '24',
rateType: 'nominal' as 'nominal' | 'effective',
periodMonths: '1',
gracePeriods: '0',
upfrontFee: '0',
recurringFee: '0',
},
);
const [breakEven, setBreakEven] = useState(
initial?.breakEven ?? {
fixed: '50000',
price: '1000',
variable: '600',
},
);
const [funding, setFunding] = useState(
initial?.funding ?? { total: '1000000', secured: '250000' },
);
const [incomeRows, setIncomeRows] = useState([
{ label: 'Vendas e serviços', amount: '200000' },
]);
const [expenseRows, setExpenseRows] = useState([
{ label: 'Despesas operacionais', amount: '150000' },
]);
const [budgetPeriod, setBudgetPeriod] = useState('Mensal');
const [snapshotHydrated, setSnapshotHydrated] = useState(false);
useEffect(() => {
const stored = restoreFinancialToolsSnapshot(snapshot);
if (stored) {
setBudgetPeriod(stored.budgetPeriod);
setLoan({
principal: stored.loan.principal,
rate: stored.loan.rate,
months: stored.loan.months,
rateType: stored.loan.rateType,
periodMonths: stored.loan.periodMonths,
gracePeriods: stored.loan.gracePeriods,
upfrontFee: stored.loan.upfrontFee,
recurringFee: stored.loan.recurringFee,
});
setBreakEven(stored.breakEven);
setFunding(stored.funding);
setIncomeRows(stored.incomes);
setExpenseRows(stored.expenses);
}
setSnapshotHydrated(true);
}, []);
useEffect(() => {
if (!snapshotHydrated) return;
const serialized = serializeFinancialToolsSnapshot({
budgetPeriod,
loan,
breakEven,
funding,
incomes: incomeRows,
expenses: expenseRows,
});
if (serialized !== snapshot) onSnapshotChange(serialized);
}, [
snapshotHydrated,
snapshot,
onSnapshotChange,
budgetPeriod,
loan,
breakEven,
funding,
incomeRows,
expenseRows,
]);
const calculations = calculateFinancialTools({
loan: {
principal: loan.principal,
annualRatePercent: loan.rate,
rateType: loan.rateType,
termMonths: Number(loan.months),
periodMonths: Number(loan.periodMonths),
gracePeriods: Number(loan.gracePeriods),
upfrontFee: loan.upfrontFee,
recurringFee: loan.recurringFee,
},
breakEven: {
fixedCosts: breakEven.fixed,
unitPrice: breakEven.price,
variableCostPerUnit: breakEven.variable,
},
funding: {
totalInvestment: funding.total,
securedFunding: funding.secured,
},
incomes: incomeRows.map((row) => row.amount),
expenses: expenseRows.map((row) => row.amount),
});
const schedule = calculations.loan.value;
const point = calculations.breakEven.value;
const gap = calculations.funding.value;
const budget = calculations.budget.value;
const calculationErrors = [
{ label: 'Empréstimo', message: calculations.loan.error },
{ label: 'Ponto de equilíbrio', message: calculations.breakEven.error },
{ label: 'Financiamento', message: calculations.funding.error },
{ label: 'Orçamento', message: calculations.budget.error },
].filter(
(entry): entry is { label: string; message: string } =>
entry.message !== null,
);
const update = <T extends Record<string, string>>(
setter: (value: T) => void,
current: T,
key: keyof T,
value: string,
) => setter({ ...current, [key]: value });
return (
<section
className="space-y-4 rounded-lg border border-slate-300 p-4"
aria-labelledby="financial-tools-title"
>
<h3 id="financial-tools-title" className="text-lg font-semibold">
Ferramentas de planeamento financeiro
</h3>
<p className="text-sm text-slate-700">
Estimativas educativas com os valores que introduzir. Não
incluem impostos, comissões ou seguros, salvo indicação. Use a
mesma moeda em cada cálculo.
</p>
<p
className="rounded bg-amber-50 p-3 text-sm text-amber-950"
role="note"
>
Os valores que aparecem ao abrir são exemplos demonstrativos.
Altere ou confirme cada pressuposto antes de interpretar os
resultados ou exportar o relatório.
</p>
<label className="block max-w-xs text-sm font-medium">
Moeda dos valores (código ISO)
<input
list="financial-currency-options"
inputMode="text"
maxLength={3}
pattern="[A-Z]{3}"
autoCapitalize="characters"
value={currency}
onChange={(event) =>
onCurrencyChange(event.target.value.toUpperCase())
}
className="mt-1 w-full rounded border p-2"
aria-invalid={
currency !== '' && !isSimulationCurrency(currency)
}
/>
</label>
<datalist id="financial-currency-options">
{simulationCurrencyOptions.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</datalist>
<button
type="button"
disabled={
!isSimulationCurrency(currency) ||
calculationErrors.length > 0
}
className="rounded border px-3 py-2 text-sm focus-visible:outline-2 disabled:opacity-50"
onClick={() => {
const csv = exportFinancialToolsCsv({
currency,
budgetPeriod,
loan: {
principal: loan.principal,
annualRatePercent: loan.rate,
termMonths: Number(loan.months),
periodMonths: Number(loan.periodMonths),
rateType: loan.rateType,
gracePeriods: Number(loan.gracePeriods),
upfrontFee: loan.upfrontFee,
recurringFee: loan.recurringFee,
},
breakEven: {
fixedCosts: breakEven.fixed,
unitPrice: breakEven.price,
variableCostPerUnit: breakEven.variable,
},
funding: {
totalInvestment: funding.total,
securedFunding: funding.secured,
},
incomes: incomeRows,
expenses: expenseRows,
});
const blob = new Blob([csv], {
type: 'text/csv;charset=utf-8',
});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'ferramentas-financeiras.csv';
link.click();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}}
>
Exportar resultados em CSV
</button>
{calculationErrors.length > 0 && (
<p role="alert" className="text-sm text-red-800">
{calculationErrors.map((entry) => (
<span key={entry.label} className="block">
{entry.label}: {entry.message}
</span>
))}
</p>
)}
<div className="grid gap-5 md:grid-cols-2">
<fieldset className="space-y-2">
<legend className="font-semibold">
Prestação indicativa —{' '}
{currency || 'moeda por seleccionar'}
</legend>
<p role="note" className="text-sm text-slate-700">
Simulação educativa, não constitui oferta nem concessão
de crédito. A investeMoz não capta depósitos nem se
apresenta como operador de microfinanças autorizado; o
registo de operadores é um processo separado desta
calculadora.
</p>
<Field
label="Capital"
value={loan.principal}
onChange={(value) =>
update(setLoan, loan, 'principal', value)
}
/>
<Field
label="Taxa anual (%)"
value={loan.rate}
step="0.000001"
onChange={(value) =>
update(setLoan, loan, 'rate', value)
}
/>
<Field
label="Prazo (meses)"
value={loan.months}
step="1"
onChange={(value) =>
update(setLoan, loan, 'months', value)
}
/>
<label className="block text-sm font-medium">
Taxa
<select
className="mt-1 w-full rounded border p-2"
value={loan.rateType}
onChange={(event) =>
update(
setLoan,
loan,
'rateType',
event.target.value as
| 'nominal'
| 'effective',
)
}
>
<option value="nominal">Nominal anual</option>
<option value="effective">Efectiva anual</option>
</select>
</label>
<Field
label="Periodicidade (meses)"
value={loan.periodMonths}
step="1"
onChange={(value) =>
update(setLoan, loan, 'periodMonths', value)
}
/>
<Field
label="Carência (prestações só de juros)"
value={loan.gracePeriods}
step="1"
onChange={(value) =>
update(setLoan, loan, 'gracePeriods', value)
}
/>
<Field
label="Comissão inicial"
value={loan.upfrontFee}
onChange={(value) =>
update(setLoan, loan, 'upfrontFee', value)
}
/>
<Field
label="Comissão por prestação"
value={loan.recurringFee}
onChange={(value) =>
update(setLoan, loan, 'recurringFee', value)
}
/>
{schedule && isSimulationCurrency(currency) && (
<>
<p aria-live="polite">
Taxa por período: {schedule.periodicRatePercent}
%; desembolso líquido: {
schedule.netDisbursed
}{' '}
{currency}; juros: {schedule.totalInterest};
comissões: {schedule.totalFees}; total pago:{' '}
{schedule.totalPaid}.
</p>
<p className="text-xs">
Método: saldo decrescente com prestação
nivelada; a última prestação ajusta cêntimos
residuais. A carência paga apenas juros. Taxa
nominal divide a taxa anual pelos períodos; taxa
efectiva converte a taxa anual para a
periodicidade indicada.
</p>
<div className="max-h-64 overflow-auto">
<table className="min-w-full text-xs">
<caption className="sr-only">
Plano de reembolso indicativo
</caption>
<thead>
<tr>
{[
'Nº',
'Juros',
'Capital',
'Comissão',
'Prestação',
'Saldo',
].map((title) => (
<th
key={title}
className="p-1 text-left"
>
{title}
</th>
))}
</tr>
</thead>
<tbody>
{schedule.schedule.map((row) => (
<tr
key={row.period}
className="border-t"
>
<th scope="row" className="p-1">
{row.period}
{row.type ===
'interest_only'
? '*'
: ''}
</th>
<td className="p-1">
{row.interest}
</td>
<td className="p-1">
{row.principal}
</td>
<td className="p-1">
{row.fee}
</td>
<td className="p-1">
{row.totalPayment}
</td>
<td className="p-1">
{row.closingBalance}
</td>
</tr>
))}
</tbody>
</table>
</div>
<p className="text-xs">
* Período de carência: pagamento apenas de juros
e comissão indicada.
</p>
</>
)}
</fieldset>
<fieldset className="space-y-2">
<legend className="font-semibold">
Ponto de equilíbrio —{' '}
{currency || 'moeda por seleccionar'}
</legend>
<Field
label={`Custos fixos (${budgetPeriod.toLowerCase()})`}
value={breakEven.fixed}
onChange={(value) =>
update(setBreakEven, breakEven, 'fixed', value)
}
/>
<Field
label="Preço por unidade"
value={breakEven.price}
onChange={(value) =>
update(setBreakEven, breakEven, 'price', value)
}
/>
<Field
label="Custo variável por unidade"
value={breakEven.variable}
onChange={(value) =>
update(setBreakEven, breakEven, 'variable', value)
}
/>
{isSimulationCurrency(currency) && (
<p aria-live="polite">
Unidades: {point?.breakEvenUnits ?? '—'}; vendas:{' '}
{point?.breakEvenRevenue ?? '—'} {currency}
</p>
)}
</fieldset>
<fieldset className="space-y-2">
<legend className="font-semibold">
Necessidade de financiamento —{' '}
{currency || 'moeda por seleccionar'}
</legend>
<Field
label="Investimento total"
value={funding.total}
onChange={(value) =>
update(setFunding, funding, 'total', value)
}
/>
<Field
label="Montante já mobilizado"
value={funding.secured}
onChange={(value) =>
update(setFunding, funding, 'secured', value)
}
/>
{isSimulationCurrency(currency) && (
<p aria-live="polite">
Diferença por financiar: {gap?.gap ?? '—'}{' '}
{currency}
</p>
)}
</fieldset>
<fieldset className="space-y-2">
<legend className="font-semibold">
Orçamento do período —{' '}
{currency || 'moeda por seleccionar'}
</legend>
<p className="text-sm">
Introduza os totais por fonte de receita e categoria de
despesa.
</p>
<label className="block text-sm font-medium">
Período do orçamento
<select
value={budgetPeriod}
onChange={(event) =>
setBudgetPeriod(event.target.value)
}
className="mt-1 w-full rounded border p-2"
>
<option>Mensal</option>
<option>Trimestral</option>
<option>Anual</option>
<option>Outro período</option>
</select>
</label>
{incomeRows.map((row, index) => (
<div
className="grid gap-2 sm:grid-cols-[1fr_1fr_auto]"
key={`income-${index}`}
>
<label className="block text-sm font-medium">
Fonte da receita {index + 1}
<input
type="text"
maxLength={120}
value={row.label}
onChange={(event) =>
setIncomeRows((rows) =>
rows.map((item, i) =>
i === index
? {
...item,
label: event.target
.value,
}
: item,
),
)
}
className="mt-1 w-full rounded border p-2"
/>
</label>
<Field
label={`Valor da receita (${budgetPeriod.toLowerCase()})`}
value={row.amount}
onChange={(value) =>
setIncomeRows((rows) =>
rows.map((item, i) =>
i === index
? { ...item, amount: value }
: item,
),
)
}
/>
<button
type="button"
disabled={incomeRows.length <= 1}
aria-label={`Remover receita ${row.label || index + 1}`}
className="self-end rounded border px-3 py-2 text-sm disabled:opacity-50"
onClick={() =>
setIncomeRows((rows) =>
rows.length > 1
? rows.filter((_, i) => i !== index)
: rows,
)
}
>
Remover
</button>
</div>
))}
<button
type="button"
disabled={incomeRows.length >= 50}
className="text-sm underline disabled:opacity-50"
onClick={() =>
setIncomeRows((rows) =>
rows.length >= 50
? rows
: [
...rows,
{
label: `Outra receita ${rows.length + 1}`,
amount: '0',
},
],
)
}
>
Adicionar receita
</button>
{expenseRows.map((row, index) => (
<div
className="grid gap-2 sm:grid-cols-[1fr_1fr_auto]"
key={`expense-${index}`}
>
<label className="block text-sm font-medium">
Categoria da despesa {index + 1}
<input
type="text"
maxLength={120}
value={row.label}
onChange={(event) =>
setExpenseRows((rows) =>
rows.map((item, i) =>
i === index
? {
...item,
label: event.target
.value,
}
: item,
),
)
}
className="mt-1 w-full rounded border p-2"
/>
</label>
<Field
label={`Valor da despesa (${budgetPeriod.toLowerCase()})`}
value={row.amount}
onChange={(value) =>
setExpenseRows((rows) =>
rows.map((item, i) =>
i === index
? { ...item, amount: value }
: item,
),
)
}
/>
<button
type="button"
disabled={expenseRows.length <= 1}
aria-label={`Remover despesa ${row.label || index + 1}`}
className="self-end rounded border px-3 py-2 text-sm disabled:opacity-50"
onClick={() =>
setExpenseRows((rows) =>
rows.length > 1
? rows.filter((_, i) => i !== index)
: rows,
)
}
>
Remover
</button>
</div>
))}
<button
type="button"
disabled={expenseRows.length >= 50}
className="text-sm underline disabled:opacity-50"
onClick={() =>
setExpenseRows((rows) =>
rows.length >= 50
? rows
: [
...rows,
{
label: `Outra despesa ${rows.length + 1}`,
amount: '0',
},
],
)
}
>
Adicionar despesa
</button>
{budget && isSimulationCurrency(currency) && (
<p aria-live="polite">
Receitas: {budget.incomeTotal} {currency}; despesas:{' '}
{budget.expenseTotal}; saldo operacional:{' '}
<strong>{budget.operatingBalance}</strong>.
</p>
)}
</fieldset>
</div>
</section>
);
}
@@ -0,0 +1,113 @@
import { useEffect, useState } from 'react';
import { fiscalComponentCodes } from '@/lib/simulation-contract';
type Parameter = {
parameter_code: string;
status: string;
value: string | null;
unit?: string;
scope_key?: string;
rule_code?: string;
rule_version?: number;
validity?: { start: string; end: 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_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.',
};
const apiComponents: Record<string, string> = {
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) ?? '');
}
export function SimulationFiscalStatus({
salaryView,
scenarioMode,
component,
periodStart,
periodEnd,
context,
}: {
salaryView?: string;
scenarioMode?: string;
component?: string;
periodStart?: string;
periodEnd?: string;
context?: Record<string, string>;
}) {
const [parameters, setParameters] = useState<Parameter[]>([]);
const [requestState, setRequestState] = useState('idle');
useEffect(() => {
const apiComponent = component ? apiComponents[component.toLowerCase()] : undefined;
if (scenarioMode !== 'approved_parameters' || !apiComponent || !periodStart || !periodEnd) {
setParameters([]);
setRequestState('idle');
return;
}
const abort = new AbortController();
setRequestState('loading');
void fetch('/api/v1/tax-parameters/resolve', {
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');
});
return () => abort.abort();
}, [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.',
};
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>;
}
File diff suppressed because it is too large Load Diff
+78 -56
View File
@@ -1,52 +1,55 @@
import { Link, usePage } from "@inertiajs/react";
import { useId, useState } from "react";
import type { ReactNode } from "react";
import { Link, usePage } from '@inertiajs/react';
import { useId, useState } from 'react';
import type { ReactNode } from 'react';
export const portalLinks = [
["/", "Início"],
["/oportunidades", "Oportunidades de Investimento"],
["/clusters", "Clusters"],
["/corredores", "Corredores"],
["/zonas", "ZEE, ZFI e parques"],
["/projectos-ancora", "Projectos âncora"],
["/educacao", "Educação"],
["/sectores", "Sectores Prioritários"],
["/como-investir", "Como Investir"],
["/legislacao", "Legislação e Incentivos"],
["/documentos", "Documentos e Formulários"],
["/apoio", "Apoio ao Investidor"],
['/', 'Início'],
['/oportunidades', 'Oportunidades de Investimento'],
['/educacao', 'Educação'],
['/sectores', 'Sectores Prioritários'],
['/como-investir', 'Como Investir'],
['/terra-duat', 'Terra e DUAT'],
['/legislacao', 'Legislação e Incentivos'],
['/documentos', 'Documentos e Formulários'],
['/apoio', 'Apoio ao Investidor'],
] as const;
const names: Record<string, string> = {
"/investidor/negocios": "Os meus negócios",
"/management/negocios": "Revisão de negócios",
'/investidor/negocios': 'Os meus negócios',
'/management/negocios': 'Revisão de negócios',
...Object.fromEntries(portalLinks),
"/parcerias": "Bolsa de Parcerias",
"/simulador-fiscal": "Simulador Fiscal",
"/balcao-virtual": "Balcão Virtual",
"/investidor/manifestacoes": "Manifestações e favoritos",
"/investidor/profile": "Perfil e empresas",
"/investidor/notifications": "Notificações",
"/management/investment/references": "Referências e formulários",
"/management/investment/zones": "Gestão de ZEE, ZFI e parques",
"/formularios/investidor": "Formulário de investidor",
"/formularios/empresa": "Formulário de empresa",
"/manifestar-interesse": "Manifestar interesse",
"/carteira": "Corredores, clusters e projectos",
"/investidor": "O meu painel",
"/login": "Entrar",
"/register": "Criar conta",
"/dashboard": "Painel",
"/acesso-gestao": "Acesso à gestão",
"/management/portfolio": "Carteira de investimento",
"/management/ai": "Assistência",
"/management/interests": "Pedidos de interesse",
"/management/portal-services": "Documentos e parcerias",
'/investidor/terra-duat': 'Os meus pedidos Terra e DUAT',
'/management/terra-duat': 'Gestão de Terra e DUAT',
'/parcerias': 'Bolsa de Parcerias',
'/simulador-fiscal': 'Simulador Fiscal',
'/balcao-virtual': 'Balcão Virtual',
'/investidor/manifestacoes': 'Manifestações e favoritos',
'/investidor/profile': 'Perfil e empresas',
'/investidor/notifications': 'Notificações',
'/management/investment/references': 'Referências e formulários',
'/management/investment/zones': 'Gestão de ZEE, ZFI e parques',
'/formularios/investidor': 'Formulário de investidor',
'/formularios/empresa': 'Formulário de empresa',
'/manifestar-interesse': 'Manifestar interesse',
'/carteira': 'Corredores, clusters e projectos',
'/investidor': 'O meu painel',
'/login': 'Entrar',
'/register': 'Criar conta',
'/dashboard': 'Painel',
'/acesso-gestao': 'Acesso à gestão',
'/management/portfolio': 'Carteira de investimento',
'/management/ai': 'Assistência',
'/management/interests': 'Pedidos de interesse',
'/management/portal-services': 'Documentos e parcerias',
};
export default function PortalNavigation({ children }: { children: ReactNode }) {
export default function PortalNavigation({
children,
}: {
children: ReactNode;
}) {
const { url, props } = usePage();
const path = url.split("?")[0];
const path = url.split('?')[0];
const parent = Object.keys(names)
.filter((p) => p !== "/" && path.startsWith(`${p}/`))
.filter((p) => p !== '/' && path.startsWith(`${p}/`))
.sort((a, b) => b.length - a.length)[0];
const pageProps = props as {
record?: { title?: string; name?: string };
@@ -61,15 +64,15 @@ export default function PortalNavigation({ children }: { children: ReactNode })
pageProps.zone?.name ??
pageProps.sector?.name ??
pageProps.initialOpportunity?.title ??
(path.includes("/edit")
? "Editar registo"
: path.startsWith("/management")
? "Gestão do portal"
: path.startsWith("/settings")
? "Definições da conta"
: "Detalhes");
(path.includes('/edit')
? 'Editar registo'
: path.startsWith('/management')
? 'Gestão do portal'
: path.startsWith('/settings')
? 'Definições da conta'
: 'Detalhes');
return (
<div className="pb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24 [&_button]:scroll-mb-24">
<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"
@@ -78,9 +81,9 @@ export default function PortalNavigation({ children }: { children: ReactNode })
</a>
<nav
aria-label="Caminho de navegação"
className="flex flex-wrap items-center gap-2 border-b bg-background px-5 py-3 text-sm text-foreground"
className="bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm"
>
{path === "/" ? (
{path === '/' ? (
<span aria-current="page">Início</span>
) : (
<>
@@ -105,7 +108,7 @@ export default function PortalNavigation({ children }: { children: ReactNode })
</div>
<a
href="/apoio"
className="fixed right-3 bottom-3 z-50 max-w-[calc(100vw-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"
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>
@@ -114,7 +117,9 @@ export default function PortalNavigation({ children }: { children: ReactNode })
}
export function PortalMenu() {
const { existingBusinessEnabled } = usePage<{ existingBusinessEnabled?: boolean }>().props;
const { existingBusinessEnabled } = usePage<{
existingBusinessEnabled?: boolean;
}>().props;
const [expanded, setExpanded] = useState(false);
const menuId = useId();
return (
@@ -133,18 +138,35 @@ export function PortalMenu() {
aria-controls={menuId}
onClick={() => setExpanded(!expanded)}
>
{expanded ? "Fechar menu" : "Abrir menu"}
{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`}
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">
<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
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
export type BusinessLocationPath = {
province_id: string;
district_id: string;
admin_post_id: string;
locality_id: string;
};
export const emptyBusinessLocation = (): BusinessLocationPath => ({
province_id: '',
district_id: '',
admin_post_id: '',
locality_id: '',
});
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>)
: {};
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 : '',
};
});
} catch {
return [];
}
}
export function encodeBusinessLocations(rows: BusinessLocationPath[]): string {
return JSON.stringify(rows.slice(0, 20));
}
export function updateBusinessLocation(
rows: BusinessLocationPath[],
index: number,
key: keyof BusinessLocationPath,
value: string,
): BusinessLocationPath[] {
if (!rows[index]) return rows;
const next = rows.map((row) => ({ ...row }));
next[index][key] = value;
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'],
};
for (const child of children[key] ?? []) next[index][child] = '';
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 locationPathFromPayload(
payload: Record<string, string | undefined>,
): BusinessLocationPath {
return {
province_id: payload.province_id ?? '',
district_id: payload.district_id ?? '',
admin_post_id: payload.admin_post_id ?? '',
locality_id: payload.locality_id ?? '',
};
}
+2
View File
@@ -0,0 +1,2 @@
export declare function csvCell(value: unknown): string;
export declare function csvCellWithDelimiter(value: unknown, delimiter: string): string;
+20
View File
@@ -0,0 +1,20 @@
function serializeCell(value, delimiter) {
const raw = String(value ?? '');
const formulaLike = /^[\u0000-\u0020\uFEFF]*[=+\-@]/.test(raw);
const numeric = /^-?\d+(?:\.\d+)?$/.test(raw);
const text = formulaLike && !numeric ? `'${raw}` : raw;
return /[",\r\n]/.test(text) || text.includes(delimiter)
? `"${text.replaceAll('"', '""')}"`
: text;
}
/** Serializes a comma-separated cell and neutralizes spreadsheet formulas. */
export function csvCell(value) {
return serializeCell(value, ',');
}
/** Serializes a cell for a locale-specific delimited export. */
export function csvCellWithDelimiter(value, delimiter) {
return serializeCell(value, delimiter);
}
+525
View File
@@ -0,0 +1,525 @@
import { csvCell } from './csv.js';
export type FinancialToolsSnapshotData = {
budgetPeriod: string;
loan: {
principal: string;
rate: string;
months: string;
rateType: 'nominal' | 'effective';
periodMonths: string;
gracePeriods: string;
upfrontFee: string;
recurringFee: string;
};
breakEven: { fixed: string; price: string; variable: string };
funding: { total: string; secured: string };
incomes: { label: string; amount: string }[];
expenses: { label: string; amount: string }[];
};
export function serializeFinancialToolsSnapshot(
data: FinancialToolsSnapshotData,
): string {
return JSON.stringify({ version: 1, data });
}
export function restoreFinancialToolsSnapshot(
snapshot: string | undefined,
): FinancialToolsSnapshotData | null {
if (!snapshot || snapshot.length > 30_000) return null;
try {
const parsed = JSON.parse(snapshot) as {
version?: unknown;
data?: unknown;
};
if (
parsed.version !== 1 ||
!parsed.data ||
typeof parsed.data !== 'object'
)
return null;
const data = parsed.data as Record<string, unknown>;
const isText = (value: unknown, limit = 80) =>
typeof value === 'string' && value.length <= limit;
const loan = data.loan as Record<string, unknown> | null;
const breakEven = data.breakEven as Record<string, unknown> | null;
const funding = data.funding as Record<string, unknown> | null;
const rowsValid = (value: unknown) =>
Array.isArray(value) &&
value.length > 0 &&
value.length <= 50 &&
value.every(
(row) =>
row &&
typeof row === 'object' &&
isText(row.label, 120) &&
isText(row.amount, 80),
);
if (
!['Mensal', 'Trimestral', 'Anual', 'Outro período'].includes(
String(data.budgetPeriod),
) ||
!loan ||
!breakEven ||
!funding ||
![
'principal',
'rate',
'months',
'periodMonths',
'gracePeriods',
'upfrontFee',
'recurringFee',
].every((key) => isText(loan[key])) ||
!['nominal', 'effective'].includes(String(loan.rateType)) ||
!['fixed', 'price', 'variable'].every((key) =>
isText(breakEven[key]),
) ||
!['total', 'secured'].every((key) => isText(funding[key])) ||
!rowsValid(data.incomes) ||
!rowsValid(data.expenses)
)
return null;
return data as unknown as FinancialToolsSnapshotData;
} catch {
return null;
}
}
function decimalToInteger(value: string, scale: number, label: string): bigint {
const match = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
if (!match || (match[2]?.length ?? 0) > scale)
throw new Error(
`${label}: introduza um valor decimal não negativo com até ${scale} casas.`,
);
const fraction = (match[2] ?? '').padEnd(scale, '0');
return BigInt(match[1]) * 10n ** BigInt(scale) + BigInt(fraction || '0');
}
function money(cents: bigint): string {
const rounded = cents < 0n ? -cents : cents;
const text = `${rounded / 100n}.${String(rounded % 100n).padStart(2, '0')}`;
return cents < 0n ? `-${text}` : text;
}
function ratePercent(value: bigint): string {
const scaled = roundRatio(value * 100_000_000n, RATE_SCALE);
return `${scaled / 1_000_000n}.${String(scaled % 1_000_000n).padStart(6, '0')}`;
}
function roundRatio(numerator: bigint, denominator: bigint): bigint {
return (numerator + denominator / 2n) / denominator;
}
const RATE_SCALE = 1_000_000_000_000n;
const divideRound = (numerator: bigint, denominator: bigint) =>
roundRatio(numerator, denominator);
const multiplyFixed = (left: bigint, right: bigint) =>
divideRound(left * right, RATE_SCALE);
function fixedPower(base: bigint, exponent: number): bigint {
let result = RATE_SCALE;
let factor = base;
let power = exponent;
while (power > 0) {
if (power % 2 === 1) result = multiplyFixed(result, factor);
power = Math.floor(power / 2);
if (power > 0) factor = multiplyFixed(factor, factor);
}
return result;
}
function fixedRoot(value: bigint, degree: number): bigint {
let low = RATE_SCALE;
let high = value;
while (low < high) {
const middle = (low + high + 1n) / 2n;
if (fixedPower(middle, degree) <= value) low = middle;
else high = middle - 1n;
}
return low;
}
/** Compatibility wrapper: monthly nominal schedule, with fees and grace set to zero. */
export function calculateLoanPayment(
principal: string,
annualRatePercent: string,
months: number,
) {
const result = buildLoanSchedule({
principal,
annualRatePercent,
termMonths: months,
periodMonths: 1,
rateType: 'nominal',
});
return {
monthlyPayment: result.schedule[0].totalPayment,
totalPaid: result.totalPaid,
status: 'estimated' as const,
};
}
/** Contribution margin is calculated from user-entered sales and variable costs. */
export function calculateBreakEven(
fixedCosts: string,
unitPrice: string,
variableCostPerUnit: string,
) {
const fixed = decimalToInteger(fixedCosts, 2, 'Custos fixos');
const price = decimalToInteger(unitPrice, 2, 'Preço unitário');
const variable = decimalToInteger(variableCostPerUnit, 2, 'Custo variável');
if (price <= variable)
throw new Error(
'O preço unitário deve ser superior ao custo variável.',
);
const units = (fixed + (price - variable) - 1n) / (price - variable);
const revenue = units * price;
return {
contributionPerUnit: money(price - variable),
breakEvenUnits: units.toString(),
breakEvenRevenue: money(revenue),
status: 'estimated' as const,
};
}
/** Funding gap is not a lending decision; the inputs must use the same currency. */
export function calculateFundingGap(
totalInvestment: string,
securedFunding: string,
) {
const total = decimalToInteger(totalInvestment, 2, 'Investimento total');
const secured = decimalToInteger(
securedFunding,
2,
'Financiamento mobilizado',
);
return {
gap: money(total - secured),
reconciles: total === secured,
status: 'estimated' as const,
};
}
export type LoanScheduleInput = {
principal: string;
annualRatePercent: string;
termMonths: number;
periodMonths: number;
rateType: 'nominal' | 'effective';
gracePeriods?: number;
upfrontFee?: string;
recurringFee?: string;
};
/** Builds a reducing-balance schedule; fees remain separate from interest and principal. */
export function buildLoanSchedule(input: LoanScheduleInput) {
const principal = decimalToInteger(input.principal, 2, 'Capital');
const annualRate = decimalToInteger(
input.annualRatePercent,
6,
'Taxa anual',
);
const upfrontFee = decimalToInteger(
input.upfrontFee ?? '0',
2,
'Comissão inicial',
);
const recurringFee = decimalToInteger(
input.recurringFee ?? '0',
2,
'Comissão periódica',
);
if (
!Number.isSafeInteger(input.periodMonths) ||
![1, 2, 3, 4, 6, 12].includes(input.periodMonths)
)
throw new Error('Periodicidade: use 1, 2, 3, 4, 6 ou 12 meses.');
if (
!Number.isSafeInteger(input.termMonths) ||
input.termMonths < input.periodMonths ||
input.termMonths > 600 ||
input.termMonths % input.periodMonths !== 0
)
throw new Error(
'O prazo deve ser múltiplo da periodicidade e não exceder 600 meses.',
);
const periods = input.termMonths / input.periodMonths;
const gracePeriods = input.gracePeriods ?? 0;
if (
!Number.isSafeInteger(gracePeriods) ||
gracePeriods < 0 ||
gracePeriods >= periods
)
throw new Error(
'A carência deve ser inferior ao número total de prestações.',
);
if (upfrontFee > principal)
throw new Error('A comissão inicial não pode exceder o capital.');
const annualFraction = divideRound(annualRate * RATE_SCALE, 100_000_000n);
let periodicRate: bigint;
if (input.rateType === 'nominal') {
periodicRate = divideRound(
annualFraction,
BigInt(12 / input.periodMonths),
);
} else {
const periodsPerYear = 12 / input.periodMonths;
periodicRate =
fixedRoot(RATE_SCALE + annualFraction, periodsPerYear) - RATE_SCALE;
}
const amortizationPeriods = periods - gracePeriods;
const growth = fixedPower(RATE_SCALE + periodicRate, amortizationPeriods);
const regularPrincipalPayment =
periodicRate === 0n
? divideRound(principal, BigInt(amortizationPeriods))
: divideRound(
principal * periodicRate * growth,
RATE_SCALE * (growth - RATE_SCALE),
);
let balance = principal;
const schedule = [];
for (let period = 1; period <= periods; period++) {
const openingBalance = balance;
const interest = divideRound(balance * periodicRate, RATE_SCALE);
const isGrace = period <= gracePeriods;
const isFinal = period === periods;
const principalPayment = isGrace
? 0n
: isFinal
? balance
: regularPrincipalPayment - interest;
if (principalPayment < 0n)
throw new Error(
'As condições não amortizam o capital; reveja a taxa e o prazo.',
);
balance -= principalPayment;
const payment = principalPayment + interest;
schedule.push({
period,
openingBalance: money(openingBalance),
interest: money(interest),
principal: money(principalPayment),
fee: money(recurringFee),
totalPayment: money(payment + recurringFee),
closingBalance: money(balance),
type: isGrace
? ('interest_only' as const)
: ('amortization' as const),
});
}
const totalInterest = schedule.reduce(
(total, row) => total + decimalToInteger(row.interest, 2, 'Juro'),
0n,
);
const totalFees = upfrontFee + recurringFee * BigInt(periods);
return {
periodicRatePercent: ratePercent(periodicRate),
netDisbursed: money(principal - upfrontFee),
upfrontFee: money(upfrontFee),
totalInterest: money(totalInterest),
totalFees: money(totalFees),
totalPaid: money(principal + totalInterest + totalFees),
schedule,
status: 'estimated' as const,
};
}
/** A simple one-period budget allows an operating deficit; it is not forced to zero. */
export function calculateBudget(incomes: string[], expenses: string[]) {
if (incomes.length === 0 || expenses.length === 0)
throw new Error(
'Introduza pelo menos uma linha de receitas e uma linha de despesas; use zero apenas quando esse valor for conhecido.',
);
const incomeTotal = incomes.reduce(
(sum, value) => sum + decimalToInteger(value, 2, 'Receita'),
0n,
);
const expenseTotal = expenses.reduce(
(sum, value) => sum + decimalToInteger(value, 2, 'Despesa'),
0n,
);
return {
incomeTotal: money(incomeTotal),
expenseTotal: money(expenseTotal),
operatingBalance: money(incomeTotal - expenseTotal),
status: 'estimated' as const,
};
}
type IndependentCalculation<T> = {
value: T | null;
error: string | null;
};
function calculateIndependently<T>(
operation: () => T,
): IndependentCalculation<T> {
try {
return { value: operation(), error: null };
} catch (cause) {
return {
value: null,
error:
cause instanceof Error
? cause.message
: 'Verifique os valores introduzidos.',
};
}
}
export function calculateFinancialTools(input: {
loan: LoanScheduleInput;
breakEven: {
fixedCosts: string;
unitPrice: string;
variableCostPerUnit: string;
};
funding: { totalInvestment: string; securedFunding: string };
incomes: string[];
expenses: string[];
}) {
return {
loan: calculateIndependently(() => buildLoanSchedule(input.loan)),
breakEven: calculateIndependently(() =>
calculateBreakEven(
input.breakEven.fixedCosts,
input.breakEven.unitPrice,
input.breakEven.variableCostPerUnit,
),
),
funding: calculateIndependently(() =>
calculateFundingGap(
input.funding.totalInvestment,
input.funding.securedFunding,
),
),
budget: calculateIndependently(() =>
calculateBudget(input.incomes, input.expenses),
),
};
}
export type FinancialToolsReportInput = {
currency: string;
generatedAt?: string;
budgetPeriod: string;
loan: LoanScheduleInput;
breakEven: {
fixedCosts: string;
unitPrice: string;
variableCostPerUnit: string;
};
funding: { totalInvestment: string; securedFunding: string };
incomes: { label: string; amount: string }[];
expenses: { label: string; amount: string }[];
};
/** Reproducible public report matching the independent calculator outputs. */
export function exportFinancialToolsCsv(
input: FinancialToolsReportInput,
): string {
const loan = buildLoanSchedule(input.loan);
const breakEven = calculateBreakEven(
input.breakEven.fixedCosts,
input.breakEven.unitPrice,
input.breakEven.variableCostPerUnit,
);
const funding = calculateFundingGap(
input.funding.totalInvestment,
input.funding.securedFunding,
);
const budget = calculateBudget(
input.incomes.map((row) => row.amount),
input.expenses.map((row) => row.amount),
);
const rows: (string | number)[][] = [
['Relatório', 'Ferramentas de planeamento financeiro (indicativo)'],
['Versão do modelo', 'financial-tools-v1'],
['Data de exportação', input.generatedAt ?? new Date().toISOString()],
['Moeda', input.currency],
['Estado', 'Estimativa com pressupostos introduzidos pelo utilizador'],
[
'Fonte dos pressupostos',
'Valores editaveis desta ferramenta; os valores iniciais sao exemplos demonstrativos',
],
['Período do orçamento e dos custos fixos', input.budgetPeriod],
[
'Fórmula da prestação',
'Saldo decrescente; taxa nominal divide pelos períodos ou taxa efectiva convertida; última prestação ajusta resíduos',
],
[
'Fórmula do ponto de equilíbrio',
'custos fixos / (preço unitário - custo variável unitário), unidades arredondadas para cima',
],
[
'Fórmula do financiamento',
'investimento total - financiamento mobilizado; saldo negativo indica excedente declarado',
],
['Fórmula do orçamento', 'soma das receitas - soma das despesas'],
[
'Limitações',
'Não é proposta bancária nem aconselhamento; não inclui impostos; taxas e condições são pressupostos do utilizador.',
],
[],
['Pressupostos do empréstimo'],
['Capital', input.loan.principal],
['Taxa anual (%)', input.loan.annualRatePercent],
['Tipo de taxa', input.loan.rateType],
['Prazo (meses)', input.loan.termMonths],
['Periodicidade (meses)', input.loan.periodMonths],
['Carência (períodos)', input.loan.gracePeriods ?? 0],
['Comissão inicial', input.loan.upfrontFee ?? '0'],
['Comissão periódica', input.loan.recurringFee ?? '0'],
['Taxa por período (%)', loan.periodicRatePercent],
['Desembolso líquido', loan.netDisbursed],
['Juros totais', loan.totalInterest],
['Comissões totais', loan.totalFees],
['Total pago', loan.totalPaid],
[],
['Pressupostos do ponto de equilíbrio'],
['Custos fixos do período', input.breakEven.fixedCosts],
['Preço unitário', input.breakEven.unitPrice],
['Custo variável unitário', input.breakEven.variableCostPerUnit],
['Margem de contribuição unitária', breakEven.contributionPerUnit],
['Unidades de equilíbrio', breakEven.breakEvenUnits],
['Receita de equilíbrio', breakEven.breakEvenRevenue],
[],
['Necessidade de financiamento'],
['Investimento total', input.funding.totalInvestment],
['Financiamento mobilizado', input.funding.securedFunding],
['Diferença por financiar', funding.gap],
[],
['Orçamento', input.currency],
['Categoria', 'Descrição', 'Montante'],
...input.incomes.map((row) => ['Receita', row.label, row.amount]),
...input.expenses.map((row) => ['Despesa', row.label, row.amount]),
['Total de receitas', '', budget.incomeTotal],
['Total de despesas', '', budget.expenseTotal],
['Saldo operacional', '', budget.operatingBalance],
[],
['Plano de reembolso', input.currency],
[
'Período',
'Saldo inicial',
'Juros',
'Capital',
'Comissão',
'Prestação total',
'Saldo final',
],
...loan.schedule.map((row) => [
row.period,
row.openingBalance,
row.interest,
row.principal,
row.fee,
row.totalPayment,
row.closingBalance,
]),
];
return `\uFEFF${rows.map((row) => row.map(csvCell).join(',')).join('\r\n')}`;
}
+283
View File
@@ -0,0 +1,283 @@
import type { forecastBusinessPlan } from '@/lib/business-financial-plan';
type Forecast = ReturnType<typeof forecastBusinessPlan>;
export type FinancialFiscalLine = {
code:
| 'revenue'
| 'cost_of_sales'
| 'operating_expenses'
| 'personnel'
| 'depreciation'
| 'interest_expense';
origin: string;
accountingEffect: 'income' | 'expense';
taxTreatment: 'unclassified';
total: string;
monthlyAmounts: Array<{ period: number; amount: string }>;
};
function cents(value: string): bigint {
const match = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(value);
if (!match)
throw new Error('O resultado financeiro contém um montante inválido.');
const amount =
BigInt(match[2]) * 100n +
BigInt((match[3] ?? '').padEnd(2, '0') || '0');
return match[1] ? -amount : amount;
}
function formatCents(value: bigint): string {
const absolute = value < 0n ? -value : value;
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`;
}
function assertForecastReconciles(forecast: Forecast): void {
if (forecast.rows.length === 0)
throw new Error(
'A previsão financeira não contém períodos para mapear.',
);
let accountingProfit = 0n;
let totalRevenue = 0n;
let totalCollections = 0n;
let cumulativeNetCashFlow = 0n;
let previousClosingCash = cents(forecast.openingCashAfterInitialUses);
let previousOpeningReceivables = cents(forecast.openingReceivables);
let totalOpeningReceivablesCollections = 0n;
let previousPeriod = 0;
for (const row of forecast.rows) {
if (!Number.isSafeInteger(row.month) || row.month <= previousPeriod)
throw new Error(
'Os períodos da previsão financeira não estão em ordem.',
);
previousPeriod = row.month;
const revenue = cents(String(row.revenue));
totalRevenue += revenue;
accountingProfit += revenue;
for (const field of [
'variableCost',
'operatingExpenses',
'payrollExpense',
'depreciation',
'interestExpense',
] as const) {
accountingProfit -= cents(String(row[field]));
}
const salesCollections =
row.salesCollections === null
? 0n
: cents(String(row.salesCollections));
const openingReceivablesCollections = cents(
String(row.openingReceivablesCollections),
);
const openingReceivablesBalance = cents(
String(row.openingReceivablesBalance),
);
if (
openingReceivablesBalance !==
previousOpeningReceivables - openingReceivablesCollections
)
throw new Error(
'O saldo de recebíveis de abertura não reconcilia com as cobranças do período.',
);
previousOpeningReceivables = openingReceivablesBalance;
totalOpeningReceivablesCollections += openingReceivablesCollections;
const otherCollections =
row.otherCollections === null
? cents(String(row.cashCollections)) -
salesCollections -
openingReceivablesCollections
: cents(String(row.otherCollections));
if (otherCollections < 0n)
throw new Error(
'A previsão financeira contém cobranças reconciliadas inválidas.',
);
const collections = cents(String(row.cashCollections));
if (
collections !==
salesCollections + openingReceivablesCollections + otherCollections
)
throw new Error(
'As cobranças mensais não reconciliam com as suas origens.',
);
totalCollections += collections;
const netCashFlow =
collections -
cents(String(row.variableCostPayments)) -
cents(String(row.operatingPayments)) -
cents(String(row.payrollPayments)) -
cents(String(row.interestPayment)) -
cents(String(row.principalRepayment));
if (netCashFlow !== cents(String(row.netCashFlow)))
throw new Error(
'O fluxo líquido mensal não reconcilia com recebimentos e pagamentos.',
);
const closingCash = cents(String(row.closingCash));
if (closingCash !== previousClosingCash + netCashFlow)
throw new Error(
'O saldo de caixa mensal não reconcilia com o período anterior.',
);
previousClosingCash = closingCash;
cumulativeNetCashFlow += netCashFlow;
}
if (accountingProfit !== cents(forecast.totalProfitBeforeTax))
throw new Error(
'O resultado contabilístico não reconcilia com as linhas mapeadas.',
);
if (totalRevenue !== cents(forecast.totalRevenue))
throw new Error(
'A facturação total não reconcilia com os períodos mapeados.',
);
if (totalCollections !== cents(forecast.totalCashCollections))
throw new Error(
'As cobranças totais não reconciliam com o calendário de caixa.',
);
if (
totalOpeningReceivablesCollections !==
cents(forecast.totalOpeningReceivablesCollections) ||
previousOpeningReceivables !== cents(forecast.openingReceivablesAtEnd)
)
throw new Error(
'Os recebíveis de abertura não reconciliam com a previsão final.',
);
if (
previousClosingCash !== cents(forecast.endingCash) ||
cumulativeNetCashFlow !==
cents(forecast.endingCash) -
cents(forecast.openingCashAfterInitialUses)
)
throw new Error(
'O saldo final de caixa não reconcilia com o calendário mensal.',
);
}
/** Maps accounting figures into a reviewable tax-input draft without deciding tax treatment. */
export function buildFinancialFiscalBridge(forecast: Forecast) {
assertForecastReconciles(forecast);
const definitions: Array<
Pick<
FinancialFiscalLine,
'code' | 'origin' | 'accountingEffect' | 'taxTreatment'
> & { field: keyof Forecast['rows'][number] }
> = [
{
code: 'revenue',
origin: 'Produtos/serviços facturados',
accountingEffect: 'income',
taxTreatment: 'unclassified',
field: 'revenue',
},
{
code: 'cost_of_sales',
origin: 'Custo variável dos produtos',
accountingEffect: 'expense',
taxTreatment: 'unclassified',
field: 'variableCost',
},
{
code: 'operating_expenses',
origin: 'Despesas operacionais reconhecidas',
accountingEffect: 'expense',
taxTreatment: 'unclassified',
field: 'operatingExpenses',
},
{
code: 'personnel',
origin: 'Despesas com pessoal reconhecidas',
accountingEffect: 'expense',
taxTreatment: 'unclassified',
field: 'payrollExpense',
},
{
code: 'depreciation',
origin: 'Depreciação contabilística',
accountingEffect: 'expense',
taxTreatment: 'unclassified',
field: 'depreciation',
},
{
code: 'interest_expense',
origin: 'Juros reconhecidos',
accountingEffect: 'expense',
taxTreatment: 'unclassified',
field: 'interestExpense',
},
];
const accountingLines: FinancialFiscalLine[] = definitions.map(
({ field, ...definition }) => {
const monthlyAmounts = forecast.rows.map((row) => ({
period: row.month,
amount: String(row[field]),
}));
return {
...definition,
total: formatCents(
monthlyAmounts.reduce(
(sum, row) => sum + cents(row.amount),
0n,
),
),
monthlyAmounts,
};
},
);
return {
status: 'incomplete' as const,
currency: forecast.currency,
accountingProfitBeforeTax: forecast.totalProfitBeforeTax,
taxableBase: {
status: 'indeterminate' as const,
amount: null,
missingInputs: [
'expense_deductibility_classification',
'approved_tax_adjustments',
'applicable_tax_period',
'approved_effective_rule',
],
},
accountingLines,
cashSchedule: forecast.rows.map((row) => ({
period: row.month,
collectionMode:
row.salesCollections === null
? ('manual' as const)
: ('scheduled' as const),
salesCollections: row.salesCollections,
openingReceivablesCollections: row.openingReceivablesCollections,
openingReceivablesBalance: row.openingReceivablesBalance,
otherCollections:
row.otherCollections ??
formatCents(
cents(row.cashCollections) -
(row.salesCollections === null
? 0n
: cents(row.salesCollections)) -
cents(row.openingReceivablesCollections),
),
collections: row.cashCollections,
collectionsTotal: row.cashCollections,
salesReceivablesBalance: row.salesReceivablesClosing,
supplierPayments: row.variableCostPayments,
operatingPayments: row.operatingPayments,
personnelPayments: row.payrollPayments,
interestPayments: row.interestPayment,
principalRepayments: row.principalRepayment,
netCashFlow: row.netCashFlow,
closingCash: row.closingCash,
})),
notes: [
'A classificação fiscal das linhas contabilísticas está pendente; este mapeamento não afirma dedutibilidade.',
'Cobranças e pagamentos são fluxos de caixa separados das receitas e despesas reconhecidas.',
'Reembolsos de capital aparecem apenas no calendário de caixa e não como despesa contabilística.',
'Nenhum imposto, contribuição, retenção ou pagamento fiscal é somado como zero ou estimado nesta ponte.',
],
};
}
+327
View File
@@ -0,0 +1,327 @@
import { csvCell } from './csv.js';
export type MonthlyCashflowInput = {
openingCash: string;
monthlyRevenue: string;
monthlyOperatingCosts: string;
monthlyDebtService: string;
/** Empty/omitted means unknown; enter "0" to explicitly declare zero tax. */
monthlyTaxAssessed?: string | null;
/** Optional per-period user assumptions; null/blank means unknown for that month. */
monthlyTaxSchedule?: (string | null)[];
vatCreditEstimated?: string;
vatRefundRequested?: string;
vatRefundRecognized?: string;
vatRefundExpectedReceipt?: string;
vatRefundExpectedMonth?: string;
currency?: string;
periods?: number;
};
function cents(value: string, label: string): bigint {
const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(value.trim());
if (!match)
throw new Error(
`${label}: introduza um montante não negativo com até duas casas decimais.`,
);
return (
BigInt(match[1]) * 100n + BigInt((match[2] ?? '').padEnd(2, '0') || '0')
);
}
function signedCents(value: string, label: string): bigint {
const match = /^(-?\d+)(?:\.(\d{1,2}))?$/.exec(value.trim());
if (!match)
throw new Error(
`${label}: introduza um montante com até duas casas decimais.`,
);
const sign = match[1].startsWith('-') ? -1n : 1n;
return (
sign *
(BigInt(match[1].replace('-', '')) * 100n +
BigInt((match[2] ?? '').padEnd(2, '0') || '0'))
);
}
function money(value: bigint): string {
const absolute = value < 0n ? -value : value;
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`;
}
/** 12-period cashflow. VAT stages are informational except an explicitly assumed receipt month. */
export function projectMonthlyCashflow(input: MonthlyCashflowInput) {
if (input.currency) {
try {
if (
new Intl.NumberFormat('en', {
style: 'currency',
currency: input.currency,
}).resolvedOptions().maximumFractionDigits !== 2
)
throw new Error(
'Esta ferramenta requer moeda com duas casas decimais.',
);
} catch (cause) {
if (cause instanceof Error && cause.message.includes('duas casas'))
throw cause;
throw new Error(
'Seleccione uma moeda suportada com duas casas decimais.',
);
}
}
const periods = input.periods ?? 12;
if (!Number.isSafeInteger(periods) || periods < 1 || periods > 60)
throw new Error('O período deve estar entre 1 e 60 meses.');
let closingBeforeUnassessedTax = signedCents(
input.openingCash,
'Saldo inicial',
);
let closingWithAssessedTax: bigint | null = closingBeforeUnassessedTax;
const revenue = cents(input.monthlyRevenue, 'Receita mensal');
const costs = cents(input.monthlyOperatingCosts, 'Custos operacionais');
const debt = cents(input.monthlyDebtService, 'Serviço da dívida');
const scalarTaxKnown =
typeof input.monthlyTaxAssessed === 'string' &&
input.monthlyTaxAssessed.trim() !== '';
if (input.monthlyTaxSchedule !== undefined && scalarTaxKnown)
throw new Error(
'Use o imposto mensal fixo ou o calendário por mês, não ambos.',
);
let taxSchedule: (bigint | null)[];
if (input.monthlyTaxSchedule !== undefined) {
if (
!Array.isArray(input.monthlyTaxSchedule) ||
input.monthlyTaxSchedule.length !== periods ||
input.monthlyTaxSchedule.some(
(value) => value !== null && typeof value !== 'string',
)
) {
throw new Error(
'O calendário do imposto deve conter um valor ou campo vazio para cada mês projectado.',
);
}
taxSchedule = input.monthlyTaxSchedule.map((value, index) =>
typeof value === 'string' && value.trim() !== ''
? cents(value, `Imposto apurado no mês ${index + 1}`)
: null,
);
} else {
const tax = scalarTaxKnown
? cents(input.monthlyTaxAssessed as string, 'Imposto apurado')
: null;
taxSchedule = Array.from({ length: periods }, () => tax);
}
const hasUnassessedTax = taxSchedule.some((tax) => tax === null);
const vatEstimate = cents(
input.vatCreditEstimated ?? '0',
'Crédito de IVA estimado',
);
const vatRequested = cents(
input.vatRefundRequested ?? '0',
'Reembolso de IVA pedido',
);
const vatRecognized = cents(
input.vatRefundRecognized ?? '0',
'Reembolso de IVA reconhecido',
);
const vatReceipt = cents(
input.vatRefundExpectedReceipt ?? '0',
'Recebimento previsto de IVA',
);
if (vatReceipt > vatRecognized) {
throw new Error(
'O recebimento previsto de IVA não pode exceder o montante reconhecido.',
);
}
const receiptMonth = input.vatRefundExpectedMonth
? Number(input.vatRefundExpectedMonth)
: 0;
if (
vatReceipt > 0n &&
(!Number.isSafeInteger(receiptMonth) ||
receiptMonth < 1 ||
receiptMonth > periods)
) {
throw new Error(
'Indique o mês previsto do recebimento entre 1 e o horizonte projectado.',
);
}
void vatEstimate;
void vatRequested;
void vatRecognized;
const rows = [];
for (let month = 1; month <= periods; month++) {
const openingBeforeUnassessedTax = closingBeforeUnassessedTax;
const openingWithAssessedTax = closingWithAssessedTax;
const refundReceived =
vatReceipt > 0n && receiptMonth === month ? vatReceipt : 0n;
const tax = taxSchedule[month - 1];
const netFlowBeforeUnassessedTax =
revenue - costs - debt + refundReceived - (tax ?? 0n);
const netFlowWithAssessedTax =
tax === null ? null : revenue - costs - debt + refundReceived - tax;
closingBeforeUnassessedTax += netFlowBeforeUnassessedTax;
if (closingWithAssessedTax !== null) {
closingWithAssessedTax =
netFlowWithAssessedTax === null
? null
: closingWithAssessedTax + netFlowWithAssessedTax;
}
rows.push({
month,
openingCashBeforeUnassessedTax: money(openingBeforeUnassessedTax),
openingCash:
openingWithAssessedTax === null
? null
: money(openingWithAssessedTax),
revenue: money(revenue),
operatingCosts: money(costs),
debtService: money(debt),
taxAssessed: tax === null ? null : money(tax),
vatRefundExpectedReceipt: money(refundReceived),
netFlowBeforeUnassessedTax: money(netFlowBeforeUnassessedTax),
closingCashBeforeUnassessedTax: money(closingBeforeUnassessedTax),
netFlow:
netFlowWithAssessedTax === null
? null
: money(netFlowWithAssessedTax),
closingCash:
closingWithAssessedTax === null
? null
: money(closingWithAssessedTax),
});
}
return {
rows,
endingCash:
closingWithAssessedTax === null
? null
: money(closingWithAssessedTax),
endingCashBeforeUnassessedTax: money(closingBeforeUnassessedTax),
firstDeficitMonth:
rows.find(
(row) =>
row.closingCash !== null &&
BigInt(row.closingCash.replace('.', '')) < 0n,
)?.month ?? null,
firstDeficitMonthBeforeUnassessedTax:
rows.find(
(row) =>
BigInt(
row.closingCashBeforeUnassessedTax.replace('.', ''),
) < 0n,
)?.month ?? null,
vatCreditEstimated: money(vatEstimate),
vatRefundRequested: money(vatRequested),
vatRefundRecognized: money(vatRecognized),
vatRefundExpectedReceipt: money(vatReceipt),
status: hasUnassessedTax
? ('incomplete' as const)
: ('estimated' as const),
};
}
/** CSV contains only assumptions and derived financial rows supplied/calculated in this browser. */
export function exportMonthlyCashflowCsv(
input: MonthlyCashflowInput,
exportedAt = new Date().toISOString(),
): string {
if (!input.currency)
throw new Error('Seleccione a moeda antes de exportar.');
const projection = projectMonthlyCashflow(input);
const rows = [
['Relatório', 'Projecção educativa de tesouraria'],
['Versão do modelo', 'monthly-cashflow-v1'],
['Data de exportação', exportedAt],
['Horizonte', `${projection.rows.length} meses`],
['Estado', projection.status],
['Moeda', input.currency ?? 'Não seleccionada'],
[
'Fonte dos pressupostos',
'Valores do formulário; os valores pré-preenchidos podem ser exemplos demonstrativos',
],
['Pressupostos', 'Saldo inicial', input.openingCash],
['Pressupostos', 'Receita mensal', input.monthlyRevenue],
[
'Pressupostos',
'Custos operacionais mensais',
input.monthlyOperatingCosts,
],
['Pressupostos', 'Serviço mensal da dívida', input.monthlyDebtService],
[
'Pressupostos',
'Imposto assumido na projecção (saída de caixa)',
input.monthlyTaxSchedule === undefined
? input.monthlyTaxAssessed?.trim() ||
'indeterminado; não informado'
: 'Calendário variável; consultar valores mensais abaixo',
],
...(input.monthlyTaxSchedule === undefined
? []
: input.monthlyTaxSchedule.map((value, index) => [
'Pressuposto mensal de imposto',
`Mês ${index + 1}`,
value?.trim() || 'indeterminado; não informado',
])),
[
'Informativo; não caixa',
'Crédito de IVA estimado',
input.vatCreditEstimated ?? '0',
],
[
'Informativo; não caixa',
'Pedido de reembolso de IVA',
input.vatRefundRequested ?? '0',
],
[
'Informativo; não caixa',
'Reembolso de IVA reconhecido',
input.vatRefundRecognized ?? '0',
],
[
'Pressuposto condicional de caixa',
'Recebimento previsto de reembolso IVA',
input.vatRefundExpectedReceipt ?? '0',
],
[
'Pressuposto condicional de caixa',
'Mês previsto do recebimento IVA',
input.vatRefundExpectedMonth ?? 'não indicado',
],
[],
[
'Mês',
'Saldo inicial',
'Receitas',
'Custos operacionais',
'Serviço da dívida',
'Imposto assumido',
'Recebimento IVA previsto',
'Fluxo líquido',
'Saldo final',
'Fluxo conhecido antes de imposto não informado',
'Caixa conhecida antes de imposto não informado',
],
...projection.rows.map((row) => [
row.month,
row.openingCash ?? 'indeterminado',
row.revenue,
row.operatingCosts,
row.debtService,
row.taxAssessed ?? 'indeterminado',
row.vatRefundExpectedReceipt,
row.netFlow ?? 'indeterminado',
row.closingCash ?? 'indeterminado',
row.netFlowBeforeUnassessedTax,
row.closingCashBeforeUnassessedTax,
]),
[],
[
'Nota',
'O imposto indicado é pressuposto do utilizador, não cálculo ou confirmação de obrigação fiscal. Meses sem pressuposto deixam o saldo total indeterminado; a caixa conhecida inclui impostos declarados e omite apenas os meses sem valor. Recebimento previsto é pressuposto não garantido. Crédito estimado, pedido e montante reconhecido não entram no caixa. Projecção exclui sazonalidade e movimentos pontuais.',
],
];
return `\uFEFF${rows
.map((row) => row.map(csvCell).join(','))
.join('\r\n')}`;
}
+555
View File
@@ -0,0 +1,555 @@
import {
AlignmentType,
BorderStyle,
Document,
Footer,
HeadingLevel,
ImageRun,
Packer,
Paragraph,
SimpleField,
ShadingType,
Table,
TableCell,
TableLayoutType,
TableRow,
TextRun,
WidthType,
} from 'docx';
import JSZip from 'jszip';
import { buildProjectDossierRows, type ProjectDossierRow } from './project-dossier.ts';
export const dossierReportSections = [
{ id: 'summary', title: 'Resumo executivo', private: true },
{ id: 'project', title: 'Identificação e descrição do projecto', private: true },
{ id: 'market', title: 'Mercado e hipóteses', private: true },
{ id: 'location', title: 'Localização', private: true },
{ id: 'finance', title: 'Plano financeiro e cálculos', private: true },
{ id: 'team', title: 'Equipa, competências e lacunas', private: true },
{ id: 'resources', title: 'Recursos e financiamento', private: true },
{ id: 'risk', title: 'O que precisa de esclarecer: riscos e respostas', private: true },
{ id: 'execution', title: 'Marcos e execução', private: true },
{ id: 'sources', title: 'Fontes, pendências e próximos passos', private: true },
{ id: 'annexes', title: 'Anexos seleccionados', private: true },
] as const;
export type DossierReportSectionId = (typeof dossierReportSections)[number]['id'];
export type DossierReference = {
version: number;
date: string;
checksum: string;
};
export type DossierCurrentCalculation = {
status: string;
version: number;
updatedAt?: string;
snapshot: Record<string, unknown> | null;
reportChecksum?: string;
};
export type DossierAttachment = {
file: File;
include: boolean;
caption: string;
};
export type DossierAttachmentKind = 'image' | 'csv' | 'text' | 'original-only';
export type DossierReportRow = {
field: string;
value: string;
origin: string;
classification: string;
};
export type DossierReportSection = {
id: DossierReportSectionId;
title: string;
private: boolean;
paragraphs: string[];
rows: DossierReportRow[];
};
export type DossierReportModel = {
title: string;
generatedAt: string;
version: string;
sections: DossierReportSection[];
references: DossierReference[];
limitations: string[];
};
export const MAX_DOSSIER_ATTACHMENT_COUNT = 10;
export const MAX_DOSSIER_ATTACHMENT_BYTES = 15 * 1024 * 1024;
export const MAX_DOSSIER_ATTACHMENT_TOTAL_BYTES = 50 * 1024 * 1024;
const MAX_EMBEDDED_TEXT_BYTES = 2 * 1024 * 1024;
const MAX_EMBEDDED_CSV_ROWS = 250;
const MAX_EMBEDDED_CSV_COLUMNS = 16;
function text(draft: Record<string, string | string[]>, key: string): string {
const value = draft[key];
if (Array.isArray(value)) return value.filter(Boolean).join(', ');
return typeof value === 'string' ? value.trim() : '';
}
function absent(value: string): string {
return value.trim() === '' ? 'Não informado' : value;
}
function classification(origin: string): string {
const normal = origin.toLocaleLowerCase('pt-MZ');
if (normal.includes('não verificada') || normal.includes('nao verificada')) return 'Informação declarada, não verificada';
if (normal.includes('estimativa') || normal.includes('estimado')) return 'Estimativa';
if (normal.includes('indeterminado') || normal.includes('insuficiente') || normal.includes('não informado')) return 'Indeterminado';
if (normal.includes('catálogo') || normal.includes('catalogo')) return 'Referência de catálogo; não equivale a verificação documental';
if (normal.includes('utilizador') || normal.includes('declarada') || normal.includes('declarado') || normal.includes('pressuposto')) return 'Informação declarada ou pressuposto';
return 'Referência/estado indicado';
}
const rowSection: Record<string, DossierReportSectionId> = {
Projecto: 'project',
Mercado: 'market',
Localização: 'location',
'Plano financeiro': 'finance',
'Empréstimo educativo': 'finance',
'Ponto de equilíbrio': 'finance',
Orçamento: 'finance',
Equipa: 'team',
'Necessidade de negócio': 'resources',
Financiamento: 'resources',
Risco: 'risk',
Execução: 'execution',
};
function makeSections(
draft: Record<string, string | string[]>,
rows: ProjectDossierRow[],
selectedSections: ReadonlySet<DossierReportSectionId>,
references: DossierReference[],
currentCalculation: DossierCurrentCalculation | null,
generatedAt: string,
version: string,
): DossierReportSection[] {
const sections = new Map<DossierReportSectionId, DossierReportSection>();
for (const section of dossierReportSections) {
if (!selectedSections.has(section.id)) continue;
sections.set(section.id, {
id: section.id,
title: section.title,
private: section.private,
paragraphs: [],
rows: [],
});
}
const summary = sections.get('summary');
if (summary) {
const suppliedSummary = text(draft, 'project_summary');
const summaryParts = [
suppliedSummary,
!suppliedSummary && text(draft, 'project_title') ? `Projecto: ${text(draft, 'project_title')}.` : '',
!suppliedSummary && text(draft, 'project_problem') ? `Necessidade abordada: ${text(draft, 'project_problem')}.` : '',
!suppliedSummary && text(draft, 'value_proposition') ? `Proposta de valor declarada: ${text(draft, 'value_proposition')}.` : '',
!suppliedSummary && text(draft, 'target_customers') ? `Clientes/beneficiários indicados: ${text(draft, 'target_customers')}.` : '',
].filter(Boolean);
summary.paragraphs.push(summaryParts.length ? summaryParts.join(' ') : 'Resumo executivo pendente: ainda não foram introduzidas informações suficientes no dossier.');
summary.rows.push(
{ field: 'Projecto', value: absent(text(draft, 'project_title')), origin: 'Informação introduzida no dossier', classification: 'Declarada pelo utilizador' },
{ field: 'Data de geração', value: new Date(generatedAt).toLocaleString('pt-MZ'), origin: 'Relógio do dispositivo no momento da exportação', classification: 'Metadado do relatório' },
{ field: 'Versão/revisão do dossier', value: version, origin: 'Revisão de rascunho guardada ou impressão digital local', classification: 'Metadado técnico' },
);
}
for (const [sectionName, field, value, origin] of rows.slice(1)) {
const id = rowSection[sectionName];
if (!id) continue;
const section = sections.get(id);
if (!section) continue;
section.rows.push({ field, value: absent(value), origin, classification: classification(origin) });
}
const project = sections.get('project');
if (project) {
const extra = [
['Data prevista de início', text(draft, 'expected_start_date')],
['Duração prevista', text(draft, 'project_duration_years')],
];
for (const [field, value] of extra) {
if (!project.rows.some((row) => row.field === field)) project.rows.push({ field, value: absent(value), origin: 'Informação do dossier', classification: value ? 'Declarada pelo utilizador' : 'Indeterminado' });
}
}
const location = sections.get('location');
if (location) {
for (const [field, key] of [
['País', 'country_id_label'], ['Província', 'province_id_label'], ['Distrito', 'district_id_label'],
['Posto administrativo', 'admin_post_id_label'], ['Localidade', 'locality_id_label'],
]) {
if (!location.rows.some((row) => row.field === field)) {
const value = text(draft, key) || (key === 'country_id_label' && text(draft, 'country_id') === 'MZ' ? 'Moçambique' : '');
location.rows.push({ field, value: absent(value), origin: 'Selecção/informação territorial do dossier', classification: value ? 'Selecção declarada; não constitui verificação do local' : 'Indeterminado' });
}
}
}
const finance = sections.get('finance');
if (finance && currentCalculation) {
const snapshot = currentCalculation.snapshot;
const result = snapshot && typeof snapshot.result === 'object' && snapshot.result !== null && !Array.isArray(snapshot.result)
? snapshot.result as Record<string, unknown>
: null;
const context = snapshot && typeof snapshot.context === 'object' && snapshot.context !== null && !Array.isArray(snapshot.context)
? snapshot.context as Record<string, unknown>
: null;
const rawValue = result?.value ?? snapshot?.indicative_total;
const knownValue = typeof rawValue === 'string' && /^(?:\d+)(?:\.\d+)?$/.test(rawValue) ? rawValue : '';
finance.rows.push(
{ field: 'Estado da simulação fiscal/aritmética anexada', value: currentCalculation.status === 'completed' ? (result?.status === 'indeterminate' ? 'Indeterminado' : 'Concluída') : 'Não concluída; resultado não incluído como confirmado', origin: 'Execução existente no simulador', classification: currentCalculation.status === 'completed' ? 'Estado da execução; verificar a explicação e o âmbito abaixo' : 'Indeterminado' },
{ field: 'Resultado indicativo', value: currentCalculation.status === 'completed' && knownValue ? `${knownValue}${typeof result?.unit === 'string' ? ` ${result.unit}` : ''}` : 'Indeterminado/não disponível', origin: 'Snapshot da execução existente; valor reproduzido sem recalcular', classification: 'Resultado do simulador; não é decisão fiscal nem aconselhamento' },
{ field: 'Explicação e dados em falta', value: typeof result?.explanation === 'string' ? result.explanation : 'Não disponível no snapshot', origin: 'Explicação guardada pela execução', classification: 'Informação do resultado do simulador' },
{ field: 'Data de referência', value: typeof context?.reference_date === 'string' ? context.reference_date : 'Não identificada', origin: 'Contexto guardado na execução', classification: 'Metadado da simulação' },
{ field: 'Versão do motor/cenário', value: `${typeof context?.engine_version === 'string' ? context.engine_version : 'não identificada'} / ${typeof context?.scenario_version === 'number' ? context.scenario_version : currentCalculation.version}`, origin: 'Contexto guardado na execução', classification: 'Metadado técnico' },
{ field: 'Fórmula e valores usados', value: snapshot && typeof snapshot.formula_version === 'string' ? `Fórmula ${snapshot.formula_version}; base ${String(snapshot.base ?? 'não disponível')}; taxa ${String(snapshot.rate_percent ?? 'não disponível')}%; redução ${String(snapshot.reduction_percent ?? 'não disponível')}%; moeda ${String(snapshot.currency ?? 'não indicada')}` : 'A fórmula não foi identificada no snapshot; ver explicação da execução', origin: 'Snapshot guardado; sem aplicação de regra legal', classification: 'Reutilização do resultado existente' },
{ field: 'Revisão do resultado', value: String(currentCalculation.version), origin: currentCalculation.updatedAt ?? 'Data não identificada', classification: 'Versão imutável da execução existente' },
...(currentCalculation.reportChecksum ? [{ field: 'Hash SHA-256 do relatório associado', value: currentCalculation.reportChecksum, origin: 'Referência imutável do relatório', classification: 'Integridade técnica; não é fonte legal' }] : []),
);
}
if (finance && !text(draft, 'business_plan_snapshot')) {
finance.paragraphs.push('Não existe plano empresarial detalhado guardado neste dossier. Os campos sem valor são indicados como “Não informado”; não se substituem por zero.');
}
const resources = sections.get('resources');
if (resources) {
resources.rows.push({ field: 'Pré-elegibilidade de financiamento', value: 'Indeterminada; não há catálogo de produtos e critérios documentados para esta consulta.', origin: 'Limite funcional conhecido', classification: 'Não verificado/não decidido' });
const needs = text(draft, 'infrastructure_needs');
resources.rows.push({ field: 'Outros recursos declarados', value: absent(needs), origin: 'Informação do dossier', classification: needs ? 'Declarada pelo utilizador' : 'Indeterminado' });
}
const sources = sections.get('sources');
if (sources) {
const marketSource = text(draft, 'market_source');
sources.rows.push({ field: 'Origem de mercado', value: absent(marketSource), origin: 'Declarada pelo utilizador; não verificada pelo portal', classification: marketSource ? 'Informação declarada, não verificada' : 'Indeterminado' });
if (!marketSource) sources.paragraphs.push('Se disponível, registar origem e data da informação de mercado e validar a fonte antes de a usar numa decisão.');
if (references.length) {
for (const [index, ref] of references.entries()) {
sources.rows.push({ field: `Referência de cálculo anexada ${index + 1}`, value: `Versão ${ref.version}; ${new Date(ref.date).toLocaleString('pt-MZ')}; SHA-256 ${ref.checksum}`, origin: 'Simulação matemática anexada ao dossier com consentimento', classification: 'Rasto de cálculo; não é fonte oficial externa' });
}
} else {
sources.rows.push({ field: 'Cálculos de simulação anexados', value: 'Nenhum cálculo externo/anterior anexado ao dossier.', origin: 'Estado actual do dossier', classification: 'Não aplicável' });
}
const nextSteps = [
!text(draft, 'project_summary') && 'Completar o resumo do projecto ou negócio.',
!text(draft, 'market_assumption') && 'Descrever, se conhecido, a hipótese de mercado e a sua origem/data.',
!text(draft, 'business_plan_snapshot') && 'Registar pressupostos financeiros se forem necessários à decisão.',
!text(draft, 'project_team_snapshot') && 'Identificar competências/equipa em falta, caso sejam relevantes.',
'Rever os pressupostos e confirmar as fontes antes de tomar decisões.',
'Verificar critérios de financiamento em produtos documentados; esta exportação não determina elegibilidade.',
].filter((item): item is string => Boolean(item));
sources.paragraphs.push(`Próximos passos sugeridos a partir dos campos em falta: ${nextSteps.join(' ')}`);
sources.paragraphs.push('Informação não carregada ou não fornecida não é inferida. A exportação não publica nem partilha o dossier.');
}
return [...sections.values()];
}
export function createProjectDossierReport(
draft: Record<string, string | string[]>,
options: {
selectedSections: ReadonlySet<DossierReportSectionId>;
version?: string;
references?: DossierReference[];
currentCalculation?: DossierCurrentCalculation | null;
generatedAt?: string;
},
): DossierReportModel {
const generatedAt = options.generatedAt ?? new Date().toISOString();
const references = options.references ?? [];
const reportRows = buildProjectDossierRows(draft);
const title = absent(text(draft, 'project_title'));
return {
title,
generatedAt,
version: options.version?.trim() || 'Rascunho sem revisão guardada',
sections: makeSections(draft, reportRows, options.selectedSections, references, options.currentCalculation ?? null, generatedAt, options.version?.trim() || 'Rascunho sem revisão guardada'),
references,
limitations: [
'Conteúdo fornecido pelo utilizador, estimativas matemáticas, selecções de catálogo e referências documentadas estão rotulados separadamente.',
'A origem de mercado introduzida pelo utilizador não foi verificada automaticamente.',
'Não há pré-aprovação nem confirmação de financiamento nesta exportação.',
'O relatório é gerado localmente e não é publicado nem partilhado pelo portal.',
],
};
}
export function classifyDossierAttachment(file: Pick<File, 'name' | 'type' | 'size'>): DossierAttachmentKind {
const name = file.name.toLocaleLowerCase('en');
const type = file.type.toLocaleLowerCase('en');
if ((type === 'image/jpeg' || type === 'image/png') && file.size <= MAX_DOSSIER_ATTACHMENT_BYTES) return 'image';
if ((type === 'text/csv' || name.endsWith('.csv') || name.endsWith('.tsv')) && file.size <= MAX_EMBEDDED_TEXT_BYTES) return 'csv';
if ((type === 'text/plain' || name.endsWith('.txt')) && file.size <= MAX_EMBEDDED_TEXT_BYTES) return 'text';
return 'original-only';
}
export function validateDossierAttachments(files: readonly Pick<File, 'size'>[]): string | null {
if (files.length > MAX_DOSSIER_ATTACHMENT_COUNT) return `Seleccione no máximo ${MAX_DOSSIER_ATTACHMENT_COUNT} anexos.`;
if (files.some((file) => file.size > MAX_DOSSIER_ATTACHMENT_BYTES)) return 'Cada anexo deve ter até 15 MB.';
if (files.reduce((total, file) => total + file.size, 0) > MAX_DOSSIER_ATTACHMENT_TOTAL_BYTES) return 'O conjunto de anexos deve ter até 50 MB.';
return null;
}
function parseDelimited(textValue: string, delimiter: string): string[][] {
const rows: string[][] = [];
let row: string[] = [];
let cell = '';
let quoted = false;
for (let index = 0; index < textValue.length; index++) {
const char = textValue[index];
if (char === '"') {
if (quoted && textValue[index + 1] === '"') { cell += '"'; index++; }
else quoted = !quoted;
} else if (!quoted && char === delimiter) {
row.push(cell); cell = '';
} else if (!quoted && (char === '\n' || char === '\r')) {
if (char === '\r' && textValue[index + 1] === '\n') index++;
row.push(cell); rows.push(row); row = []; cell = '';
} else cell += char;
}
if (cell || row.length) { row.push(cell); rows.push(row); }
const cleaned = rows.map((values) => values.map((value) => value.replace(/^\uFEFF/, '')));
return cleaned.slice(0, MAX_EMBEDDED_CSV_ROWS).map((values) => values.slice(0, MAX_EMBEDDED_CSV_COLUMNS));
}
function csvDelimiter(value: string): string {
const first = value.split(/\r?\n/, 1)[0] ?? '';
const semicolons = (first.match(/;/g) ?? []).length;
const commas = (first.match(/,/g) ?? []).length;
const tabs = (first.match(/\t/g) ?? []).length;
return tabs > commas && tabs > semicolons ? '\t' : semicolons > commas ? ';' : ',';
}
function safePackageName(name: string, used: Set<string>): string {
const basename = name.split(/[\\/]/).pop() ?? 'anexo';
const cleaned = basename.normalize('NFKC').replace(/[^\p{L}\p{N}._-]+/gu, '_').replace(/^\.+/, '').slice(0, 120) || 'anexo';
let candidate = cleaned;
let suffix = 2;
while (used.has(candidate.toLocaleLowerCase('en'))) {
const dot = cleaned.lastIndexOf('.');
candidate = dot > 0 ? `${cleaned.slice(0, dot)}_${suffix}${cleaned.slice(dot)}` : `${cleaned}_${suffix}`;
suffix++;
}
used.add(candidate.toLocaleLowerCase('en'));
return candidate;
}
function attachmentStatus(attachment: DossierAttachment, annexesIncluded: boolean): string {
if (!attachment.include) return 'Não seleccionado para exportação';
if (!annexesIncluded) return 'Original no pacote ZIP; secção de anexos não foi incluída no relatório';
const kind = classifyDossierAttachment(attachment.file);
if (kind === 'image') return `Fotografia incorporada${attachment.caption ? `; legenda: ${attachment.caption}` : ''}; original também no pacote ZIP`;
if (kind === 'csv') return 'Tabela incorporada; original também no pacote ZIP';
if (kind === 'text') return 'Texto incorporado; original também no pacote ZIP';
return 'Conteúdo não incorporado; original preservado no pacote ZIP';
}
function tableForDocx(headers: string[], data: string[][]): Table {
const widths = headers.length === 4 ? [1850, 1850, 3450, 2210] : headers.length === 3 ? [1900, 4400, 3060] : headers.map(() => Math.floor(9360 / headers.length));
const tableRows = [headers, ...data].map((values, rowIndex) => new TableRow({
tableHeader: rowIndex === 0,
cantSplit: true,
children: headers.map((_, cellIndex) => new TableCell({
width: { size: widths[cellIndex] ?? 1500, type: WidthType.DXA },
shading: rowIndex === 0 ? { type: ShadingType.CLEAR, fill: '123B35' } : undefined,
margins: { top: 80, bottom: 80, left: 100, right: 100 },
children: [new Paragraph({ children: [new TextRun({ text: values[cellIndex] ?? '', bold: rowIndex === 0, color: rowIndex === 0 ? 'FFFFFF' : '17211F', size: 18 })] })],
})),
}));
return new Table({
rows: tableRows,
width: { size: 100, type: WidthType.PERCENTAGE },
columnWidths: widths,
layout: TableLayoutType.FIXED,
borders: Object.fromEntries(['top', 'bottom', 'left', 'right', 'insideHorizontal', 'insideVertical'].map((side) => [side, { style: BorderStyle.SINGLE, size: 4, color: 'CBD5D1' }])) as never,
});
}
function sectionTable(section: DossierReportSection): Table | null {
if (!section.rows.length) return null;
return tableForDocx(['Campo', 'Conteúdo', 'Classificação / origem'], section.rows.map((row) => [row.field, row.value, `${row.classification}. ${row.origin}`]));
}
async function imageRuns(attachment: DossierAttachment): Promise<(Paragraph | Table)[]> {
const file = attachment.file;
const type = file.type === 'image/jpeg' ? 'jpg' : 'png';
const data = new Uint8Array(await file.arrayBuffer());
let sourceWidth = 0;
let sourceHeight = 0;
if (type === 'png') {
if (data.length < 24 || data[0] !== 0x89 || data[1] !== 0x50 || data[2] !== 0x4e || data[3] !== 0x47 || data[12] !== 0x49 || data[13] !== 0x48 || data[14] !== 0x44 || data[15] !== 0x52) {
throw new Error(`A fotografia ${file.name} não tem um cabeçalho PNG válido.`);
}
sourceWidth = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(16);
sourceHeight = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(20);
} else {
if (data.length < 4 || data[0] !== 0xff || data[1] !== 0xd8) throw new Error(`A fotografia ${file.name} não tem um cabeçalho JPEG válido.`);
const frameMarkers = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
for (let offset = 2; offset + 8 < data.length;) {
if (data[offset] !== 0xff) { offset++; continue; }
while (data[offset] === 0xff) offset++;
const marker = data[offset++];
if (marker === 0xd9 || marker === 0xda) break;
if ([0x01, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7].includes(marker)) continue;
const segmentLength = (data[offset] << 8) | data[offset + 1];
if (segmentLength < 2 || offset + segmentLength > data.length) break;
if (frameMarkers.has(marker)) {
sourceHeight = (data[offset + 3] << 8) | data[offset + 4];
sourceWidth = (data[offset + 5] << 8) | data[offset + 6];
break;
}
offset += segmentLength;
}
}
if (!sourceWidth || !sourceHeight || sourceWidth * sourceHeight > 40_000_000 || sourceWidth > 12_000 || sourceHeight > 12_000) {
throw new Error(`As dimensões da fotografia ${file.name} são inválidas ou excedem o limite de segurança.`);
}
const scale = Math.min(1, 520 / sourceWidth, 620 / sourceHeight);
const width = Math.max(1, Math.round(sourceWidth * scale));
const height = Math.max(1, Math.round(sourceHeight * scale));
return [
new Paragraph({ alignment: AlignmentType.CENTER, children: [new ImageRun({ data, type, transformation: { width, height }, altText: { name: file.name, description: attachment.caption || file.name, title: file.name } })] }),
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: attachment.caption || file.name, italics: true, size: 18 })] }),
];
}
async function annexDocxBlocks(attachments: DossierAttachment[]): Promise<(Paragraph | Table)[]> {
const blocks: (Paragraph | Table)[] = [];
for (const attachment of attachments.filter((item) => item.include)) {
const kind = classifyDossierAttachment(attachment.file);
blocks.push(new Paragraph({ text: attachment.file.name, heading: HeadingLevel.HEADING_3, keepNext: true }));
if (kind === 'image') {
blocks.push(...await imageRuns(attachment));
} else if (kind === 'text') {
const contents = (await attachment.file.text()).replace(/^\uFEFF/, '');
for (const line of contents.split(/\r?\n/).slice(0, 1000)) blocks.push(new Paragraph({ children: [new TextRun({ text: line || ' ' })] }));
} else if (kind === 'csv') {
const contents = (await attachment.file.text()).replace(/^\uFEFF/, '');
const rows = parseDelimited(contents, csvDelimiter(contents));
const headers = rows[0] ?? [];
const data = rows.slice(1);
if (headers.length) blocks.push(tableForDocx(headers, data));
if (contents.split(/\r?\n/).length > MAX_EMBEDDED_CSV_ROWS) blocks.push(new Paragraph('A tabela foi truncada para 250 linhas no relatório; o original completo acompanha o pacote ZIP.'));
} else {
blocks.push(new Paragraph('Este formato não foi incorporado ao DOCX. Para preservar o original, exporte também o pacote ZIP de anexos com o respectivo índice.'));
}
}
return blocks;
}
export async function generateProjectDossierDocx(
model: DossierReportModel,
attachments: DossierAttachment[],
annexesIncluded: boolean,
): Promise<Blob> {
const children: (Paragraph | Table)[] = [
new Paragraph({ text: 'InvestMoz', heading: HeadingLevel.HEADING_2 }),
new Paragraph({ text: 'Relatório consolidado do projecto', heading: HeadingLevel.TITLE }),
new Paragraph({ children: [new TextRun({ text: model.title, bold: true, size: 30 })] }),
new Paragraph({ children: [new TextRun({ text: `Gerado em ${new Date(model.generatedAt).toLocaleString('pt-MZ')} · versão ${model.version}`, color: '52615D', size: 20 })] }),
new Paragraph({ children: [new TextRun({ text: 'Documento privado gerado neste dispositivo. A exportação não publica nem partilha o conteúdo.', bold: true, color: '8A4B08' })] }),
];
for (const section of model.sections) {
if (section.id === 'annexes') {
children.push(new Paragraph({ text: section.title, heading: HeadingLevel.HEADING_1 }));
if (annexesIncluded) children.push(...await annexDocxBlocks(attachments));
if (!attachments.some((item) => item.include)) children.push(new Paragraph('Nenhum anexo foi seleccionado.'));
if (attachments.some((item) => item.include && classifyDossierAttachment(item.file) === 'original-only')) children.push(new Paragraph('Os ficheiros que não podem ser incorporados de forma legível devem ser exportados também no pacote ZIP, com índice.'));
continue;
}
children.push(new Paragraph({ text: section.title, heading: HeadingLevel.HEADING_1, keepNext: true }));
for (const paragraph of section.paragraphs) children.push(new Paragraph({ children: [new TextRun({ text: paragraph })] }));
const table = sectionTable(section);
if (table) children.push(table);
if (!section.rows.length && !section.paragraphs.length) children.push(new Paragraph('Não há informação fornecida nesta secção.'));
}
const footer = new Footer({ children: [new Paragraph({ alignment: AlignmentType.RIGHT, children: [new TextRun({ text: 'InvestMoz · relatório privado · página ' }), new SimpleField('PAGE')] })] });
const doc = new Document({
creator: 'InvestMoz',
title: `Relatório do projecto — ${model.title}`,
description: 'Dossier consolidado exportado localmente a partir do formulário InvestMoz.',
styles: {
default: { document: { run: { font: 'Aptos', size: 20, color: '17211F' }, paragraph: { spacing: { after: 120, line: 276 } } } },
paragraphStyles: [
{ id: 'Title', name: 'Title', basedOn: 'Normal', run: { font: 'Aptos Display', size: 34, bold: true, color: '123B35' }, paragraph: { spacing: { before: 200, after: 220 } } },
{ id: 'Heading1', name: 'Heading 1', basedOn: 'Normal', next: 'Normal', run: { font: 'Aptos Display', size: 26, bold: true, color: '123B35' }, paragraph: { spacing: { before: 320, after: 150 }, keepNext: true } },
{ id: 'Heading2', name: 'Heading 2', basedOn: 'Normal', next: 'Normal', run: { font: 'Aptos', size: 24, bold: true, color: '27675C' }, paragraph: { spacing: { before: 260, after: 120 }, keepNext: true } },
{ id: 'Heading3', name: 'Heading 3', basedOn: 'Normal', next: 'Normal', run: { font: 'Aptos', size: 22, bold: true, color: '27675C' }, paragraph: { spacing: { before: 200, after: 100 }, keepNext: true } },
],
},
sections: [{
properties: { page: { size: { width: 12240, height: 15840 }, margin: { top: 900, right: 960, bottom: 900, left: 960, footer: 450, header: 450 } } },
footers: { default: footer },
children,
}],
});
return Packer.toBlob(doc);
}
function escapeHtml(value: string): string {
return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;');
}
async function fileDataUrl(file: File): Promise<string> {
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return `data:${file.type};base64,${btoa(binary)}`;
}
function htmlTable(headers: string[], rows: string[][]): string {
return `<table><thead><tr>${headers.map((value) => `<th>${escapeHtml(value)}</th>`).join('')}</tr></thead><tbody>${rows.map((row) => `<tr>${headers.map((_, index) => `<td>${escapeHtml(row[index] ?? '')}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
}
export async function createProjectDossierPrintHtml(
model: DossierReportModel,
attachments: DossierAttachment[],
annexesIncluded: boolean,
): Promise<string> {
const content: string[] = [];
for (const section of model.sections) {
content.push(`<section><h2>${escapeHtml(section.title)}</h2>`);
for (const paragraph of section.paragraphs) content.push(`<p>${escapeHtml(paragraph)}</p>`);
if (section.rows.length) content.push(htmlTable(['Campo', 'Conteúdo', 'Classificação / origem'], section.rows.map((row) => [row.field, row.value, `${row.classification}. ${row.origin}`])));
if (section.id === 'annexes') {
const selected = attachments.filter((item) => item.include);
if (!selected.length) content.push('<p>Nenhum anexo foi seleccionado.</p>');
if (!annexesIncluded) content.push('<p>A secção de anexos foi omitida do relatório. Os originais seleccionados continuam no pacote ZIP.</p>');
else for (const attachment of selected) {
const kind = classifyDossierAttachment(attachment.file);
content.push(`<h3>${escapeHtml(attachment.file.name)}</h3>`);
if (kind === 'image') content.push(`<figure><img alt="${escapeHtml(attachment.caption || attachment.file.name)}" src="${await fileDataUrl(attachment.file)}"><figcaption>${escapeHtml(attachment.caption || attachment.file.name)}</figcaption></figure>`);
else if (kind === 'text') content.push(`<pre>${escapeHtml((await attachment.file.text()).slice(0, MAX_EMBEDDED_TEXT_BYTES))}</pre>`);
else if (kind === 'csv') {
const source = (await attachment.file.text()).slice(0, MAX_EMBEDDED_TEXT_BYTES);
const rows = parseDelimited(source, csvDelimiter(source));
content.push(htmlTable(rows[0] ?? [], rows.slice(1)));
} else content.push('<p>Conteúdo original não incorporado nesta versão PDF. Para obter o original, exporte também o pacote ZIP com índice.</p>');
}
}
if (!section.rows.length && !section.paragraphs.length && section.id !== 'annexes') content.push('<p>Não há informação fornecida nesta secção.</p>');
content.push('</section>');
}
return `<!doctype html><html lang="pt-MZ"><head><meta charset="utf-8"><title>Relatório — ${escapeHtml(model.title)}</title><style>
@page{size:A4;margin:18mm 17mm 20mm}*{box-sizing:border-box}body{font:10.5pt/1.45 Arial,sans-serif;color:#17211f;margin:0}h1{font-size:24pt;color:#123b35;margin:0 0 7mm}h2{font-size:16pt;color:#123b35;border-bottom:1px solid #b8c9c3;padding-bottom:2mm;margin:8mm 0 3mm;break-after:avoid}h3{font-size:12pt;color:#27675c;break-after:avoid}p{white-space:pre-wrap}table{width:100%;border-collapse:collapse;table-layout:fixed;margin:3mm 0 5mm;break-inside:auto}th,td{border:1px solid #cbd5d1;padding:5px 6px;text-align:left;vertical-align:top;overflow-wrap:anywhere}th{background:#123b35;color:white}tr{break-inside:avoid}th:first-child,td:first-child{width:22%}th:last-child,td:last-child{width:32%;font-size:9pt;color:#40524d}.private{padding:3mm;background:#fff4df;border-left:3px solid #b66a0c;font-weight:bold}section{break-inside:auto}figure{margin:5mm auto;text-align:center;break-inside:avoid}img{max-width:100%;max-height:210mm;object-fit:contain}figcaption{font-style:italic;color:#52615d}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:9.5pt/1.4 Arial,sans-serif}@media print{a{color:inherit;text-decoration:none}.no-print{display:none}}
</style></head><body><h1>InvestMoz<br>Relatório consolidado do projecto</h1><p><strong>${escapeHtml(model.title)}</strong><br>Gerado em ${escapeHtml(new Date(model.generatedAt).toLocaleString('pt-MZ'))}<br>Versão/revisão: ${escapeHtml(model.version)}</p><p class="private">Documento privado. O portal não publica nem partilha este conteúdo.</p>${content.join('')}<footer><small>InvestMoz · Relatório privado · ${escapeHtml(model.version)}</small></footer><script>window.addEventListener('load',()=>setTimeout(()=>window.print(),350));</script></body></html>`;
}
export async function generateProjectDossierPackage(
docxBlob: Blob,
attachments: DossierAttachment[],
annexesIncluded: boolean,
): Promise<Blob> {
const zip = new JSZip();
zip.file('Relatorio/relatorio-projecto-investmoz.docx', docxBlob);
const usedNames = new Set<string>();
const selected = attachments.filter((item) => item.include);
const index = ['ÍNDICE DO PACOTE DE RELATÓRIO INVESTMOZ', '', 'O relatório e os anexos são privados e foram seleccionados localmente pelo utilizador.', ''].join('\n');
const records: string[] = [];
for (const attachment of selected) {
const filename = safePackageName(attachment.file.name, usedNames);
zip.file(`Anexos/${filename}`, attachment.file, { binary: true });
records.push(`Ficheiro: ${filename}\nTamanho: ${attachment.file.size} bytes\nTipo: ${attachment.file.type || 'desconhecido'}\nSituação: ${attachmentStatus(attachment, annexesIncluded)}\nLegenda: ${attachment.caption || 'Não indicada'}\n`);
}
zip.file('indice-anexos.txt', `${index}${records.length ? records.join('\n') : 'Não foram seleccionados anexos.\n'}`);
return zip.generateAsync({ type: 'blob', mimeType: 'application/zip', compression: 'DEFLATE', compressionOptions: { level: 6 } });
}
+179
View File
@@ -0,0 +1,179 @@
import { csvCellWithDelimiter } from './csv.js';
import {
calculateFinancialTools,
restoreFinancialToolsSnapshot,
} from './financial-calculators.ts';
import {
forecastBusinessPlan,
restoreBusinessPlanSnapshot,
} from './business-financial-plan.ts';
import { getProjectReadiness, readPlannedRiskResponses } from './project-readiness.ts';
export type TeamNeed = {
competency: string;
state: 'available' | 'gap' | 'unknown';
action: string;
estimated_cost: string;
due_date: string;
};
export type ProjectMilestone = {
title: string;
due_date: string;
status: 'planned' | 'in_progress' | 'completed';
planned_amount: string;
actual_amount: string;
};
export function readRows<T>(value: string, allowed: readonly string[]): T[] {
try {
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')),
);
} catch {
return [];
}
}
export type ProjectDossierRow = [section: string, field: string, value: string, origin: string];
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'],
];
const plannedResponses = readPlannedRiskResponses(draft);
for (const item of getProjectReadiness(draft)) {
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(' · ')
: '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']);
}
const finance = restoreFinancialToolsSnapshot(String(draft.financial_tools_snapshot ?? ''));
if (finance) {
const calculation = calculateFinancialTools({
loan: {
principal: finance.loan.principal,
annualRatePercent: finance.loan.rate,
rateType: finance.loan.rateType,
termMonths: Number(finance.loan.months),
periodMonths: Number(finance.loan.periodMonths),
gracePeriods: Number(finance.loan.gracePeriods),
upfrontFee: finance.loan.upfrontFee,
recurringFee: finance.loan.recurringFee,
},
breakEven: {
fixedCosts: finance.breakEven.fixed,
unitPrice: finance.breakEven.price,
variableCostPerUnit: finance.breakEven.variable,
},
funding: {
totalInvestment: finance.funding.total,
securedFunding: finance.funding.secured,
},
incomes: finance.incomes.map((row) => row.amount),
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';
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],
);
for (const income of finance.incomes) {
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']);
}
}
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';
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'],
);
} catch {
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, 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 {
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')}`;
}
+174
View File
@@ -0,0 +1,174 @@
export type ProjectReadinessKind = 'missing' | 'unverified' | 'risk';
export type ProjectReadinessItem = {
id: string;
kind: ProjectReadinessKind;
title: string;
origin: string;
affected: string;
consequence: string;
nextAction: string;
fieldKey: string;
};
export type PlannedRiskResponse = {
risk_id: string;
action: string;
owner: string;
estimated_cost: string;
due_date: string;
};
export type ReadinessDraft = Record<string, string | string[]>;
function value(draft: ReadinessDraft, key: string): string {
const current = draft[key];
return typeof current === 'string' ? current.trim() : '';
}
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)),
)
: [];
} catch {
return [];
}
}
export function getProjectReadiness(
draft: ReadinessDraft,
): ProjectReadinessItem[] {
const items: ProjectReadinessItem[] = [];
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') ||
value(draft, 'financial_tools_snapshot') ||
value(draft, 'annual_operating_costs');
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 benefits = value(draft, 'claimed_benefits');
const customerStatus = value(draft, 'customer_validation_status');
const costStatus = value(draft, 'cost_estimate_status');
const locationStatus = value(draft, 'location_assessment_status');
const fundingStatus = value(draft, 'funding_status');
const collectionStatus = value(draft, 'receivables_timing_status');
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.',
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.',
fieldKey: 'target_customers',
});
} 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',
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.',
fieldKey: 'market_source',
});
}
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.',
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.',
fieldKey: 'financial',
});
}
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',
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.',
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.',
fieldKey: 'financial',
});
}
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',
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.',
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.',
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.',
fieldKey: 'team',
});
}
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.`,
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.',
fieldKey: 'financial',
});
}
if (benefits) {
items.push({
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.',
fieldKey: 'tax',
});
}
return items;
}
export function readPlannedRiskResponses(draft: ReadinessDraft): PlannedRiskResponse[] {
try {
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',
));
} catch {
return [];
}
}
export function serializePlannedRiskResponses(responses: PlannedRiskResponse[]): string {
return JSON.stringify(responses.slice(0, 30));
}
+61
View File
@@ -0,0 +1,61 @@
import { isApiErrorV1 } from './simulation-contract.ts';
export type SimulationApiChoice = { id: string; label: string };
function scalar(value: unknown): string {
return typeof value === 'string' ||
(typeof value === 'number' && Number.isFinite(value))
? String(value)
: '';
}
/** Parse API bodies without leaking JSON parser errors into the public form. */
export async function readSimulationApiJson(
response: Response,
): Promise<unknown> {
try {
return await response.json();
} catch {
return null;
}
}
/** Prefer field validation details, falling back to the shared API message. */
export function simulationApiErrorMessage(value: unknown): string | undefined {
if (!isApiErrorV1(value)) return undefined;
const validationMessages = Object.values(value.errors ?? {}).flat();
return validationMessages.length
? validationMessages.join(' ')
: value.message;
}
/** Explain a failed status check without implying the accepted job was lost. */
export function simulationPollingFailureMessage(value: unknown): string {
return (
simulationApiErrorMessage(value) ??
'O cenário foi recebido, mas não foi possível confirmar o estado do cálculo. Consulte o histórico antes de tentar novamente.'
);
}
/** Validate and normalize the public reference catalog envelope. */
export function simulationCatalogChoices(
value: unknown,
): SimulationApiChoice[] {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!Array.isArray((value as Record<string, unknown>).data)
)
throw new Error('O servidor devolveu opções com formato inválido.');
return (value as { data: unknown[] }).data.flatMap((row) => {
if (!row || typeof row !== 'object' || Array.isArray(row)) return [];
const record = row as Record<string, unknown>;
const choice = {
id: scalar(record.id ?? record.value),
label: scalar(record.label ?? record.name),
};
return choice.id && choice.label ? [choice] : [];
});
}
+672
View File
@@ -0,0 +1,672 @@
/** Shared vocabulary for simulator values. Decimal amounts stay strings at API boundaries. */
export type DecimalString = string;
export type ResultStatus =
| 'calculated'
| 'estimated'
| 'indeterminate'
| 'not_applicable';
export const fiscalComponentCodes = [
'IRPS',
'INSS',
'IVA',
'IRPC',
'ISPC',
'RETENCOES',
] as const;
export type FiscalComponentCode = (typeof fiscalComponentCodes)[number];
export type SimulationContext = {
contractVersion: 1;
referenceDate: string;
currency: string | null;
currencyFractionDigits: number | null;
scenarioId: string;
engineVersion: string;
rulesetVersion: string | null;
};
export type SimulationResult<TValue = DecimalString> = {
status: ResultStatus;
value: TValue | null;
unit: string | null;
explanation: string;
missingInputs: string[];
sourceIds: string[];
};
/** Exact JSON envelope returned by the v1 API (wire keys stay snake_case). */
export type ApiSimulationResultV1 = {
status: ResultStatus;
value: DecimalString | null;
unit: string | null;
explanation: string;
missing_inputs: string[];
source_ids: string[];
};
export type ApiSimulationResultContextV1 = {
reference_date: string;
currency: string | null;
currency_fraction_digits: number | null;
scenario_id: string;
scenario_version: number;
engine_version: string;
ruleset_version: string | null;
};
export type ApiSimulationResultSnapshotV1 = {
contract_version: 1;
context: ApiSimulationResultContextV1;
result: ApiSimulationResultV1;
indicative_total: DecimalString | null;
legal_interpretation: false;
formula_version: string;
};
const apiDecimalPattern = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/;
const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** Runtime guard for untrusted API JSON; zero remains a valid decimal value. */
export function isApiSimulationResultSnapshotV1(
value: unknown,
): value is ApiSimulationResultSnapshotV1 {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const snapshot = value as Record<string, unknown>;
const context = snapshot.context;
const result = snapshot.result;
if (
snapshot.contract_version !== 1 ||
snapshot.legal_interpretation !== false ||
typeof snapshot.formula_version !== 'string' ||
!snapshot.formula_version.trim() ||
!(
snapshot.indicative_total === null ||
(typeof snapshot.indicative_total === 'string' &&
apiDecimalPattern.test(snapshot.indicative_total))
) ||
!context ||
typeof context !== 'object' ||
Array.isArray(context) ||
!result ||
typeof result !== 'object' ||
Array.isArray(result)
)
return false;
const meta = context as Record<string, unknown>;
const output = result as Record<string, unknown>;
const currencyValid =
meta.currency === null ||
(typeof meta.currency === 'string' && /^[A-Z]{3}$/.test(meta.currency));
const currencyDigitsValid =
meta.currency_fraction_digits === null ||
(Number.isInteger(meta.currency_fraction_digits) &&
Number(meta.currency_fraction_digits) >= 0 &&
Number(meta.currency_fraction_digits) <= 6);
if (
!isIsoDate(meta.reference_date) ||
!uuidPattern.test(String(meta.scenario_id)) ||
!Number.isSafeInteger(meta.scenario_version) ||
Number(meta.scenario_version) < 1 ||
typeof meta.engine_version !== 'string' ||
!meta.engine_version.trim() ||
!(
meta.ruleset_version === null ||
typeof meta.ruleset_version === 'string'
) ||
!currencyValid ||
!currencyDigitsValid ||
(meta.currency === null) !== (meta.currency_fraction_digits === null) ||
![
'calculated',
'estimated',
'indeterminate',
'not_applicable',
].includes(String(output.status)) ||
!(
output.value === null ||
(typeof output.value === 'string' &&
apiDecimalPattern.test(output.value))
) ||
output.value !== snapshot.indicative_total ||
!(output.unit === null || typeof output.unit === 'string') ||
typeof output.explanation !== 'string' ||
!output.explanation.trim() ||
!Array.isArray(output.missing_inputs) ||
!output.missing_inputs.every(
(item) => typeof item === 'string' && item.length > 0,
) ||
!Array.isArray(output.source_ids) ||
!output.source_ids.every(
(item) => typeof item === 'string' && item.length > 0,
)
)
return false;
if (
(output.status === 'calculated' || output.status === 'estimated') &&
output.value === null
)
return false;
if (
output.status === 'indeterminate' &&
(output.value !== null || output.missing_inputs.length === 0)
)
return false;
if (output.status === 'not_applicable' && output.value !== null)
return false;
return true;
}
export const apiSimulationExecutionStatuses = [
'queued',
'running',
'completed',
'failed',
'cancelled',
] as const;
export type ApiSimulationExecutionStatus =
(typeof apiSimulationExecutionStatuses)[number];
/** Minimum execution fields consumed by the public form and result reader. */
export type ApiSimulationExecutionV1 = {
id: string;
status: ApiSimulationExecutionStatus;
version_no: number;
result_snapshot?: Record<string, unknown> | null;
[key: string]: unknown;
};
export function isApiSimulationExecutionV1(
value: unknown,
): value is ApiSimulationExecutionV1 {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const execution = value as Record<string, unknown>;
const hasSnapshot = Object.prototype.hasOwnProperty.call(
execution,
'result_snapshot',
);
const snapshot = execution.result_snapshot;
const snapshotValid =
snapshot === undefined || snapshot === null
? execution.status !== 'completed'
: !!snapshot &&
typeof snapshot === 'object' &&
!Array.isArray(snapshot) &&
(isApiSimulationResultSnapshotV1(snapshot) ||
(typeof (snapshot as Record<string, unknown>)
.indicative_total === 'string' &&
/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(
(snapshot as Record<string, string>).indicative_total,
) &&
!Object.prototype.hasOwnProperty.call(
snapshot,
'contract_version',
)));
return (
typeof execution.id === 'string' &&
uuidPattern.test(execution.id) &&
apiSimulationExecutionStatuses.includes(
execution.status as ApiSimulationExecutionStatus,
) &&
Number.isSafeInteger(execution.version_no) &&
Number(execution.version_no) > 0 &&
snapshotValid &&
(execution.status !== 'completed' || hasSnapshot)
);
}
export type ApiSimulationCreateResponseV1 = {
data: ApiSimulationExecutionV1;
replayed: boolean;
access_token?: string;
};
export function isApiSimulationCreateResponseV1(
value: unknown,
): value is ApiSimulationCreateResponseV1 {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const response = value as Record<string, unknown>;
return (
isApiSimulationExecutionV1(response.data) &&
typeof response.replayed === 'boolean' &&
(response.access_token === undefined ||
(typeof response.access_token === 'string' &&
response.access_token.length >= 32 &&
response.access_token.length <= 256))
);
}
export function isApiSimulationReadResponseV1(
value: unknown,
): value is { data: ApiSimulationExecutionV1 } {
return (
!!value &&
typeof value === 'object' &&
!Array.isArray(value) &&
isApiSimulationExecutionV1((value as Record<string, unknown>).data)
);
}
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
!!value && typeof value === 'object' && !Array.isArray(value);
const isIsoDateTime = (value: unknown): value is string =>
typeof value === 'string' &&
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(
value,
) &&
Number.isFinite(Date.parse(value));
const isIsoDate = (value: unknown): value is string =>
typeof value === 'string' &&
(() => {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (!match) return false;
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (year < 1 || month < 1 || month > 12 || day < 1) return false;
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
const daysInMonth = [
31,
leap ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
return day <= daysInMonth[month - 1];
})();
export function isApiErrorV1(value: unknown): value is {
message?: string;
errors?: Record<string, string[]>;
[key: string]: unknown;
} {
if (!isPlainObject(value)) return false;
if (value.message !== undefined && typeof value.message !== 'string')
return false;
if (value.errors !== undefined) {
if (!isPlainObject(value.errors)) return false;
if (
!Object.values(value.errors).every(
(messages) =>
Array.isArray(messages) &&
messages.every((message) => typeof message === 'string'),
)
)
return false;
}
return typeof value.message === 'string' || value.errors !== undefined;
}
export function isApiQuestionnaireReadResponseV1(value: unknown): value is {
data: {
id: string;
code: string;
version_no: number;
locale: 'pt-MZ';
schema_snapshot: Record<string, unknown>;
status: 'published';
valid_from: string | null;
valid_to: string | null;
};
} {
if (!isPlainObject(value) || !isPlainObject(value.data)) return false;
const data = value.data;
return (
typeof data.id === 'string' &&
uuidPattern.test(data.id) &&
typeof data.code === 'string' &&
/^[a-z0-9][a-z0-9-]{0,79}$/.test(data.code) &&
Number.isSafeInteger(data.version_no) &&
Number(data.version_no) > 0 &&
data.locale === 'pt-MZ' &&
isPlainObject(data.schema_snapshot) &&
data.status === 'published' &&
(data.valid_from === null || isIsoDate(data.valid_from)) &&
(data.valid_to === null || isIsoDate(data.valid_to))
);
}
export function isApiSimulationReportReadResponseV1(value: unknown): value is {
data: {
id: string;
simulation_id: string;
version_no: number;
status: 'queued' | 'ready' | 'failed';
report_snapshot: Record<string, unknown> | null;
report_sha256: string | null;
};
} {
if (!isPlainObject(value) || !isPlainObject(value.data)) return false;
const data = value.data;
const shapeValid =
typeof data.id === 'string' &&
uuidPattern.test(data.id) &&
typeof data.simulation_id === 'string' &&
uuidPattern.test(data.simulation_id) &&
Number.isSafeInteger(data.version_no) &&
Number(data.version_no) > 0 &&
(data.status === 'queued' ||
data.status === 'ready' ||
data.status === 'failed') &&
(data.report_snapshot === null ||
isPlainObject(data.report_snapshot)) &&
(data.report_sha256 === null ||
(typeof data.report_sha256 === 'string' &&
/^[a-f0-9]{64}$/i.test(data.report_sha256)));
if (!shapeValid) return false;
if (data.status === 'ready') {
return (
isPlainObject(data.report_snapshot) &&
typeof data.report_sha256 === 'string' &&
/^[a-f0-9]{64}$/i.test(data.report_sha256)
);
}
return data.report_snapshot === null && data.report_sha256 === null;
}
export type ApiSimulationJobV1 = {
id: string;
simulation_id: string;
job_type: 'execute' | 'report';
status: 'pending' | 'running' | 'succeeded' | 'failed';
attempts: number;
available_at: string;
started_at: string | null;
finished_at: string | null;
error_code: string | null;
};
export function isApiSimulationJobsReadResponseV1(value: unknown): value is {
data: ApiSimulationJobV1[];
} {
if (!isPlainObject(value) || !Array.isArray(value.data)) return false;
return value.data.every((job: unknown) => {
if (!isPlainObject(job)) return false;
return (
typeof job.id === 'string' &&
uuidPattern.test(job.id) &&
typeof job.simulation_id === 'string' &&
uuidPattern.test(job.simulation_id) &&
(job.job_type === 'execute' || job.job_type === 'report') &&
(job.status === 'pending' ||
job.status === 'running' ||
job.status === 'succeeded' ||
job.status === 'failed') &&
Number.isSafeInteger(job.attempts) &&
Number(job.attempts) >= 0 &&
Number(job.attempts) <= 3 &&
isIsoDateTime(job.available_at) &&
(job.started_at === null || isIsoDateTime(job.started_at)) &&
(job.finished_at === null || isIsoDateTime(job.finished_at)) &&
(job.error_code === null || typeof job.error_code === 'string')
);
});
}
export type ApiSimulationHistoryEntryV1 = {
id: string;
scope: 'personal' | 'organization';
organization_name: string | null;
status: ApiSimulationExecutionStatus;
version_no: number;
created_at: string | null;
updated_at: string | null;
has_ready_report: boolean;
};
export type ApiSimulationHistoryResponseV1 = {
data: ApiSimulationHistoryEntryV1[];
meta: {
current_page: number;
last_page: number;
per_page: number;
total: number;
};
};
export function isApiSimulationHistoryResponseV1(
value: unknown,
): value is ApiSimulationHistoryResponseV1 {
if (
!isPlainObject(value) ||
!Array.isArray(value.data) ||
!isPlainObject(value.meta)
)
return false;
const meta = value.meta;
if (
![meta.current_page, meta.last_page, meta.per_page, meta.total].every(
(item) => Number.isSafeInteger(item) && Number(item) >= 0,
) ||
Number(meta.current_page) < 1 ||
Number(meta.last_page) < 1 ||
Number(meta.per_page) < 1
)
return false;
return value.data.every((entry: unknown) => {
if (!isPlainObject(entry)) return false;
return (
typeof entry.id === 'string' &&
uuidPattern.test(entry.id) &&
(entry.scope === 'personal' || entry.scope === 'organization') &&
(entry.organization_name === null ||
typeof entry.organization_name === 'string') &&
apiSimulationExecutionStatuses.includes(
entry.status as ApiSimulationExecutionStatus,
) &&
Number.isSafeInteger(entry.version_no) &&
Number(entry.version_no) > 0 &&
(entry.created_at === null || isIsoDateTime(entry.created_at)) &&
(entry.updated_at === null || isIsoDateTime(entry.updated_at)) &&
typeof entry.has_ready_report === 'boolean'
);
});
}
export type ApiSimulationDraftV1 = {
id: string;
version_no: number;
snapshot_sha256: string;
personal_snapshot: Record<string, unknown> | [];
economic_snapshot: Record<string, unknown>;
simulation_sources: ApiSimulationSourceV1[];
updated_at: string | null;
expires_at?: string | null;
};
export type ApiSimulationDraftSummaryV1 = {
id: string;
title: string;
updated_at: string | null;
expires_at: string | null;
version_no: number;
};
export type ApiSimulationSourceV1 = {
simulation_id: string;
source_version_no: number;
result_snapshot: Record<string, unknown>;
report_sha256: string;
consented_at: string;
};
function isApiSimulationSourceV1(
value: unknown,
): value is ApiSimulationSourceV1 {
if (!isPlainObject(value)) return false;
return (
typeof value.simulation_id === 'string' &&
uuidPattern.test(value.simulation_id) &&
Number.isSafeInteger(value.source_version_no) &&
Number(value.source_version_no) > 0 &&
isPlainObject(value.result_snapshot) &&
typeof value.report_sha256 === 'string' &&
/^[a-f0-9]{64}$/i.test(value.report_sha256) &&
isIsoDateTime(value.consented_at)
);
}
function isApiSimulationDraftV1(value: unknown): value is ApiSimulationDraftV1 {
if (!isPlainObject(value)) return false;
return (
typeof value.id === 'string' &&
uuidPattern.test(value.id) &&
Number.isSafeInteger(value.version_no) &&
Number(value.version_no) > 0 &&
typeof value.snapshot_sha256 === 'string' &&
/^[a-f0-9]{64}$/i.test(value.snapshot_sha256) &&
(isPlainObject(value.personal_snapshot) ||
(Array.isArray(value.personal_snapshot) &&
value.personal_snapshot.length === 0)) &&
isPlainObject(value.economic_snapshot) &&
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))
);
}
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;
}
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 isApiSimulationDraftReadResponseV1(
value: unknown,
): value is { data: ApiSimulationDraftV1 | null } {
if (!isPlainObject(value)) return false;
return value.data === null || isApiSimulationDraftV1(value.data);
}
export function isApiSimulationDraftWriteResponseV1(value: unknown): value is {
data: { id: string; version_no: number; replayed?: boolean };
expires_at?: string | null;
} {
if (!isPlainObject(value) || !isPlainObject(value.data)) return false;
const data = value.data;
return (
typeof data.id === 'string' &&
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)) &&
(data.replayed === undefined || typeof data.replayed === 'boolean')
);
}
export function isApiSimulationDraftAttachResponseV1(
value: unknown,
): value is { data: ApiSimulationDraftV1; replayed: boolean } {
return (
isPlainObject(value) &&
isApiSimulationDraftV1(value.data) &&
typeof value.replayed === 'boolean'
);
}
export function indeterminateFiscalComponent(
component: FiscalComponentCode,
referenceDate: string,
): SimulationResult<DecimalString> & {
component: FiscalComponentCode;
referenceDate: string;
} {
return {
component,
referenceDate,
status: 'indeterminate',
value: null,
unit: null,
explanation: `A componente ${component} não tem regra oficial aprovada e vigente associada neste simulador.`,
missingInputs: [
'approved_rule',
'effective_parameters',
'applicable_classification',
],
sourceIds: [],
};
}
export type SimulationSnapshot = {
personal_snapshot: Record<string, unknown>;
economic_snapshot: Record<string, unknown>;
context: SimulationContext;
};
const intl = Intl as unknown as {
supportedValuesOf?: (key: 'currency') => string[];
};
export function simulationCurrencyFractionDigits(value: string): number | null {
try {
const digits = new Intl.NumberFormat('en', {
style: 'currency',
currency: value,
}).resolvedOptions().maximumFractionDigits;
return digits !== undefined && Number.isInteger(digits) ? digits : null;
} catch {
return null;
}
}
export const simulationCurrencyOptions = [
...new Set([
'MZN',
'USD',
'EUR',
'ZAR',
...(intl.supportedValuesOf?.('currency') ?? []),
]),
]
.filter((code) => simulationCurrencyFractionDigits(code) === 2)
.sort();
export const isSimulationCurrency = (value: string): boolean =>
simulationCurrencyOptions.includes(value);
/** Rejects contradictory states so missing/unknown values cannot silently become zero. */
export function validateSimulationResult<TValue>(
result: SimulationResult<TValue>,
): string[] {
const errors: string[] = [];
if (!result.explanation.trim()) errors.push('explanation');
if (result.status === 'calculated' && result.value === null)
errors.push('calculated_value');
if (
result.status === 'indeterminate' &&
(result.value !== null || result.missingInputs.length === 0)
)
errors.push('indeterminate_inputs');
if (result.status === 'not_applicable' && result.value !== null)
errors.push('not_applicable_value');
if (result.status === 'estimated' && result.value === null)
errors.push('estimated_value');
return errors;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,16 +1,17 @@
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 Props = { record: Opportunity; modalities: string[] };
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;
};
export default function BusinessInterest({ record, modalities }: Props) {
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("");
@@ -38,6 +39,7 @@ export default function BusinessInterest({ record, modalities }: Props) {
};
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> : (
<form className={`${card} space-y-4`} onSubmit={submit}>
@@ -1,32 +1,39 @@
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";
type PublicBusiness = {
id: string; slug: string; title: 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 Props = { results: { data: PublicBusiness[]; links: { url: string | null; label: string; active: boolean }[] }; filters: { q?: string } };
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; province_id?: string; district_id?: string; admin_post_id?: string; locality_id?: string }; territorySelection?: TerritoryOption[] };
export default function BusinessMarketplace({ results, filters }: Props) {
export default function BusinessMarketplace({ results, filters, territorySelection = [] }: Props) {
const [query, setQuery] = useState(filters.q ?? "");
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 } : {}), ...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 }, { preserveState: true, preserveScroll: true });
router.get("/negocios", { q: query || 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)} />
<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>}
<ul className="grid gap-4 md:grid-cols-2">
{results.data.map((record) => (
<li className={card} key={record.id}>
<h2 className="text-xl font-bold"><Link className="underline" href={`/negocios/${record.slug}`}>{record.title}</Link></h2>
<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>}
@@ -34,7 +41,7 @@ export default function BusinessMarketplace({ results, filters }: Props) {
))}
</ul>
<nav aria-label="Paginação das oportunidades" className="flex flex-wrap gap-3">
{results.links.map((link) => link.url ? <Link key={link.label} href={link.url} className={link.active ? "font-bold underline" : "underline"} dangerouslySetInnerHTML={{ __html: link.label }} /> : null)}
{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,6 +1,6 @@
import { router } from "@inertiajs/react";
import { useState } from "react";
import { Field, input, button, card, api } from "./shared";
import { router } from '@inertiajs/react';
import { useState } from 'react';
import { Field, input, button, card, api } from './shared';
export type BusinessObject = {
id: string;
@@ -9,42 +9,44 @@ export type BusinessObject = {
payload: Record<string, string>;
};
const kinds: Record<string, string> = {
company: "Empresa",
participation: "Participação",
asset: "Activo físico",
property: "Imóvel/propriedade",
unit: "Unidade imobiliária",
improvement: "Benfeitoria",
agricultural_investment: "Investimento agrícola",
land_right: "Direito fundiário",
contract: "Contrato",
license: "Licença",
authorization: "Autorização",
encumbrance: "Ónus ou encargo",
valuation: "Avaliação declarada",
capital_request: "Pedido de capital",
company: 'Empresa',
participation: 'Participação',
asset: 'Activo físico',
property: 'Imóvel/propriedade',
unit: 'Unidade imobiliária',
improvement: 'Benfeitoria',
agricultural_investment: 'Investimento agrícola',
land_right: 'Direito fundiário',
contract: 'Contrato',
license: 'Licença',
authorization: 'Autorização',
encumbrance: 'Ónus ou encargo',
valuation: 'Avaliação declarada',
capital_request: 'Pedido de capital',
};
const fields: Record<string, string> = {
label: "Designação reservada",
declared_holder: "Titular declarado",
document_reference: "Referência documental",
source_reference: "Fonte da informação",
competent_entity: "Entidade emissora/competente declarada",
purpose: "Finalidade autorizada declarada",
location_description: "Localização reservada",
boundaries_description: "Limites declarados",
occupancy: "Ocupação/utilização",
condition: "Conservação/operação",
encumbrances: "Ónus, garantias ou litígios declarados",
restrictions: "Restrições declaradas",
required_authorizations: "Autorizações necessárias declaradas",
transfer_condition: "Condição de cessão/transmissão declarada",
valid_from: "Início de validade",
valid_until: "Fim de validade",
area: "Área (decimal com ponto)",
participation_percent: "Participação (%)",
amount: "Valor (decimal com ponto)",
currency: "Moeda (código de três letras)",
label: 'Designação reservada',
declared_holder: 'Titular declarado',
document_reference: 'Referência documental',
source_reference: 'Fonte da informação',
source_date: 'Data da fonte',
resource_status: 'Situação do recurso',
competent_entity: 'Entidade emissora/competente declarada',
purpose: 'Finalidade autorizada declarada',
location_description: 'Localização reservada',
boundaries_description: 'Limites declarados',
occupancy: 'Ocupação/utilização',
condition: 'Conservação/operação',
encumbrances: 'Ónus, garantias ou litígios declarados',
restrictions: 'Restrições declaradas',
required_authorizations: 'Autorizações necessárias declaradas',
transfer_condition: 'Condição de cessão/transmissão declarada',
valid_from: 'Início de validade',
valid_until: 'Fim de validade',
area: 'Área (decimal com ponto)',
participation_percent: 'Participação (%)',
amount: 'Valor (decimal com ponto)',
currency: 'Moeda (código de três letras)',
};
export default function BusinessObjects({
businessId,
@@ -62,16 +64,19 @@ export default function BusinessObjects({
const [kind, setKind] = useState(objectKinds[0]);
const [objectId, setObjectId] = useState<string | null>(null);
const [payload, setPayload] = useState<Record<string, string>>({});
const [reason, setReason] = useState("");
const [error, setError] = useState("");
const [reason, setReason] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
return (
<section className={`${card} space-y-4`}>
<h2 className="text-xl font-bold">Activos, contratos e direitos declarados</h2>
<h2 className="text-xl font-bold">
Activos, contratos e direitos declarados
</h2>
<p>
Registe separadamente cada elemento. Todos ficam pendentes de verificação; a
declaração não confirma titularidade, validade ou transmissibilidade. Não use este
formulário para anexar ficheiros.
Registe separadamente cada elemento. Todos ficam pendentes de
verificação; a declaração não confirma titularidade, validade ou
transmissibilidade. Não use este formulário para anexar
ficheiros.
</p>
{!objects.length && <p>Nenhum elemento registado.</p>}
{objects.map((o) => (
@@ -82,30 +87,36 @@ export default function BusinessObjects({
<p>Pendente de verificação</p>
<dl>
{Object.entries(o.payload)
.filter(([key, value]) => key !== "label" && value)
.filter(([key, value]) => key !== 'label' && value)
.map(([key, value]) => (
<div key={key}>
<dt className="font-semibold">
{fields[key] ??
(
{
area_unit: "Unidade da área",
value_kind: "Natureza do valor",
contract_type: "Tipo de contrato",
area_unit:
'Unidade da área',
value_kind:
'Natureza do valor',
contract_type:
'Tipo de contrato',
} as Record<string, string>
)[key] ??
key}
</dt>
<dd className="break-words">
{key === "value_kind"
{key === 'value_kind'
? ((
{
asking: "Pedido",
indicative: "Indicativo",
appraised: "Avaliado — declaração pendente",
proposed: "Proposto",
negotiated: "Negociado — declaração pendente",
confirmed: "Confirmado — declaração pendente",
asking: 'Pedido',
indicative: 'Indicativo',
appraised:
'Avaliado — declaração pendente',
proposed: 'Proposto',
negotiated:
'Negociado — declaração pendente',
confirmed:
'Confirmado — declaração pendente',
} as Record<string, string>
)[value] ?? value)
: value}
@@ -121,7 +132,7 @@ export default function BusinessObjects({
setObjectId(o.id);
setKind(o.kind);
setPayload(o.payload);
setReason("");
setReason('');
}}
>
Editar elemento
@@ -135,12 +146,12 @@ export default function BusinessObjects({
onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
setError("");
setError('');
try {
await api(
`/api/v1/existing-business/listings/${businessId}/objects${objectId ? `/${objectId}` : ""}`,
`/api/v1/existing-business/listings/${businessId}/objects${objectId ? `/${objectId}` : ''}`,
{
...(objectId ? { _method: "PUT" } : {}),
...(objectId ? { _method: 'PUT' } : {}),
kind,
payload,
reason,
@@ -152,7 +163,7 @@ export default function BusinessObjects({
setError(
err instanceof Error
? err.message
: "Não foi possível guardar o elemento.",
: 'Não foi possível guardar o elemento.',
);
} finally {
setBusy(false);
@@ -160,7 +171,9 @@ export default function BusinessObjects({
}}
>
<h3 className="font-bold">
{objectId ? "Editar elemento reservado" : "Acrescentar elemento reservado"}
{objectId
? 'Editar elemento reservado'
: 'Acrescentar elemento reservado'}
</h3>
<Field label="Natureza">
<select
@@ -177,30 +190,65 @@ export default function BusinessObjects({
</select>
</Field>
<div className="grid gap-4 md:grid-cols-2">
{Object.entries(fields).map(([key, label]) => (
<Field key={key} label={label}>
<input
className={input}
type={key.startsWith("valid_") ? "date" : "text"}
value={payload[key] ?? ""}
maxLength={key === "label" ? 200 : 2000}
required={key === "label" || key === "source_reference"}
onChange={(e) =>
setPayload({ ...payload, [key]: e.target.value })
}
/>
</Field>
))}
{Object.entries(fields)
.filter(([key]) => key !== 'resource_status')
.map(([key, label]) => (
<Field key={key} label={label}>
<input
className={input}
type={
key.startsWith('valid_')
? 'date'
: 'text'
}
value={payload[key] ?? ''}
maxLength={key === 'label' ? 200 : 2000}
required={
key === 'label' ||
key === 'source_reference'
}
onChange={(e) =>
setPayload({
...payload,
[key]: e.target.value,
})
}
/>
</Field>
))}
<Field label={fields.resource_status}>
<select
className={input}
value={payload.resource_status ?? ''}
onChange={(e) =>
setPayload({
...payload,
resource_status: e.target.value,
})
}
>
<option value="">Por confirmar</option>
<option value="available">Disponível</option>
<option value="contracted">Contratado</option>
<option value="planned">Previsto</option>
<option value="unconfirmed">
Por confirmar
</option>
</select>
</Field>
<Field label="Unidade da área">
<select
className={input}
value={payload.area_unit ?? ""}
value={payload.area_unit ?? ''}
onChange={(e) =>
setPayload({ ...payload, area_unit: e.target.value })
setPayload({
...payload,
area_unit: e.target.value,
})
}
>
<option value="">Não indicada</option>
{["m2", "ha", "km2"].map((x) => (
{['m2', 'ha', 'km2'].map((x) => (
<option key={x}>{x}</option>
))}
</select>
@@ -208,19 +256,25 @@ export default function BusinessObjects({
<Field label="Natureza do valor">
<select
className={input}
value={payload.value_kind ?? ""}
value={payload.value_kind ?? ''}
onChange={(e) =>
setPayload({ ...payload, value_kind: e.target.value })
setPayload({
...payload,
value_kind: e.target.value,
})
}
>
<option value="">Não indicada</option>
{Object.entries({
asking: "Pedido",
indicative: "Indicativo",
appraised: "Avaliado (declaração por verificar)",
proposed: "Proposto",
negotiated: "Negociado (declaração por verificar)",
confirmed: "Confirmado (declaração por verificar)",
asking: 'Pedido',
indicative: 'Indicativo',
appraised:
'Avaliado (declaração por verificar)',
proposed: 'Proposto',
negotiated:
'Negociado (declaração por verificar)',
confirmed:
'Confirmado (declaração por verificar)',
}).map(([key, label]) => (
<option key={key} value={key}>
{label}
@@ -231,19 +285,22 @@ export default function BusinessObjects({
<Field label="Tipo de contrato">
<select
className={input}
value={payload.contract_type ?? ""}
value={payload.contract_type ?? ''}
onChange={(e) =>
setPayload({ ...payload, contract_type: e.target.value })
setPayload({
...payload,
contract_type: e.target.value,
})
}
>
<option value="">Não indicado</option>
{Object.entries({
purchase: "Compra",
sale: "Venda",
lease: "Arrendamento",
operation: "Exploração",
management: "Gestão",
other: "Outro",
purchase: 'Compra',
sale: 'Venda',
lease: 'Arrendamento',
operation: 'Exploração',
management: 'Gestão',
other: 'Outro',
}).map(([key, label]) => (
<option key={key} value={key}>
{label}
@@ -264,7 +321,7 @@ export default function BusinessObjects({
</Field>
{error && <p role="alert">{error}</p>}
<button className={button} disabled={busy}>
{busy ? "A guardar…" : "Guardar elemento reservado"}
{busy ? 'A guardar…' : 'Guardar elemento reservado'}
</button>
{objectId && (
<button
@@ -273,7 +330,7 @@ export default function BusinessObjects({
onClick={() => {
setObjectId(null);
setPayload({});
setReason("");
setReason('');
}}
>
Cancelar edição
@@ -7,10 +7,10 @@ type Business = {
province?: string | null; district?: string | null; locality?: string | null; sector?: { name: string; slug: string } | null;
};
export default function BusinessOpportunity({ record }: { record: Business }) {
export default function BusinessOpportunity({ record, returnUrl = "/negocios", interestUrl = `/negocios/${record.slug}/manifestar-interesse` }: { record: Business; returnUrl?: string; interestUrl?: string }) {
return (
<Frame title={record.title}>
<Link href="/negocios" className="underline">Voltar às oportunidades</Link>
<Link href={returnUrl} className="underline">Voltar às oportunidades</Link>
<section className={`${card} space-y-4`}>
<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>}
@@ -18,7 +18,7 @@ export default function BusinessOpportunity({ record }: { record: Business }) {
{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={`/negocios/${record.slug}/manifestar-interesse`}>Manifestar interesse</Link>
<Link className={button} href={interestUrl}>Manifestar interesse</Link>
</section>
</Frame>
);
+43 -37
View File
@@ -15,6 +15,7 @@ export type Business = {
amount_max?: string | null;
available_percentage?: string | null;
funds_use?: string | null;
territory_paths?: string[][];
submitted_at?: string | null;
published_at?: string | null;
expires_at?: string | null;
@@ -31,43 +32,48 @@ export type Business = {
};
};
export const businessStates: Record<string, string> = {
draft: "Rascunho",
submitted: "Submetido",
in_review: "Em revisão",
needs_information: "Pendente de informação",
withdrawn: "Retirado",
triage: "Triagem",
information_pending: "Informação pendente",
review: "Em revisão",
approval_l1: "Aprovação nível 1",
approval_l2: "Aprovação nível 2",
approved: "Aprovado",
published: "Publicado",
suspended: "Suspenso",
rejected: "Rejeitado",
cancelled: "Cancelado",
archived: "Arquivado",
draft: 'Rascunho',
submitted: 'Submetido',
in_review: 'Em revisão',
needs_information: 'Pendente de informação',
withdrawn: 'Retirado',
triage: 'Triagem',
information_pending: 'Informação pendente',
review: 'Em revisão',
approval_l1: 'Aprovação nível 1',
approval_l2: 'Aprovação nível 2',
approved: 'Aprovado',
published: 'Publicado',
suspended: 'Suspenso',
rejected: 'Rejeitado',
cancelled: 'Cancelado',
archived: 'Arquivado',
};
export const businessModalities: Record<string, string> = {
company_sale: "Venda da empresa",
participation_sale: "Venda de participação",
capital_increase: "Aumento de capital",
financial_investor: "Investidor financeiro",
strategic_partner: "Sócio estratégico",
buyer_search: "Procura de comprador",
position_assignment: "Cessão de posição",
franchise: "Franchising",
asset_sale: "Venda de activos",
asset_lease: "Arrendamento de activos",
business_unit_transfer: "Transferência de unidade de negócio",
joint_venture: "Joint venture",
succession: "Sucessão empresarial",
recovery: "Recuperação",
expansion: "Expansão",
internationalization: "Internacionalização",
real_estate: "Imobiliário",
agricultural_investment: "Investimento agrícola",
land_right: "Direito fundiário",
mining_license: "Licença mineira",
forestry_license: "Licença florestal",
company_sale: 'Venda da empresa',
participation_sale: 'Venda de participação',
capital_increase: 'Aumento de capital',
financial_investor: 'Investidor financeiro',
strategic_partner: 'Sócio estratégico',
buyer_search: 'Procura de comprador',
position_assignment: 'Cessão de posição',
franchise: 'Franchising',
asset_sale: 'Venda de activos',
asset_lease: 'Arrendamento de activos',
business_unit_transfer: 'Transferência de unidade de negócio',
joint_venture: 'Joint venture',
succession: 'Sucessão empresarial',
recovery: 'Recuperação',
expansion: 'Expansão',
internationalization: 'Internacionalização',
real_estate: 'Imobiliário',
agricultural_investment: 'Investimento agrícola',
land_right: 'Direito fundiário',
mining_license: 'Licença mineira',
forestry_license: 'Licença florestal',
investment_project: 'Projecto de investimento',
business_partnership: 'Parceria empresarial',
financing_request: 'Procura de financiamento',
concession_opportunity: 'Concessão',
supply_opportunity: 'Oportunidade de fornecimento',
};
File diff suppressed because it is too large Load Diff
+125 -96
View File
@@ -51,6 +51,7 @@ export default function Catalogue({
district_id: String(filters.district_id ?? ""),
admin_post_id: String(filters.admin_post_id ?? ""),
locality_id: String(filters.locality_id ?? ""),
include_national: Boolean(filters.include_national && filters.include_national !== "0"),
cluster_id: String(filters.cluster_id ?? ""),
zee_id: String(filters.zee_id ?? ""),
zfi_id: String(filters.zfi_id ?? ""),
@@ -90,7 +91,7 @@ export default function Catalogue({
lastRequest.current = draftFilterKey;
router.get(
catalogueUrl,
{ ...data, education: data.education ? 1 : 0 },
{ ...data, education: data.education ? 1 : 0, include_national: data.include_national ? 1 : 0 },
{
preserveState: true,
preserveScroll: true,
@@ -201,11 +202,19 @@ export default function Catalogue({
<Link className={card} href={dimensionUrl("zfi")}>
Por ZFI
</Link>
<Link className={card} href="/zonas?category=zee">Fichas de ZEE</Link>
<Link className={card} href="/zonas?category=zfi">Fichas de ZFI</Link>
<Link className={card} href="/zonas?category=industrial_park">Parques industriais</Link>
<Link className={card} href="/carteira?kind=project">Projectos âncora documentados</Link>
<Link className={card} href="/negocios">Negócios e participações publicados</Link>
</nav>
<p>
Combine contexto territorial, dimensão e necessidades. As fichas documentais e as
oportunidades mantêm a sua origem e natureza.
</p>
<p className={card}>
Negócios existentes, participações, imóveis e activos só surgem como anúncio depois de revisão e publicação expressa. A pesquisa de negócios é um catálogo separado; ausência de resultados não confirma inexistência do activo. As referências governamentais da carteira são separadas de anúncios privados.
</p>
<form
className={card + " space-y-4"}
onSubmit={(e) => {
@@ -213,97 +222,11 @@ export default function Catalogue({
setPoints(null);
setComparison([]);
setSelected([]);
form.transform((data) => ({ ...data, education: data.education ? 1 : 0 }));
form.transform((data) => ({ ...data, education: data.education ? 1 : 0, include_national: data.include_national ? 1 : 0 }));
form.get(catalogueUrl, { preserveState: true });
}}
>
<Field label="Pesquisar oportunidades">
<input
className={input}
value={form.data.q}
onChange={(e) => form.setData("q", e.target.value)}
autoComplete="off"
aria-describedby="search-suggestions"
/>
</Field>
{suggestions.length > 0 && (
<ul
id="search-suggestions"
aria-label="Sugestões de pesquisa"
className="space-y-2"
>
{suggestions.map((s) => (
<li key={s.slug}>
<Link href={`/oportunidades/${s.slug}`} className="underline">
{s.title}
</Link>
</li>
))}
</ul>
)}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{(
[
["zee_id", "zee", "ZEE"],
["zfi_id", "zfi", "ZFI"],
["park_id", "industrial_park", "Parque industrial"],
] as const
).map(([field, category, label]) => (
<Field key={field} label={label}>
<select
className={input}
value={form.data[field]}
onChange={(e) => form.setData(field, e.target.value)}
>
<option value="">Todos</option>
{(references.zones ?? [])
.filter((z) => z.category === category)
.map((z) => (
<option key={z.id} value={z.id}>
{z.name}
</option>
))}
</select>
</Field>
))}
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
const key = (
["cluster_id", "corridor_id", "project_id", "geo_location_id"] as const
)[i];
return (
<Field
key={group}
label={["Cluster", "Corredor", "Projecto âncora", "Localização"][i]}
>
<select
className={input}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
>
<option value="">Todos</option>
{references[group].map((r) => (
<option value={r.id} key={r.id}>
{r.name}
</option>
))}
</select>
</Field>
);
})}
<Field label="Sector">
<select
className={input}
value={form.data.sector}
onChange={(e) => form.setData("sector", e.target.value)}
>
<option value="">Todos</option>
{references.sectors.map((s) => (
<option key={s.id} value={s.slug}>
{s.name}
</option>
))}
</select>
</Field>
<section aria-label="Localização da oportunidade" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
(key, index) => (
<TerritoryLevel
@@ -313,10 +236,7 @@ export default function Catalogue({
selected={territoryPath[index]}
endpoint="/api/v1/catalogs/jurisdictions"
onChange={(value) => {
const path = [
...territoryPath.slice(0, index),
...(value ? [value] : []),
];
const path = [...territoryPath.slice(0, index), ...(value ? [value] : [])];
setTerritoryPath(path);
form.setData((data) => ({
...data,
@@ -327,11 +247,68 @@ export default function Catalogue({
district_id: path[1]?.id ?? "",
admin_post_id: path[2]?.id ?? "",
locality_id: path[3]?.id ?? "",
zee_id: "",
zfi_id: "",
park_id: "",
}));
}}
/>
),
)}
</section>
<Field label="Pesquisar oportunidades">
<input
className={input}
value={form.data.q}
onChange={(e) => form.setData("q", e.target.value)}
autoComplete="off"
aria-describedby="search-suggestions"
/>
</Field>
{suggestions.length > 0 && (
<ul id="search-suggestions" aria-label="Sugestões de pesquisa" className="space-y-2">
{suggestions.map((s) => (
<li key={s.slug}>
<Link href={`/oportunidades/${s.slug}`} className="underline">{s.title}</Link>
</li>
))}
</ul>
)}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{([
["zee_id", "zee", "ZEE"],
["zfi_id", "zfi", "ZFI"],
["park_id", "industrial_park", "Parque industrial"],
] as const).map(([field, category, label]) => (
<Field key={field} label={label}>
<select className={input} value={form.data[field]} onChange={(e) => form.setData(field, e.target.value)}>
<option value="">Todos</option>
{(references.zones ?? []).filter((zone) => zone.category === category).map((zone) => (
<option key={zone.id} value={zone.id}>{zone.name}</option>
))}
</select>
</Field>
))}
{(["clusters", "corridors", "projects"] as const).map((group, index) => {
const key = (["cluster_id", "corridor_id", "project_id"] as const)[index];
const label = (["Cluster", "Corredor", "Projecto âncora"] as const)[index];
return (
<Field key={group} label={label}>
<select className={input} value={form.data[key]} onChange={(e) => form.setData(key, e.target.value)}>
<option value="">Todos</option>
{references[group].map((item) => <option value={item.id} key={item.id}>{item.name}</option>)}
</select>
</Field>
);
})}
<Field label="Sector">
<select className={input} value={form.data.sector} onChange={(e) => form.setData("sector", e.target.value)}>
<option value="">Todos</option>
{references.sectors.map((sector) => <option key={sector.id} value={sector.slug}>{sector.name}</option>)}
</select>
</Field>
</div>
<section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Field label="Estado de preparação">
<select
className={input}
@@ -387,7 +364,7 @@ export default function Catalogue({
onChange={(e) => form.setData("before", e.target.value)}
/>
</Field>
</div>
</section>
<label className="flex gap-2">
<input
type="checkbox"
@@ -396,6 +373,11 @@ export default function Catalogue({
/>
Apenas oportunidades na educação
</label>
<label className="flex gap-2">
<input type="checkbox" checked={form.data.include_national}
onChange={(e) => form.setData("include_national", e.target.checked)} />
Incluir âmbito nacional
</label>
<details>
<summary className="cursor-pointer font-semibold">
Subsector, educação, infraestruturas, competências e apoios
@@ -467,8 +449,50 @@ export default function Catalogue({
</p>
))}
</form>
{(territoryPath.length > 0 || form.data.q || form.data.dimension || form.data.sector || form.data.cluster_id || form.data.corridor_id || form.data.project_id || form.data.geo_location_id || form.data.zee_id || form.data.zfi_id || form.data.park_id || form.data.include_national || form.data.education || form.data.maturity_level || form.data.min_amount || form.data.max_amount || form.data.currency || form.data.before || form.data.facets.length > 0) && (
<section aria-label="Filtros activos" className="flex flex-wrap items-center gap-2">
<strong>Filtros activos:</strong>
{territoryPath.map((node, index) => <span key={node.id} className="rounded border px-2 py-1">{node.name} <button type="button" aria-label={`Remover localização ${node.name}`} onClick={() => {
const path = territoryPath.slice(0, index);
setTerritoryPath(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: "", district: "", geo_location_id: "" }));
}}>×</button></span>)}
{form.data.sector && <span className="rounded border px-2 py-1">Sector: {references.sectors.find((s) => s.slug === form.data.sector)?.name ?? form.data.sector}</span>}
{form.data.cluster_id && <span className="rounded border px-2 py-1">Cluster: {references.clusters.find((v) => v.id === form.data.cluster_id)?.name} <button type="button" aria-label="Remover filtro Cluster" onClick={() => form.setData("cluster_id", "")}>×</button></span>}
{form.data.corridor_id && <span className="rounded border px-2 py-1">Corredor: {references.corridors.find((v) => v.id === form.data.corridor_id)?.name} <button type="button" aria-label="Remover filtro Corredor" onClick={() => form.setData("corridor_id", "")}>×</button></span>}
{form.data.project_id && <span className="rounded border px-2 py-1">Projecto: {references.projects.find((v) => v.id === form.data.project_id)?.name} <button type="button" aria-label="Remover filtro Projecto" onClick={() => form.setData("project_id", "")}>×</button></span>}
{form.data.q && <span className="rounded border px-2 py-1">Pesquisa: {form.data.q} <button type="button" aria-label="Remover pesquisa" onClick={() => form.setData("q", "")}>×</button></span>}
{form.data.dimension && <span className="rounded border px-2 py-1">Dimensão: {form.data.dimension} <button type="button" aria-label="Remover dimensão" onClick={() => form.setData("dimension", "")}>×</button></span>}
{form.data.geo_location_id && <span className="rounded border px-2 py-1">Localização adicional: {references.locations.find((v) => v.id === form.data.geo_location_id)?.name ?? "seleccionada"} <button type="button" aria-label="Remover localização adicional" onClick={() => form.setData("geo_location_id", "")}>×</button></span>}
{form.data.zee_id && <span className="rounded border px-2 py-1">ZEE: {references.zones?.find((z) => z.id === form.data.zee_id)?.name ?? "seleccionada"} <button type="button" aria-label="Remover filtro ZEE" onClick={() => form.setData("zee_id", "")}>×</button></span>}
{form.data.zfi_id && <span className="rounded border px-2 py-1">ZFI: {references.zones?.find((z) => z.id === form.data.zfi_id)?.name ?? "seleccionada"} <button type="button" aria-label="Remover filtro ZFI" onClick={() => form.setData("zfi_id", "")}>×</button></span>}
{form.data.park_id && <span className="rounded border px-2 py-1">Parque: {references.zones?.find((z) => z.id === form.data.park_id)?.name ?? "seleccionado"} <button type="button" aria-label="Remover filtro parque" onClick={() => form.setData("park_id", "")}>×</button></span>}
{form.data.education && <span className="rounded border px-2 py-1">Educação <button type="button" aria-label="Remover filtro de educação" onClick={() => form.setData("education", false)}>×</button></span>}
{form.data.maturity_level && <span className="rounded border px-2 py-1">Maturidade: {form.data.maturity_level} <button type="button" aria-label="Remover maturidade" onClick={() => form.setData("maturity_level", "")}>×</button></span>}
{(form.data.min_amount || form.data.max_amount) && <span className="rounded border px-2 py-1">Montante: {form.data.min_amount || "sem mínimo"}–{form.data.max_amount || "sem máximo"} {form.data.currency} <button type="button" aria-label="Remover intervalo de montante" onClick={() => form.setData((data) => ({ ...data, min_amount: "", max_amount: "", currency: "" }))}>×</button></span>}
{form.data.currency && !form.data.min_amount && !form.data.max_amount && <span className="rounded border px-2 py-1">Moeda: {form.data.currency} <button type="button" aria-label="Remover moeda" onClick={() => form.setData("currency", "")}>×</button></span>}
{form.data.before && <span className="rounded border px-2 py-1">Data até: {form.data.before} <button type="button" aria-label="Remover data-alvo" onClick={() => form.setData("before", "")}>×</button></span>}
{form.data.facets.map((id) => {
const option = references.options.find((item) => item.id === id);
return <span key={id} className="rounded border px-2 py-1">{option?.label ?? `Opção ${id}`} <button type="button" aria-label={`Remover filtro ${option?.label ?? id}`} onClick={() => form.setData("facets", form.data.facets.filter((value) => value !== id))}>×</button></span>;
})}
{form.data.include_national && <span className="rounded border px-2 py-1">Âmbito nacional incluído</span>}
{territoryPath.length > 0 && <button type="button" className="underline" onClick={() => {
setTerritoryPath([]);
form.setData((data) => ({ ...data, province_id: "", district_id: "", admin_post_id: "", locality_id: "", province: "", district: "", geo_location_id: "" }));
}}>Remover localização</button>}
{form.data.sector && <button type="button" className="underline" onClick={() => form.setData("sector", "")}>Remover sector</button>}
{form.data.include_national && <button type="button" className="underline" onClick={() => form.setData("include_national", false)}>Remover âmbito nacional</button>}
</section>
)}
<div className="flex flex-wrap items-center gap-4">
<p role="status">{results.total} oportunidades publicadas</p>
{results.total === 0 && (form.data.province_id || form.data.district_id || form.data.admin_post_id || form.data.locality_id) && (
<button type="button" className="underline" onClick={() => {
setTerritoryPath([]);
form.setData((data) => ({ ...data, province_id: "", district_id: "", admin_post_id: "", locality_id: "", province: "", district: "", geo_location_id: "" }));
}}>Alargar pesquisa (remover localização)</button>
)}
{["grid", "list", "map", "combined"].map((value, i) => (
<button
key={value}
@@ -531,13 +555,18 @@ export default function Catalogue({
{r.sector?.name} · {r.province || "Localização não indicada"}
</p>
<h2 className="text-xl font-bold">
<Link href={`/oportunidades/${r.slug}`}>{r.title}</Link>
<Link href={`/oportunidades/${r.slug}${query() ? `?${query()}` : ""}`}>{r.title}</Link>
</h2>
{!r.last_validated_at && (
<p className="rounded border border-amber-700 bg-amber-50 p-3 text-sm">
Esta ficha não regista data de validação documental. Confirme a origem e as condições antes de agir.
</p>
)}
<p>{r.summary}</p>
<p className="font-semibold">{money(r)}</p>
<p>{r.maturity_label}</p>
<div className="flex flex-wrap gap-4">
<Link className="underline" href={`/oportunidades/${r.slug}`}>
<Link className="underline" href={`/oportunidades/${r.slug}${query() ? `?${query()}` : ""}`}>
Ver ficha
</Link>
<button
+8
View File
@@ -7,18 +7,26 @@ export default function Detail({
record: r,
context: c,
zone_origin,
returnUrl = "/oportunidades",
}: {
record: Opportunity;
context: Context;
zone_origin?: { id: string; name: string } | null;
returnUrl?: string;
}) {
const { auth } = usePage<{ auth: { user: unknown } }>().props;
const [sharing, setSharing] = useState("");
return (
<Frame title={r.title}>
<Link href={returnUrl} className="underline">Voltar à pesquisa</Link>
<p>
{r.reference} · {r.sector?.name} · {r.province} {r.district}
</p>
{!r.last_validated_at && (
<p className="rounded border border-amber-700 bg-amber-50 p-4">
Esta ficha não regista data de validação documental. Confirme a origem e as condições antes de agir. Preparar uma manifestação expressa interesse; não confirma a oferta nem representa aprovação.
</p>
)}
<p className="text-xl">{r.summary}</p>
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
{c.primary_territory_path && c.primary_territory_path.length > 0 && (
+4 -2
View File
@@ -38,6 +38,7 @@ export type Opportunity = {
expected_impact: string | null;
financing_modality: string | null;
status: string;
last_validated_at?: string | null;
};
export type Context = {
primary_territory_path?: { id: string; name: string; location_type: string }[];
@@ -118,15 +119,16 @@ export async function api(url: string, body?: unknown) {
.find((c) => c.startsWith("XSRF-TOKEN="))
?.slice(11) ?? "",
);
const formData = typeof FormData !== "undefined" && body instanceof FormData;
const response = await fetch(url, {
method: body === undefined ? "GET" : "POST",
credentials: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
...(formData ? {} : { "Content-Type": "application/json" }),
"X-XSRF-TOKEN": token,
},
...(body === undefined ? {} : { 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.");
@@ -0,0 +1,123 @@
import { router } from "@inertiajs/react";
import { useState } from "react";
import { api, button, card, Field, input } from "./shared";
export type ZoneAttachment = {
id: string;
kind: string;
caption: string;
source_reference: string;
source_date: string | null;
rights_status?: string;
rights_basis?: string | null;
personal_data_status?: string;
review_status?: string;
independent_review?: boolean;
publicly_selected?: boolean;
version_no?: number;
file_name?: string;
file_status?: string;
document_id?: string;
malware_scan_status?: 'pending' | 'scanning' | 'clean' | 'infected' | 'inconclusive' | 'failed';
malware_failure_reason?: string | null;
media_type: string;
size_bytes: number | null;
download_url: string;
};
export default function ZoneAttachments({
zoneId,
attachments,
management,
zonePublished,
}: {
zoneId: string;
attachments: ZoneAttachment[];
management: boolean;
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 [busy, setBusy] = useState(false);
async function send(url: string, payload: unknown) {
setBusy(true);
setError("");
try {
await api(url, payload);
router.reload();
} catch (failure) {
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>
</>}
{error && <p role="alert">{error}</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>;
})}
</section>
);
}
+220 -2
View File
@@ -1,10 +1,12 @@
import { Link, router, useForm } from "@inertiajs/react";
import InvestmentTerritory from "@/components/investment-territory";
import InvestmentMapPanel from "@/components/investment-map-panel";
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
import { useState } from "react";
import { Frame, Field, input, button, card, api } from "./shared";
import ZoneRelations from "./zone-relations";
import ZoneMap from "./zone-map";
import ZoneAttachments from "./zone-attachments";
import type { ZoneTargets } from "./zone-relations";
type Zone = {
@@ -22,6 +24,19 @@ type Zone = {
legal_source_id?: string;
publication_status?: string;
validation_status: string;
physical_category?: string | null;
legal_regime?: string | null;
operational_status?: string;
development_status?: string;
availability_status?: string;
area_value?: string | null;
area_unit?: string | null;
area_components?: unknown[];
source_evidence?: unknown[];
aliases?: string[];
activities?: { name: string; status: string; source_reference?: string | null }[];
resources?: { name: string; status: string; source_reference?: string | null }[];
historical_territory?: { name: string; district?: string; province?: string; source_reference?: string } | null;
};
type Source = {
id: string;
@@ -35,6 +50,33 @@ type Source = {
version_no: number;
validation_status: string;
};
type ZoneEditorForm = {
version_no: number;
code: string;
category: string;
physical_category: string;
legal_regime: string;
operational_status: string;
development_status: string;
availability_status: string;
area_value: string;
area_unit: string;
area_components_json: string;
source_evidence_json: string;
activities: { name: string; status: string; source_reference: string | null }[];
resources: { name: string; status: string; source_reference: string | null }[];
aliases_text: string;
historical_name: string;
historical_district: string;
historical_province: string;
historical_source_reference: string;
name: string;
name_en: string;
description: string;
description_en: string;
operator_id: string;
legal_source_id: string;
};
type Props = {
targets: ZoneTargets | null;
related: { id: string; title: string }[];
@@ -47,6 +89,7 @@ type Props = {
geometries: { id: string; version_no: number; purpose: string; validation_status: string }[];
record: Zone;
management: boolean;
zoneExtensionsAvailable?: boolean;
source: Source | null;
operator: string | null;
operators: { id: string; name: string }[];
@@ -59,6 +102,13 @@ type Props = {
version_no: number;
}[];
revisions: { version_no: number; action: string; created_at: string }[];
locations: { id: string; name: string; location_type: string; scope_type: string; source_reference: string; validation_status: string }[];
attachments: {
id: string; kind: string; caption: string; source_reference: string; source_date: string | null;
rights_status?: string; rights_basis?: string | null; personal_data_status?: string; review_status?: string;
reviewed_by?: number | null; independent_review?: boolean; publicly_selected?: boolean; uploaded_by?: number;
version_no?: number; file_name?: string; media_type: string; size_bytes: number | null; download_url: string;
}[];
opportunities: {
data: { id: number; title: string; slug: string }[];
next_page_url: string | null;
@@ -75,20 +125,56 @@ function Editor({
geometries,
record: z,
management,
zoneExtensionsAvailable = false,
source,
operator,
operators,
legalSources,
links,
revisions,
locations,
attachments,
opportunities,
}: Props) {
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
const form = useForm({
const [locationPath, setLocationPath] = useState<TerritoryOption[]>([]);
const [locationSource, setLocationSource] = useState("");
const [locationScope, setLocationScope] = useState("administrative");
const [activityName, setActivityName] = useState("");
const [activityStatus, setActivityStatus] = useState("potential");
const [activitySource, setActivitySource] = useState("");
const [resourceName, setResourceName] = useState("");
const [resourceStatus, setResourceStatus] = useState("unconfirmed");
const [resourceSource, setResourceSource] = useState("");
const [attachmentFile, setAttachmentFile] = useState<File | null>(null);
const [attachmentKind, setAttachmentKind] = useState("legal_instrument");
const [attachmentCaption, setAttachmentCaption] = useState("");
const [attachmentSource, setAttachmentSource] = useState("");
const [attachmentSourceDate, setAttachmentSourceDate] = useState("");
const [attachmentRightsBasis, setAttachmentRightsBasis] = useState("");
const [attachmentRightsStatus, setAttachmentRightsStatus] = useState("pending");
const [reviewChoices, setReviewChoices] = useState<Record<string, { rights: string; personal: string }>>({});
const form = useForm<ZoneEditorForm>({
version_no: z.version_no,
code: z.code,
category: z.category,
physical_category: z.physical_category ?? "unknown",
legal_regime: z.legal_regime ?? "pending",
operational_status: z.operational_status ?? "unknown",
development_status: z.development_status ?? "unknown",
availability_status: z.availability_status ?? "not_informed",
area_value: z.area_value ?? "",
area_unit: z.area_unit ?? "",
area_components_json: JSON.stringify(z.area_components ?? [], null, 2),
source_evidence_json: JSON.stringify(z.source_evidence ?? [], null, 2),
activities: (z.activities ?? []).map((activity) => ({ ...activity, source_reference: activity.source_reference ?? null })),
resources: (z.resources ?? []).map((resource) => ({ ...resource, source_reference: resource.source_reference ?? null })),
aliases_text: (z.aliases ?? []).join("\n"),
historical_name: z.historical_territory?.name ?? "",
historical_district: z.historical_territory?.district ?? "",
historical_province: z.historical_territory?.province ?? "",
historical_source_reference: z.historical_territory?.source_reference ?? "",
name: z.name,
name_en: z.name_en ?? "",
description: z.description ?? "",
@@ -132,8 +218,11 @@ function Editor({
setBusy(true);
setMessage("");
try {
const { area_components_json, source_evidence_json, ...base } = form.data;
await api(`/api/v2/investment/admin/zones/${z.id}`, {
...form.data,
...base,
area_components: JSON.parse(area_components_json),
source_evidence: JSON.parse(source_evidence_json),
_method: "PUT",
});
router.reload();
@@ -175,6 +264,96 @@ function Editor({
<option value="industrial_park">Parque industrial</option>
</select>
</Field>
<Field label="Categoria física">
<select className={input} value={form.data.physical_category} onChange={(e) => form.setData("physical_category", e.target.value)}>
<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><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="other">Outra</option>
</select>
</Field>
<Field label="Regime jurídico">
<select className={input} value={form.data.legal_regime} onChange={(e) => form.setData("legal_regime", e.target.value)}>
<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>
</select>
</Field>
<Field label="Estado operacional">
<select className={input} value={form.data.operational_status} onChange={(e) => form.setData("operational_status", e.target.value)}>
<option value="unknown">Não confirmado</option><option value="operational">Operacional</option>
<option value="implementation">Em implementação</option><option value="planned">Planeado</option><option value="suspended">Suspenso</option>
</select>
</Field>
{zoneExtensionsAvailable && <Field label="Estado de desenvolvimento">
<select className={input} value={form.data.development_status} onChange={(e) => form.setData("development_status", e.target.value)}>
<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 className={input} value={form.data.availability_status} onChange={(e) => form.setData("availability_status", e.target.value)}>
<option value="not_informed">Não informada</option><option value="confirmed">Confirmada</option><option value="unavailable">Indisponível</option><option value="reported_unverified">Reportada, por verificar</option>
</select>
</Field>}
<Field label="Área documentada">
<input className={input} type="number" min="0" step="0.0001" value={form.data.area_value} onChange={(e) => form.setData("area_value", e.target.value)} />
</Field>
<Field label="Unidade da área">
<select className={input} value={form.data.area_unit} onChange={(e) => form.setData("area_unit", e.target.value)}>
<option value="">Por confirmar</option><option value="ha">hectares (ha)</option><option value="km2">quilómetros quadrados (km²)</option>
</select>
</Field>
{zoneExtensionsAvailable && <Field label="Áreas por âmbito (JSON; valor, unidade, fonte, data, estado)">
<textarea className={input} rows={6} value={form.data.area_components_json} onChange={(e) => form.setData("area_components_json", e.target.value)} />
</Field>}
{zoneExtensionsAvailable && <Field label="Evidência e fontes (JSON; tipo e o que comprova)">
<textarea className={input} rows={6} value={form.data.source_evidence_json} onChange={(e) => form.setData("source_evidence_json", e.target.value)} />
</Field>}
<Field label="Designações alternativas (uma por linha)">
<textarea className={input} rows={2} value={form.data.aliases_text} onChange={(e) => form.setData("aliases_text", e.target.value)} />
</Field>
<Field label="Localização histórica">
<input className={input} value={form.data.historical_name} onChange={(e) => form.setData("historical_name", e.target.value)} />
</Field>
<Field label="Distrito histórico">
<input className={input} value={form.data.historical_district} onChange={(e) => form.setData("historical_district", e.target.value)} />
</Field>
<Field label="Província histórica">
<input className={input} value={form.data.historical_province} onChange={(e) => form.setData("historical_province", e.target.value)} />
</Field>
<Field label="Fonte da localização histórica">
<input className={input} value={form.data.historical_source_reference} onChange={(e) => form.setData("historical_source_reference", e.target.value)} />
</Field>
<section className="space-y-3 md:col-span-2" aria-label="Actividades documentadas">
<h2 className="font-semibold">Actividades e sectores</h2>
{form.data.activities.map((activity, index) => <p key={`${activity.name}-${index}`}>{activity.name} · {activity.status} · {activity.source_reference ?? "fonte por registar"}</p>)}
<div className="grid gap-2 md:grid-cols-3">
<input className={input} aria-label="Actividade" placeholder="Actividade" value={activityName} onChange={(e) => setActivityName(e.target.value)} />
<select className={input} aria-label="Estado da actividade" value={activityStatus} onChange={(e) => setActivityStatus(e.target.value)}>
<option value="potential">Potencial referido pela fonte</option><option value="proposed">Proposta</option><option value="authorized">Autorizada</option><option value="conditional">Condicionada</option><option value="excluded">Excluída</option>
</select>
<input className={input} aria-label="Fonte da actividade" placeholder="URL ou referência" value={activitySource} onChange={(e) => setActivitySource(e.target.value)} />
</div>
<button type="button" className={button} disabled={!activityName.trim()} onClick={() => {
form.setData("activities", [...form.data.activities, { name: activityName.trim(), status: activityStatus, source_reference: activitySource.trim() || null }]);
setActivityName(""); setActivitySource("");
}}>Adicionar actividade</button>
</section>
<section className="space-y-3 md:col-span-2" aria-label="Infra-estruturas e recursos">
<h2 className="font-semibold">Infra-estruturas e recursos</h2>
{form.data.resources.map((resource, index) => <p key={`${resource.name}-${index}`}>{resource.name} · {resource.status} · {resource.source_reference ?? "fonte por registar"}</p>)}
<div className="grid gap-2 md:grid-cols-3">
<input className={input} aria-label="Recurso" placeholder="Estrada, energia, água…" value={resourceName} onChange={(e) => setResourceName(e.target.value)} />
<select className={input} aria-label="Estado do recurso" value={resourceStatus} onChange={(e) => setResourceStatus(e.target.value)}>
<option value="existing">Existente, fonte confirmada</option><option value="planned">Planeado</option><option value="unconfirmed">Não confirmado</option>
</select>
<input className={input} aria-label="Fonte do recurso" placeholder="URL ou referência" value={resourceSource} onChange={(e) => setResourceSource(e.target.value)} />
</div>
<button type="button" className={button} disabled={!resourceName.trim()} onClick={() => {
form.setData("resources", [...form.data.resources, { name: resourceName.trim(), status: resourceStatus, source_reference: resourceSource.trim() || null }]);
setResourceName(""); setResourceSource("");
}}>Adicionar recurso</button>
</section>
{(
[
["description", "Descrição PT"],
@@ -221,6 +400,36 @@ function Editor({
Guardar rascunho
</button>
</form>
<ZoneAttachments zoneId={z.id} attachments={attachments} management={true} zonePublished={z.publication_status === "published"} />
<section className={card + " space-y-4"} aria-label="Localizações documentadas">
<h2 className="text-xl font-bold">Localizações documentadas</h2>
<p>As localizações acrescentadas ficam pendentes até revisão independente. Não são inferidas pelo nome.</p>
{locations.map((location) => (
<div key={location.id} className="rounded border p-3">
<p>{location.name} · {location.scope_type} · {location.validation_status}</p>
<p className="text-sm">{location.source_reference}</p>
{location.validation_status === "pending" && (
<button type="button" className={button} disabled={busy} onClick={() => action(`/api/v2/investment/admin/zone-locations/${location.id}/validate`, { version_no: 1 })}>
Rever localização
</button>
)}
</div>
))}
<TerritoryFields endpoint="/management/territory-options" onChange={setLocationPath} />
<Field label="Tipo de abrangência">
<select className={input} value={locationScope} onChange={(event) => setLocationScope(event.target.value)}>
<option value="legal_scope">Perímetro legal</option><option value="administrative">Unidade administrativa</option>
<option value="site">Instalação/local</option><option value="influence">Área de influência</option>
</select>
</Field>
<Field label="Fonte e fundamento da associação">
<input className={input} minLength={10} maxLength={2000} value={locationSource} onChange={(event) => setLocationSource(event.target.value)} />
</Field>
<button type="button" className={button} disabled={busy || !locationPath.length || locationSource.length < 10} onClick={() => {
const selected = locationPath[locationPath.length - 1];
void action(`/api/v2/investment/admin/zones/${z.id}`, { ...form.data, locations: [{ geo_location_id: selected.id, scope_type: locationScope, source_reference: locationSource }], _method: "PUT" });
}}>Guardar outra localização</button>
</section>
<section className={card}>
<h2 className="text-xl font-bold">Revisão independente</h2>
<p>
@@ -386,6 +595,14 @@ function Editor({
) : (
<>
<p className="whitespace-pre-line">{z.description}</p>
<p>Categoria física: {z.physical_category ?? "Por confirmar"} · Regime jurídico: {z.legal_regime ?? "Por confirmar"}{zoneExtensionsAvailable ? ` · Desenvolvimento: ${z.development_status ?? "Por confirmar"} · Disponibilidade: ${z.availability_status ?? "Não informada"}` : ""}</p>
{z.area_value && <p>Área documentada: {z.area_value} {z.area_unit}</p>}
{zoneExtensionsAvailable && !!z.area_components?.length && <section className={card}><h2 className="font-bold">Áreas por âmbito</h2><ul>{z.area_components.map((area, index) => <li key={index}>{JSON.stringify(area)}</li>)}</ul></section>}
{zoneExtensionsAvailable && !!z.source_evidence?.length && <section className={card}><h2 className="font-bold">Fontes e o que comprovam</h2><ul>{z.source_evidence.map((evidence, index) => <li key={index}>{JSON.stringify(evidence)}</li>)}</ul></section>}
{z.historical_territory?.name && <p>Localização histórica: {z.historical_territory.name}{z.historical_territory.district ? ` · ${z.historical_territory.district}` : ""}{z.historical_territory.province ? ` · ${z.historical_territory.province}` : ""}</p>}
{z.activities?.length ? <section className={card}><h2 className="text-xl font-bold">Actividades e sectores referidos</h2><ul>{z.activities.map((activity, index) => <li key={`${activity.name}-${index}`}>{activity.name} · {activity.status === "potential" ? "potencial referido; não confirmado como autorizado" : activity.status === "proposed" ? "proposto; não confirmado como autorizado" : activity.status === "authorized" ? "autorizado segundo a fonte indicada" : activity.status === "conditional" ? "condicionado segundo a fonte indicada" : "excluído segundo a fonte indicada"}{activity.source_reference ? ` · ${activity.source_reference}` : ""}</li>)}</ul></section> : null}
{z.resources?.length ? <section className={card}><h2 className="text-xl font-bold">Infra-estruturas e recursos</h2>{z.resources.map((resource, index) => <p key={`${resource.name}-${index}`}>{resource.name} · {resource.status}{resource.source_reference ? ` · ${resource.source_reference}` : ""}</p>)}</section> : null}
{locations.length > 0 && <section className={card}><h2 className="text-xl font-bold">Abrangência territorial</h2><ul>{locations.map((location) => <li key={location.id}>{location.name} ({location.location_type}) · {location.scope_type}</li>)}</ul></section>}
<ZoneMap id={z.id} />
{z.description_en && (
<details>
@@ -396,6 +613,7 @@ function Editor({
</details>
)}
<p>Operador: {operator ?? "Informação pública por disponibilizar"}</p>
<ZoneAttachments zoneId={z.id} attachments={attachments} management={false} zonePublished={z.publication_status === "published"} />
{source && (
<section className={card}>
<h2 className="text-xl font-bold">Fonte e vigência</h2>
+111 -2
View File
@@ -10,14 +10,26 @@ type Zone = {
category: string;
description: string | null;
province: string | null;
district: string | null;
version_no: number;
publication_status: string;
validation_status: string;
territory_path?: { id: string; name: string; location_type: string }[];
legal_regime?: string | null;
operational_status?: string;
development_status?: string;
availability_status?: string;
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 }[];
};
export default function Zones({
records,
filters,
management,
zoneExtensionsAvailable = false,
territorySelection = [],
}: {
records: {
@@ -26,12 +38,20 @@ export default function Zones({
next_page_url: string | null;
prev_page_url: string | null;
};
filters: { q?: string; category?: 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 [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) {
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); });
return (
<Frame
title={management ? "Gestão de ZEE, ZFI e parques" : "ZEE, ZFI e parques industriais"}
@@ -59,10 +79,34 @@ export default function Zones({
<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>
</Field>
<Field label="Actividade documentada">
<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>
</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>}
{!records.total && (
<p className={card}>
Sem registos disponíveis para estes filtros. As zonas aguardam cadastro e
@@ -81,8 +125,15 @@ export default function Zones({
</h2>
<p>
{zone.code} · {zone.category.toUpperCase()} ·{" "}
{zone.province ?? "Localização por confirmar"}
{[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>}
<p>{zone.description}</p>
<p>Validação: {zone.validation_status}</p>
{management && (
@@ -134,6 +185,64 @@ export default function Zones({
<option value="industrial_park">Parque industrial</option>
</select>
</Field>
<Field label="Categoria física">
<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>
</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>
<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>
</select>
</Field>
<Field label="Área (valor) — se documentada">
<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>
</Field>
<Field label="Actividade documentada (opcional)">
<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>
</Field>
<Field label="Designações alternativas">
<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} />
</Field>
<Field label="Distrito histórico">
<input name="historical_district" className={input} maxLength={120} />
</Field>
<Field label="Província histórica">
<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} />
</Field>
{error && <p role="alert">{error}</p>}
<button className={button} disabled={busy}>
Guardar rascunho
@@ -0,0 +1,23 @@
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>;
}
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>; }
@@ -0,0 +1,35 @@
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 }[];
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' };
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>;
}
+101
View File
@@ -0,0 +1,101 @@
import { Link, useForm } from '@inertiajs/react';
import { useEffect, useMemo, useState } from 'react';
import { TerritoryFields, type TerritoryOption } from '@/components/investment-territory';
type Parcel = Record<string, string>;
type Payload = Record<string, any>;
const emptyParcel = (): Parcel => ({ province_id: '', district_id: '', admin_post_id: '', locality_id: '', place_description: '', area: '', area_unit: '', cadastral_reference: '', coordinates: '', geometry_confidence: 'unknown' });
const emptyPayload = (user: { name: string; email: string }): Payload => ({
support_kind: '', request_description: '', project_reference: '', applicant_category: '', full_name: user.name ?? '', contact_person: '', email: user.email ?? '', phone: '', preferred_contact: '',
country: '', nationality: '', representative_name: '', representative_role: '', representation_basis: '', nuit: '', constitution_or_residency_note: '', area_status: '', parcels: [emptyParcel()],
purpose: '', activity: '', known_occupants: 'unknown', occupant_description: '', known_improvements: 'unknown', improvements_description: '', prior_right_status: 'unknown', prior_right_description: '', conflict_status: 'unknown', conflict_description: '',
official_process: {}, attachments_to_follow: [], exploration_plan: { activity_rows: [], notes: '' },
consultation: { status: 'not_started', participants: [] }, additional_information: '', truth_declaration: false, contact_consent: false,
});
const supportKinds: Record<string, string> = {
investment: 'Terra para projecto de investimento', home: 'Orientação para habitação', family_exploitation: 'Exploração familiar', recognition: 'Reconhecimento/titulação de área ocupada', regularization: 'Regularização cadastral', delimitation: 'Delimitação/demarcação', change_of_use: 'Alteração de uso ou área', transfer: 'Transmissão/herança', existing_process: 'Acompanhamento de processo existente', conflict_guidance: 'Esclarecimento sobre conflito/restrição', other: 'Outro',
};
export default function LandForm({ case: existing, user, disclaimer, modelVersion }: { case: { id: string; reference: string; version: number; status: string; payload: Payload } | null; user: { name: string; email: string }; disclaimer: string; modelVersion: string }) {
const [step, setStep] = useState(0);
const initial = useMemo(() => existing?.payload ?? emptyPayload(user), [existing?.id]);
const form = useForm({ version: existing?.version ?? 1, payload: initial });
const update = (field: string, value: unknown) => form.setData('payload', { ...form.data.payload, [field]: value });
const updateParcel = (index: number, key: string, value: unknown) => {
const parcels = [...(form.data.payload.parcels ?? [emptyParcel()])];
parcels[index] = { ...parcels[index], [key]: value };
update('parcels', parcels);
};
const text = (key: string, label: string, required = false, type = 'text', help?: string) => <label className="block space-y-1" key={key}><span className="text-sm font-medium">{label}{required ? ' *' : ''}</span><input className="w-full rounded border p-2" type={type} required={required} value={form.data.payload[key] ?? ''} onChange={(event) => update(key, event.target.value)} aria-invalid={Boolean(form.errors[`payload.${key}`])} />{help && <span className="block text-xs text-slate-600">{help}</span>}{form.errors[`payload.${key}`] && <span role="alert" className="text-sm text-red-700">{form.errors[`payload.${key}`]}</span>}</label>;
const areaStatus = form.data.payload.area_status;
const category = form.data.payload.applicant_category;
const current = form.data.payload;
const saveUrl = existing ? `/investidor/terra-duat/${existing.id}` : '/investidor/terra-duat';
const save = () => existing
? form.put(saveUrl, { preserveScroll: true })
: form.post(saveUrl, { preserveScroll: true });
const support = () => existing && form.post(`/investidor/terra-duat/${existing.id}/solicitar-apoio`, { preserveScroll: true });
const canEdit = !existing || ['draft', 'waiting_applicant'].includes(existing.status);
return <main className="mx-auto max-w-5xl space-y-6 p-6">
<header className="space-y-2"><Link href="/terra-duat" className="underline">Terra e DUAT</Link><h1 className="text-3xl font-bold">Formulário de orientação e preparação</h1><p className="text-sm">Modelo {modelVersion}{existing ? ` · Referência interna ${existing.reference} · versão ${existing.version}` : ''}</p><p className="rounded border border-amber-400 bg-amber-50 p-3">{disclaimer}</p><p className="text-sm">A referência é interna do InvestMoz, não é número oficial de processo. Preencha só o que sabe; documentos são opcionais para pedir orientação.</p></header>
<ol className="grid grid-cols-2 gap-2 sm:grid-cols-4" aria-label="Etapas do formulário">{['Pedido e requerente','Localização e situação','Plano e consulta','Rever'].map((title, index) => <li key={title}><button type="button" onClick={() => setStep(index)} aria-current={step === index ? 'step' : undefined} className={`w-full rounded border p-2 text-sm ${step === index ? 'bg-emerald-800 text-white' : ''}`}>{index + 1}. {title}</button></li>)}</ol>
{step === 0 && <section className="grid gap-4 rounded border p-4 sm:grid-cols-2"><h2 className="sm:col-span-2 text-xl font-semibold">A. Tipo de apoio e requerente</h2>
<label className="space-y-1"><span className="text-sm font-medium">Pretende apoio para *</span><select className="w-full rounded border p-2" required value={current.support_kind ?? ''} onChange={(event) => update('support_kind', event.target.value)}><option value="">Seleccione</option>{Object.entries(supportKinds).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label>
{text('request_description', 'Descrição do pedido', true)}{text('project_reference', 'Projecto/oportunidade já registado, se existir')}
<label className="space-y-1"><span className="text-sm font-medium">Categoria do requerente *</span><select className="w-full rounded border p-2" required value={current.applicant_category ?? ''} onChange={(event) => update('applicant_category', event.target.value)}><option value="">Seleccione</option><option value="individual">Pessoa singular</option><option value="entity">Pessoa colectiva</option><option value="community">Comunidade</option><option value="other">Outra</option></select></label>
{text('full_name', 'Nome ou denominação', true)}{category === 'community' && text('contact_person', 'Pessoa de contacto da comunidade')}{text('email', 'Email (facultativo)', false, 'email')}{text('phone', 'Telefone (facultativo)', false, 'tel')}
<label className="space-y-1"><span className="text-sm font-medium">Canal preferido *</span><select className="w-full rounded border p-2" required value={current.preferred_contact ?? ''} onChange={(event) => update('preferred_contact', event.target.value)}><option value="">Seleccione</option><option value="email">Email</option><option value="phone">Telefone</option><option value="any">Qualquer um indicado</option></select></label>
{text('country', 'País, se aplicável')}{text('nationality', 'Nacionalidade, se aplicável')}
{category === 'entity' && <>{text('representative_name', 'Representante')}{text('representative_role', 'Função/qualidade da representação')}{text('representation_basis', 'Fundamento ou documento de representação (referência)')}{text('constitution_or_residency_note', 'Constituição/residência — detalhe apenas se relevante')}</>}
{text('nuit', 'NUIT/identificação — facultativo e apenas se necessário')}
</section>}
{step === 1 && <section className="space-y-5 rounded border p-4"><h2 className="text-xl font-semibold">B. Localização, finalidade e situação conhecida</h2>
<label className="block space-y-1"><span className="text-sm font-medium">Situação da localização *</span><select className="w-full rounded border p-2" required value={current.area_status ?? ''} onChange={(event) => update('area_status', event.target.value)}><option value="">Seleccione</option><option value="identified">Tenho uma área identificada</option><option value="seeking">Procuro uma localização</option><option value="location_support">Preciso de apoio para confirmar/localizar</option><option value="unknown">Ainda não sei</option></select></label>
{current.area_status !== 'seeking' && current.area_status !== 'unknown' && (current.parcels ?? []).map((parcel: Parcel, index: number) => <ParcelEditor key={index} index={index} parcel={parcel} onChange={(key, value) => updateParcel(index, key, value)} onRemove={() => update('parcels', current.parcels.filter((_: Parcel, i: number) => i !== index))} />)}
{areaStatus !== 'seeking' && <button type="button" className="rounded border px-3 py-2" onClick={() => update('parcels', [...(current.parcels ?? []), emptyParcel()])}>Adicionar outra parcela (até 10)</button>}
{text('purpose', 'Uso pretendido *', true)}{text('activity', 'Actividade económica, se aplicável')}
<StatusField label="Ocupantes ou utilizações conhecidas?" value={current.known_occupants} choices={['yes','no_as_far_as_known','unknown']} labels={['Sim','Não, segundo a informação disponível','Não sei']} onChange={(v) => update('known_occupants', v)} />
{current.known_occupants === 'yes' && text('occupant_description', 'Descrição dos ocupantes/usos')}
<StatusField label="Construções, benfeitorias, machambas, servidões ou usos comunitários?" value={current.known_improvements} choices={['yes','unknown','none_identified']} labels={['Sim','Não sei','Não identificados na informação disponível']} onChange={(v) => update('known_improvements', v)} />
{current.known_improvements === 'yes' && text('improvements_description', 'Descrição')}
<StatusField label="Título, autorização ou antecedentes?" value={current.prior_right_status} choices={['yes','unknown','no_documents']} labels={['Sim','Não sei','Não disponho de documentos']} onChange={(v) => update('prior_right_status', v)} />
{current.prior_right_status === 'yes' && text('prior_right_description', 'Descrição/referência dos antecedentes')}
<StatusField label="Conflito, oposição ou possível sobreposição conhecida?" value={current.conflict_status} choices={['yes','unknown','no_knowledge']} labels={['Sim','Não sei','Não tenho conhecimento']} onChange={(v) => update('conflict_status', v)} />
{current.conflict_status === 'yes' && text('conflict_description', 'Descrição (não constitui resolução de litígio)')}
{current.support_kind === 'existing_process' && <fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2"><legend className="font-medium">Processo existente — informação comunicada pelo requerente</legend>{(['official_reference','receiving_entity','presented_at','reported_status','pending_items','proof_available'] as const).map((key) => <label key={key} className="space-y-1"><span>{({official_reference:'Número oficial, se atribuído',receiving_entity:'Entidade receptora',presented_at:'Data de apresentação',reported_status:'Estado comunicado pela entidade',pending_items:'Pendências conhecidas',proof_available:'Comprovativo disponível'})[key]}</span>{key === 'proof_available' ? <select className="w-full rounded border p-2" value={current.official_process?.[key] ?? ''} onChange={(e) => update('official_process',{...current.official_process,[key]:e.target.value})}><option value="">Não sei</option><option value="yes">Sim</option><option value="no">Não</option></select> : <input className="w-full rounded border p-2" type={key === 'presented_at' ? 'date' : 'text'} value={current.official_process?.[key] ?? ''} onChange={(e) => update('official_process',{...current.official_process,[key]:e.target.value})} />}</label>)}</fieldset>}
</section>}
{step === 2 && <section className="space-y-5 rounded border p-4"><h2 className="text-xl font-semibold">C. Plano de exploração e consulta comunitária (quando aplicável)</h2><p>As tabelas são facultativas. Os períodos são definidos por si; o sistema não impõe cinco anos nem soma áreas repetidas como novas parcelas.</p>
{(current.exploration_plan?.activity_rows ?? []).map((row: any, index: number) => <div key={index} className="grid gap-3 rounded border p-3 sm:grid-cols-2"><h3 className="sm:col-span-2 font-semibold">Actividade {index + 1}</h3>{(['period','activity','area','area_unit','stage','targets','structures','investment'] as const).map((key) => <label key={key} className="space-y-1"><span>{({period:'Período',activity:'Actividade',area:'Área (não somada)',area_unit:'Unidade',stage:'Existente/planeado',targets:'Metas',structures:'Construções/vedações',investment:'Investimento previsto'})[key]}</span>{key === 'area_unit' ? <select className="w-full rounded border p-2" value={row[key] ?? ''} onChange={(e) => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.map((r:any,i:number)=>i===index?{...r,[key]:e.target.value}:r)})}><option value="">Por confirmar</option><option value="m2">m²</option><option value="hectares">Hectares</option><option value="other">Outra</option></select> : key === 'stage' ? <select className="w-full rounded border p-2" value={row[key] ?? ''} onChange={(e) => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.map((r:any,i:number)=>i===index?{...r,[key]:e.target.value}:r)})}><option value="">Por confirmar</option><option value="existing">Existente</option><option value="planned">Planeado</option><option value="unknown">Não sei</option></select> : <input className="w-full rounded border p-2" type={['area','investment'].includes(key) ? 'number' : 'text'} min={['area','investment'].includes(key) ? 0 : undefined} value={row[key] ?? ''} onChange={(e) => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.map((r:any,i:number)=>i===index?{...r,[key]:e.target.value}:r)})} />}</label>)}<button type="button" className="text-left text-sm underline" onClick={() => update('exploration_plan',{...current.exploration_plan,activity_rows:current.exploration_plan.activity_rows.filter((_:any,i:number)=>i!==index)})}>Remover linha</button></div>)}
{(current.exploration_plan?.activity_rows?.length ?? 0) < 30 && <button type="button" className="rounded border px-3 py-2" onClick={() => update('exploration_plan',{...current.exploration_plan,activity_rows:[...(current.exploration_plan?.activity_rows ?? []),{period:'',activity:'',area:'',area_unit:'',stage:'',targets:'',structures:'',investment:''}]})}>Adicionar período/actividade</button>}
<label className="block space-y-1"><span>Notas do plano</span><textarea className="w-full rounded border p-2" value={current.exploration_plan?.notes ?? ''} onChange={(e)=>update('exploration_plan',{...current.exploration_plan,notes:e.target.value})}/></label>
<fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2"><legend className="font-semibold">Preparação/acompanhamento de consulta — não preencher como realizada</legend><label><span>Estado comunicado</span><select className="w-full rounded border p-2" value={current.consultation?.status ?? 'not_started'} onChange={(e)=>update('consultation',{...current.consultation,status:e.target.value})}><option value="not_started">Não iniciada</option><option value="preparing">Em preparação</option><option value="reported_completed">Requerente informa que ocorreu</option><option value="unknown">Não sei</option></select></label>{(['community','location','date','facilitators','language','interventions','opposition','agreements','minutes_reference','opinions_received'] as const).map(key=><label className="space-y-1" key={key}><span>{({community:'Comunidade',location:'Local',date:'Data',facilitators:'Responsáveis/facilitadores',language:'Língua/tradução',interventions:'Intervenções e divergências',opposition:'Oposição comunicada',agreements:'Acordos/compromissos comunicados',minutes_reference:'Referência de acta recebida',opinions_received:'Pareceres recebidos'})[key]}</span>{['interventions','opposition','agreements','opinions_received'].includes(key)?<textarea className="w-full rounded border p-2" value={current.consultation?.[key]??''} onChange={e=>update('consultation',{...current.consultation,[key]:e.target.value})}/>:<input className="w-full rounded border p-2" type={key==='date'?'date':'text'} value={current.consultation?.[key]??''} onChange={e=>update('consultation',{...current.consultation,[key]:e.target.value})}/>}</label>)}
{(current.consultation?.participants ?? []).map((person:any,index:number)=><div key={index} className="flex gap-2"><input className="w-full rounded border p-2" aria-label="Nome de participante" placeholder="Nome, se aplicável" value={person.name??''} onChange={e=>update('consultation',{...current.consultation,participants:current.consultation.participants.map((p:any,i:number)=>i===index?{...p,name:e.target.value}:p)})}/><input className="w-full rounded border p-2" aria-label="Função de participante" placeholder="Função" value={person.role??''} onChange={e=>update('consultation',{...current.consultation,participants:current.consultation.participants.map((p:any,i:number)=>i===index?{...p,role:e.target.value}:p)})}/></div>)}
{(current.consultation?.participants?.length ?? 0)<200 && <button type="button" className="text-sm underline" onClick={()=>update('consultation',{...current.consultation,participants:[...(current.consultation?.participants??[]),{name:'',role:''}]})}>Adicionar participante</button>}
</fieldset>
</section>}
{step === 3 && <section className="space-y-4 rounded border p-4"><h2 className="text-xl font-semibold">D. Rever e pedir apoio</h2><label className="block space-y-1"><span>Informação complementar</span><textarea className="w-full rounded border p-2" value={current.additional_information ?? ''} onChange={(e)=>update('additional_information',e.target.value)} /></label><label className="flex gap-2"><input type="checkbox" checked={Boolean(current.truth_declaration)} onChange={(e)=>update('truth_declaration',e.target.checked)} />Confirmo que as respostas correspondem à informação de que disponho e assinalei dúvidas conhecidas.</label><label className="flex gap-2"><input type="checkbox" checked={Boolean(current.contact_consent)} onChange={(e)=>update('contact_consent',e.target.checked)} />Autorizo o contacto para responder a este pedido. Esta autorização não permite publicação dos documentos.</label><p className="rounded bg-amber-50 p-3 text-sm">Ainda não carregue actas, documentos de identidade ou informações sensíveis que não sejam necessárias à orientação. Os anexos são opcionais e ficam reservados quando enviados.</p><p className="text-sm">O estado da consulta e dos processos externos será sempre apresentado como informação comunicada, não como confirmação oficial.</p></section>}
<footer className="flex flex-wrap justify-between gap-3 border-t pt-4"><button type="button" disabled={step===0} className="rounded border px-4 py-2 disabled:opacity-50" onClick={()=>setStep(step-1)}>Anterior</button><div className="flex flex-wrap gap-3"><button type="button" disabled={!canEdit || form.processing} className="rounded border px-4 py-2 disabled:opacity-50" onClick={save}>Guardar rascunho</button>{step<3 ? <button type="button" className="rounded bg-emerald-800 px-4 py-2 text-white" onClick={()=>setStep(step+1)}>Continuar</button> : existing ? <button type="button" disabled={!canEdit || form.processing} className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50" onClick={support}>Solicitar apoio</button> : <button type="button" disabled={form.processing} className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50" onClick={save}>Guardar rascunho e continuar para solicitar apoio</button>}</div></footer>
{Object.keys(form.errors).length>0 && <div role="alert" className="rounded border border-red-500 p-3"><p>Revise os campos assinalados antes de continuar.</p><ul>{Object.entries(form.errors).map(([key,value])=><li key={key}>{String(value)}</li>)}</ul></div>}
{existing && <Link href={`/investidor/terra-duat/${existing.id}`} className="underline">Voltar ao acompanhamento</Link>}
</main>;
}
function StatusField({label,value,choices,labels,onChange}:{label:string;value:string;choices:string[];labels:string[];onChange:(value:string)=>void}) { return <label className="block space-y-1"><span className="text-sm font-medium">{label}</span><select className="w-full rounded border p-2" value={value??'unknown'} onChange={e=>onChange(e.target.value)}>{choices.map((choice,i)=><option key={choice} value={choice}>{labels[i]}</option>)}</select></label>; }
function ParcelEditor({index,parcel,onChange,onRemove}:{index:number;parcel:Parcel;onChange:(key:string,value:string)=>void;onRemove:()=>void}) {
const [path,setPath]=useState<TerritoryOption[]>([]);
useEffect(()=>{
const ids=['province_id','district_id','admin_post_id','locality_id'].map(k=>parcel[k]).filter(Boolean);
if (!ids.length) { setPath([]); return; }
const abort=new AbortController();
void (async()=>{const result:TerritoryOption[]=[];let parent='';for(let i=0;i<ids.length;i++){const type=['province','district','admin_post','locality'][i];const params=new URLSearchParams({type,id:ids[i],...(parent?{parent_id:parent}:{})});const response=await fetch(`/api/v1/investment/territory-options?${params}`,{signal:abort.signal,headers:{Accept:'application/json'}});if(!response.ok)break;const body=await response.json();const option=body.data?.[0] as TerritoryOption|undefined;if(!option)break;result.push(option);parent=option.id;}if(!abort.signal.aborted)setPath(result);})().catch(()=>{});
return ()=>abort.abort();
},[]);
const initial=useMemo(()=>path,[path]);
return <fieldset className="grid gap-3 rounded border p-3 sm:grid-cols-2"><legend className="px-1 font-semibold">Parcela/área {index+1}</legend><div className="sm:col-span-2"><TerritoryFields initial={initial} endpoint="/api/v1/investment/territory-options" onChange={(next)=>{(['province_id','district_id','admin_post_id','locality_id'] as const).forEach((field,i)=>onChange(field,next[i]?.id??''));}} /></div>
<label className="space-y-1"><span>Área estimada (se conhecida)</span><input type="number" min="0" className="w-full rounded border p-2" value={parcel.area??''} onChange={e=>onChange('area',e.target.value)}/></label><label className="space-y-1"><span>Unidade</span><select className="w-full rounded border p-2" value={parcel.area_unit??''} onChange={e=>onChange('area_unit',e.target.value)}><option value="">Por confirmar</option><option value="m2">m²</option><option value="hectares">Hectares</option><option value="other">Outra</option><option value="unknown">Não sei</option></select></label>
<label className="space-y-1"><span>Referência cadastral, se existente</span><input className="w-full rounded border p-2" value={parcel.cadastral_reference??''} onChange={e=>onChange('cadastral_reference',e.target.value)}/></label><label className="space-y-1"><span>Coordenadas ou planta, se disponíveis</span><input className="w-full rounded border p-2" value={parcel.coordinates??''} onChange={e=>onChange('coordinates',e.target.value)}/></label><label className="space-y-1"><span>Precisão indicada</span><select className="w-full rounded border p-2" value={parcel.geometry_confidence??'unknown'} onChange={e=>onChange('geometry_confidence',e.target.value)}><option value="declared">Declarada pelo requerente</option><option value="approximate">Aproximada</option><option value="confirmed_by_authority">Confirmada por entidade, segundo documento referido</option><option value="unknown">Por confirmar</option></select></label><label className="space-y-1 sm:col-span-2"><span>Descrição do local</span><textarea className="w-full rounded border p-2" value={parcel.place_description??''} onChange={e=>onChange('place_description',e.target.value)}/></label><button type="button" className="text-left text-sm underline" onClick={onRemove}>Remover parcela</button><p className="text-xs text-slate-600">A selecção territorial e qualquer intersecção cartográfica não confirmam direitos, limites ou disponibilidade.</p>
</fieldset>;
}
@@ -0,0 +1,24 @@
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>;
}
@@ -0,0 +1,4 @@
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>;}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
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>;}
+31 -1
View File
@@ -10,22 +10,27 @@ type Record = {
slug: string;
is_active?: boolean;
status?: string;
geography_scope?: string;
primary_territory?: { name: string; location_type: string; source_system?: string; source_code?: string | null } | null;
};
export default function Catalog({
resource,
records,
filters,
sectors,
geographyReviewCount = 0,
}: {
resource: 'sectors' | 'opportunities';
records: Paginated<Record>;
filters: { q?: string; status?: string; sector_id?: number | string };
filters: { q?: string; status?: string; sector_id?: number | string; geography_scope?: string };
sectors: { id: number; name: string }[];
geographyReviewCount?: number;
}) {
const form = useForm({
q: filters.q ?? '',
status: filters.status ?? '',
sector_id: String(filters.sector_id ?? ''),
geography_scope: filters.geography_scope ?? '',
});
return (
<Management
@@ -34,6 +39,11 @@ export default function Catalog({
<Link className={button} href={`/management/${resource}/create`}>
Criar {resource === 'sectors' ? 'sector' : 'oportunidade'}
</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.
</p>
)}
<form
className="flex flex-wrap gap-3"
onSubmit={(event) => {
@@ -74,6 +84,7 @@ export default function Catalog({
))}
</select>
{resource === 'opportunities' && (
<>
<select
aria-label="Sector"
className={`${control} max-w-xs`}
@@ -89,6 +100,20 @@ export default function Catalog({
</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>
</>
)}
<button className={button} disabled={form.processing}>
Pesquisar
@@ -123,6 +148,11 @@ 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>
)}
</div>
<Link
className="underline"
+17
View File
@@ -67,6 +67,7 @@ export default function Editor({
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.territory_version = String(record?.territory_version ?? 0);
["province_id", "district_id", "admin_post_id", "locality_id"].forEach((field, index) => {
initial[field] = territoryPath[index]?.id ?? "";
@@ -180,6 +181,22 @@ 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>
</select>
</Field>
<Field label="Estado" error={form.errors.status}>
<select
className={control}
+17 -5
View File
@@ -45,7 +45,8 @@ type Consent = { purpose: string; policy_version: string | null; status: string;
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 consentForm = useForm({ reason: "" });
const contactConsentForm = useForm({ reason: "" });
const sharingConsentForm = useForm({ reason: "" });
const rows: [string, string | number | null][] = [
["Nome", interest.full_name],
["Email", interest.email],
@@ -111,15 +112,26 @@ export default function InterestDetail({ interest, history = [], assignees = [],
{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)} />
</Field>
<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();
consentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
sharingConsentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
}}>
<Field label="Motivo do pedido de revogação" error={consentForm.errors.reason}>
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={consentForm.data.reason} onChange={(event) => consentForm.setData("reason", event.target.value)} />
<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={consentForm.processing}>Revogar autorização de partilha</button>
<button className={button} disabled={sharingConsentForm.processing}>Revogar autorização de partilha</button>
</form>
)}
</section>
+1
View File
@@ -53,6 +53,7 @@ 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/corridors">Corredores</Link>
<Link href="/management/territory-associations">
Localizações dos investimentos
</Link>
+112
View File
@@ -0,0 +1,112 @@
import { Head, Link } from '@inertiajs/react';
import { PortalMenu } from '@/layouts/portal-navigation';
type DocumentResource = {
title: string;
description: string | null;
category: string;
topic: string;
document_type: string;
document_number: string | null;
document_date: string | null;
applicable_from: string | null;
applicable_until: string | null;
source_url: string | null;
language: string;
version_label: string | null;
territorial_scope: string;
territory_name: string | null;
source_confirmation: string;
legal_status: string;
source_reference: string;
issuer: string | null;
file_name: string;
size_bytes: number | null;
view_url: string | null;
links: {
target_type: string;
target_key: string;
relationship: string;
applicability: string;
condition_text: string | null;
basis_reference: string | null;
review_status: string;
}[];
};
const modulePaths: Record<string, { href: string; label: string }> = {
simulator: { href: '/Simulador', label: 'Simulador fiscal' },
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',
};
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',
};
export default function DocumentPage({
resource,
backUrl,
downloadUrl,
}: {
resource: DocumentResource;
backUrl: string;
downloadUrl: string;
}) {
return (
<div className="min-h-screen bg-slate-50 text-slate-900">
<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>
<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>}
</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>
</dl>
<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_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>}
</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>
</article>
</main>
</div>
);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+16 -3
View File
@@ -3,16 +3,19 @@ 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';
export default function Index({
records,
management,
filters,
territorySelection = [],
}: {
records: Paginated<Dossier>;
management: boolean;
filters: { q?: string; kind?: 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 ?? '' });
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 (
@@ -54,6 +57,7 @@ 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 ?? '' }))} />
<button className={button}>Pesquisar</button>
</form>
<div className="grid gap-4 md:grid-cols-2">
@@ -80,6 +84,7 @@ 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.priority && (
<p>
{r.content.priority}{' '}
@@ -95,7 +100,15 @@ export default function Index({
))}
</div>
{!records.data.length && (
<p>Ainda não existem fichas publicadas para esta pesquisa.</p>
<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>
</nav>
</div>
)}
<Pagination page={records} />
</Frame>
+50 -11
View File
@@ -1,4 +1,5 @@
import { Link, useForm, router } from "@inertiajs/react";
import { Link, useForm, router, usePage } from "@inertiajs/react";
import { useState } from "react";
import InvestmentMapPanel from "@/components/investment-map-panel";
import { Management } from "../management/shared";
import { Layout, Field, control, button, labels, kind } from "./shared";
@@ -8,6 +9,8 @@ export default function Show(props: Props) {
}
type Props = {
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;
zones?: {
id: string;
name: string;
@@ -31,7 +34,11 @@ function Editor({
opportunities = [],
chains = [],
zones = [],
anchorProject = null,
existingSubmissions = [],
}: Props) {
const { auth } = usePage<{ auth: { user: unknown } }>().props;
const [creatingManifestation, setCreatingManifestation] = useState(false);
const form = useForm({
title: record.title,
source: record.source,
@@ -48,6 +55,22 @@ function Editor({
{kind(record)} · {record.content.code}
</p>
<p className="text-sm">Fonte: {record.source}</p>
{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>
)}
{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>
)}
{!management && (record.cluster_id || record.corridor_id || record.project_id) && (
<InvestmentMapPanel
filters={
@@ -73,16 +96,32 @@ function Editor({
</section>
)}
{origin && <p>Exploração iniciada em: {origin.title}</p>}
{!management && (
<button
type="button"
className={button}
onClick={() =>
router.post("/investidor/manifestacoes", { dossier_id: record.id })
}
>
Preparar manifestação com necessidades e anexos
</button>
{!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>
{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>
)}
<button
type="button"
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;
setCreatingManifestation(true);
router.post("/investidor/manifestacoes", { dossier_id: record.id }, { onFinish: () => setCreatingManifestation(false) });
}}
>
{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>
)}
{chains.length > 0 && (
<section>
+48 -7
View File
@@ -1,4 +1,4 @@
import { Link, useForm } from "@inertiajs/react";
import { Link, router, useForm } from "@inertiajs/react";
import InvestmentTerritory, { TerritoryFields } from "@/components/investment-territory";
import { Management, Field, button, control } from "../management/shared";
import { titles, statuses, stages, roles } from "./types";
@@ -65,6 +65,7 @@ export default function Editor({
structure,
record,
projects,
viewerId,
chains,
memberships,
chainLinks,
@@ -73,6 +74,7 @@ export default function Editor({
structure: Structure;
record: StructureRecord | null;
projects: { id: string; name: string; code: string }[];
viewerId: number;
chains: Chain[];
chainLinks: ChainLink[];
gaps: Gap[];
@@ -81,13 +83,24 @@ export default function Editor({
project_id: string;
name: string;
role: string;
association_type: string;
source_reference: string | null;
evidence_reference: string | null;
valid_from: string | null;
valid_until: string | null;
validation_status: string;
version_no: number;
editor_id: number | null;
}[];
}) {
const isProject = structure === "projects";
const isCluster = structure === "clusters";
const isCorridor = structure === "corridors";
const singular = isProject ? "projecto" : isCluster ? "cluster" : "corredor";
const form = useForm({
code: record?.code ?? "",
name: record?.name ?? "",
status: record?.status ?? (isProject ? "draft" : "planned"),
status: record?.status ?? (isProject ? "draft" : isCluster ? "planned" : "proposed"),
sector: record?.sector ?? "",
description: record?.description ?? "",
budget_amount: record?.budget_amount ?? "",
@@ -99,9 +112,9 @@ export default function Editor({
admin_post_id: "",
locality_id: "",
});
const association = useForm({ project_id: "", role: "complementary" });
const association = useForm({ project_id: "", version_no: 0, role: "complementary", association_type: "potential", source_reference: "", evidence_reference: "", valid_from: "", valid_until: "" });
return (
<Management title={`${record ? "Editar" : "Criar"} ${isProject ? "projecto" : "cluster"}`}>
<Management title={`${record ? "Editar" : "Criar"} ${singular}`}>
<Link className="underline" href={`/management/${structure}`}>
Voltar a {titles[structure].toLowerCase()}
</Link>
@@ -155,7 +168,7 @@ export default function Editor({
))}
</select>
</Field>
{!isProject && (
{isCluster && (
<Field label="Sector do cluster" error={form.errors.sector}>
<input
className={control}
@@ -216,11 +229,21 @@ export default function Editor({
</Field>
</>
)}
{isCorridor && (
<Field label="Descrição" error={form.errors.description}>
<textarea
className={control}
rows={5}
value={form.data.description}
onChange={(e) => form.setData("description", e.target.value)}
/>
</Field>
)}
<button className={button} disabled={form.processing}>
Guardar
</button>
</form>
{!isProject && record && (
{isCluster && record && (
<>
<section className="max-w-3xl space-y-4">
<h2 className="text-xl font-semibold">Projectos associados</h2>
@@ -235,6 +258,14 @@ export default function Editor({
· {roles[member.role]}
</p>
))}
{memberships.map((member) => (
<div key={`${member.id}-governance`} className="text-sm">
{member.validation_status} - {member.association_type} - {member.source_reference ?? "Sem fonte"} - {member.evidence_reference ?? "Sem evidencia"} - {member.valid_from ?? "Sem inicio"} - {member.valid_until ?? "Sem termo"}
{member.validation_status === "pending" && member.editor_id !== viewerId && (
<button className={button} type="button" onClick={() => router.post(`/management/structure-relations/cluster-project/${member.id}/validate`, { version_no: member.version_no }, { preserveScroll: true })}>Validar associacao</button>
)}
</div>
))}
{!memberships.length && <p>Ainda não existem projectos associados.</p>}
<form
className="space-y-3"
@@ -250,7 +281,8 @@ export default function Editor({
className={control}
value={association.data.project_id}
onChange={(e) =>
association.setData("project_id", e.target.value)
association.setData((data) => ({ ...data, project_id: e.target.value,
version_no: memberships.find((member) => member.project_id === e.target.value)?.version_no ?? 0 }))
}
>
<option value="">Seleccione</option>
@@ -274,6 +306,15 @@ export default function Editor({
))}
</select>
</Field>
<Field label="Tipo de associacao" error={association.errors.association_type}>
<select className={control} value={association.data.association_type} onChange={(e) => association.setData("association_type", e.target.value)}>
<option value="official">Oficial</option><option value="influence">Influencia</option><option value="proximity">Proximidade</option><option value="potential">Potencial</option><option value="historical">Historica</option>
</select>
</Field>
<Field label="Referencia da fonte" error={association.errors.source_reference}><textarea className={control} value={association.data.source_reference} onChange={(e) => association.setData("source_reference", e.target.value)} /></Field>
<Field label="Referencia da evidencia" error={association.errors.evidence_reference}><input className={control} value={association.data.evidence_reference} onChange={(e) => association.setData("evidence_reference", e.target.value)} /></Field>
<Field label="Vigente desde" error={association.errors.valid_from}><input className={control} type="date" value={association.data.valid_from} onChange={(e) => association.setData("valid_from", e.target.value)} /></Field>
<Field label="Vigente ate" error={association.errors.valid_until}><input className={control} type="date" value={association.data.valid_until} onChange={(e) => association.setData("valid_until", e.target.value)} /></Field>
<button className={button} disabled={association.processing}>
Guardar associação
</button>
+5 -1
View File
@@ -23,7 +23,11 @@ export default function Index({
return (
<Management title={titles[structure]}>
<Link className={button} href={`/management/${structure}/create`}>
{structure === 'projects' ? 'Criar projecto' : 'Criar cluster'}
{structure === 'projects'
? 'Criar projecto'
: structure === 'clusters'
? 'Criar cluster'
: 'Criar corredor'}
</Link>
<form
className="flex flex-wrap items-end gap-3"
+3 -2
View File
@@ -1,4 +1,4 @@
export type Structure = 'projects' | 'clusters';
export type Structure = 'projects' | 'clusters' | 'corridors';
export type StructureRecord = {
id: string;
code: string;
@@ -11,7 +11,7 @@ export type StructureRecord = {
start_date?: string | null;
end_date?: string | null;
};
export const titles = { projects: 'Projectos', clusters: 'Clusters' };
export const titles = { projects: 'Projectos', clusters: 'Clusters', corridors: 'Corredores' };
export const statuses: Record<Structure, Record<string, string>> = {
projects: {
draft: 'Rascunho',
@@ -22,6 +22,7 @@ export const statuses: Record<Structure, Record<string, string>> = {
cancelled: 'Cancelado',
},
clusters: { planned: 'Planeado', active: 'Activo', inactive: 'Inactivo' },
corridors: { proposed: 'Proposto', active: 'Activo', closed: 'Encerrado' },
};
export const stages: Record<string, string> = {
input: 'Insumos',