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:
@@ -119,12 +119,23 @@ export function buildFinancialRatiosTable(
|
||||
rows['Retorno do capital'].push(
|
||||
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
|
||||
? declaration(settings.assetsByMonth[end])
|
||||
: null,
|
||||
: settings === undefined && assets !== null && fixed !== null
|
||||
? assets - fixed
|
||||
: null,
|
||||
currentLiabilities = settingsValid
|
||||
? declaration(settings.liabilitiesByMonth[end])
|
||||
: null;
|
||||
: settings === undefined &&
|
||||
liabilities !== null &&
|
||||
loans !== null
|
||||
? liabilities - loans
|
||||
: null;
|
||||
const validCurrent =
|
||||
currentAssets !== null &&
|
||||
currentLiabilities !== 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.`,
|
||||
);
|
||||
}
|
||||
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);
|
||||
if (blockedPeriods.length)
|
||||
result.issues.push(
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -363,6 +363,13 @@ async function annexDocxBlocks(
|
||||
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(
|
||||
model: DossierReportModel,
|
||||
attachments: DossierAttachment[],
|
||||
@@ -371,7 +378,7 @@ export async function generateProjectDossierDocx(
|
||||
const children: (Paragraph | Table)[] = [
|
||||
new Paragraph({ text: 'InvesteMoz', heading: HeadingLevel.HEADING_2 }),
|
||||
new Paragraph({
|
||||
text: 'Relatório consolidado do projecto',
|
||||
text: reportHeading(model),
|
||||
heading: HeadingLevel.TITLE,
|
||||
}),
|
||||
new Paragraph({
|
||||
@@ -499,7 +506,11 @@ export async function generateProjectDossierDocx(
|
||||
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(
|
||||
new Paragraph('Não há informação fornecida nesta secção.'),
|
||||
);
|
||||
@@ -741,6 +752,7 @@ export async function createProjectDossierPrintHtml(
|
||||
if (
|
||||
!section.rows.length &&
|
||||
!section.paragraphs.length &&
|
||||
!section.tables?.length &&
|
||||
section.id !== 'annexes'
|
||||
)
|
||||
content.push('<p>Não há informação fornecida nesta secção.</p>');
|
||||
@@ -753,7 +765,7 @@ export async function createProjectDossierPrintHtml(
|
||||
).replaceAll('<', '\\3c ');
|
||||
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}}
|
||||
</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(
|
||||
|
||||
@@ -12,6 +12,7 @@ import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { financialPlanWarnings } from './financial-plan-warnings.ts';
|
||||
import { pathStates } from './investor-path.ts';
|
||||
import { financialIssuesForDisplay } from './financial-issue-presentation.ts';
|
||||
import {
|
||||
buildProjectDossierRows,
|
||||
type ProjectDossierRow,
|
||||
@@ -46,6 +47,7 @@ export const dossierReportSections = [
|
||||
export type DossierReportSectionId =
|
||||
| (typeof dossierReportSections)[number]['id']
|
||||
| 'financial-report'
|
||||
| 'investor-report'
|
||||
| 'supply';
|
||||
export type DossierReference = {
|
||||
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(
|
||||
file: Pick<File, 'name' | 'type' | 'size'>,
|
||||
): DossierAttachmentKind {
|
||||
|
||||
@@ -642,6 +642,19 @@ export const simulationFieldGroups: Record<
|
||||
d.purpose !== 'simulate_only' ||
|
||||
['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',
|
||||
label: 'Que problema ou necessidade pretende resolver?',
|
||||
|
||||
Reference in New Issue
Block a user