tests / ci (push) Canceled after 0s
As despesas de arranque passam a oferecer as categorias habituais de uma empresa nova (constituição e despesas legais, mobiliário, seguros, rendas, computadores, outras despesas de início de actividade), acrescentadas só quando o investidor o pede e sem alterar as linhas que já escreveu, e mostram o total, ou o que falta para o calcular. Cada produto ou serviço mostra a margem por unidade (preço menos custo variável, em valor e em percentagem do preço) e avisa quando o custo excede o preço. Os testes que carregam os editores passam a usar um resolvedor comum para o campo decimal e as bibliotecas de totais e margens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
404 lines
17 KiB
TypeScript
404 lines
17 KiB
TypeScript
import { DecimalInput } from '@/components/decimal-input';
|
|
import { presentDecimal } from '@/lib/decimal-input';
|
|
import {
|
|
startupExpensesTotal,
|
|
withStartupExpenseCategories,
|
|
} from '@/lib/startup-asset-requirements';
|
|
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}
|
|
<DecimalInput
|
|
min="0"
|
|
step="0.01"
|
|
className="min-w-0 rounded border p-2"
|
|
value={value}
|
|
onValueChange={(value) => save(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
|
|
<DecimalInput
|
|
min="1900"
|
|
max="9999"
|
|
step="1"
|
|
className="rounded border p-2"
|
|
value={a.startYear}
|
|
onValueChange={(value) => update({ startYear: 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>
|
|
<button
|
|
type="button"
|
|
className="ml-2 rounded border p-2"
|
|
disabled={
|
|
withStartupExpenseCategories(a.startupExpenses)
|
|
.length === a.startupExpenses.length ||
|
|
withStartupExpenseCategories(a.startupExpenses).length >
|
|
40
|
|
}
|
|
onClick={() =>
|
|
update({
|
|
startupExpenses: withStartupExpenseCategories(
|
|
a.startupExpenses,
|
|
),
|
|
})
|
|
}
|
|
>
|
|
Acrescentar as categorias habituais
|
|
</button>
|
|
<p className="text-sm text-slate-600">
|
|
Categorias habituais: constituição e despesas legais,
|
|
mobiliário, seguros, rendas, computadores e outras despesas
|
|
de início de actividade. Indique zero nas que não se
|
|
aplicam.
|
|
</p>
|
|
{a.startupExpenses.length > 0 && (
|
|
<p className="text-sm font-medium">
|
|
{startupExpensesTotal(a.startupExpenses) !== null
|
|
? `Total das despesas de arranque: ${presentDecimal(
|
|
startupExpensesTotal(a.startupExpenses)!,
|
|
)} ${plan.currency}`
|
|
: 'Total das despesas de arranque por determinar: indique o montante de cada despesa (zero quando não se aplica).'}
|
|
</p>
|
|
)}
|
|
</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>
|
|
);
|
|
}
|