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