feat: apply owner warning decisions and add editable annual planning example
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
businessPlanWarnings,
|
||||
type PlanWarningMetrics,
|
||||
type PlanWarningLimits,
|
||||
} from '@/lib/business-plan-guidance';
|
||||
|
||||
export function BusinessPlanWarnings({
|
||||
metrics,
|
||||
limits,
|
||||
}: {
|
||||
metrics: PlanWarningMetrics;
|
||||
limits?: PlanWarningLimits;
|
||||
}) {
|
||||
const [dismissed, setDismissed] = useState<string[]>([]);
|
||||
const scope = JSON.stringify(metrics);
|
||||
const warnings = businessPlanWarnings(metrics, limits).filter(
|
||||
(warning) => !dismissed.includes(`${scope}:${warning.id}`),
|
||||
);
|
||||
if (!warnings.length) return null;
|
||||
return (
|
||||
<aside
|
||||
aria-label="Avisos de planeamento"
|
||||
className="my-3 space-y-2 rounded border border-amber-400 bg-amber-50 p-3 text-sm text-amber-950"
|
||||
>
|
||||
<h4 className="font-semibold">Avisos — pode continuar</h4>
|
||||
{warnings.map((warning) => (
|
||||
<div
|
||||
key={warning.id}
|
||||
className="flex items-start justify-between gap-3"
|
||||
>
|
||||
<p role="status">
|
||||
<span aria-hidden="true">⚠ </span>
|
||||
{warning.message}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 underline"
|
||||
aria-label={`Dispensar aviso: ${warning.message}`}
|
||||
onClick={() =>
|
||||
setDismissed((previous) => [
|
||||
...previous,
|
||||
`${scope}:${warning.id}`,
|
||||
])
|
||||
}
|
||||
>
|
||||
Dispensar
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -43,7 +43,7 @@ export default function CatalogueChoiceSelect({
|
||||
id: value,
|
||||
name:
|
||||
selected?.label ??
|
||||
`${value} — valor anterior; confirme a selecção`,
|
||||
'Escolha guardada — designação por recuperar',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
calculateAnnualReferencePlan,
|
||||
newAnnualReferencePlan,
|
||||
type AnnualReferencePlan,
|
||||
} from '@/lib/business-plan-guidance';
|
||||
import { businessPlanNumberError } from '@/lib/business-financial-plan';
|
||||
import { BusinessPlanWarnings } from './business-plan-warnings';
|
||||
|
||||
const annualLabels = {
|
||||
sales: 'Vendas previstas',
|
||||
directCosts: 'Custo directo das vendas',
|
||||
payroll: 'Folha de pagamento',
|
||||
payrollCharges: 'Encargos da folha de pagamento',
|
||||
otherOperatingExpenses: 'Outras despesas operacionais',
|
||||
interest: 'Juros',
|
||||
taxes: 'Impostos estimados do exemplo',
|
||||
cashReceived: 'Caixa recebida',
|
||||
cashSpent: 'Caixa gasta',
|
||||
} as const;
|
||||
const openingLabels = {
|
||||
openingCash: 'Caixa necessária',
|
||||
otherCurrentAssets: 'Outros activos correntes',
|
||||
longTermAssets: 'Activos de longo prazo',
|
||||
ownerCapital: 'Capital do proprietário disponível',
|
||||
investorCapital: 'Capital do investidor disponível',
|
||||
loans: 'Empréstimos disponíveis',
|
||||
additionalMoney: 'Dinheiro adicional angariado',
|
||||
} as const;
|
||||
function ExampleNumber({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
const error = businessPlanNumberError(value);
|
||||
return (
|
||||
<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}
|
||||
aria-invalid={!!error}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
{error && (
|
||||
<span role="alert" className="text-red-800">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
export function SimulationAnnualExample({ currency }: { currency: string }) {
|
||||
const [plan, setPlan] = useState<AnnualReferencePlan>(
|
||||
newAnnualReferencePlan,
|
||||
);
|
||||
let result: ReturnType<typeof calculateAnnualReferencePlan> | undefined;
|
||||
let error = '';
|
||||
try {
|
||||
result = calculateAnnualReferencePlan(plan);
|
||||
} catch (cause) {
|
||||
error =
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Reveja os campos do exemplo.';
|
||||
}
|
||||
const amount = (value: string | number | null) =>
|
||||
value === null
|
||||
? 'Por determinar'
|
||||
: Number(value).toLocaleString('pt-MZ', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return (
|
||||
<section
|
||||
aria-label="Cenário anual de exemplo"
|
||||
className="my-4 space-y-4 rounded border border-sky-400 bg-sky-50 p-4"
|
||||
>
|
||||
<h4 className="text-lg font-semibold">
|
||||
Cenário anual de exemplo — editável
|
||||
</h4>
|
||||
<p className="text-sm">
|
||||
Valores fornecidos no plano de referência. Moeda de
|
||||
apresentação: {currency || 'por seleccionar no plano'}. As
|
||||
edições deste ensaio ficam nesta demonstração; os dados do
|
||||
investimento continuam no seu formulário.
|
||||
</p>
|
||||
<p className="rounded border border-amber-400 p-3 text-sm">
|
||||
Linhas mensais por reconciliar. Conservam-se os totais anuais
|
||||
definidos pelo proprietário; não se distribuem valores pelos
|
||||
meses nem se completam linhas em falta. Os impostos são
|
||||
montantes do exemplo, sem activar taxas fiscais.
|
||||
</p>
|
||||
<details open>
|
||||
<summary className="font-semibold">
|
||||
Despesas e activos iniciais
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{plan.startupExpenses.map((row, index) => (
|
||||
<ExampleNumber
|
||||
key={row.label}
|
||||
label={row.label}
|
||||
value={row.amount}
|
||||
onChange={(value) =>
|
||||
setPlan((previous) => ({
|
||||
...previous,
|
||||
startupExpenses:
|
||||
previous.startupExpenses.map(
|
||||
(entry, i) =>
|
||||
i === index
|
||||
? {
|
||||
...entry,
|
||||
amount: value,
|
||||
}
|
||||
: entry,
|
||||
),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{Object.entries(openingLabels).map(([key, label]) => (
|
||||
<ExampleNumber
|
||||
key={key}
|
||||
label={label}
|
||||
value={plan[key as keyof typeof openingLabels]}
|
||||
onChange={(value) =>
|
||||
setPlan((previous) => ({
|
||||
...previous,
|
||||
[key]: value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
{plan.years.map((year, index) => (
|
||||
<details key={year.year}>
|
||||
<summary className="font-semibold">
|
||||
Pressupostos anuais — {year.year}
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Object.entries(annualLabels).map(([key, label]) => (
|
||||
<ExampleNumber
|
||||
key={key}
|
||||
label={label}
|
||||
value={year[key as keyof typeof annualLabels]}
|
||||
onChange={(value) =>
|
||||
setPlan((previous) => ({
|
||||
...previous,
|
||||
years: previous.years.map((entry, i) =>
|
||||
i === index
|
||||
? { ...entry, [key]: value }
|
||||
: entry,
|
||||
),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded border border-red-400 bg-red-50 p-3 text-red-900"
|
||||
>
|
||||
{error} Os valores introduzidos permanecem nos campos.
|
||||
</p>
|
||||
)}
|
||||
{result && (
|
||||
<>
|
||||
<dl className="grid gap-3 sm:grid-cols-2">
|
||||
{[
|
||||
[
|
||||
'Despesas totais de arranque',
|
||||
result.startupExpenses,
|
||||
],
|
||||
['Total de activos iniciais', result.assets],
|
||||
[
|
||||
'Financiamento total requerido',
|
||||
result.requiredFunding,
|
||||
],
|
||||
[
|
||||
'Financiamento disponível',
|
||||
result.availableFunding,
|
||||
],
|
||||
].map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd className="font-semibold">
|
||||
{amount(value)} {currency}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="py-2 text-left font-semibold">
|
||||
Resultados anuais do exemplo{' '}
|
||||
{currency && `(${currency})`}
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Resultado</th>
|
||||
{result.years.map((year) => (
|
||||
<th key={year.year}>{year.year}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(
|
||||
[
|
||||
'sales',
|
||||
'directCosts',
|
||||
'grossMargin',
|
||||
'grossMarginPercent',
|
||||
'operatingExpenses',
|
||||
'operatingProfit',
|
||||
'netProfit',
|
||||
'monthlyFixedCosts',
|
||||
'monthlyBreakEven',
|
||||
'cashFlow',
|
||||
'closingCash',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<tr key={key}>
|
||||
<th className="py-1 font-medium">
|
||||
{
|
||||
{
|
||||
sales: 'Vendas',
|
||||
directCosts:
|
||||
'Custo directo das vendas',
|
||||
grossMargin: 'Margem bruta',
|
||||
grossMarginPercent:
|
||||
'Margem bruta (%)',
|
||||
operatingExpenses:
|
||||
'Despesas operacionais',
|
||||
operatingProfit:
|
||||
'Lucro antes de juros e impostos',
|
||||
netProfit: 'Lucro líquido',
|
||||
monthlyFixedCosts:
|
||||
'Custo fixo mensal estimado',
|
||||
monthlyBreakEven:
|
||||
'Ponto de equilíbrio mensal',
|
||||
cashFlow:
|
||||
'Fluxo líquido de caixa',
|
||||
closingCash:
|
||||
'Saldo de caixa',
|
||||
}[key]
|
||||
}
|
||||
</th>
|
||||
{result.years.map((year) => (
|
||||
<td key={year.year}>
|
||||
{amount(year[key])}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{result.years.map((year, index) => (
|
||||
<div key={year.year}>
|
||||
<h5 className="font-semibold">
|
||||
Avisos — {year.year}
|
||||
</h5>
|
||||
<BusinessPlanWarnings
|
||||
metrics={{
|
||||
currency,
|
||||
fundingGap:
|
||||
index === 0
|
||||
? Number(result.fundingGap)
|
||||
: undefined,
|
||||
netProfit: Number(year.netProfit),
|
||||
sales: Number(year.sales),
|
||||
directCosts: Number(year.directCosts),
|
||||
monthlyBreakEven: year.monthlyBreakEven,
|
||||
monthlyExpenses:
|
||||
Number(year.operatingExpenses) / 12,
|
||||
cash: Number(year.closingCash),
|
||||
growthPercent:
|
||||
year.growthPercent ?? undefined,
|
||||
ownAndInvestorCapital:
|
||||
index === 0
|
||||
? Number(plan.ownerCapital) +
|
||||
Number(plan.investorCapital)
|
||||
: undefined,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-sm">
|
||||
Margem bruta = vendas − custo directo. Lucro líquido =
|
||||
margem bruta − despesas operacionais − juros − impostos.
|
||||
Ponto de equilíbrio = (despesas operacionais ÷ 12) ÷
|
||||
(margem bruta ÷ vendas), sem arredondar os valores
|
||||
intermédios. Caixa final = caixa anterior + recebimentos
|
||||
− pagamentos.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
simulationCurrencyOptions,
|
||||
} from '@/lib/simulation-contract';
|
||||
import { buildFinancialFiscalBridge } from '@/lib/financial-fiscal-bridge';
|
||||
import { BusinessPlanWarnings } from '@/components/business-plan-warnings';
|
||||
import { SimulationAnnualExample } from '@/components/simulation-annual-example';
|
||||
|
||||
const emptyPlan: BusinessFinancialPlanInput = {
|
||||
currency: '',
|
||||
@@ -76,18 +78,21 @@ function MoneyInput({
|
||||
onChange,
|
||||
allowNegative = false,
|
||||
step = '0.01',
|
||||
optional = false,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
allowNegative?: boolean;
|
||||
step?: string;
|
||||
optional?: boolean;
|
||||
}) {
|
||||
const errorId = useId();
|
||||
const [touched, setTouched] = useState(false);
|
||||
const error = touched
|
||||
? businessPlanNumberError(value, { allowNegative })
|
||||
: '';
|
||||
const error =
|
||||
touched && (!optional || value.trim() !== '')
|
||||
? businessPlanNumberError(value, { allowNegative })
|
||||
: '';
|
||||
return (
|
||||
<label className="block text-sm font-medium">
|
||||
{label}
|
||||
@@ -139,6 +144,7 @@ export function SimulationBusinessPlan({
|
||||
);
|
||||
const [workingPlan, setWorkingPlan] =
|
||||
useState<BusinessFinancialPlanInput | null>(null);
|
||||
const [showExample, setShowExample] = useState(false);
|
||||
useEffect(() => setWorkingPlan(null), [snapshot]);
|
||||
if (hasOversizedStoredSnapshot) {
|
||||
return (
|
||||
@@ -914,6 +920,16 @@ export function SimulationBusinessPlan({
|
||||
separados. Não calcula impostos, não converte moedas e não
|
||||
substitui um plano contabilístico validado.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
onClick={() => setShowExample((previous) => !previous)}
|
||||
>
|
||||
{showExample
|
||||
? 'Fechar cenário de exemplo'
|
||||
: 'Carregar cenário anual de exemplo'}
|
||||
</button>
|
||||
{showExample && <SimulationAnnualExample currency={currency} />}
|
||||
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
|
||||
<label className="grid gap-1 text-sm">
|
||||
Importar plano financeiro InvestMoz (.json, até 60 KB)
|
||||
@@ -957,6 +973,17 @@ export function SimulationBusinessPlan({
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<MoneyInput
|
||||
optional
|
||||
label="Crescimento anual pretendido (%)"
|
||||
value={plan.annualGrowthPercent ?? ''}
|
||||
onChange={(value) => update('annualGrowthPercent', value)}
|
||||
/>
|
||||
<p className="text-sm">
|
||||
A meta de crescimento pode exceder 100%, com aviso. É uma
|
||||
hipótese declarada; as agendas de vendas introduzidas mantêm
|
||||
os seus valores.
|
||||
</p>
|
||||
|
||||
<p className="text-sm text-slate-700">
|
||||
O plano financeiro aceita moedas ISO suportadas com duas
|
||||
@@ -2498,24 +2525,29 @@ export function SimulationBusinessPlan({
|
||||
>
|
||||
Exportar plano em CSV
|
||||
</button>
|
||||
<p
|
||||
role={
|
||||
result.fundingStatus === 'balanced'
|
||||
? 'status'
|
||||
: 'alert'
|
||||
}
|
||||
className={
|
||||
result.fundingStatus === 'balanced'
|
||||
? 'rounded bg-emerald-50 p-3 text-sm'
|
||||
: 'rounded bg-amber-50 p-3 text-sm'
|
||||
}
|
||||
>
|
||||
{result.fundingStatus === 'balanced'
|
||||
? 'As fontes de financiamento reconciliam com os usos iniciais.'
|
||||
: result.fundingStatus === 'shortfall'
|
||||
? `Falta financiar ${result.fundingGap} ${currency} dos usos iniciais.`
|
||||
: `As fontes excedem os usos iniciais em ${result.fundingGap.replace('-', '')} ${currency}.`}
|
||||
</p>
|
||||
<BusinessPlanWarnings
|
||||
metrics={{
|
||||
currency,
|
||||
fundingGap: Number(result.fundingGap),
|
||||
growthPercent: plan.annualGrowthPercent?.trim()
|
||||
? Number(plan.annualGrowthPercent)
|
||||
: undefined,
|
||||
}}
|
||||
/>
|
||||
{result.fundingStatus !== 'shortfall' && (
|
||||
<p
|
||||
role="status"
|
||||
className={
|
||||
result.fundingStatus === 'balanced'
|
||||
? 'rounded bg-emerald-50 p-3 text-sm'
|
||||
: 'rounded bg-amber-50 p-3 text-sm'
|
||||
}
|
||||
>
|
||||
{result.fundingStatus === 'balanced'
|
||||
? 'As fontes de financiamento reconciliam com os usos iniciais.'
|
||||
: `As fontes excedem os usos iniciais em ${result.fundingGap.replace('-', '')} ${currency}.`}
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{[
|
||||
['Fundo de maneio líquido', result.workingCapital],
|
||||
|
||||
Reference in New Issue
Block a user