Resumo ({currency})
diff --git a/resources/js/components/startup-asset-requirements.tsx b/resources/js/components/startup-asset-requirements.tsx
index 1de8bc49..8cb96a36 100644
--- a/resources/js/components/startup-asset-requirements.tsx
+++ b/resources/js/components/startup-asset-requirements.tsx
@@ -8,9 +8,11 @@ import { newReportAssumptions } from '@/lib/integral-financial-report';
export function StartupAssetRequirements({
plan,
onChange,
+ showError = true,
}: {
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
+ showError?: boolean;
}) {
const a =
plan.reportAssumptions ?? newReportAssumptions(plan.periods ?? 12);
@@ -166,7 +168,7 @@ export function StartupAssetRequirements({
não se presumem vendas de activos excedentários. A
depreciação mantém a base e a vida útil declaradas.
- {error &&
{error}
}
+ {showError && error &&
{error}
}
{budget && (
<>
diff --git a/resources/js/lib/business-financial-plan.ts b/resources/js/lib/business-financial-plan.ts
index 81e2a989..f5a35897 100644
--- a/resources/js/lib/business-financial-plan.ts
+++ b/resources/js/lib/business-financial-plan.ts
@@ -1837,10 +1837,38 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
entry.paymentLagMonths! < 0 ||
entry.paymentLagMonths! > 12)),
)
- )
+ ) {
+ // Diagnose only an already-rejected schedule; preserve every validation
+ // condition above and all payment calculations below.
+ if (useSupplierPaymentTerms && Array.isArray(schedule)) {
+ const overflowMonth = schedule.findIndex((entry) => {
+ if (!entry || !Array.isArray(entry.paymentInstallments))
+ return false;
+ try {
+ return (
+ entry.paymentInstallments.reduce(
+ (sum, part) =>
+ sum +
+ percentMicro(
+ part.percent,
+ 'Percentagem da parcela',
+ ),
+ 0n,
+ ) > 100_000_000n
+ );
+ } catch {
+ return false;
+ }
+ });
+ if (overflowMonth >= 0)
+ throw new Error(
+ `${product.label} — encomenda do mês ${overflowMonth + 1}: a soma das percentagens em «Parcelas ao fornecedor» excede 100%. Corrija os campos «Percentagem» desta encomenda; o plano não pode ser calculado com esta distribuição.`,
+ );
+ }
throw new Error(
`${product.label}: declare encomendas e prazos de entrega para todos os ${periods} meses.`,
);
+ }
return {
opening,
orders: schedule.slice(0, periods).map((entry, month) => ({
diff --git a/resources/js/lib/financial-issue-presentation.ts b/resources/js/lib/financial-issue-presentation.ts
index bb5ff7f6..4bc3d431 100644
--- a/resources/js/lib/financial-issue-presentation.ts
+++ b/resources/js/lib/financial-issue-presentation.ts
@@ -5,6 +5,20 @@ import {
type InvestmentReportTable,
} from './integral-financial-report.ts';
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
+import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
+
+/** The local startup editor owns this error when report tables are unavailable. */
+export function startupErrorMessage(plan: BusinessFinancialPlanInput): string {
+ if (plan.startupAssetRequirements)
+ try {
+ calculateStartupAssetRequirements(plan);
+ } catch (cause) {
+ return cause instanceof Error
+ ? cause.message
+ : 'Confira os dados de arranque.';
+ }
+ return '';
+}
/** Do not hide a forecast error when the report editor itself cannot show the tables. */
export function forecastErrorShownInReport(
diff --git a/resources/js/lib/integral-financial-report.ts b/resources/js/lib/integral-financial-report.ts
index 7c71c524..cd47d036 100644
--- a/resources/js/lib/integral-financial-report.ts
+++ b/resources/js/lib/integral-financial-report.ts
@@ -537,9 +537,13 @@ export function buildIntegralFinancialTables(
table('balance').issues.push(
`Mês ${i + 1}: existências insuficientes para as vendas declaradas.`,
);
- if (depreciation > fixed || principal > loans)
+ if (depreciation > fixed)
table('balance').issues.push(
- `Mês ${i + 1}: depreciação superior aos activos ou reembolso superior à dívida; confira os dados.`,
+ `Balanço Projectado — mês ${i + 1}: a depreciação acumulada excede os activos fixos disponíveis. Confira «Base depreciável contabilística» e «Vida útil (meses)» face a «Aquisição de activos» e «Activos fixos anteriores (valor líquido)»; corrija os pressupostos inconsistentes.`,
+ );
+ if (principal > loans)
+ table('balance').issues.push(
+ `Balanço Projectado — mês ${i + 1}: o capital reembolsado acumulado excede a dívida declarada. Confira «Reembolso de capital» face a «Empréstimo recebido» e «Suprimentos»; corrija os pressupostos inconsistentes.`,
);
const assets =
cash +
diff --git a/tests/frontend/business-financial-plan.test.mjs b/tests/frontend/business-financial-plan.test.mjs
index d075fae7..cda2fd41 100644
--- a/tests/frontend/business-financial-plan.test.mjs
+++ b/tests/frontend/business-financial-plan.test.mjs
@@ -1684,7 +1684,7 @@ void test('supplier order installments reconcile exact cents, cash dates and una
];
assert.throws(
() => forecastBusinessPlan(malformedPlan),
- /declare encomendas/,
+ /soma das percentagens.*excede 100%/,
);
const snapshot = JSON.parse(serializeBusinessPlanSnapshot(plan));
snapshot.plan.products[0].productInventoryPurchasesByPeriod[0].paymentInstallments[1].lagMonths = 13;
diff --git a/tests/frontend/v12-diagnostics.test.mjs b/tests/frontend/v12-diagnostics.test.mjs
new file mode 100644
index 00000000..72449d84
--- /dev/null
+++ b/tests/frontend/v12-diagnostics.test.mjs
@@ -0,0 +1,204 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import { compileFunction } from 'node:vm';
+import ts from 'typescript';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import * as business from '../../resources/js/lib/business-financial-plan.ts';
+import * as integral from '../../resources/js/lib/integral-financial-report.ts';
+import * as startup from '../../resources/js/lib/startup-asset-requirements.ts';
+import * as presentation from '../../resources/js/lib/financial-issue-presentation.ts';
+import * as annual from '../../resources/js/lib/annual-example-report.ts';
+import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
+import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
+
+const require = createRequire(import.meta.url);
+const modules = {
+ '@/lib/business-financial-plan': business,
+ '@/lib/integral-financial-report': integral,
+ '@/lib/startup-asset-requirements': startup,
+ '@/lib/financial-issue-presentation': presentation,
+ '@/lib/annual-example-report': annual,
+ '@/lib/financial-plan-warnings': warnings,
+ './business-plan-warnings': { BusinessPlanWarnings: () => null },
+};
+function component(name) {
+ if (modules[`./${name}`]) return modules[`./${name}`];
+ const code = ts.transpileModule(
+ fs.readFileSync(
+ new URL(
+ `../../resources/js/components/${name}.tsx`,
+ import.meta.url,
+ ),
+ 'utf8',
+ ),
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ jsx: ts.JsxEmit.ReactJSX,
+ },
+ },
+ ).outputText;
+ const module = { exports: {} };
+ compileFunction(code, ['require', 'module', 'exports'])(
+ (id) =>
+ modules[id] ??
+ (id.startsWith('./') ? component(id.slice(2)) : require(id)),
+ module,
+ module.exports,
+ );
+ modules[`./${name}`] = module.exports;
+ return module.exports;
+}
+const { StartupAssetRequirements } = component('startup-asset-requirements');
+const { IntegralFinancialPlan } = component('integral-financial-plan');
+const planWithStartup = () => ({
+ ...financialReportFixture(2),
+ startupAssetRequirements: {
+ cashRequired: '',
+ otherCurrentAssetsRequired: '0',
+ longTermAssetsRequired: '600',
+ priorAssetInvestment: '600',
+ },
+});
+
+test('D1: one startup diagnostic across real local and report components; standalone and unreadable report retain it', () => {
+ const plan = planWithStartup(),
+ error = presentation.startupErrorMessage(plan);
+ const render = () =>
+ renderToStaticMarkup(
+ React.createElement(
+ React.Fragment,
+ null,
+ React.createElement(StartupAssetRequirements, {
+ plan,
+ onChange() {},
+ showError: !presentation.forecastErrorShownInReport(
+ plan,
+ presentation.startupErrorMessage(plan),
+ ),
+ }),
+ React.createElement(IntegralFinancialPlan, {
+ plan,
+ onChange() {},
+ }),
+ ),
+ );
+ assert.ok(error.includes('caixa requerida'));
+ assert.equal(render().split(error).length - 1, 1);
+ assert.equal(
+ renderToStaticMarkup(
+ React.createElement(StartupAssetRequirements, {
+ plan,
+ onChange() {},
+ }),
+ ).split(error).length - 1,
+ 1,
+ );
+ plan.reportAssumptions.startupExpenses = 'invalid';
+ assert.equal(render().split(error).length - 1, 1);
+ plan.reportSource = 'annual_example';
+ assert.equal(presentation.forecastErrorShownInReport(plan, error), false);
+ plan.startupAssetRequirements.cashRequired = '0';
+ plan.reportAssumptions = financialReportFixture(2).reportAssumptions;
+ assert.equal(presentation.startupErrorMessage(plan), '');
+ delete plan.reportSource;
+ plan.reportAssumptions = financialReportFixture(2).reportAssumptions;
+ assert.ok(!render().includes(error));
+});
+
+test('D2: depreciation and principal diagnostics are independent, both retained, and disappear on correction', () => {
+ const plan = financialReportFixture(2);
+ plan.bankLoanProceeds = '100';
+ plan.depreciationLifeMonths = 1;
+ const issues = () =>
+ integral.buildIntegralFinancialTables(plan).flatMap((t) => t.issues);
+ plan.assetDepreciation = '700';
+ assert.equal(
+ issues().filter((x) => x.includes('Base depreciável contabilística'))
+ .length,
+ 2,
+ );
+ assert.ok(!issues().some((x) => x.includes('Reembolso de capital')));
+ plan.assetDepreciation = '600';
+ plan.monthlyPrincipalRepayment = '200';
+ assert.equal(
+ issues().filter((x) => x.includes('Reembolso de capital')).length,
+ 2,
+ );
+ assert.ok(
+ !issues().some((x) => x.includes('Base depreciável contabilística')),
+ );
+ plan.assetDepreciation = '700';
+ assert.equal(issues().length, 4);
+ plan.assetDepreciation = '600';
+ plan.monthlyPrincipalRepayment = '0';
+ assert.deepEqual(issues(), []);
+ const recovered = business.restoreBusinessPlanSnapshot(
+ business.serializeBusinessPlanSnapshot(plan),
+ );
+ assert.deepEqual(
+ business.forecastBusinessPlan(recovered),
+ business.forecastBusinessPlan(plan),
+ );
+});
+
+function supplier() {
+ const plan = financialReportFixture(2);
+ plan.useProductInventorySchedule = true;
+ plan.useSupplierPaymentTerms = true;
+ plan.products[0] = {
+ ...plan.products[0],
+ label: 'Fornecedor sintético V12',
+ monthlyUnits: '0',
+ productInventoryOpening: '0',
+ productInventoryPurchasesByPeriod: [
+ {
+ amount: '200',
+ leadMonths: 0,
+ paymentInstallments: [
+ { lagMonths: 0, percent: '60' },
+ { lagMonths: 1, percent: '40' },
+ ],
+ },
+ { amount: '0', leadMonths: 0, paymentInstallments: [] },
+ ],
+ };
+ return plan;
+}
+test('D3: 110% rejects with product, order month and percentage; 100% restores exact payments and unrelated validation remains', () => {
+ const plan = supplier(),
+ valid = business.forecastBusinessPlan(plan);
+ const parts =
+ plan.products[0].productInventoryPurchasesByPeriod[0]
+ .paymentInstallments;
+ parts[1].percent = '50';
+ assert.throws(
+ () => business.forecastBusinessPlan(plan),
+ /Fornecedor sintético V12 — encomenda do mês 1:.*excede 100%/,
+ );
+ assert.equal(
+ business.restoreBusinessPlanSnapshot(
+ business.serializeBusinessPlanSnapshot(plan),
+ ),
+ null,
+ );
+ parts[1].percent = '40';
+ assert.deepEqual(business.forecastBusinessPlan(plan), valid);
+ assert.deepEqual(
+ business.forecastBusinessPlan(
+ business.restoreBusinessPlanSnapshot(
+ business.serializeBusinessPlanSnapshot(plan),
+ ),
+ ),
+ valid,
+ );
+ plan.products[0].productInventoryPurchasesByPeriod[0].leadMonths = 13;
+ assert.throws(
+ () => business.forecastBusinessPlan(plan),
+ /declare purchases and lead times/,
+ );
+});