Plano de negócio: despesas de arranque por categoria com total e margem por produto ou serviço
tests / ci (push) Waiting to run

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
This commit is contained in:
Claude
2026-12-04 23:55:11 +02:00
committed by nala
parent 2cecb28c36
commit c558960500
15 changed files with 236 additions and 34 deletions
@@ -1,4 +1,9 @@
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,
@@ -212,6 +217,40 @@ export function IntegralFinancialPlan({
>
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
@@ -1,4 +1,6 @@
import { DecimalInput } from '@/components/decimal-input';
import { presentDecimal } from '@/lib/decimal-input';
import { productUnitMargin } from '@/lib/product-margin';
import { WarningLimitsEditor } from './warning-limits-editor';
import { SupplierAdvancesEditor } from '@/components/supplier-advances';
import { PeriodInvestmentsEditor } from '@/components/period-investments';
@@ -87,6 +89,30 @@ const emptyPlan: BusinessFinancialPlanInput = {
periods: 12,
};
/** Price less variable cost of one unit, so each service shows its own margin. */
function ProductMarginNote({
price,
cost,
currency,
}: {
price: string;
cost: string;
currency: string;
}) {
const margin = productUnitMargin(price, cost);
if (!margin) return null;
const negative = margin.amount.startsWith('-');
return (
<p
className={`text-sm ${negative ? 'text-red-800' : 'text-slate-700'}`}
>
{negative
? `O custo variável excede o preço: cada unidade vendida dá um prejuízo de ${presentDecimal(margin.amount.slice(1))} ${currency}. Reveja o preço ou o custo.`
: `Margem por unidade: ${presentDecimal(margin.amount)} ${currency} (${margin.percent.replace('.', ',')}% do preço). Só deduz o custo variável; despesas operacionais e pessoal são cobertas pela soma das margens.`}
</p>
);
}
function MoneyInput({
label,
value,
@@ -1193,6 +1219,11 @@ export function SimulationBusinessPlan({
}
/>
</div>
<ProductMarginNote
price={product.unitPrice}
cost={product.unitVariableCost}
currency={currency}
/>
{plan.useProductInventorySchedule && (
<div className="space-y-2 rounded border p-3">
<MoneyInput
+34
View File
@@ -0,0 +1,34 @@
const cents = (value: string) => {
if (!/^\d+(?:\.\d{1,2})?$/.test(value)) return null;
const [a, b = ''] = value.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
const decimal = (n: bigint) => {
const sign = n < 0n ? '-' : '';
const v = n < 0n ? -n : n;
return `${sign}${v / 100n}.${String(v % 100n).padStart(2, '0')}`;
};
/**
* Gross margin of one unit of a product or service: price less its variable
* cost, and that margin as a share of the price (one decimal). Null until both
* values are valid amounts and the price is above zero.
*/
export function productUnitMargin(
unitPrice: string,
unitVariableCost: string,
): { amount: string; percent: string } | null {
const price = cents(unitPrice.trim());
const cost = cents(unitVariableCost.trim());
if (price === null || cost === null || price === 0n) return null;
const margin = price - cost;
// Tenths of a percent, rounded half away from zero.
const tenths =
(margin * 2000n + (margin < 0n ? -price : price)) / (2n * price);
const sign = tenths < 0n ? '-' : '';
const t = tenths < 0n ? -tenths : tenths;
return {
amount: decimal(margin),
percent: `${sign}${t / 10n}.${t % 10n}`,
};
}
@@ -68,3 +68,42 @@ export function calculateStartupAssetRequirements(
startupExpenses,
};
}
/** Usual start-up expenses of a new company (mapa de erros, ponto 4), offered as a starting list. */
export const startupExpenseCategories = [
'Constituição da empresa e despesas legais',
'Mobiliário',
'Seguros',
'Rendas',
'Computadores e equipamento informático',
'Outras despesas de início de actividade',
] as const;
/** Adds the usual categories that are still missing; existing rows and amounts are kept. */
export function withStartupExpenseCategories(
rows: { label: string; amount: string }[],
): { label: string; amount: string }[] {
const present = new Set(rows.map((row) => row.label.trim().toLowerCase()));
return [
...rows,
...startupExpenseCategories
.filter((label) => !present.has(label.toLowerCase()))
.map((label) => ({ label, amount: '' })),
];
}
/** Total of the start-up expenses, or null while an amount is missing or invalid. */
export function startupExpensesTotal(
rows: { label: string; amount: string }[],
): string | null {
try {
return startupAmount(
rows.reduce(
(sum, row) => sum + money(row.amount, 'o montante'),
0n,
),
);
} catch {
return null;
}
}
@@ -14,7 +14,7 @@ import {
import * as contract from '../../resources/js/lib/simulation-contract.ts';
import * as bridge from '../../resources/js/lib/financial-fiscal-bridge.ts';
import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
import { decimalInputModule } from './helpers/decimal-input.mjs';
import { decimalInputModule, sharedModule } from './helpers/decimal-input.mjs';
// Exercise the real input callbacks and the parent's snapshot echo, including
// effects. No server, database or fiscal rates are used by this regression.
@@ -112,9 +112,8 @@ function editor(initialSnapshot) {
PlanEconomicClassification: () => null,
},
}[name] ??
(name === '@/components/decimal-input'
? decimalInputModule
: require(name)),
sharedModule(name) ??
require(name),
module,
module.exports,
);
@@ -9,7 +9,7 @@ import ts from 'typescript';
import * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
import * as business from '../../resources/js/lib/business-financial-plan.ts';
import * as catalogue from '../../resources/js/lib/catalogue-choice.ts';
import { decimalInputModule } from './helpers/decimal-input.mjs';
import { decimalInputModule, sharedModule } from './helpers/decimal-input.mjs';
const require = createRequire(import.meta.url);
function load(name, mocks) {
const source = fs.readFileSync(
@@ -25,11 +25,7 @@ function load(name, mocks) {
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(key) =>
mocks[key] ??
(key === '@/components/decimal-input'
? decimalInputModule
: require(key)),
(key) => mocks[key] ?? sharedModule(key) ?? require(key),
module,
module.exports,
);
@@ -31,6 +31,7 @@ import {
} from '../../resources/js/lib/project-dossier-report.ts';
import {
decimalInputModule,
sharedModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
@@ -364,9 +365,7 @@ void test('actual editor controls preserve declarations through snapshot reload
(name) =>
name === '@/lib/business-plan-guidance'
? guidance
: name === '@/components/decimal-input'
? decimalInputModule
: require(name),
: (sharedModule(name) ?? require(name)),
module,
module.exports,
);
@@ -8,7 +8,7 @@ import ts from 'typescript';
import * as finance from '../../resources/js/lib/financial-calculators.ts';
import * as contract from '../../resources/js/lib/simulation-contract.ts';
import * as fundingContext from '../../resources/js/lib/planning-finance-context.ts';
import { decimalInputModule } from './helpers/decimal-input.mjs';
import { decimalInputModule, sharedModule } from './helpers/decimal-input.mjs';
const require = createRequire(import.meta.url);
const nodes = tree => Array.isArray(tree) ? tree.flatMap(nodes) : tree && typeof tree === 'object' ? [tree, ...nodes(tree.props?.children)] : [];
const text = tree => Array.isArray(tree) ? tree.map(text).join('') : tree?.props ? text(tree.props.children) : typeof tree === 'string' ? tree : '';
@@ -17,7 +17,7 @@ function harness(snapshot = '') {
const memory=[], deps=[];
const hooks={...React, useState(initial) {const id=cursor++;if(!(id in memory))memory[id]=typeof initial==='function'?initial():initial;return[memory[id],next=>{const value=typeof next==='function'?next(memory[id]):next;if(!Object.is(value,memory[id])){memory[id]=value;dirty=true;}}];},useEffect(effect, next) {const id=cursor++;if(!deps[id]||next.some((value,i)=>!Object.is(value,deps[id][i]))){queue.push(effect);deps[id]=next;}}};
const module={exports:{}};
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:(id==='@/components/decimal-input'?decimalInputModule:require(id)),module,module.exports);
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:(sharedModule(id) ?? require(id)),module,module.exports);
const props={currency:'MZN',focus:'funding',loanRelevant:false,snapshot,sourceFunding:{total:'2000000',secured:''},onSnapshotChange(value){props.snapshot=value;dirty=true;},onCurrencyChange(){},onFundingChange(key,value){props.sourceFunding={...props.sourceFunding,[key]:value};dirty=true;}};
const render=()=>{for(let i=0;i<12;i++){cursor=0;queue=[];dirty=false;tree=module.exports.SimulationFinancialTools(props);for(const effect of queue)effect();if(!dirty)return;}throw new Error('Render did not settle');};
render();
+16
View File
@@ -55,3 +55,19 @@ export function typeNumber(node, value) {
}
node.props.onChange({ target: { value: text } });
}
const sharedLibs = [
'decimal-input',
'product-margin',
'startup-asset-requirements',
];
/**
* Modules every simulator harness can load as they are: the decimal field and
* the small pure libraries the editors use for totals and margins.
*/
export function sharedModule(id) {
if (id === '@/components/decimal-input') return decimalInputModule;
const lib = sharedLibs.find((name) => id === `@/lib/${name}`);
return lib ? require(`../../../resources/js/lib/${lib}.ts`) : undefined;
}
@@ -17,6 +17,7 @@ import {
} from '../../resources/js/lib/business-financial-plan.ts';
import {
decimalInputModule,
sharedModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
@@ -54,9 +55,7 @@ void test('one startup editor retains all rows and persists an edit without dupl
? { BusinessPlanWarnings: () => null }
: name === './startup-asset-requirements'
? { StartupAssetRequirements: () => null }
: name === '@/components/decimal-input'
? decimalInputModule
: require(name),
: (sharedModule(name) ?? require(name)),
module,
module.exports,
);
@@ -7,6 +7,7 @@ import React from 'react';
import ts from 'typescript';
import {
decimalInputModule,
sharedModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
@@ -68,9 +69,7 @@ function harness(file, snapshot = '') {
? finance
: id === '@/lib/investment-operating-assistance'
? operating
: id === '@/components/decimal-input'
? decimalInputModule
: require(id),
: (sharedModule(id) ?? require(id)),
module,
module.exports,
);
@@ -0,0 +1,58 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
startupExpenseCategories,
startupExpensesTotal,
withStartupExpenseCategories,
} from '../../resources/js/lib/startup-asset-requirements.ts';
import { productUnitMargin } from '../../resources/js/lib/product-margin.ts';
test('start-up expenses offer the usual categories without touching what the investor wrote, and show a total (tarefa 22)', () => {
const rows = withStartupExpenseCategories([
{ label: 'Seguros', amount: '12000' },
{ label: 'Licença de hotelaria', amount: '35000.50' },
]);
assert.deepEqual(rows.slice(0, 2), [
{ label: 'Seguros', amount: '12000' },
{ label: 'Licença de hotelaria', amount: '35000.50' },
]);
assert.equal(rows.length, 2 + startupExpenseCategories.length - 1);
assert.equal(
rows.filter((row) => row.label === 'Seguros').length,
1,
'a category already present is not repeated',
);
assert.equal(withStartupExpenseCategories(rows).length, rows.length);
assert.equal(
startupExpensesTotal(rows),
null,
'empty amounts leave the total open',
);
const filled = rows.map((row) =>
row.amount ? row : { ...row, amount: '0' },
);
filled[2].amount = '150000';
assert.equal(startupExpensesTotal(filled), '197000.50');
});
test('each product or service shows its unit margin, and a loss when the cost exceeds the price', () => {
assert.deepEqual(productUnitMargin('1500.50', '900'), {
amount: '600.50',
percent: '40.0',
});
assert.deepEqual(productUnitMargin('3500', '1200'), {
amount: '2300.00',
percent: '65.7',
});
assert.deepEqual(productUnitMargin('100', '150'), {
amount: '-50.00',
percent: '-50.0',
});
assert.equal(productUnitMargin('0', '10'), null);
assert.equal(productUnitMargin('', '10'), null);
assert.equal(
productUnitMargin('25.000', '10'),
null,
'an unconfirmed legacy value shows no margin',
);
});
@@ -32,6 +32,7 @@ import {
import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts';
import {
decimalInputModule,
sharedModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
@@ -218,9 +219,7 @@ void test('F16 real editor adopts only acquisitions on explicit action and can r
? requirements
: name === '@/lib/integral-financial-report'
? { newReportAssumptions }
: name === '@/components/decimal-input'
? decimalInputModule
: require(name),
: (sharedModule(name) ?? require(name)),
module,
module.exports,
);
+2 -4
View File
@@ -14,7 +14,7 @@ import * as annual from '../../resources/js/lib/annual-example-report.ts';
import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
import * as irpcScenario from '../../resources/js/lib/irpc-plan-scenario.ts';
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import { decimalInputModule } from './helpers/decimal-input.mjs';
import { decimalInputModule, sharedModule } from './helpers/decimal-input.mjs';
const require = createRequire(import.meta.url);
const modules = {
@@ -51,9 +51,7 @@ function component(name) {
modules[id] ??
(id.startsWith('./')
? component(id.slice(2))
: id === '@/components/decimal-input'
? decimalInputModule
: require(id)),
: (sharedModule(id) ?? require(id))),
module,
module.exports,
);
+2 -6
View File
@@ -11,7 +11,7 @@ import { complementaryFixture } from './fixtures/complementary-plan.mjs';
import * as business from '../../resources/js/lib/business-financial-plan.ts';
import * as dossier from '../../resources/js/lib/project-dossier.ts';
import * as complementary from '../../resources/js/lib/complementary-report.ts';
import { decimalInputModule } from './helpers/decimal-input.mjs';
import { decimalInputModule, sharedModule } from './helpers/decimal-input.mjs';
test('V12 final: supplier import without product stock identifies the incompatible controls without weakening rejection', () => {
const plan = financialReportFixture(2);
@@ -106,11 +106,7 @@ test('V12 final: actual personnel component receives currency, withholds reconci
},
};
compileFunction(code, ['require', 'module', 'exports'])(
(key) =>
mocks[key] ??
(key === '@/components/decimal-input'
? decimalInputModule
: require(key)),
(key) => mocks[key] ?? sharedModule(key) ?? require(key),
module,
module.exports,
);