feat(qa): integrate financial example, growth, dividends and detailed declarations
This commit is contained in:
@@ -117,6 +117,20 @@ export type BusinessFinancialPlanInput = {
|
||||
annualExampleSnapshot?: string;
|
||||
currency: string;
|
||||
annualGrowthPercent?: string;
|
||||
/** Explicit opt-in; saved forecasts without this choice retain their values. */
|
||||
applyAnnualGrowth?: boolean;
|
||||
dividendsByPeriod?: string[];
|
||||
operatingExpenseLines?: {
|
||||
label: string;
|
||||
monthlyAmount: string;
|
||||
amountsByPeriod?: string[];
|
||||
}[];
|
||||
fundingBreakdown?: {
|
||||
ownerCapital: string;
|
||||
investorCapital: string;
|
||||
additionalCapital: string;
|
||||
};
|
||||
reportSource?: 'investor' | 'annual_example';
|
||||
presentationCurrency?: string;
|
||||
fxRate?: string;
|
||||
fxDate?: string;
|
||||
@@ -180,7 +194,18 @@ export function serializeBusinessPlanSnapshot(
|
||||
plan: BusinessFinancialPlanInput,
|
||||
): string {
|
||||
const snapshot = JSON.stringify({
|
||||
version: 17,
|
||||
version: [
|
||||
'applyAnnualGrowth',
|
||||
'dividendsByPeriod',
|
||||
'operatingExpenseLines',
|
||||
'fundingBreakdown',
|
||||
'reportSource',
|
||||
].some(
|
||||
(key) =>
|
||||
plan[key as keyof BusinessFinancialPlanInput] !== undefined,
|
||||
)
|
||||
? 18
|
||||
: 17,
|
||||
plan: {
|
||||
...plan,
|
||||
...(plan.useSupplierPaymentTerms === true
|
||||
@@ -262,12 +287,64 @@ export function restoreBusinessPlanSnapshot(
|
||||
decoded.version !== 14 &&
|
||||
decoded.version !== 15 &&
|
||||
decoded.version !== 16 &&
|
||||
decoded.version !== 17) ||
|
||||
decoded.version !== 17 &&
|
||||
decoded.version !== 18) ||
|
||||
!decoded.plan ||
|
||||
typeof decoded.plan !== 'object'
|
||||
)
|
||||
return null;
|
||||
const plan = decoded.plan as Record<string, unknown>;
|
||||
if (
|
||||
decoded.version < 18 &&
|
||||
[
|
||||
'applyAnnualGrowth',
|
||||
'dividendsByPeriod',
|
||||
'operatingExpenseLines',
|
||||
'fundingBreakdown',
|
||||
'reportSource',
|
||||
].some((key) => plan[key] !== undefined)
|
||||
)
|
||||
return null;
|
||||
const shortText = (v: unknown) =>
|
||||
typeof v === 'string' && v.length <= 160;
|
||||
const amounts = (v: unknown) =>
|
||||
Array.isArray(v) && v.length <= 60 && v.every(shortText);
|
||||
if (
|
||||
(plan.applyAnnualGrowth !== undefined &&
|
||||
typeof plan.applyAnnualGrowth !== 'boolean') ||
|
||||
(plan.reportSource !== undefined &&
|
||||
(typeof plan.reportSource !== 'string' ||
|
||||
!['investor', 'annual_example'].includes(
|
||||
plan.reportSource,
|
||||
))) ||
|
||||
(plan.dividendsByPeriod !== undefined &&
|
||||
!amounts(plan.dividendsByPeriod))
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
plan.operatingExpenseLines !== undefined &&
|
||||
(!Array.isArray(plan.operatingExpenseLines) ||
|
||||
plan.operatingExpenseLines.length > 40 ||
|
||||
plan.operatingExpenseLines.some(
|
||||
(r: Record<string, unknown>) =>
|
||||
!r ||
|
||||
!shortText(r.label) ||
|
||||
!shortText(r.monthlyAmount) ||
|
||||
(r.amountsByPeriod !== undefined &&
|
||||
!amounts(r.amountsByPeriod)),
|
||||
))
|
||||
)
|
||||
return null;
|
||||
if (plan.fundingBreakdown !== undefined) {
|
||||
const f = plan.fundingBreakdown as Record<string, unknown>;
|
||||
if (
|
||||
!f ||
|
||||
!['ownerCapital', 'investorCapital', 'additionalCapital'].every(
|
||||
(k) => shortText(f[k]),
|
||||
)
|
||||
)
|
||||
return null;
|
||||
}
|
||||
// A blank percentage is an unfinished draft, not a zero assumption.
|
||||
// Editable recovery also retains invalid percentages for correction.
|
||||
// The zero below is only an upper-bound validation accumulator, never
|
||||
@@ -468,7 +545,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
if (scheduledRate > 100_000_000n) return null;
|
||||
}
|
||||
if (
|
||||
decoded.version === 17 &&
|
||||
decoded.version >= 17 &&
|
||||
!Array.isArray(plan.openingPayablesInstallments)
|
||||
)
|
||||
return null;
|
||||
@@ -476,7 +553,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
plan.openingPayablesInstallments !== undefined &&
|
||||
(!Array.isArray(plan.openingPayablesInstallments) ||
|
||||
plan.openingPayablesInstallments.length > 60 ||
|
||||
(decoded.version !== 17 &&
|
||||
(decoded.version < 17 &&
|
||||
plan.openingPayablesInstallments.length > 0) ||
|
||||
plan.openingPayablesInstallments.some(
|
||||
(entry) =>
|
||||
@@ -871,7 +948,7 @@ export function monthlyProjectedSales(
|
||||
)
|
||||
return null;
|
||||
total += multiplyQuantity(
|
||||
quantity(units),
|
||||
projectedUnits(input, product, month),
|
||||
cents(price, `Preço de ${product.label}`),
|
||||
);
|
||||
}
|
||||
@@ -879,6 +956,30 @@ export function monthlyProjectedSales(
|
||||
});
|
||||
}
|
||||
|
||||
/** Grow quantities only when no monthly quantity was explicitly declared. Prices and unit costs remain declared inputs. */
|
||||
function projectedUnits(
|
||||
input: BusinessFinancialPlanInput,
|
||||
product: ProductLine,
|
||||
month: number,
|
||||
): bigint {
|
||||
const explicit = product.monthlyUnitsByPeriod?.[month];
|
||||
if (explicit !== undefined) return quantity(explicit);
|
||||
let value = quantity(product.monthlyUnits);
|
||||
if (!input.applyAnnualGrowth) return value;
|
||||
const rate = percentMicro(
|
||||
input.annualGrowthPercent ?? '',
|
||||
'Crescimento anual',
|
||||
);
|
||||
if (rate < 0n) throw new Error('Este valor não pode ser negativo.');
|
||||
// percentMicro uses millionths of a percentage point.
|
||||
const denominator = percentMicro('100', 'Crescimento anual');
|
||||
const years = Math.floor(month / 12);
|
||||
const numerator = (denominator + rate) ** BigInt(years);
|
||||
const divisor = denominator ** BigInt(years);
|
||||
value = (value * numerator + divisor / 2n) / divisor;
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Existing purchase orders are planning references, never a proxy for deductible VAT or invoice dates. */
|
||||
export function monthlyProjectedPurchaseOrders(
|
||||
input: BusinessFinancialPlanInput,
|
||||
@@ -1186,19 +1287,37 @@ function applyScenario(
|
||||
),
|
||||
}))
|
||||
: base.inventoryPurchaseSchedule,
|
||||
monthlyOperatingExpenses: moneyChange(
|
||||
base.monthlyOperatingExpenses,
|
||||
adjustment.operatingCostsPercent,
|
||||
'Despesas operacionais',
|
||||
),
|
||||
monthlyOperatingExpensesByPeriod:
|
||||
base.monthlyOperatingExpensesByPeriod?.map((amount, month) =>
|
||||
monthlyOperatingExpenses: base.operatingExpenseLines
|
||||
? base.monthlyOperatingExpenses
|
||||
: moneyChange(
|
||||
base.monthlyOperatingExpenses,
|
||||
adjustment.operatingCostsPercent,
|
||||
'Despesas operacionais',
|
||||
),
|
||||
operatingExpenseLines: base.operatingExpenseLines?.map((line) => ({
|
||||
...line,
|
||||
monthlyAmount: moneyChange(
|
||||
line.monthlyAmount,
|
||||
adjustment.operatingCostsPercent,
|
||||
line.label,
|
||||
),
|
||||
amountsByPeriod: line.amountsByPeriod?.map((value) =>
|
||||
moneyChange(
|
||||
amount,
|
||||
value,
|
||||
adjustment.operatingCostsPercent,
|
||||
`Despesas operacionais mes ${month + 1}`,
|
||||
line.label,
|
||||
),
|
||||
),
|
||||
})),
|
||||
monthlyOperatingExpensesByPeriod: base.operatingExpenseLines
|
||||
? base.monthlyOperatingExpensesByPeriod
|
||||
: base.monthlyOperatingExpensesByPeriod?.map((amount, month) =>
|
||||
moneyChange(
|
||||
amount,
|
||||
adjustment.operatingCostsPercent,
|
||||
`Despesas operacionais mes ${month + 1}`,
|
||||
),
|
||||
),
|
||||
monthlyOperatingPayments: moneyChange(
|
||||
base.monthlyOperatingPayments,
|
||||
adjustment.operatingCostsPercent,
|
||||
@@ -1287,6 +1406,17 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
|
||||
|
||||
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
|
||||
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
if (input.fundingBreakdown) {
|
||||
const f = input.fundingBreakdown;
|
||||
const total =
|
||||
cents(f.ownerCapital, 'Capital do proprietário') +
|
||||
cents(f.investorCapital, 'Capital do investidor') +
|
||||
cents(f.additionalCapital, 'Capital adicional');
|
||||
if (total !== cents(input.equity, 'Capital introduzido'))
|
||||
throw new Error(
|
||||
'O capital discriminado não corresponde ao capital introduzido. Confira os campos de financiamento.',
|
||||
);
|
||||
}
|
||||
if (input.annualGrowthPercent?.trim()) {
|
||||
if (
|
||||
percentMicro(
|
||||
@@ -1591,7 +1721,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
return {
|
||||
units:
|
||||
unitsByPeriod?.map(quantity) ??
|
||||
Array(periods).fill(quantity(product.monthlyUnits)),
|
||||
Array.from({ length: periods }, (_, month) =>
|
||||
projectedUnits(input, product, month),
|
||||
),
|
||||
prices: parseMoneySchedule(
|
||||
priceSchedule,
|
||||
basePrice,
|
||||
@@ -1740,10 +1872,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
.map((entry) => entry.leadMonths)
|
||||
: Array<number>(periods).fill(inventoryPurchaseLeadMonths);
|
||||
const inventoryProjectionEnabled = inventoryPurchasesByPeriod !== null;
|
||||
const operatingExpenses = cents(
|
||||
input.monthlyOperatingExpenses,
|
||||
'Despesas operacionais',
|
||||
);
|
||||
const operatingExpenses = input.operatingExpenseLines
|
||||
? 0n
|
||||
: cents(input.monthlyOperatingExpenses, 'Despesas operacionais');
|
||||
const moneySchedule = (
|
||||
schedule: string[] | undefined,
|
||||
base: bigint,
|
||||
@@ -1820,11 +1951,32 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
variablePayments,
|
||||
'Pagamentos de compras',
|
||||
);
|
||||
const operatingExpenseByPeriod = moneySchedule(
|
||||
input.monthlyOperatingExpensesByPeriod,
|
||||
operatingExpenses,
|
||||
'Despesas operacionais',
|
||||
);
|
||||
let operatingExpenseByPeriod: bigint[] = input.operatingExpenseLines
|
||||
? []
|
||||
: moneySchedule(
|
||||
input.monthlyOperatingExpensesByPeriod,
|
||||
operatingExpenses,
|
||||
'Despesas operacionais',
|
||||
);
|
||||
if (input.operatingExpenseLines) {
|
||||
if (!input.operatingExpenseLines.length)
|
||||
throw new Error('Acrescente pelo menos uma despesa discriminada.');
|
||||
const schedules = input.operatingExpenseLines.map((line) => {
|
||||
if (!line.label.trim())
|
||||
throw new Error('Indique a designação da despesa.');
|
||||
return moneySchedule(
|
||||
line.amountsByPeriod,
|
||||
cents(line.monthlyAmount, line.label),
|
||||
line.label,
|
||||
);
|
||||
});
|
||||
operatingExpenseByPeriod = Array.from({ length: periods }, (_, month) =>
|
||||
schedules.reduce((sum, s) => sum + s[month], 0n),
|
||||
);
|
||||
}
|
||||
const dividends = input.dividendsByPeriod
|
||||
? moneySchedule(input.dividendsByPeriod, 0n, 'Dividendos')
|
||||
: Array<bigint>(periods).fill(0n);
|
||||
const operatingPayments = cents(
|
||||
input.monthlyOperatingPayments,
|
||||
'Pagamentos operacionais',
|
||||
@@ -2192,7 +2344,8 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
periodPayrollPayment +
|
||||
interestPayment +
|
||||
principalRepayment +
|
||||
openingPayablesPayments;
|
||||
openingPayablesPayments +
|
||||
dividends[month - 1];
|
||||
const netCashFlow = allCollections - totalPayments;
|
||||
cash += netCashFlow;
|
||||
totalProfitBeforeTax += profitBeforeTax;
|
||||
@@ -2256,6 +2409,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
payrollPayments: format(periodPayrollPayment),
|
||||
interestPayment: format(interestPayment),
|
||||
principalRepayment: format(principalRepayment),
|
||||
dividends: format(dividends[month - 1]),
|
||||
netCashFlow: format(netCashFlow),
|
||||
closingCash: format(cash),
|
||||
});
|
||||
@@ -3170,6 +3324,7 @@ export function exportBusinessPlanCsv(
|
||||
'Pagamento de compras',
|
||||
'Resultado antes impostos',
|
||||
'Pagamento capital',
|
||||
...(input.dividendsByPeriod ? ['Dividendos distribuídos'] : []),
|
||||
'Fluxo líquido',
|
||||
'Caixa final',
|
||||
],
|
||||
@@ -3203,6 +3358,7 @@ export function exportBusinessPlanCsv(
|
||||
row.variableCostPayments,
|
||||
row.profitBeforeTax,
|
||||
row.principalRepayment,
|
||||
...(input.dividendsByPeriod ? [row.dividends] : []),
|
||||
row.netCashFlow,
|
||||
row.closingCash,
|
||||
]),
|
||||
|
||||
Reference in New Issue
Block a user