diff --git a/resources/js/components/integral-financial-plan.tsx b/resources/js/components/integral-financial-plan.tsx
index 1cb790fa..f85ff7b1 100644
--- a/resources/js/components/integral-financial-plan.tsx
+++ b/resources/js/components/integral-financial-plan.tsx
@@ -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
+
+ 40
+ }
+ onClick={() =>
+ update({
+ startupExpenses: withStartupExpenseCategories(
+ a.startupExpenses,
+ ),
+ })
+ }
+ >
+ Acrescentar as categorias habituais
+
+
+ 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.
+
+ {a.startupExpenses.length > 0 && (
+
+ {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).'}
+
+ )}
Os saldos anteriores têm de reconciliar entre si. Não inclua os
diff --git a/resources/js/components/simulation-business-plan.tsx b/resources/js/components/simulation-business-plan.tsx
index e5b2e99c..a2256330 100644
--- a/resources/js/components/simulation-business-plan.tsx
+++ b/resources/js/components/simulation-business-plan.tsx
@@ -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 (
+
+ {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.`}
+
+ );
+}
+
function MoneyInput({
label,
value,
@@ -1193,6 +1219,11 @@ export function SimulationBusinessPlan({
}
/>
+
{plan.useProductInventorySchedule && (
{
+ 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}`,
+ };
+}
diff --git a/resources/js/lib/startup-asset-requirements.ts b/resources/js/lib/startup-asset-requirements.ts
index 86c745cb..bce1a681 100644
--- a/resources/js/lib/startup-asset-requirements.ts
+++ b/resources/js/lib/startup-asset-requirements.ts
@@ -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;
+ }
+}
diff --git a/tests/frontend/business-plan-editing.test.mjs b/tests/frontend/business-plan-editing.test.mjs
index cbcc77c0..ca4f93f2 100644
--- a/tests/frontend/business-plan-editing.test.mjs
+++ b/tests/frontend/business-plan-editing.test.mjs
@@ -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,
);
diff --git a/tests/frontend/business-plan-guidance-ui.test.mjs b/tests/frontend/business-plan-guidance-ui.test.mjs
index 54df0dea..7e7e4df6 100644
--- a/tests/frontend/business-plan-guidance-ui.test.mjs
+++ b/tests/frontend/business-plan-guidance-ui.test.mjs
@@ -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,
);
diff --git a/tests/frontend/financial-plan-pending-requirements.test.mjs b/tests/frontend/financial-plan-pending-requirements.test.mjs
index e04b9803..5db8af70 100644
--- a/tests/frontend/financial-plan-pending-requirements.test.mjs
+++ b/tests/frontend/financial-plan-pending-requirements.test.mjs
@@ -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,
);
diff --git a/tests/frontend/financial-tools-source.test.mjs b/tests/frontend/financial-tools-source.test.mjs
index 7cf6f7a3..a0548a46 100644
--- a/tests/frontend/financial-tools-source.test.mjs
+++ b/tests/frontend/financial-tools-source.test.mjs
@@ -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();
diff --git a/tests/frontend/helpers/decimal-input.mjs b/tests/frontend/helpers/decimal-input.mjs
index 4f55ff4e..e7720c95 100644
--- a/tests/frontend/helpers/decimal-input.mjs
+++ b/tests/frontend/helpers/decimal-input.mjs
@@ -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;
+}
diff --git a/tests/frontend/integral-financial-plan-ui.test.mjs b/tests/frontend/integral-financial-plan-ui.test.mjs
index 0412efbd..d2331aa5 100644
--- a/tests/frontend/integral-financial-plan-ui.test.mjs
+++ b/tests/frontend/integral-financial-plan-ui.test.mjs
@@ -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,
);
diff --git a/tests/frontend/investment-assistance-controls.test.mjs b/tests/frontend/investment-assistance-controls.test.mjs
index cd63fb8f..55cfdac8 100644
--- a/tests/frontend/investment-assistance-controls.test.mjs
+++ b/tests/frontend/investment-assistance-controls.test.mjs
@@ -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,
);
diff --git a/tests/frontend/startup-categories-and-margin.test.mjs b/tests/frontend/startup-categories-and-margin.test.mjs
new file mode 100644
index 00000000..631ce7cc
--- /dev/null
+++ b/tests/frontend/startup-categories-and-margin.test.mjs
@@ -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',
+ );
+});
diff --git a/tests/frontend/startup-example-correspondence.test.mjs b/tests/frontend/startup-example-correspondence.test.mjs
index 825304b2..e6ed688f 100644
--- a/tests/frontend/startup-example-correspondence.test.mjs
+++ b/tests/frontend/startup-example-correspondence.test.mjs
@@ -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,
);
diff --git a/tests/frontend/v12-diagnostics.test.mjs b/tests/frontend/v12-diagnostics.test.mjs
index cf853e55..b2485133 100644
--- a/tests/frontend/v12-diagnostics.test.mjs
+++ b/tests/frontend/v12-diagnostics.test.mjs
@@ -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,
);
diff --git a/tests/frontend/v12-final-gaps.test.mjs b/tests/frontend/v12-final-gaps.test.mjs
index 0162b832..bd27d824 100644
--- a/tests/frontend/v12-final-gaps.test.mjs
+++ b/tests/frontend/v12-final-gaps.test.mjs
@@ -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,
);