feat(finance): validate opt-in day terms without supplier advances
This commit is contained in:
@@ -0,0 +1,364 @@
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
type BusinessFinancialPlanInput,
|
||||
} from '@/lib/business-financial-plan';
|
||||
import {
|
||||
dayTermLabels,
|
||||
type DayTermKind,
|
||||
type DayTermOperation,
|
||||
type DayTerms,
|
||||
} from '@/lib/financial-day-terms';
|
||||
|
||||
const kinds = Object.keys(dayTermLabels) as DayTermKind[];
|
||||
const empty = (): DayTerms => ({
|
||||
sales: false,
|
||||
purchases: false,
|
||||
services: false,
|
||||
operations: [],
|
||||
});
|
||||
|
||||
export function FinancialDayTerms({
|
||||
plan,
|
||||
onChange,
|
||||
}: {
|
||||
plan: BusinessFinancialPlanInput;
|
||||
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||
}) {
|
||||
const config = plan.dayTerms ?? empty();
|
||||
const save = (next: DayTerms) => onChange({ ...plan, dayTerms: next });
|
||||
const update = (index: number, patch: Partial<DayTermOperation>) =>
|
||||
save({
|
||||
...config,
|
||||
operations: config.operations.map((o, i) =>
|
||||
i === index ? { ...o, ...patch } : o,
|
||||
),
|
||||
});
|
||||
let economic: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||
let calculated: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||
try {
|
||||
economic = forecastBusinessPlan({ ...plan, dayTerms: undefined });
|
||||
} catch {
|
||||
/* Existing diagnostics remain in the report. */
|
||||
}
|
||||
try {
|
||||
calculated = forecastBusinessPlan(plan);
|
||||
} catch {
|
||||
/* One existing report diagnostic, no duplicate here. */
|
||||
}
|
||||
const prepare = (kind: DayTermKind) => {
|
||||
if (
|
||||
!economic ||
|
||||
config[kind] ||
|
||||
config.operations.some((o) => o.kind === kind)
|
||||
)
|
||||
return;
|
||||
const operations: DayTermOperation[] = [];
|
||||
for (const row of economic.rows) {
|
||||
const amount =
|
||||
kind === 'sales'
|
||||
? row.revenue
|
||||
: kind === 'purchases'
|
||||
? row.inventoryReceipts
|
||||
: row.operatingExpenses;
|
||||
if (amount === null || Number(amount) === 0) continue;
|
||||
operations.push({
|
||||
kind,
|
||||
month: row.month,
|
||||
amount,
|
||||
originId: `${kind}-${row.month}`,
|
||||
parcelId: '1',
|
||||
recognitionBasis: 'monthly',
|
||||
recognitionDate: '',
|
||||
originBasis: 'recognition',
|
||||
originDate: '',
|
||||
termDays: '',
|
||||
});
|
||||
}
|
||||
save({ ...config, operations: [...config.operations, ...operations] });
|
||||
};
|
||||
return (
|
||||
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
||||
<summary className="font-semibold">
|
||||
Prazos em dias — operações sem adiantamentos
|
||||
</summary>
|
||||
<p>
|
||||
Adesão opcional por agenda. A agenda em dias substitui
|
||||
integralmente a agenda de caixa correspondente, incluindo
|
||||
cobranças mensais e recuperações de vendas do período. Os
|
||||
valores manuais correspondentes ficam guardados, inactivos;
|
||||
outras receitas explicitamente classificadas mantêm-se activas.
|
||||
Os saldos de abertura mantêm as agendas próprias. Para misturar
|
||||
operações datadas e coortes, distribua o total reconhecido entre
|
||||
parcelas sem repetir montantes.
|
||||
</p>
|
||||
<p>
|
||||
Mercadorias: só após recepção reconhecida. Serviços adquiridos:
|
||||
este modo abrange a totalidade das despesas operacionais
|
||||
declaradas; use-o apenas se todas corresponderem a serviços
|
||||
elegíveis. Não inclui salários, impostos, juros, empréstimos ou
|
||||
novos activos. Antecipações e datas insuficientes bloqueiam o
|
||||
cálculo automático, sem conversão para pagamentos normais.
|
||||
</p>
|
||||
<p>
|
||||
Sem data individual, escolha explicitamente «Último dia do mês
|
||||
(aproximação)». O vencimento também será aproximado. A origem
|
||||
dos pagamentos é o evento contratual indicado; não se presume
|
||||
que factura e recepção coincidam. O prazo em dias deste editor é
|
||||
independente do campo histórico usado nos avisos de crédito.
|
||||
</p>
|
||||
<p>
|
||||
Ano inicial:{' '}
|
||||
{plan.reportAssumptions?.startYear ||
|
||||
'preencha o ano no relatório financeiro integral'}
|
||||
. Horizonte: {plan.periods} meses. Os vencimentos posteriores
|
||||
ficam identificados fora do horizonte.
|
||||
</p>
|
||||
{kinds.map((kind) => (
|
||||
<fieldset
|
||||
key={kind}
|
||||
className="min-w-0 space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend className="font-medium">
|
||||
{dayTermLabels[kind]}
|
||||
</legend>
|
||||
<label className="grid gap-1">
|
||||
Modo de {dayTermLabels[kind]}
|
||||
<select
|
||||
className="w-full rounded border p-2"
|
||||
value={config[kind] ? 'days' : 'manual'}
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.value === 'days' &&
|
||||
!window.confirm(
|
||||
`Activar prazos em dias para ${dayTermLabels[kind]}? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
save({
|
||||
...config,
|
||||
[kind]: e.target.value === 'days',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="manual">
|
||||
Agenda anterior/manual preservada
|
||||
</option>
|
||||
<option value="days">
|
||||
Prazos em dias (adesão explícita)
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={
|
||||
!economic ||
|
||||
config[kind] ||
|
||||
config.operations.some((o) => o.kind === kind)
|
||||
}
|
||||
onClick={() => prepare(kind)}
|
||||
>
|
||||
Preparar coortes mensais de {dayTermLabels[kind]}
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Preparar coortes não activa o modo. Revise os valores,
|
||||
indique o prazo de cada parcela e só depois escolha o
|
||||
modo em dias.
|
||||
</p>
|
||||
{config.operations.map((o, index) =>
|
||||
o.kind !== kind ? null : (
|
||||
<div
|
||||
key={index}
|
||||
className="grid min-w-0 gap-2 rounded border p-3 sm:grid-cols-2 lg:grid-cols-3"
|
||||
aria-label={`Parcela ${index + 1} de ${dayTermLabels[kind]}`}
|
||||
>
|
||||
{(
|
||||
[
|
||||
['Origem', 'originId'],
|
||||
['Parcela', 'parcelId'],
|
||||
['Montante', 'amount'],
|
||||
['Prazo (dias)', 'termDays'],
|
||||
] as const
|
||||
).map(([label, key]) => (
|
||||
<label
|
||||
key={key}
|
||||
className="grid min-w-0 gap-1"
|
||||
>
|
||||
{label}
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={o[key]}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<label className="grid gap-1">
|
||||
Mês económico
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type="number"
|
||||
min="1"
|
||||
max={plan.periods}
|
||||
value={o.month}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
month: Number(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Reconhecimento
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={o.recognitionBasis}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
recognitionBasis: e.target
|
||||
.value as DayTermOperation['recognitionBasis'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Data por confirmar (excluída)
|
||||
</option>
|
||||
<option value="monthly">
|
||||
Último dia do mês (aproximação)
|
||||
</option>
|
||||
<option value="date">
|
||||
Data individual
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{o.recognitionBasis === 'date' && (
|
||||
<label className="grid gap-1">
|
||||
Data de reconhecimento
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type="date"
|
||||
value={o.recognitionDate}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
recognitionDate:
|
||||
e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label className="grid gap-1">
|
||||
Origem do prazo
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
value={o.originBasis}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
originBasis: e.target
|
||||
.value as DayTermOperation['originBasis'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Evento por confirmar (excluído)
|
||||
</option>
|
||||
<option value="recognition">
|
||||
Na data do reconhecimento
|
||||
</option>
|
||||
<option value="date">
|
||||
Data do evento contratual
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{o.originBasis === 'date' && (
|
||||
<label className="grid gap-1">
|
||||
Data de origem do prazo
|
||||
<input
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
type="date"
|
||||
value={o.originDate}
|
||||
onChange={(e) =>
|
||||
update(index, {
|
||||
originDate: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
onClick={() =>
|
||||
save({
|
||||
...config,
|
||||
operations:
|
||||
config.operations.filter(
|
||||
(_, i) => i !== index,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Remover parcela {index + 1}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={config.operations.length >= 240}
|
||||
onClick={() =>
|
||||
save({
|
||||
...config,
|
||||
operations: [
|
||||
...config.operations,
|
||||
{
|
||||
kind,
|
||||
originId: '',
|
||||
parcelId: '',
|
||||
month: 1,
|
||||
amount: '',
|
||||
termDays: '',
|
||||
recognitionBasis: 'unknown',
|
||||
recognitionDate: '',
|
||||
originBasis: 'unknown',
|
||||
originDate: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
Adicionar parcela de {dayTermLabels[kind]}
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
{calculated?.dayTermEvents && (
|
||||
<section aria-label="Vencimentos em dias" className="space-y-2">
|
||||
<h4 className="font-semibold">Vencimentos previstos</h4>
|
||||
{calculated.dayTermEvents.map((e) => (
|
||||
<p
|
||||
key={JSON.stringify([
|
||||
e.kind,
|
||||
e.originId,
|
||||
e.parcelId,
|
||||
])}
|
||||
>
|
||||
{dayTermLabels[e.kind]} — {e.originId}/{e.parcelId}:
|
||||
reconhecimento {e.recognition}; origem {e.origin};
|
||||
vencimento {e.due}; {e.amount} {plan.currency}.{' '}
|
||||
{e.approximate
|
||||
? 'Aproximação mensal explícita.'
|
||||
: 'Datas individuais.'}{' '}
|
||||
{e.outsideHorizon
|
||||
? 'Fora do horizonte; não incluído na caixa do plano.'
|
||||
: `Caixa no mês ${e.dueMonth}.`}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
|
||||
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
|
||||
import { PlanEconomicClassification } from '@/components/plan-economic-classification';
|
||||
import { FinancialPlanDetails } from '@/components/financial-plan-details';
|
||||
import { FinancialDayTerms } from '@/components/financial-day-terms';
|
||||
import { StartupAssetRequirements } from '@/components/startup-asset-requirements';
|
||||
import {
|
||||
forecastErrorShownInReport,
|
||||
@@ -948,6 +949,7 @@ export function SimulationBusinessPlan({
|
||||
)}
|
||||
<PlanEconomicClassification plan={plan} onChange={savePlan} />
|
||||
<FinancialPlanDetails plan={plan} onChange={savePlan} />
|
||||
<FinancialDayTerms plan={plan} onChange={savePlan} />
|
||||
<StartupAssetRequirements
|
||||
plan={plan}
|
||||
onChange={savePlan}
|
||||
|
||||
Reference in New Issue
Block a user