Files
Investidor-V2/resources/js/components/integral-financial-plan.tsx
T
Claude a3f2d2d7ca Plano de negócio como resultado da simulação
O relatório do investidor segue o modelo: resumo executivo (com objectivos,
missão e chaves para o sucesso), startup, mercado, vendas e marcos, pessoal
e plano financeiro, com as tabelas anuais nos capítulos e o detalhe mensal
do primeiro ano em anexo, sem colunas técnicas. Antes de exportar aparece
«Falta preencher» com ligação aos campos.

O cenário fiscal calcula o IRPC de cada ano à taxa geral de 32% sobre o
lucro antes de impostos, em vez de 72 campos mensais. Os rácios passam a
ser calculados a partir do balanço quando o investidor não classifica o
activo e o passivo correntes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-04 21:11:45 +02:00

373 lines
15 KiB
TypeScript

import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
buildIntegralFinancialTables,
newReportAssumptions,
isReportAssumptions,
} from '@/lib/integral-financial-report';
import { InvestmentReportTables } from './investment-report-tables';
import { BusinessPlanWarnings } from './business-plan-warnings';
import { financialPlanWarnings } from '@/lib/financial-plan-warnings';
import { StartupAssetRequirements } from './startup-asset-requirements';
import {
irpcPlanScenarios,
irpcScenarioSchedule,
type IrpcPlanScenario,
} from '@/lib/irpc-plan-scenario';
import { useState } from 'react';
export function IntegralFinancialPlan({
plan,
onChange,
}: {
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
if (plan.reportSource === 'annual_example') {
return (
<p role="status">
Seleccione o plano do investidor para consultar o relatório
financeiro.
</p>
);
}
if (plan.reportAssumptions && !isReportAssumptions(plan.reportAssumptions))
return (
<p role="alert">
Os dados complementares guardados não têm uma estrutura
reconhecida. Foram preservados e não serão substituídos
automaticamente.
</p>
);
const a =
plan.reportAssumptions ?? newReportAssumptions(plan.periods ?? 12);
const update = (patch: Partial<typeof a>) =>
onChange({ ...plan, reportAssumptions: { ...a, ...patch } });
const numeric = (
label: string,
value: string,
save: (value: string) => void,
) => (
<label className="grid gap-1 text-sm">
{label}
<input
type="number"
min="0"
step="0.01"
className="min-w-0 rounded border p-2"
value={value}
onChange={(event) => save(event.target.value)}
/>
</label>
);
return (
<details className="my-4 rounded border border-teal-500 p-3">
<summary className="font-semibold">
Relatório financeiro integral — dados do investimento
</summary>
<p className="my-2">
Utiliza as vendas, custos e agendas do plano financeiro. Todos
os montantes são projecções declaradas em{' '}
{plan.currency || 'moeda por seleccionar'}. Campos em falta
permanecem por determinar; indique zero apenas quando aplicável.
</p>
<StartupAssetRequirements
plan={plan}
onChange={onChange}
showError={false}
/>
<div className="grid gap-3 sm:grid-cols-2">
<label className="grid gap-1 text-sm">
Ano inicial
<input
type="number"
min="1900"
max="9999"
step="1"
className="rounded border p-2"
value={a.startYear}
onChange={(event) =>
update({ startYear: event.target.value })
}
/>
</label>
{!plan.startupAssetRequirements &&
numeric(
'Activos fixos anteriores (valor líquido)',
a.openingFixedAssets,
(openingFixedAssets) => update({ openingFixedAssets }),
)}
{!plan.startupAssetRequirements &&
numeric(
'Outros activos anteriores',
a.openingOtherAssets,
(openingOtherAssets) => update({ openingOtherAssets }),
)}
{numeric(
'Capital e resultados anteriores',
a.openingEquity,
(openingEquity) => update({ openingEquity }),
)}
<label className="grid gap-1 text-sm">
Tratamento das subvenções
<select
className="rounded border p-2"
value={a.grantsTreatment}
onChange={(event) =>
update({
grantsTreatment: event.target
.value as typeof a.grantsTreatment,
})
}
>
<option value="">Por indicar / sem subvenção</option>
<option value="capital">Capital</option>
<option value="deferred">Passivo diferido</option>
</select>
</label>
<label className="grid gap-1 text-sm">
Natureza dos recebimentos manuais
<select
className="rounded border p-2"
value={a.manualCollectionsKind}
onChange={(event) =>
update({
manualCollectionsKind: event.target
.value as typeof a.manualCollectionsKind,
})
}
>
<option value="">Por indicar / sem montante</option>
<option value="sales">Cobranças de vendas</option>
<option value="other_income">
Outras receitas reconhecidas e recebidas
</option>
</select>
</label>
</div>
<fieldset className="my-3 space-y-2">
<legend>
Despesas de arranque — reconhecidas e pagas na abertura
</legend>
{a.startupExpenses.map((row, index) => (
<div className="grid gap-2 sm:grid-cols-3" key={index}>
<label className="grid text-sm">
Despesa {index + 1}
<input
className="rounded border p-2"
value={row.label}
maxLength={160}
onChange={(event) =>
update({
startupExpenses: a.startupExpenses.map(
(entry, i) =>
i === index
? {
...entry,
label: event.target
.value,
}
: entry,
),
})
}
/>
</label>
{numeric(
`Montante de arranque ${index + 1}`,
row.amount,
(amount) =>
update({
startupExpenses: a.startupExpenses.map(
(entry, i) =>
i === index
? { ...entry, amount }
: entry,
),
}),
)}
<button
type="button"
className="rounded border p-2"
onClick={() =>
update({
startupExpenses: a.startupExpenses.filter(
(_, i) => i !== index,
),
})
}
>
Remover despesa
</button>
</div>
))}
<button
type="button"
className="rounded border p-2"
disabled={a.startupExpenses.length >= 40}
onClick={() =>
update({
startupExpenses: [
...a.startupExpenses,
{ label: '', amount: '' },
],
})
}
>
Adicionar despesa de arranque
</button>
</fieldset>
<p className="my-2 text-sm">
Os saldos anteriores têm de reconciliar entre si. Não inclua os
novos activos no saldo anterior, nem os novos capitais nos
resultados anteriores.
</p>
<p className="text-sm">
Sem linhas significa que não declarou despesas de arranque; para
confirmar a inexistência, registe uma linha «Sem despesas de
arranque» com zero.
</p>
<TaxScenario
plan={plan}
onApply={(result) =>
update({
taxExpenseByMonth: result.expense,
taxPaymentByMonth: result.payment,
taxSource: result.source,
})
}
/>
<label className="my-2 grid gap-1 text-sm">
Fonte ou pressuposto dos impostos estimados
<input
className="rounded border p-2"
maxLength={1000}
value={a.taxSource}
onChange={(event) =>
update({ taxSource: event.target.value })
}
/>
</label>
<details>
<summary>Impostos por mês — estimativa e tesouraria</summary>
<p className="text-sm">
Preenchidos pelo cenário fiscal ou por si. Não certifica
pagamentos; um mês sem imposto fica com zero.
</p>
{Array.from({ length: plan.periods ?? 12 }, (_, index) => (
<div className="my-2 grid gap-2 sm:grid-cols-2" key={index}>
{numeric(
`Imposto reconhecido — mês ${index + 1}`,
a.taxExpenseByMonth[index] ?? '',
(value) =>
update({
taxExpenseByMonth: Array.from(
{ length: plan.periods ?? 12 },
(_, i) =>
i === index
? value
: (a.taxExpenseByMonth[i] ??
''),
),
}),
)}
{numeric(
`Pagamento fiscal previsto — mês ${index + 1}`,
a.taxPaymentByMonth[index] ?? '',
(value) =>
update({
taxPaymentByMonth: Array.from(
{ length: plan.periods ?? 12 },
(_, i) =>
i === index
? value
: (a.taxPaymentByMonth[i] ??
''),
),
}),
)}
</div>
))}
</details>
<InvestmentReportTables
tables={buildIntegralFinancialTables(plan)}
/>
<BusinessPlanWarnings
warnings={financialPlanWarnings(
plan,
buildIntegralFinancialTables(plan),
)}
/>
</details>
);
}
/** Own component so its state never runs when the plan editor is used as a plain function. */
function TaxScenario({
plan,
onApply,
}: {
plan: BusinessFinancialPlanInput;
onApply: (result: ReturnType<typeof irpcScenarioSchedule>) => void;
}) {
const [scenario, setScenario] = useState<IrpcPlanScenario>('general');
const [scenarioError, setScenarioError] = useState('');
return (
<section
aria-label="Cenário fiscal"
className="my-3 space-y-2 rounded border p-3"
>
<h4 className="font-semibold">Cenário fiscal</h4>
<p className="text-sm">
Escolha o cenário e o simulador calcula o IRPC de cada ano a
partir do lucro antes de impostos, para ver o lucro líquido
e a viabilidade. Pode depois ajustar mês a mês.
</p>
<label className="grid gap-1 text-sm">
Cenário
<select
className="rounded border p-2"
value={scenario}
onChange={(event) =>
setScenario(event.target.value as IrpcPlanScenario)
}
>
{Object.entries(irpcPlanScenarios).map(
([key, option]) => (
<option key={key} value={key}>
{option.label}
</option>
),
)}
</select>
</label>
<button
type="button"
className="rounded bg-emerald-800 px-3 py-2 text-white"
onClick={() => {
try {
const result = irpcScenarioSchedule(
plan,
scenario,
);
setScenarioError('');
onApply(result);
} catch (cause) {
setScenarioError(
cause instanceof Error
? `Complete primeiro o plano: ${cause.message}`
: 'Complete primeiro as vendas e os custos do plano.',
);
}
}}
>
Calcular os impostos com este cenário
</button>
{scenarioError && (
<p role="alert" className="text-sm text-red-800">
{scenarioError}
</p>
)}
</section>
);
}