Plano de negócio como resultado da simulação

O relatório do investidor segue o modelo: resumo executivo (com objectivos,
missão e chaves para o sucesso), startup, mercado, vendas e marcos, pessoal
e plano financeiro, com as tabelas anuais nos capítulos e o detalhe mensal
do primeiro ano em anexo, sem colunas técnicas. Antes de exportar aparece
«Falta preencher» com ligação aos campos.

O cenário fiscal calcula o IRPC de cada ano à taxa geral de 32% sobre o
lucro antes de impostos, em vez de 72 campos mensais. Os rácios passam a
ser calculados a partir do balanço quando o investidor não classifica o
activo e o passivo correntes.

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 21:11:45 +02:00
committed by nala
parent a082c2542a
commit a3f2d2d7ca
14 changed files with 622 additions and 17 deletions
@@ -40,7 +40,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
$economic = [ $economic = [
'preparation_step', 'planning_assumptions_snapshot', 'initial_budget_snapshot', 'fiscal_tools_selection', 'planned_funding', 'requested_funding', 'approved_funding', 'planning_loan', 'preparation_step', 'planning_assumptions_snapshot', 'initial_budget_snapshot', 'fiscal_tools_selection', 'planned_funding', 'requested_funding', 'approved_funding', 'planning_loan',
'context_opportunity', 'context_applicability_snapshot', 'investment_regime', 'context_reuse', 'compatible_fields_snapshot', 'published_iva_base', 'published_iva_base_source', 'published_iva_currency', 'published_iva_date', 'published_iva_scope', 'monthly_iva_settings', 'monthly_iva_snapshot', 'modelo_a_snapshot', 'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'cashflow_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type', 'context_opportunity', 'context_applicability_snapshot', 'investment_regime', 'context_reuse', 'compatible_fields_snapshot', 'published_iva_base', 'published_iva_base_source', 'published_iva_currency', 'published_iva_date', 'published_iva_scope', 'monthly_iva_settings', 'monthly_iva_snapshot', 'modelo_a_snapshot', 'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'cashflow_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type',
'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'web_plan', 'management_summary', 'location_rationale', 'project_risk_responses_snapshot', 'project_questionnaire_version', 'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'web_plan', 'management_summary', 'plan_objectives', 'plan_mission', 'plan_success_keys', 'location_rationale', 'project_risk_responses_snapshot', 'project_questionnaire_version',
'customer_validation_status', 'cost_estimate_status', 'location_assessment_status', 'funding_status', 'receivables_timing_status', 'customer_validation_status', 'cost_estimate_status', 'location_assessment_status', 'funding_status', 'receivables_timing_status',
'project_type_other', 'sector_id', 'activity_id', 'products_services', 'maturity_stage', 'expected_start_date', 'project_type_other', 'sector_id', 'activity_id', 'products_services', 'maturity_stage', 'expected_start_date',
'project_duration_years', 'existing_project_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'project_duration_years', 'existing_project_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id',
@@ -176,7 +176,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000']; $rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000'];
} }
$rules['economic_snapshot.selection_labels'] = ['nullable', 'array']; $rules['economic_snapshot.selection_labels'] = ['nullable', 'array'];
foreach (['project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'opportunity_description', 'products_services', 'community_benefits', 'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'web_plan', 'management_summary', 'location_rationale'] as $field) { foreach (['project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'opportunity_description', 'products_services', 'community_benefits', 'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'web_plan', 'management_summary', 'plan_objectives', 'plan_mission', 'plan_success_keys', 'location_rationale'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000']; $rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000'];
} }
$rules['personal_snapshot.email'] = ['nullable', 'email:rfc', 'max:254']; $rules['personal_snapshot.email'] = ['nullable', 'email:rfc', 'max:254'];
@@ -8,6 +8,12 @@ import { InvestmentReportTables } from './investment-report-tables';
import { BusinessPlanWarnings } from './business-plan-warnings'; import { BusinessPlanWarnings } from './business-plan-warnings';
import { financialPlanWarnings } from '@/lib/financial-plan-warnings'; import { financialPlanWarnings } from '@/lib/financial-plan-warnings';
import { StartupAssetRequirements } from './startup-asset-requirements'; import { StartupAssetRequirements } from './startup-asset-requirements';
import {
irpcPlanScenarios,
irpcScenarioSchedule,
type IrpcPlanScenario,
} from '@/lib/irpc-plan-scenario';
import { useState } from 'react';
export function IntegralFinancialPlan({ export function IntegralFinancialPlan({
plan, plan,
@@ -220,6 +226,16 @@ export function IntegralFinancialPlan({
confirmar a inexistência, registe uma linha «Sem despesas de confirmar a inexistência, registe uma linha «Sem despesas de
arranque» com zero. arranque» com zero.
</p> </p>
<TaxScenario
plan={plan}
onApply={(result) =>
update({
taxExpenseByMonth: result.expense,
taxPaymentByMonth: result.payment,
taxSource: result.source,
})
}
/>
<label className="my-2 grid gap-1 text-sm"> <label className="my-2 grid gap-1 text-sm">
Fonte ou pressuposto dos impostos estimados Fonte ou pressuposto dos impostos estimados
<input <input
@@ -234,8 +250,8 @@ export function IntegralFinancialPlan({
<details> <details>
<summary>Impostos por mês — estimativa e tesouraria</summary> <summary>Impostos por mês — estimativa e tesouraria</summary>
<p className="text-sm"> <p className="text-sm">
Não activa taxas fiscais nem certifica pagamentos. Preencha Preenchidos pelo cenário fiscal ou por si. Não certifica
cada mês, incluindo zero declarado. pagamentos; um mês sem imposto fica com zero.
</p> </p>
{Array.from({ length: plan.periods ?? 12 }, (_, index) => ( {Array.from({ length: plan.periods ?? 12 }, (_, index) => (
<div className="my-2 grid gap-2 sm:grid-cols-2" key={index}> <div className="my-2 grid gap-2 sm:grid-cols-2" key={index}>
@@ -284,3 +300,73 @@ export function IntegralFinancialPlan({
</details> </details>
); );
} }
/** Own component so its state never runs when the plan editor is used as a plain function. */
function TaxScenario({
plan,
onApply,
}: {
plan: BusinessFinancialPlanInput;
onApply: (result: ReturnType<typeof irpcScenarioSchedule>) => void;
}) {
const [scenario, setScenario] = useState<IrpcPlanScenario>('general');
const [scenarioError, setScenarioError] = useState('');
return (
<section
aria-label="Cenário fiscal"
className="my-3 space-y-2 rounded border p-3"
>
<h4 className="font-semibold">Cenário fiscal</h4>
<p className="text-sm">
Escolha o cenário e o simulador calcula o IRPC de cada ano a
partir do lucro antes de impostos, para ver o lucro líquido
e a viabilidade. Pode depois ajustar mês a mês.
</p>
<label className="grid gap-1 text-sm">
Cenário
<select
className="rounded border p-2"
value={scenario}
onChange={(event) =>
setScenario(event.target.value as IrpcPlanScenario)
}
>
{Object.entries(irpcPlanScenarios).map(
([key, option]) => (
<option key={key} value={key}>
{option.label}
</option>
),
)}
</select>
</label>
<button
type="button"
className="rounded bg-emerald-800 px-3 py-2 text-white"
onClick={() => {
try {
const result = irpcScenarioSchedule(
plan,
scenario,
);
setScenarioError('');
onApply(result);
} catch (cause) {
setScenarioError(
cause instanceof Error
? `Complete primeiro o plano: ${cause.message}`
: 'Complete primeiro as vendas e os custos do plano.',
);
}
}}
>
Calcular os impostos com este cenário
</button>
{scenarioError && (
<p role="alert" className="text-sm text-red-800">
{scenarioError}
</p>
)}
</section>
);
}
@@ -9,6 +9,7 @@ import {
createProjectDossierPrintHtml, createProjectDossierPrintHtml,
createProjectDossierReport, createProjectDossierReport,
createIntegralFinancialReport, createIntegralFinancialReport,
createInvestorDecisionReport,
dossierReportSections, dossierReportSections,
generateProjectDossierDocx, generateProjectDossierDocx,
generateProjectDossierPackage, generateProjectDossierPackage,
@@ -25,6 +26,8 @@ type Props = {
version: string; version: string;
references?: DossierReference[]; references?: DossierReference[];
currentCalculation?: DossierCurrentCalculation | null; currentCalculation?: DossierCurrentCalculation | null;
/** Take the investor to the step and field that still needs data. */
onCorrect?: (field: string) => void;
}; };
const defaultSections = new Set<DossierReportSectionId>( const defaultSections = new Set<DossierReportSectionId>(
@@ -58,9 +61,10 @@ export function ProjectDossierExport({
version, version,
references = [], references = [],
currentCalculation = null, currentCalculation = null,
onCorrect,
}: Props) { }: Props) {
const [selectedSections, setSelectedSections] = useState(defaultSections); const [selectedSections, setSelectedSections] = useState(defaultSections);
const [reportMode, setReportMode] = useState('dossier'); const [reportMode, setReportMode] = useState('investor');
const [attachments, setAttachments] = useState<DossierAttachment[]>([]); const [attachments, setAttachments] = useState<DossierAttachment[]>([]);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [busy, setBusy] = useState(''); const [busy, setBusy] = useState('');
@@ -132,7 +136,13 @@ export function ProjectDossierExport({
const report = useMemo( const report = useMemo(
() => () =>
reportMode === 'financial' reportMode === 'investor'
? createInvestorDecisionReport(draft, {
version,
references,
currentCalculation,
})
: reportMode === 'financial'
? createIntegralFinancialReport(draft, { ? createIntegralFinancialReport(draft, {
version, version,
references, references,
@@ -153,6 +163,11 @@ export function ProjectDossierExport({
selectedSectionSet, selectedSectionSet,
], ],
); );
const missing =
reportMode === 'investor'
? (report as ReturnType<typeof createInvestorDecisionReport>)
.missing
: [];
function model() { function model() {
return report; return report;
} }
@@ -295,7 +310,7 @@ export function ProjectDossierExport({
<fieldset <fieldset
className="space-y-2" className="space-y-2"
disabled={reportMode === 'financial'} disabled={reportMode !== 'dossier'}
> >
<legend className="font-medium"> <legend className="font-medium">
Escolha as secções a incluir Escolha as secções a incluir
@@ -432,6 +447,9 @@ export function ProjectDossierExport({
onChange={(e) => setReportMode(e.target.value)} onChange={(e) => setReportMode(e.target.value)}
disabled={Boolean(busy)} disabled={Boolean(busy)}
> >
<option value="investor">
Plano de negócio — relatório do investidor
</option>
<option value="dossier"> <option value="dossier">
Dossier e contexto — secções seleccionadas Dossier e contexto — secções seleccionadas
</option> </option>
@@ -440,6 +458,36 @@ export function ProjectDossierExport({
</option> </option>
</select> </select>
</label> </label>
{missing.length > 0 && (
<section
aria-label="Falta preencher"
className="rounded border border-amber-300 bg-amber-50 p-3 text-sm"
>
<h4 className="font-semibold">Falta preencher</h4>
<p>
Pode exportar o rascunho, mas o plano só fica completo
para partilhar com bancos ou parceiros depois de
preencher:
</p>
<ul className="list-disc space-y-1 pl-5">
{missing.map((gap, index) => (
<li key={index}>
{gap.field && onCorrect ? (
<button
type="button"
className="text-left underline"
onClick={() => onCorrect(gap.field!)}
>
{gap.message}
</button>
) : (
gap.message
)}
</li>
))}
</ul>
</section>
)}
<details className="rounded border p-3"> <details className="rounded border p-3">
<summary>Conferir o relatório antes de exportar</summary> <summary>Conferir o relatório antes de exportar</summary>
<DossierReportPreview report={report} /> <DossierReportPreview report={report} />
+37 -3
View File
@@ -275,11 +275,30 @@ const fieldGuidance: Record<
'Pode começar por descrever o que pretende produzir ou prestar.', 'Pode começar por descrever o que pretende produzir ou prestar.',
}, },
project_summary: { project_summary: {
why: 'Reúne os objectivos, a missão e as chaves para o sucesso que pretende comunicar aos parceiros.', why: 'Abre o plano de negócio: em poucas linhas, o que é o negócio e o que pretende alcançar.',
example: example:
'Exemplo apenas de organização do texto: Objectivos. Missão. Chaves para o sucesso.', 'Exemplo ilustrativo: “Hotel de 20 quartos em Vilankulo para turismo de praia e negócios.”',
clarify: clarify:
'Descreva as suas escolhas em texto livre. Não precisa de adoptar a estrutura ou os valores do exemplo TEMPO.', 'Escreva em texto corrido; os objectivos, a missão e as chaves para o sucesso têm campos próprios a seguir.',
},
plan_objectives: {
why: 'Os objectivos mostram a bancos e parceiros o que o negócio pretende atingir e como medir o progresso.',
example:
'Exemplo ilustrativo: lucro líquido de pelo menos 30% no primeiro ano; crescer de 24 para 35 clientes no ano seguinte.',
clarify:
'Prefira objectivos com números e prazos; pode rever depois de preencher o plano financeiro.',
},
plan_mission: {
why: 'A missão resume para quem o negócio existe e como pretende servir os clientes.',
example:
'Exemplo ilustrativo: servir os clientes com a lealdade de um parceiro de negócio, com resposta rápida e de qualidade.',
clarify: 'Uma ou duas frases chegam.',
},
plan_success_keys: {
why: 'As chaves para o sucesso são os poucos factores de que o negócio depende para resultar.',
example:
'Exemplo ilustrativo: qualidade do serviço, boas relações com os clientes, equipa com experiência complementar.',
clarify: 'Indique três a cinco factores, separados por vírgulas ou por linhas.',
}, },
project_problem: { project_problem: {
why: 'Uma necessidade concreta ajuda a explicar a razão do projecto.', why: 'Uma necessidade concreta ajuda a explicar a razão do projecto.',
@@ -4325,6 +4344,21 @@ export function SimulationForm() {
) && ) &&
draft.purpose === 'simulate_only' && ( draft.purpose === 'simulate_only' && (
<ProjectDossierExport <ProjectDossierExport
onCorrect={(key) => {
const target = journeySections.findIndex(
(section) =>
(
simulationFieldGroups[section.id] ??
[]
).some((field) => field.key === key),
);
if (target >= 0) setStep(target);
window.requestAnimationFrame(() =>
document
.getElementById(`field-${key}`)
?.focus(),
);
}}
draft={draft} draft={draft}
version={ version={
draftVersionNo draftVersionNo
@@ -119,11 +119,22 @@ export function buildFinancialRatiosTable(
rows['Retorno do capital'].push( rows['Retorno do capital'].push(
consistent && profitValid ? quotient(net, capital, true) : unknown, consistent && profitValid ? quotient(net, capital, true) : unknown,
); );
// Ask only what cannot be calculated: without a declared
// classification, the balance gives the current amounts and loans
// are read as long-term (stated in the table notes).
const fixed = cell(balance, 'Activos fixos líquidos', i),
loans = cell(balance, 'Empréstimos e suprimentos por reembolsar', i);
const currentAssets = settingsValid const currentAssets = settingsValid
? declaration(settings.assetsByMonth[end]) ? declaration(settings.assetsByMonth[end])
: settings === undefined && assets !== null && fixed !== null
? assets - fixed
: null, : null,
currentLiabilities = settingsValid currentLiabilities = settingsValid
? declaration(settings.liabilitiesByMonth[end]) ? declaration(settings.liabilitiesByMonth[end])
: settings === undefined &&
liabilities !== null &&
loans !== null
? liabilities - loans
: null; : null;
const validCurrent = const validCurrent =
currentAssets !== null && currentAssets !== null &&
@@ -158,6 +169,10 @@ export function buildFinancialRatiosTable(
`${headers[i + 1]}: capital negativo; o retorno conserva o sinal matemático e exige interpretação desta situação.`, `${headers[i + 1]}: capital negativo; o retorno conserva o sinal matemático e exige interpretação desta situação.`,
); );
} }
if (settings === undefined)
result.notes.push(
'Activo e passivo correntes calculados a partir do balanço: activo corrente = total do activo − activos fixos líquidos; passivo corrente = total do passivo − empréstimos e suprimentos, considerados de longo prazo. Se parte dos empréstimos vencer em menos de um ano, declare a classificação.',
);
result.rows = Object.values(rows); result.rows = Object.values(rows);
if (blockedPeriods.length) if (blockedPeriods.length)
result.issues.push( result.issues.push(
+58
View File
@@ -0,0 +1,58 @@
import {
forecastBusinessPlan,
type BusinessFinancialPlanInput,
} from "./business-financial-plan.ts";
/**
* Fiscal scenario for the investor's business plan: the yearly IRPC is the
* documented rate applied to each year's profit before tax. It guides the
* viability reading; it is not a tax assessment.
*/
export const irpcPlanScenarios = {
general: {
label: "Regime geral do IRPC — taxa de 32%",
rate: 32,
source: "Cenário fiscal: IRPC à taxa geral de 32% (Código do IRPC, artigo 61.º, n.º 1) sobre o lucro antes de impostos de cada ano.",
},
} as const;
export type IrpcPlanScenario = keyof typeof irpcPlanScenarios;
const SIMPLIFICATIONS =
" Estimativa para avaliar a viabilidade, não é liquidação: o imposto de cada ano é registado no último mês desse ano; um ano com prejuízo tem imposto zero; não inclui reporte de prejuízos, benefícios fiscais, pagamentos por conta nem o calendário de pagamento da Autoridade Tributária.";
function cents(value: string): bigint {
const match = /^(-?)(\d+)\.(\d{2})$/.exec(value);
if (!match) throw new Error("Resultado mensal com formato inesperado.");
const amount = BigInt(match[2]) * 100n + BigInt(match[3]);
return match[1] ? -amount : amount;
}
function money(value: bigint): string {
return `${value / 100n}.${String(value % 100n).padStart(2, "0")}`;
}
/** Yearly tax on 12-month blocks, rounded half-up to the cent. */
export function irpcScenarioSchedule(
plan: BusinessFinancialPlanInput,
scenario: IrpcPlanScenario,
): { expense: string[]; payment: string[]; source: string } {
const { rate, source } = irpcPlanScenarios[scenario];
const rows = forecastBusinessPlan(plan).rows;
const expense = rows.map(() => "0.00");
for (let start = 0; start < rows.length; start += 12) {
const block = rows.slice(start, start + 12);
const profit = block.reduce(
(total, row) => total + cents(String(row.profitBeforeTax)),
0n,
);
if (profit <= 0n) continue;
const tax = (profit * BigInt(rate) * 2n + 100n) / 200n;
expense[start + block.length - 1] = money(tax);
}
return {
expense,
payment: [...expense],
source: source + SIMPLIFICATIONS,
};
}
+15 -3
View File
@@ -363,6 +363,13 @@ async function annexDocxBlocks(
return blocks; return blocks;
} }
/** The investor decision report is a business plan, not the audit dossier. */
function reportHeading(model: DossierReportModel): string {
return model.sections[0]?.id === 'investor-report'
? 'Plano de negócio'
: 'Relatório consolidado do projecto';
}
export async function generateProjectDossierDocx( export async function generateProjectDossierDocx(
model: DossierReportModel, model: DossierReportModel,
attachments: DossierAttachment[], attachments: DossierAttachment[],
@@ -371,7 +378,7 @@ export async function generateProjectDossierDocx(
const children: (Paragraph | Table)[] = [ const children: (Paragraph | Table)[] = [
new Paragraph({ text: 'InvesteMoz', heading: HeadingLevel.HEADING_2 }), new Paragraph({ text: 'InvesteMoz', heading: HeadingLevel.HEADING_2 }),
new Paragraph({ new Paragraph({
text: 'Relatório consolidado do projecto', text: reportHeading(model),
heading: HeadingLevel.TITLE, heading: HeadingLevel.TITLE,
}), }),
new Paragraph({ new Paragraph({
@@ -499,7 +506,11 @@ export async function generateProjectDossierDocx(
children.push(tableForDocx(slice.headers, slice.rows)); children.push(tableForDocx(slice.headers, slice.rows));
} }
} }
if (!section.rows.length && !section.paragraphs.length) if (
!section.rows.length &&
!section.paragraphs.length &&
!section.tables?.length
)
children.push( children.push(
new Paragraph('Não há informação fornecida nesta secção.'), new Paragraph('Não há informação fornecida nesta secção.'),
); );
@@ -741,6 +752,7 @@ export async function createProjectDossierPrintHtml(
if ( if (
!section.rows.length && !section.rows.length &&
!section.paragraphs.length && !section.paragraphs.length &&
!section.tables?.length &&
section.id !== 'annexes' section.id !== 'annexes'
) )
content.push('<p>Não há informação fornecida nesta secção.</p>'); content.push('<p>Não há informação fornecida nesta secção.</p>');
@@ -753,7 +765,7 @@ export async function createProjectDossierPrintHtml(
).replaceAll('<', '\\3c '); ).replaceAll('<', '\\3c ');
return `<!doctype html><html lang="pt-MZ"><head><meta charset="utf-8"><title>Relatório — ${escapeHtml(model.title)}</title><style> return `<!doctype html><html lang="pt-MZ"><head><meta charset="utf-8"><title>Relatório — ${escapeHtml(model.title)}</title><style>
@page{size:A4;margin:18mm 17mm 20mm;@bottom-left{content:${printFooter};font:9pt/1.3 Arial,sans-serif;color:#40524d;vertical-align:middle;width:80%}@bottom-right{content:counter(page) " / " counter(pages);font:9pt/1.3 Arial,sans-serif;color:#40524d;vertical-align:middle}}*{box-sizing:border-box}body{font:10.5pt/1.45 Arial,sans-serif;color:#17211f;margin:0}h1{font-size:24pt;color:#123b35;margin:0 0 7mm}h2{font-size:16pt;color:#123b35;border-bottom:1px solid #b8c9c3;padding-bottom:2mm;margin:8mm 0 3mm;break-after:avoid}h3{font-size:12pt;color:#27675c;break-after:avoid}p{white-space:pre-wrap}table{width:100%;border-collapse:collapse;table-layout:fixed;margin:3mm 0 5mm;break-inside:auto}th,td{border:1px solid #cbd5d1;padding:5px 6px;text-align:left;vertical-align:top;overflow-wrap:anywhere}th{background:#123b35;color:white}tr{break-inside:avoid}.report-table th:first-child,.report-table td:first-child{width:22%}.report-table th:last-child,.report-table td:last-child{width:32%}.report-table td:last-child{font-size:9pt;color:#40524d}.annex-table{table-layout:fixed;font-size:9pt}thead{display:table-header-group}.private{padding:3mm;background:#fff4df;border-left:3px solid #b66a0c;font-weight:bold}section{break-inside:auto}figure{margin:5mm auto;text-align:center;break-inside:avoid}img{max-width:100%;max-height:210mm;object-fit:contain}figcaption{font-style:italic;color:#52615d}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:9.5pt/1.4 Arial,sans-serif}@media screen{body{max-width:1040px;margin:24px auto;padding:24px}table{font-size:11pt}}@media screen{body{max-width:1040px;margin:24px auto;padding:24px}table{font-size:11pt}}@media print{a{color:inherit;text-decoration:none}.no-print{display:none}th{color:#17211f;background:#edf4f1}footer{display:none}} @page{size:A4;margin:18mm 17mm 20mm;@bottom-left{content:${printFooter};font:9pt/1.3 Arial,sans-serif;color:#40524d;vertical-align:middle;width:80%}@bottom-right{content:counter(page) " / " counter(pages);font:9pt/1.3 Arial,sans-serif;color:#40524d;vertical-align:middle}}*{box-sizing:border-box}body{font:10.5pt/1.45 Arial,sans-serif;color:#17211f;margin:0}h1{font-size:24pt;color:#123b35;margin:0 0 7mm}h2{font-size:16pt;color:#123b35;border-bottom:1px solid #b8c9c3;padding-bottom:2mm;margin:8mm 0 3mm;break-after:avoid}h3{font-size:12pt;color:#27675c;break-after:avoid}p{white-space:pre-wrap}table{width:100%;border-collapse:collapse;table-layout:fixed;margin:3mm 0 5mm;break-inside:auto}th,td{border:1px solid #cbd5d1;padding:5px 6px;text-align:left;vertical-align:top;overflow-wrap:anywhere}th{background:#123b35;color:white}tr{break-inside:avoid}.report-table th:first-child,.report-table td:first-child{width:22%}.report-table th:last-child,.report-table td:last-child{width:32%}.report-table td:last-child{font-size:9pt;color:#40524d}.annex-table{table-layout:fixed;font-size:9pt}thead{display:table-header-group}.private{padding:3mm;background:#fff4df;border-left:3px solid #b66a0c;font-weight:bold}section{break-inside:auto}figure{margin:5mm auto;text-align:center;break-inside:avoid}img{max-width:100%;max-height:210mm;object-fit:contain}figcaption{font-style:italic;color:#52615d}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:9.5pt/1.4 Arial,sans-serif}@media screen{body{max-width:1040px;margin:24px auto;padding:24px}table{font-size:11pt}}@media screen{body{max-width:1040px;margin:24px auto;padding:24px}table{font-size:11pt}}@media print{a{color:inherit;text-decoration:none}.no-print{display:none}th{color:#17211f;background:#edf4f1}footer{display:none}}
</style></head><body><h1>InvesteMoz<br>Relatório consolidado do projecto</h1><p><strong>${escapeHtml(model.title)}</strong><br>Gerado em ${escapeHtml(new Date(model.generatedAt).toLocaleString('pt-MZ'))}<br>Versão/revisão: ${escapeHtml(model.version)}</p><p class="private">Documento privado. O portal não publica nem partilha este conteúdo.</p>${content.join('')}<footer><small>InvesteMoz · Relatório privado · ${escapeHtml(model.version)}</small></footer><script>window.addEventListener('load',()=>setTimeout(()=>window.print(),350));</script></body></html>`; </style></head><body><h1>InvesteMoz<br>${reportHeading(model)}</h1><p><strong>${escapeHtml(model.title)}</strong><br>Gerado em ${escapeHtml(new Date(model.generatedAt).toLocaleString('pt-MZ'))}<br>Versão/revisão: ${escapeHtml(model.version)}</p><p class="private">Documento privado. O portal não publica nem partilha este conteúdo.</p>${content.join('')}<footer><small>InvesteMoz · Relatório privado · ${escapeHtml(model.version)}</small></footer><script>window.addEventListener('load',()=>setTimeout(()=>window.print(),350));</script></body></html>`;
} }
export async function generateProjectDossierPackage( export async function generateProjectDossierPackage(
+171
View File
@@ -12,6 +12,7 @@ import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts'; import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { financialPlanWarnings } from './financial-plan-warnings.ts'; import { financialPlanWarnings } from './financial-plan-warnings.ts';
import { pathStates } from './investor-path.ts'; import { pathStates } from './investor-path.ts';
import { financialIssuesForDisplay } from './financial-issue-presentation.ts';
import { import {
buildProjectDossierRows, buildProjectDossierRows,
type ProjectDossierRow, type ProjectDossierRow,
@@ -46,6 +47,7 @@ export const dossierReportSections = [
export type DossierReportSectionId = export type DossierReportSectionId =
| (typeof dossierReportSections)[number]['id'] | (typeof dossierReportSections)[number]['id']
| 'financial-report' | 'financial-report'
| 'investor-report'
| 'supply'; | 'supply';
export type DossierReference = { export type DossierReference = {
version: number; version: number;
@@ -982,6 +984,175 @@ export function createIntegralFinancialReport(
}; };
} }
/** Investor decision report: the business-plan chapters the simulation must deliver.
* The tables are the same eleven integral tables (one source, one calculation);
* only the order, the narrative and the plain presentation change. */
export const investorReportFields = {
objectives: 'plan_objectives',
mission: 'plan_mission',
successKeys: 'plan_success_keys',
} as const;
export type InvestorReportGap = { message: string; field?: string };
export function createInvestorDecisionReport(
draft: Record<string, string | string[]>,
options: Omit<
Parameters<typeof createProjectDossierReport>[1],
'selectedSections'
> = {},
): DossierReportModel & { missing: InvestorReportGap[] } {
const integral = createIntegralFinancialReport(draft, options);
const tables = integral.sections.flatMap((s) => s.tables ?? []);
// As in the model: chapters show the yearly columns; the first year's
// months go to the closing annex. Same cells, no recalculation.
const columns = (
table: InvestmentReportTable,
keep: (header: string, index: number) => boolean,
): InvestmentReportTable => {
const kept = table.headers
.map((header, index) => (index === 0 || keep(header, index) ? index : -1))
.filter((index) => index >= 0);
return {
...table,
headers: kept.map((index) => table.headers[index]),
rows: table.rows.map((row) => kept.map((index) => row[index] ?? '')),
};
};
const yearly = (table: InvestmentReportTable) =>
table.headers.some((h) => /^\d{4}( \(parcial\))?$/.test(h))
? columns(table, (h) => /^\d{4}( \(parcial\))?$/.test(h))
: table;
const firstYearMonths = (table: InvestmentReportTable) =>
columns(table, (h, index) => /^\d{4}-\d{2}$/.test(h) && index <= 12);
const pick = (...ids: string[]) =>
ids.flatMap((id) => tables.filter((t) => t.id === id).map(yearly));
const said = (key: string) => text(draft, key);
const labelled = (label: string, key: string) =>
said(key) ? [`${label}: ${said(key)}`] : [];
const missing: InvestorReportGap[] = [];
for (const [label, key] of [
['Resumo executivo', 'project_summary'],
['Objectivos', investorReportFields.objectives],
['Missão', investorReportFields.mission],
['Chaves para o sucesso', investorReportFields.successKeys],
] as const)
if (!said(key))
missing.push({
message: `${label}: Preencha este campo para continuar.`,
field: key,
});
const expected = integralFinancialTableIds.filter(
(id) => !tables.some((t) => t.id === id),
);
if (expected.length)
missing.push({
message: `Tabelas ainda sem dados suficientes: ${expected.length} de ${integralFinancialTableIds.length}.`,
});
for (const issue of financialIssuesForDisplay(tables))
missing.push({
message: `${issue.message} (${issue.tables.join('; ')})`,
});
const chapter = (
title: string,
paragraphs: string[],
chapterTables: InvestmentReportTable[] = [],
): DossierReportSection => ({
id: 'investor-report',
title,
private: true,
paragraphs,
rows: [],
tables: chapterTables,
});
const optional = (title: string, paragraphs: string[]) =>
paragraphs.length ? [chapter(title, paragraphs)] : [];
const sections: DossierReportSection[] = [
chapter('1. Resumo Executivo', [
...(said('project_summary') ? [said('project_summary')] : []),
...labelled('Objectivos', investorReportFields.objectives),
...labelled('Missão', investorReportFields.mission),
...labelled('Chaves para o sucesso', investorReportFields.successKeys),
]),
chapter(
'2. Resumo da Startup',
['Despesas e activos iniciais e o financiamento total requerido.'],
pick('startup'),
),
...optional('3. Produtos e Serviços', [
...(said('products_services') ? [said('products_services')] : []),
...labelled('Proposta de valor', 'value_proposition'),
]),
chapter(
'4. Análise de Mercado',
[
...labelled('Clientes', 'target_customers'),
...labelled('Hipótese de mercado', 'market_assumption'),
...labelled('Concorrência', 'competitor_assumption'),
],
pick('market-analysis'),
),
chapter(
'5. Estratégia e Implementação',
[
...labelled('Vendas', 'sales_channel_assumption'),
...labelled('Marketing', 'marketing_approach'),
...labelled('Presença digital', 'web_plan'),
],
pick('sales', 'milestones'),
),
chapter(
'6. Resumo da Gestão',
labelled('Organização e gestão', 'management_summary'),
pick('personnel'),
),
chapter(
'7. Plano Financeiro',
[
'Projecções calculadas a partir dos mesmos dados das tabelas anteriores; não são contas realizadas nem confirmação de financiamento.',
],
pick(
'funding',
'break-even',
'profit-loss',
'cashflow',
'balance',
'ratios',
),
),
];
const monthly = ['sales', 'profit-loss', 'cashflow', 'balance'].flatMap(
(id) =>
tables
.filter(
(t) =>
t.id === id &&
t.headers.some((h) => /^\d{4}-\d{2}$/.test(h)),
)
.map((t) => ({
...firstYearMonths(t),
title: `${t.title} — mês a mês, primeiro ano`,
issues: [],
})),
);
if (monthly.length)
sections.push(
chapter(
'Anexo — detalhe mensal do primeiro ano',
['Os mesmos valores das tabelas anuais, por mês.'],
monthly,
),
);
return {
...integral,
sections,
missing,
limitations: [
'Projecções preparadas pelo investidor no InvesteMoz; não constituem aprovação, garantia de financiamento nem resultado oficial.',
],
};
}
export function classifyDossierAttachment( export function classifyDossierAttachment(
file: Pick<File, 'name' | 'type' | 'size'>, file: Pick<File, 'name' | 'type' | 'size'>,
): DossierAttachmentKind { ): DossierAttachmentKind {
+13
View File
@@ -642,6 +642,19 @@ export const simulationFieldGroups: Record<
d.purpose !== 'simulate_only' || d.purpose !== 'simulate_only' ||
['small_business', 'investor'].includes(String(d.journey_type)), ['small_business', 'investor'].includes(String(d.journey_type)),
}, },
...(
[
['plan_objectives', 'Objectivos do negócio'],
['plan_mission', 'Missão'],
['plan_success_keys', 'Chaves para o sucesso'],
] as const
).map(([key, label]) => ({
key,
label,
type: 'textarea' as const,
showWhen: (d: SimulationDraft) =>
['small_business', 'investor'].includes(String(d.journey_type)),
})),
{ {
key: 'project_problem', key: 'project_problem',
label: 'Que problema ou necessidade pretende resolver?', label: 'Que problema ou necessidade pretende resolver?',
@@ -131,4 +131,14 @@ class InvestmentContextContinuityTest extends TestCase
$apply(['sector' => 'sector:'.$agro->id], ['sector_id', 'sector']); $apply(['sector' => 'sector:'.$agro->id], ['sector_id', 'sector']);
$this->getJson('/investimentos/'.$id.'/contexto')->assertJsonPath('context.fields.sector_id', (string) $agro->id)->assertJsonPath('context.fields.sector', $agro->name); $this->getJson('/investimentos/'.$id.'/contexto')->assertJsonPath('context.fields.sector_id', (string) $agro->id)->assertJsonPath('context.fields.sector', $agro->name);
} }
public function test_the_business_plan_executive_summary_fields_are_saved_in_the_draft(): void
{
// Investor report model: objectives, mission and keys to success are requested from the investor.
$owner = User::factory()->create();
$id = $this->dossier($owner, 'Plano de negócio');
$economic = ['purpose' => 'simulate_only', 'journey_type' => 'investor', 'project_title' => 'Hotel', 'plan_objectives' => 'Lucro no segundo ano.', 'plan_mission' => 'Servir bem.', 'plan_success_keys' => 'Qualidade.'];
$this->actingAs($owner)->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
$this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => [...$economic, 'plan_mission' => str_repeat('a', 10001)]], ['Idempotency-Key' => (string) Str::uuid()])->assertUnprocessable();
}
} }
@@ -95,11 +95,29 @@ void test('approved formulas are presented from the same monthly and annual stat
assert.equal(get(t, 'Crescimento das vendas')[2], '0,00%'); assert.equal(get(t, 'Crescimento das vendas')[2], '0,00%');
assert.equal(get(t, 'Crescimento das vendas').at(-1), 'Por determinar'); assert.equal(get(t, 'Crescimento das vendas').at(-1), 'Por determinar');
}); });
void test('inconsistent balance blocks only dependent indicators; missing liquidity does not invent maturity', () => { void test('inconsistent balance blocks only dependent indicators; without classification liquidity comes from the balance', () => {
const { plan, source } = fixture(); const { plan, source } = fixture();
delete plan.ratioCurrentBalances; delete plan.ratioCurrentBalances;
let t = buildFinancialRatiosTable(plan, source); let t = buildFinancialRatiosTable(plan, source);
assert.equal(get(t, 'Liquidez corrente')[1], 'Por determinar'); // Mapa de erros, plano de negócio: ratios are calculated from the balance;
// loans are read as long-term and the rule is stated in the notes.
const balance = source.find((b) => b.id === 'balance');
const value = (label) =>
Number(balance.rows.find((r) => r[0] === label)[1]);
const expected =
(value('Total do activo') - value('Activos fixos líquidos')) /
(value('Total do passivo') -
value('Empréstimos e suprimentos por reembolsar'));
assert.equal(
get(t, 'Liquidez corrente')[1],
expected.toFixed(2).replace('.', ',') + '×',
);
assert.ok(
t.notes.some((n) =>
n.startsWith('Activo e passivo correntes calculados a partir do balanço'),
),
);
assert.ok(!t.issues.some((i) => i.includes('Activo corrente — mês')));
assert.equal(get(t, 'Margem líquida')[1], '26,00%'); assert.equal(get(t, 'Margem líquida')[1], '26,00%');
assert.equal(get(t, 'Retorno do capital')[1], '14,77%'); assert.equal(get(t, 'Retorno do capital')[1], '14,77%');
source source
@@ -10,6 +10,7 @@ import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import * as report from '../../resources/js/lib/integral-financial-report.ts'; import * as report from '../../resources/js/lib/integral-financial-report.ts';
import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts'; import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
import * as annual from '../../resources/js/lib/annual-example-report.ts'; import * as annual from '../../resources/js/lib/annual-example-report.ts';
import * as irpcScenario from '../../resources/js/lib/irpc-plan-scenario.ts';
import { import {
serializeBusinessPlanSnapshot, serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot, restoreBusinessPlanSnapshot,
@@ -36,6 +37,8 @@ void test('one startup editor retains all rows and persists an edit without dupl
(name) => (name) =>
name === '@/lib/integral-financial-report' name === '@/lib/integral-financial-report'
? report ? report
: name === '@/lib/irpc-plan-scenario'
? irpcScenario
: name === './investment-report-tables' : name === './investment-report-tables'
? { InvestmentReportTables: () => null } ? { InvestmentReportTables: () => null }
: name === '@/lib/financial-plan-warnings' : name === '@/lib/financial-plan-warnings'
@@ -0,0 +1,135 @@
import assert from "node:assert/strict";
import test from "node:test";
import { financialReportFixture } from "./fixtures/integral-financial-plan.mjs";
import {
forecastBusinessPlan,
serializeBusinessPlanSnapshot,
} from "../../resources/js/lib/business-financial-plan.ts";
import { buildIntegralFinancialTables } from "../../resources/js/lib/integral-financial-report.ts";
import { irpcScenarioSchedule } from "../../resources/js/lib/irpc-plan-scenario.ts";
import {
createInvestorDecisionReport,
createProjectDossierPrintHtml,
} from "../../resources/js/lib/project-dossier-report.ts";
const toCents = (value) => {
const [whole, fraction = "00"] = String(value).replace("-", "").split(".");
const amount = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, "0"));
return String(value).startsWith("-") ? -amount : amount;
};
void test("the fiscal scenario applies the documented 32% IRPC to each year profit, never to a loss (Criar Hotel)", () => {
const plan = financialReportFixture(36);
const rows = forecastBusinessPlan(plan).rows;
const result = irpcScenarioSchedule(plan, "general");
assert.equal(result.expense.length, 36);
assert.deepEqual(result.payment, result.expense);
for (let year = 0; year < 3; year++) {
const profit = rows
.slice(year * 12, year * 12 + 12)
.reduce((t, r) => t + toCents(r.profitBeforeTax), 0n);
const expected = profit > 0n ? (profit * 32n * 2n + 100n) / 200n : 0n;
assert.equal(toCents(result.expense[year * 12 + 11]), expected);
for (let m = 0; m < 11; m++)
assert.equal(result.expense[year * 12 + m], "0.00");
}
assert.match(result.source, /artigo 61\.º, n\.º 1/);
assert.match(result.source, /não é liquidação/);
// The calculated schedule is accepted by the report as declared taxes.
plan.reportAssumptions = {
...plan.reportAssumptions,
taxExpenseByMonth: result.expense,
taxPaymentByMonth: result.payment,
taxSource: result.source,
};
const pl = buildIntegralFinancialTables(plan).find(
(t) => t.id === "profit-loss",
);
assert.deepEqual(pl.issues, []);
});
void test("the simulation result is a business plan in the model order, without audit columns (Criar Hotel)", async () => {
const plan = financialReportFixture(36);
const draft = {
project_title: "Hotel QA sintético",
project_summary: "Hotel de praia.",
plan_objectives: "Lucro no segundo ano.",
plan_mission: "Servir bem.",
plan_success_keys: "Qualidade, localização.",
business_plan_snapshot: serializeBusinessPlanSnapshot(plan),
};
const report = createInvestorDecisionReport(draft, {
generatedAt: "2026-12-04T12:00:00Z",
});
assert.equal(report.title, "Hotel QA sintético");
assert.deepEqual(
report.sections.map((s) => s.title),
[
"1. Resumo Executivo",
"2. Resumo da Startup",
"4. Análise de Mercado",
"5. Estratégia e Implementação",
"6. Resumo da Gestão",
"7. Plano Financeiro",
"Anexo — detalhe mensal do primeiro ano",
],
);
assert.ok(report.sections.every((s) => s.rows.length === 0));
// Chapters carry the yearly columns only; the annex carries 12 months.
const pl = report.sections[5].tables.find((t) => t.id === "profit-loss");
assert.ok(pl.headers.slice(1).every((h) => /^\d{4}( \(parcial\))?$/.test(h)));
assert.equal(pl.headers.length, 4);
const annex = report.sections[6].tables.find((t) => t.id === "profit-loss");
assert.equal(annex.headers.length, 13);
assert.ok(annex.headers.slice(1).every((h) => /^\d{4}-\d{2}$/.test(h)));
assert.deepEqual(report.sections[0].paragraphs, [
"Hotel de praia.",
"Objectivos: Lucro no segundo ano.",
"Missão: Servir bem.",
"Chaves para o sucesso: Qualidade, localização.",
]);
const ids = report.sections.slice(0, -1).flatMap((s) =>
(s.tables ?? []).map((t) => t.id),
);
assert.deepEqual(
ids.filter((id) =>
[
"startup",
"sales",
"funding",
"break-even",
"profit-loss",
"cashflow",
"balance",
].includes(id),
),
[
"startup",
"sales",
"funding",
"break-even",
"profit-loss",
"cashflow",
"balance",
],
);
assert.ok(!report.missing.some((gap) => gap.field));
const html = await createProjectDossierPrintHtml(report, [], false);
assert.match(html, /<h1>InvesteMoz<br>Plano de negócio<\/h1>/);
assert.doesNotMatch(html, /Classificação \/ origem/);
});
void test("missing executive summary fields are listed with the field to open (Criar Hotel)", () => {
const report = createInvestorDecisionReport({ project_title: "Hotel" });
const fields = report.missing.filter((g) => g.field).map((g) => g.field);
assert.deepEqual(fields, [
"project_summary",
"plan_objectives",
"plan_mission",
"plan_success_keys",
]);
assert.match(
report.missing[0].message,
/Preencha este campo para continuar/,
);
});
+2
View File
@@ -12,6 +12,7 @@ import * as startup from '../../resources/js/lib/startup-asset-requirements.ts';
import * as presentation from '../../resources/js/lib/financial-issue-presentation.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 annual from '../../resources/js/lib/annual-example-report.ts';
import * as warnings from '../../resources/js/lib/financial-plan-warnings.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 { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
@@ -22,6 +23,7 @@ const modules = {
'@/lib/financial-issue-presentation': presentation, '@/lib/financial-issue-presentation': presentation,
'@/lib/annual-example-report': annual, '@/lib/annual-example-report': annual,
'@/lib/financial-plan-warnings': warnings, '@/lib/financial-plan-warnings': warnings,
'@/lib/irpc-plan-scenario': irpcScenario,
'./business-plan-warnings': { BusinessPlanWarnings: () => null }, './business-plan-warnings': { BusinessPlanWarnings: () => null },
}; };
function component(name) { function component(name) {