File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,81 @@
|
||||
export type BusinessLocationPath = {
|
||||
province_id: string;
|
||||
district_id: string;
|
||||
admin_post_id: string;
|
||||
locality_id: string;
|
||||
};
|
||||
|
||||
export const emptyBusinessLocation = (): BusinessLocationPath => ({
|
||||
province_id: '',
|
||||
district_id: '',
|
||||
admin_post_id: '',
|
||||
locality_id: '',
|
||||
});
|
||||
|
||||
export function decodeBusinessLocations(value?: string): BusinessLocationPath[] {
|
||||
if (!value) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.slice(0, 20).map((entry) => {
|
||||
const row = entry && typeof entry === 'object'
|
||||
? (entry as Record<string, unknown>)
|
||||
: {};
|
||||
return {
|
||||
province_id: typeof row.province_id === 'string' ? row.province_id : '',
|
||||
district_id: typeof row.district_id === 'string' ? row.district_id : '',
|
||||
admin_post_id: typeof row.admin_post_id === 'string' ? row.admin_post_id : '',
|
||||
locality_id: typeof row.locality_id === 'string' ? row.locality_id : '',
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function encodeBusinessLocations(rows: BusinessLocationPath[]): string {
|
||||
return JSON.stringify(rows.slice(0, 20));
|
||||
}
|
||||
|
||||
export function updateBusinessLocation(
|
||||
rows: BusinessLocationPath[],
|
||||
index: number,
|
||||
key: keyof BusinessLocationPath,
|
||||
value: string,
|
||||
): BusinessLocationPath[] {
|
||||
if (!rows[index]) return rows;
|
||||
const next = rows.map((row) => ({ ...row }));
|
||||
next[index][key] = value;
|
||||
const children: Partial<Record<keyof BusinessLocationPath, (keyof BusinessLocationPath)[]>> = {
|
||||
province_id: ['district_id', 'admin_post_id', 'locality_id'],
|
||||
district_id: ['admin_post_id', 'locality_id'],
|
||||
admin_post_id: ['locality_id'],
|
||||
};
|
||||
for (const child of children[key] ?? []) next[index][child] = '';
|
||||
return next;
|
||||
}
|
||||
|
||||
export function hasDuplicateBusinessLocationPath(rows: BusinessLocationPath[]): boolean {
|
||||
const paths = rows.map((row) => [
|
||||
row.province_id,
|
||||
row.district_id,
|
||||
row.admin_post_id,
|
||||
row.locality_id,
|
||||
].filter(Boolean));
|
||||
return paths.some((path, index) => path.length > 0 && paths.slice(index + 1).some((other) => {
|
||||
if (other.length === 0) return false;
|
||||
const common = Math.min(path.length, other.length);
|
||||
return path.slice(0, common).every((id, part) => id === other[part]);
|
||||
}));
|
||||
}
|
||||
|
||||
export function locationPathFromPayload(
|
||||
payload: Record<string, string | undefined>,
|
||||
): BusinessLocationPath {
|
||||
return {
|
||||
province_id: payload.province_id ?? '',
|
||||
district_id: payload.district_id ?? '',
|
||||
admin_post_id: payload.admin_post_id ?? '',
|
||||
locality_id: payload.locality_id ?? '',
|
||||
};
|
||||
}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
export declare function csvCell(value: unknown): string;
|
||||
export declare function csvCellWithDelimiter(value: unknown, delimiter: string): string;
|
||||
@@ -0,0 +1,20 @@
|
||||
function serializeCell(value, delimiter) {
|
||||
const raw = String(value ?? '');
|
||||
const formulaLike = /^[\u0000-\u0020\uFEFF]*[=+\-@]/.test(raw);
|
||||
const numeric = /^-?\d+(?:\.\d+)?$/.test(raw);
|
||||
const text = formulaLike && !numeric ? `'${raw}` : raw;
|
||||
|
||||
return /[",\r\n]/.test(text) || text.includes(delimiter)
|
||||
? `"${text.replaceAll('"', '""')}"`
|
||||
: text;
|
||||
}
|
||||
|
||||
/** Serializes a comma-separated cell and neutralizes spreadsheet formulas. */
|
||||
export function csvCell(value) {
|
||||
return serializeCell(value, ',');
|
||||
}
|
||||
|
||||
/** Serializes a cell for a locale-specific delimited export. */
|
||||
export function csvCellWithDelimiter(value, delimiter) {
|
||||
return serializeCell(value, delimiter);
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
import { csvCell } from './csv.js';
|
||||
|
||||
export type FinancialToolsSnapshotData = {
|
||||
budgetPeriod: string;
|
||||
loan: {
|
||||
principal: string;
|
||||
rate: string;
|
||||
months: string;
|
||||
rateType: 'nominal' | 'effective';
|
||||
periodMonths: string;
|
||||
gracePeriods: string;
|
||||
upfrontFee: string;
|
||||
recurringFee: string;
|
||||
};
|
||||
breakEven: { fixed: string; price: string; variable: string };
|
||||
funding: { total: string; secured: string };
|
||||
incomes: { label: string; amount: string }[];
|
||||
expenses: { label: string; amount: string }[];
|
||||
};
|
||||
|
||||
export function serializeFinancialToolsSnapshot(
|
||||
data: FinancialToolsSnapshotData,
|
||||
): string {
|
||||
return JSON.stringify({ version: 1, data });
|
||||
}
|
||||
|
||||
export function restoreFinancialToolsSnapshot(
|
||||
snapshot: string | undefined,
|
||||
): FinancialToolsSnapshotData | null {
|
||||
if (!snapshot || snapshot.length > 30_000) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(snapshot) as {
|
||||
version?: unknown;
|
||||
data?: unknown;
|
||||
};
|
||||
if (
|
||||
parsed.version !== 1 ||
|
||||
!parsed.data ||
|
||||
typeof parsed.data !== 'object'
|
||||
)
|
||||
return null;
|
||||
const data = parsed.data as Record<string, unknown>;
|
||||
const isText = (value: unknown, limit = 80) =>
|
||||
typeof value === 'string' && value.length <= limit;
|
||||
const loan = data.loan as Record<string, unknown> | null;
|
||||
const breakEven = data.breakEven as Record<string, unknown> | null;
|
||||
const funding = data.funding as Record<string, unknown> | null;
|
||||
const rowsValid = (value: unknown) =>
|
||||
Array.isArray(value) &&
|
||||
value.length > 0 &&
|
||||
value.length <= 50 &&
|
||||
value.every(
|
||||
(row) =>
|
||||
row &&
|
||||
typeof row === 'object' &&
|
||||
isText(row.label, 120) &&
|
||||
isText(row.amount, 80),
|
||||
);
|
||||
if (
|
||||
!['Mensal', 'Trimestral', 'Anual', 'Outro período'].includes(
|
||||
String(data.budgetPeriod),
|
||||
) ||
|
||||
!loan ||
|
||||
!breakEven ||
|
||||
!funding ||
|
||||
![
|
||||
'principal',
|
||||
'rate',
|
||||
'months',
|
||||
'periodMonths',
|
||||
'gracePeriods',
|
||||
'upfrontFee',
|
||||
'recurringFee',
|
||||
].every((key) => isText(loan[key])) ||
|
||||
!['nominal', 'effective'].includes(String(loan.rateType)) ||
|
||||
!['fixed', 'price', 'variable'].every((key) =>
|
||||
isText(breakEven[key]),
|
||||
) ||
|
||||
!['total', 'secured'].every((key) => isText(funding[key])) ||
|
||||
!rowsValid(data.incomes) ||
|
||||
!rowsValid(data.expenses)
|
||||
)
|
||||
return null;
|
||||
return data as unknown as FinancialToolsSnapshotData;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decimalToInteger(value: string, scale: number, label: string): bigint {
|
||||
const match = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
|
||||
if (!match || (match[2]?.length ?? 0) > scale)
|
||||
throw new Error(
|
||||
`${label}: introduza um valor decimal não negativo com até ${scale} casas.`,
|
||||
);
|
||||
const fraction = (match[2] ?? '').padEnd(scale, '0');
|
||||
return BigInt(match[1]) * 10n ** BigInt(scale) + BigInt(fraction || '0');
|
||||
}
|
||||
|
||||
function money(cents: bigint): string {
|
||||
const rounded = cents < 0n ? -cents : cents;
|
||||
const text = `${rounded / 100n}.${String(rounded % 100n).padStart(2, '0')}`;
|
||||
return cents < 0n ? `-${text}` : text;
|
||||
}
|
||||
|
||||
function ratePercent(value: bigint): string {
|
||||
const scaled = roundRatio(value * 100_000_000n, RATE_SCALE);
|
||||
return `${scaled / 1_000_000n}.${String(scaled % 1_000_000n).padStart(6, '0')}`;
|
||||
}
|
||||
|
||||
function roundRatio(numerator: bigint, denominator: bigint): bigint {
|
||||
return (numerator + denominator / 2n) / denominator;
|
||||
}
|
||||
|
||||
const RATE_SCALE = 1_000_000_000_000n;
|
||||
const divideRound = (numerator: bigint, denominator: bigint) =>
|
||||
roundRatio(numerator, denominator);
|
||||
const multiplyFixed = (left: bigint, right: bigint) =>
|
||||
divideRound(left * right, RATE_SCALE);
|
||||
|
||||
function fixedPower(base: bigint, exponent: number): bigint {
|
||||
let result = RATE_SCALE;
|
||||
let factor = base;
|
||||
let power = exponent;
|
||||
while (power > 0) {
|
||||
if (power % 2 === 1) result = multiplyFixed(result, factor);
|
||||
power = Math.floor(power / 2);
|
||||
if (power > 0) factor = multiplyFixed(factor, factor);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function fixedRoot(value: bigint, degree: number): bigint {
|
||||
let low = RATE_SCALE;
|
||||
let high = value;
|
||||
while (low < high) {
|
||||
const middle = (low + high + 1n) / 2n;
|
||||
if (fixedPower(middle, degree) <= value) low = middle;
|
||||
else high = middle - 1n;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/** Compatibility wrapper: monthly nominal schedule, with fees and grace set to zero. */
|
||||
export function calculateLoanPayment(
|
||||
principal: string,
|
||||
annualRatePercent: string,
|
||||
months: number,
|
||||
) {
|
||||
const result = buildLoanSchedule({
|
||||
principal,
|
||||
annualRatePercent,
|
||||
termMonths: months,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
});
|
||||
return {
|
||||
monthlyPayment: result.schedule[0].totalPayment,
|
||||
totalPaid: result.totalPaid,
|
||||
status: 'estimated' as const,
|
||||
};
|
||||
}
|
||||
|
||||
/** Contribution margin is calculated from user-entered sales and variable costs. */
|
||||
export function calculateBreakEven(
|
||||
fixedCosts: string,
|
||||
unitPrice: string,
|
||||
variableCostPerUnit: string,
|
||||
) {
|
||||
const fixed = decimalToInteger(fixedCosts, 2, 'Custos fixos');
|
||||
const price = decimalToInteger(unitPrice, 2, 'Preço unitário');
|
||||
const variable = decimalToInteger(variableCostPerUnit, 2, 'Custo variável');
|
||||
if (price <= variable)
|
||||
throw new Error(
|
||||
'O preço unitário deve ser superior ao custo variável.',
|
||||
);
|
||||
const units = (fixed + (price - variable) - 1n) / (price - variable);
|
||||
const revenue = units * price;
|
||||
return {
|
||||
contributionPerUnit: money(price - variable),
|
||||
breakEvenUnits: units.toString(),
|
||||
breakEvenRevenue: money(revenue),
|
||||
status: 'estimated' as const,
|
||||
};
|
||||
}
|
||||
|
||||
/** Funding gap is not a lending decision; the inputs must use the same currency. */
|
||||
export function calculateFundingGap(
|
||||
totalInvestment: string,
|
||||
securedFunding: string,
|
||||
) {
|
||||
const total = decimalToInteger(totalInvestment, 2, 'Investimento total');
|
||||
const secured = decimalToInteger(
|
||||
securedFunding,
|
||||
2,
|
||||
'Financiamento mobilizado',
|
||||
);
|
||||
return {
|
||||
gap: money(total - secured),
|
||||
reconciles: total === secured,
|
||||
status: 'estimated' as const,
|
||||
};
|
||||
}
|
||||
|
||||
export type LoanScheduleInput = {
|
||||
principal: string;
|
||||
annualRatePercent: string;
|
||||
termMonths: number;
|
||||
periodMonths: number;
|
||||
rateType: 'nominal' | 'effective';
|
||||
gracePeriods?: number;
|
||||
upfrontFee?: string;
|
||||
recurringFee?: string;
|
||||
};
|
||||
|
||||
/** Builds a reducing-balance schedule; fees remain separate from interest and principal. */
|
||||
export function buildLoanSchedule(input: LoanScheduleInput) {
|
||||
const principal = decimalToInteger(input.principal, 2, 'Capital');
|
||||
const annualRate = decimalToInteger(
|
||||
input.annualRatePercent,
|
||||
6,
|
||||
'Taxa anual',
|
||||
);
|
||||
const upfrontFee = decimalToInteger(
|
||||
input.upfrontFee ?? '0',
|
||||
2,
|
||||
'Comissão inicial',
|
||||
);
|
||||
const recurringFee = decimalToInteger(
|
||||
input.recurringFee ?? '0',
|
||||
2,
|
||||
'Comissão periódica',
|
||||
);
|
||||
if (
|
||||
!Number.isSafeInteger(input.periodMonths) ||
|
||||
![1, 2, 3, 4, 6, 12].includes(input.periodMonths)
|
||||
)
|
||||
throw new Error('Periodicidade: use 1, 2, 3, 4, 6 ou 12 meses.');
|
||||
if (
|
||||
!Number.isSafeInteger(input.termMonths) ||
|
||||
input.termMonths < input.periodMonths ||
|
||||
input.termMonths > 600 ||
|
||||
input.termMonths % input.periodMonths !== 0
|
||||
)
|
||||
throw new Error(
|
||||
'O prazo deve ser múltiplo da periodicidade e não exceder 600 meses.',
|
||||
);
|
||||
const periods = input.termMonths / input.periodMonths;
|
||||
const gracePeriods = input.gracePeriods ?? 0;
|
||||
if (
|
||||
!Number.isSafeInteger(gracePeriods) ||
|
||||
gracePeriods < 0 ||
|
||||
gracePeriods >= periods
|
||||
)
|
||||
throw new Error(
|
||||
'A carência deve ser inferior ao número total de prestações.',
|
||||
);
|
||||
if (upfrontFee > principal)
|
||||
throw new Error('A comissão inicial não pode exceder o capital.');
|
||||
|
||||
const annualFraction = divideRound(annualRate * RATE_SCALE, 100_000_000n);
|
||||
let periodicRate: bigint;
|
||||
if (input.rateType === 'nominal') {
|
||||
periodicRate = divideRound(
|
||||
annualFraction,
|
||||
BigInt(12 / input.periodMonths),
|
||||
);
|
||||
} else {
|
||||
const periodsPerYear = 12 / input.periodMonths;
|
||||
periodicRate =
|
||||
fixedRoot(RATE_SCALE + annualFraction, periodsPerYear) - RATE_SCALE;
|
||||
}
|
||||
|
||||
const amortizationPeriods = periods - gracePeriods;
|
||||
const growth = fixedPower(RATE_SCALE + periodicRate, amortizationPeriods);
|
||||
const regularPrincipalPayment =
|
||||
periodicRate === 0n
|
||||
? divideRound(principal, BigInt(amortizationPeriods))
|
||||
: divideRound(
|
||||
principal * periodicRate * growth,
|
||||
RATE_SCALE * (growth - RATE_SCALE),
|
||||
);
|
||||
let balance = principal;
|
||||
const schedule = [];
|
||||
for (let period = 1; period <= periods; period++) {
|
||||
const openingBalance = balance;
|
||||
const interest = divideRound(balance * periodicRate, RATE_SCALE);
|
||||
const isGrace = period <= gracePeriods;
|
||||
const isFinal = period === periods;
|
||||
const principalPayment = isGrace
|
||||
? 0n
|
||||
: isFinal
|
||||
? balance
|
||||
: regularPrincipalPayment - interest;
|
||||
if (principalPayment < 0n)
|
||||
throw new Error(
|
||||
'As condições não amortizam o capital; reveja a taxa e o prazo.',
|
||||
);
|
||||
balance -= principalPayment;
|
||||
const payment = principalPayment + interest;
|
||||
schedule.push({
|
||||
period,
|
||||
openingBalance: money(openingBalance),
|
||||
interest: money(interest),
|
||||
principal: money(principalPayment),
|
||||
fee: money(recurringFee),
|
||||
totalPayment: money(payment + recurringFee),
|
||||
closingBalance: money(balance),
|
||||
type: isGrace
|
||||
? ('interest_only' as const)
|
||||
: ('amortization' as const),
|
||||
});
|
||||
}
|
||||
const totalInterest = schedule.reduce(
|
||||
(total, row) => total + decimalToInteger(row.interest, 2, 'Juro'),
|
||||
0n,
|
||||
);
|
||||
const totalFees = upfrontFee + recurringFee * BigInt(periods);
|
||||
return {
|
||||
periodicRatePercent: ratePercent(periodicRate),
|
||||
netDisbursed: money(principal - upfrontFee),
|
||||
upfrontFee: money(upfrontFee),
|
||||
totalInterest: money(totalInterest),
|
||||
totalFees: money(totalFees),
|
||||
totalPaid: money(principal + totalInterest + totalFees),
|
||||
schedule,
|
||||
status: 'estimated' as const,
|
||||
};
|
||||
}
|
||||
|
||||
/** A simple one-period budget allows an operating deficit; it is not forced to zero. */
|
||||
export function calculateBudget(incomes: string[], expenses: string[]) {
|
||||
if (incomes.length === 0 || expenses.length === 0)
|
||||
throw new Error(
|
||||
'Introduza pelo menos uma linha de receitas e uma linha de despesas; use zero apenas quando esse valor for conhecido.',
|
||||
);
|
||||
const incomeTotal = incomes.reduce(
|
||||
(sum, value) => sum + decimalToInteger(value, 2, 'Receita'),
|
||||
0n,
|
||||
);
|
||||
const expenseTotal = expenses.reduce(
|
||||
(sum, value) => sum + decimalToInteger(value, 2, 'Despesa'),
|
||||
0n,
|
||||
);
|
||||
return {
|
||||
incomeTotal: money(incomeTotal),
|
||||
expenseTotal: money(expenseTotal),
|
||||
operatingBalance: money(incomeTotal - expenseTotal),
|
||||
status: 'estimated' as const,
|
||||
};
|
||||
}
|
||||
|
||||
type IndependentCalculation<T> = {
|
||||
value: T | null;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
function calculateIndependently<T>(
|
||||
operation: () => T,
|
||||
): IndependentCalculation<T> {
|
||||
try {
|
||||
return { value: operation(), error: null };
|
||||
} catch (cause) {
|
||||
return {
|
||||
value: null,
|
||||
error:
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Verifique os valores introduzidos.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function calculateFinancialTools(input: {
|
||||
loan: LoanScheduleInput;
|
||||
breakEven: {
|
||||
fixedCosts: string;
|
||||
unitPrice: string;
|
||||
variableCostPerUnit: string;
|
||||
};
|
||||
funding: { totalInvestment: string; securedFunding: string };
|
||||
incomes: string[];
|
||||
expenses: string[];
|
||||
}) {
|
||||
return {
|
||||
loan: calculateIndependently(() => buildLoanSchedule(input.loan)),
|
||||
breakEven: calculateIndependently(() =>
|
||||
calculateBreakEven(
|
||||
input.breakEven.fixedCosts,
|
||||
input.breakEven.unitPrice,
|
||||
input.breakEven.variableCostPerUnit,
|
||||
),
|
||||
),
|
||||
funding: calculateIndependently(() =>
|
||||
calculateFundingGap(
|
||||
input.funding.totalInvestment,
|
||||
input.funding.securedFunding,
|
||||
),
|
||||
),
|
||||
budget: calculateIndependently(() =>
|
||||
calculateBudget(input.incomes, input.expenses),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export type FinancialToolsReportInput = {
|
||||
currency: string;
|
||||
generatedAt?: string;
|
||||
budgetPeriod: string;
|
||||
loan: LoanScheduleInput;
|
||||
breakEven: {
|
||||
fixedCosts: string;
|
||||
unitPrice: string;
|
||||
variableCostPerUnit: string;
|
||||
};
|
||||
funding: { totalInvestment: string; securedFunding: string };
|
||||
incomes: { label: string; amount: string }[];
|
||||
expenses: { label: string; amount: string }[];
|
||||
};
|
||||
|
||||
/** Reproducible public report matching the independent calculator outputs. */
|
||||
export function exportFinancialToolsCsv(
|
||||
input: FinancialToolsReportInput,
|
||||
): string {
|
||||
const loan = buildLoanSchedule(input.loan);
|
||||
const breakEven = calculateBreakEven(
|
||||
input.breakEven.fixedCosts,
|
||||
input.breakEven.unitPrice,
|
||||
input.breakEven.variableCostPerUnit,
|
||||
);
|
||||
const funding = calculateFundingGap(
|
||||
input.funding.totalInvestment,
|
||||
input.funding.securedFunding,
|
||||
);
|
||||
const budget = calculateBudget(
|
||||
input.incomes.map((row) => row.amount),
|
||||
input.expenses.map((row) => row.amount),
|
||||
);
|
||||
const rows: (string | number)[][] = [
|
||||
['Relatório', 'Ferramentas de planeamento financeiro (indicativo)'],
|
||||
['Versão do modelo', 'financial-tools-v1'],
|
||||
['Data de exportação', input.generatedAt ?? new Date().toISOString()],
|
||||
['Moeda', input.currency],
|
||||
['Estado', 'Estimativa com pressupostos introduzidos pelo utilizador'],
|
||||
[
|
||||
'Fonte dos pressupostos',
|
||||
'Valores editaveis desta ferramenta; os valores iniciais sao exemplos demonstrativos',
|
||||
],
|
||||
['Período do orçamento e dos custos fixos', input.budgetPeriod],
|
||||
[
|
||||
'Fórmula da prestação',
|
||||
'Saldo decrescente; taxa nominal divide pelos períodos ou taxa efectiva convertida; última prestação ajusta resíduos',
|
||||
],
|
||||
[
|
||||
'Fórmula do ponto de equilíbrio',
|
||||
'custos fixos / (preço unitário - custo variável unitário), unidades arredondadas para cima',
|
||||
],
|
||||
[
|
||||
'Fórmula do financiamento',
|
||||
'investimento total - financiamento mobilizado; saldo negativo indica excedente declarado',
|
||||
],
|
||||
['Fórmula do orçamento', 'soma das receitas - soma das despesas'],
|
||||
[
|
||||
'Limitações',
|
||||
'Não é proposta bancária nem aconselhamento; não inclui impostos; taxas e condições são pressupostos do utilizador.',
|
||||
],
|
||||
[],
|
||||
['Pressupostos do empréstimo'],
|
||||
['Capital', input.loan.principal],
|
||||
['Taxa anual (%)', input.loan.annualRatePercent],
|
||||
['Tipo de taxa', input.loan.rateType],
|
||||
['Prazo (meses)', input.loan.termMonths],
|
||||
['Periodicidade (meses)', input.loan.periodMonths],
|
||||
['Carência (períodos)', input.loan.gracePeriods ?? 0],
|
||||
['Comissão inicial', input.loan.upfrontFee ?? '0'],
|
||||
['Comissão periódica', input.loan.recurringFee ?? '0'],
|
||||
['Taxa por período (%)', loan.periodicRatePercent],
|
||||
['Desembolso líquido', loan.netDisbursed],
|
||||
['Juros totais', loan.totalInterest],
|
||||
['Comissões totais', loan.totalFees],
|
||||
['Total pago', loan.totalPaid],
|
||||
[],
|
||||
['Pressupostos do ponto de equilíbrio'],
|
||||
['Custos fixos do período', input.breakEven.fixedCosts],
|
||||
['Preço unitário', input.breakEven.unitPrice],
|
||||
['Custo variável unitário', input.breakEven.variableCostPerUnit],
|
||||
['Margem de contribuição unitária', breakEven.contributionPerUnit],
|
||||
['Unidades de equilíbrio', breakEven.breakEvenUnits],
|
||||
['Receita de equilíbrio', breakEven.breakEvenRevenue],
|
||||
[],
|
||||
['Necessidade de financiamento'],
|
||||
['Investimento total', input.funding.totalInvestment],
|
||||
['Financiamento mobilizado', input.funding.securedFunding],
|
||||
['Diferença por financiar', funding.gap],
|
||||
[],
|
||||
['Orçamento', input.currency],
|
||||
['Categoria', 'Descrição', 'Montante'],
|
||||
...input.incomes.map((row) => ['Receita', row.label, row.amount]),
|
||||
...input.expenses.map((row) => ['Despesa', row.label, row.amount]),
|
||||
['Total de receitas', '', budget.incomeTotal],
|
||||
['Total de despesas', '', budget.expenseTotal],
|
||||
['Saldo operacional', '', budget.operatingBalance],
|
||||
[],
|
||||
['Plano de reembolso', input.currency],
|
||||
[
|
||||
'Período',
|
||||
'Saldo inicial',
|
||||
'Juros',
|
||||
'Capital',
|
||||
'Comissão',
|
||||
'Prestação total',
|
||||
'Saldo final',
|
||||
],
|
||||
...loan.schedule.map((row) => [
|
||||
row.period,
|
||||
row.openingBalance,
|
||||
row.interest,
|
||||
row.principal,
|
||||
row.fee,
|
||||
row.totalPayment,
|
||||
row.closingBalance,
|
||||
]),
|
||||
];
|
||||
return `\uFEFF${rows.map((row) => row.map(csvCell).join(',')).join('\r\n')}`;
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import type { forecastBusinessPlan } from '@/lib/business-financial-plan';
|
||||
|
||||
type Forecast = ReturnType<typeof forecastBusinessPlan>;
|
||||
|
||||
export type FinancialFiscalLine = {
|
||||
code:
|
||||
| 'revenue'
|
||||
| 'cost_of_sales'
|
||||
| 'operating_expenses'
|
||||
| 'personnel'
|
||||
| 'depreciation'
|
||||
| 'interest_expense';
|
||||
origin: string;
|
||||
accountingEffect: 'income' | 'expense';
|
||||
taxTreatment: 'unclassified';
|
||||
total: string;
|
||||
monthlyAmounts: Array<{ period: number; amount: string }>;
|
||||
};
|
||||
|
||||
function cents(value: string): bigint {
|
||||
const match = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(value);
|
||||
if (!match)
|
||||
throw new Error('O resultado financeiro contém um montante inválido.');
|
||||
const amount =
|
||||
BigInt(match[2]) * 100n +
|
||||
BigInt((match[3] ?? '').padEnd(2, '0') || '0');
|
||||
return match[1] ? -amount : amount;
|
||||
}
|
||||
|
||||
function formatCents(value: bigint): string {
|
||||
const absolute = value < 0n ? -value : value;
|
||||
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function assertForecastReconciles(forecast: Forecast): void {
|
||||
if (forecast.rows.length === 0)
|
||||
throw new Error(
|
||||
'A previsão financeira não contém períodos para mapear.',
|
||||
);
|
||||
|
||||
let accountingProfit = 0n;
|
||||
let totalRevenue = 0n;
|
||||
let totalCollections = 0n;
|
||||
let cumulativeNetCashFlow = 0n;
|
||||
let previousClosingCash = cents(forecast.openingCashAfterInitialUses);
|
||||
let previousOpeningReceivables = cents(forecast.openingReceivables);
|
||||
let totalOpeningReceivablesCollections = 0n;
|
||||
let previousPeriod = 0;
|
||||
|
||||
for (const row of forecast.rows) {
|
||||
if (!Number.isSafeInteger(row.month) || row.month <= previousPeriod)
|
||||
throw new Error(
|
||||
'Os períodos da previsão financeira não estão em ordem.',
|
||||
);
|
||||
previousPeriod = row.month;
|
||||
|
||||
const revenue = cents(String(row.revenue));
|
||||
totalRevenue += revenue;
|
||||
accountingProfit += revenue;
|
||||
for (const field of [
|
||||
'variableCost',
|
||||
'operatingExpenses',
|
||||
'payrollExpense',
|
||||
'depreciation',
|
||||
'interestExpense',
|
||||
] as const) {
|
||||
accountingProfit -= cents(String(row[field]));
|
||||
}
|
||||
|
||||
const salesCollections =
|
||||
row.salesCollections === null
|
||||
? 0n
|
||||
: cents(String(row.salesCollections));
|
||||
const openingReceivablesCollections = cents(
|
||||
String(row.openingReceivablesCollections),
|
||||
);
|
||||
const openingReceivablesBalance = cents(
|
||||
String(row.openingReceivablesBalance),
|
||||
);
|
||||
if (
|
||||
openingReceivablesBalance !==
|
||||
previousOpeningReceivables - openingReceivablesCollections
|
||||
)
|
||||
throw new Error(
|
||||
'O saldo de recebíveis de abertura não reconcilia com as cobranças do período.',
|
||||
);
|
||||
previousOpeningReceivables = openingReceivablesBalance;
|
||||
totalOpeningReceivablesCollections += openingReceivablesCollections;
|
||||
const otherCollections =
|
||||
row.otherCollections === null
|
||||
? cents(String(row.cashCollections)) -
|
||||
salesCollections -
|
||||
openingReceivablesCollections
|
||||
: cents(String(row.otherCollections));
|
||||
if (otherCollections < 0n)
|
||||
throw new Error(
|
||||
'A previsão financeira contém cobranças reconciliadas inválidas.',
|
||||
);
|
||||
|
||||
const collections = cents(String(row.cashCollections));
|
||||
if (
|
||||
collections !==
|
||||
salesCollections + openingReceivablesCollections + otherCollections
|
||||
)
|
||||
throw new Error(
|
||||
'As cobranças mensais não reconciliam com as suas origens.',
|
||||
);
|
||||
totalCollections += collections;
|
||||
|
||||
const netCashFlow =
|
||||
collections -
|
||||
cents(String(row.variableCostPayments)) -
|
||||
cents(String(row.operatingPayments)) -
|
||||
cents(String(row.payrollPayments)) -
|
||||
cents(String(row.interestPayment)) -
|
||||
cents(String(row.principalRepayment));
|
||||
if (netCashFlow !== cents(String(row.netCashFlow)))
|
||||
throw new Error(
|
||||
'O fluxo líquido mensal não reconcilia com recebimentos e pagamentos.',
|
||||
);
|
||||
const closingCash = cents(String(row.closingCash));
|
||||
if (closingCash !== previousClosingCash + netCashFlow)
|
||||
throw new Error(
|
||||
'O saldo de caixa mensal não reconcilia com o período anterior.',
|
||||
);
|
||||
previousClosingCash = closingCash;
|
||||
cumulativeNetCashFlow += netCashFlow;
|
||||
}
|
||||
|
||||
if (accountingProfit !== cents(forecast.totalProfitBeforeTax))
|
||||
throw new Error(
|
||||
'O resultado contabilístico não reconcilia com as linhas mapeadas.',
|
||||
);
|
||||
if (totalRevenue !== cents(forecast.totalRevenue))
|
||||
throw new Error(
|
||||
'A facturação total não reconcilia com os períodos mapeados.',
|
||||
);
|
||||
if (totalCollections !== cents(forecast.totalCashCollections))
|
||||
throw new Error(
|
||||
'As cobranças totais não reconciliam com o calendário de caixa.',
|
||||
);
|
||||
if (
|
||||
totalOpeningReceivablesCollections !==
|
||||
cents(forecast.totalOpeningReceivablesCollections) ||
|
||||
previousOpeningReceivables !== cents(forecast.openingReceivablesAtEnd)
|
||||
)
|
||||
throw new Error(
|
||||
'Os recebíveis de abertura não reconciliam com a previsão final.',
|
||||
);
|
||||
if (
|
||||
previousClosingCash !== cents(forecast.endingCash) ||
|
||||
cumulativeNetCashFlow !==
|
||||
cents(forecast.endingCash) -
|
||||
cents(forecast.openingCashAfterInitialUses)
|
||||
)
|
||||
throw new Error(
|
||||
'O saldo final de caixa não reconcilia com o calendário mensal.',
|
||||
);
|
||||
}
|
||||
|
||||
/** Maps accounting figures into a reviewable tax-input draft without deciding tax treatment. */
|
||||
export function buildFinancialFiscalBridge(forecast: Forecast) {
|
||||
assertForecastReconciles(forecast);
|
||||
const definitions: Array<
|
||||
Pick<
|
||||
FinancialFiscalLine,
|
||||
'code' | 'origin' | 'accountingEffect' | 'taxTreatment'
|
||||
> & { field: keyof Forecast['rows'][number] }
|
||||
> = [
|
||||
{
|
||||
code: 'revenue',
|
||||
origin: 'Produtos/serviços facturados',
|
||||
accountingEffect: 'income',
|
||||
taxTreatment: 'unclassified',
|
||||
field: 'revenue',
|
||||
},
|
||||
{
|
||||
code: 'cost_of_sales',
|
||||
origin: 'Custo variável dos produtos',
|
||||
accountingEffect: 'expense',
|
||||
taxTreatment: 'unclassified',
|
||||
field: 'variableCost',
|
||||
},
|
||||
{
|
||||
code: 'operating_expenses',
|
||||
origin: 'Despesas operacionais reconhecidas',
|
||||
accountingEffect: 'expense',
|
||||
taxTreatment: 'unclassified',
|
||||
field: 'operatingExpenses',
|
||||
},
|
||||
{
|
||||
code: 'personnel',
|
||||
origin: 'Despesas com pessoal reconhecidas',
|
||||
accountingEffect: 'expense',
|
||||
taxTreatment: 'unclassified',
|
||||
field: 'payrollExpense',
|
||||
},
|
||||
{
|
||||
code: 'depreciation',
|
||||
origin: 'Depreciação contabilística',
|
||||
accountingEffect: 'expense',
|
||||
taxTreatment: 'unclassified',
|
||||
field: 'depreciation',
|
||||
},
|
||||
{
|
||||
code: 'interest_expense',
|
||||
origin: 'Juros reconhecidos',
|
||||
accountingEffect: 'expense',
|
||||
taxTreatment: 'unclassified',
|
||||
field: 'interestExpense',
|
||||
},
|
||||
];
|
||||
const accountingLines: FinancialFiscalLine[] = definitions.map(
|
||||
({ field, ...definition }) => {
|
||||
const monthlyAmounts = forecast.rows.map((row) => ({
|
||||
period: row.month,
|
||||
amount: String(row[field]),
|
||||
}));
|
||||
return {
|
||||
...definition,
|
||||
total: formatCents(
|
||||
monthlyAmounts.reduce(
|
||||
(sum, row) => sum + cents(row.amount),
|
||||
0n,
|
||||
),
|
||||
),
|
||||
monthlyAmounts,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
status: 'incomplete' as const,
|
||||
currency: forecast.currency,
|
||||
accountingProfitBeforeTax: forecast.totalProfitBeforeTax,
|
||||
taxableBase: {
|
||||
status: 'indeterminate' as const,
|
||||
amount: null,
|
||||
missingInputs: [
|
||||
'expense_deductibility_classification',
|
||||
'approved_tax_adjustments',
|
||||
'applicable_tax_period',
|
||||
'approved_effective_rule',
|
||||
],
|
||||
},
|
||||
accountingLines,
|
||||
cashSchedule: forecast.rows.map((row) => ({
|
||||
period: row.month,
|
||||
collectionMode:
|
||||
row.salesCollections === null
|
||||
? ('manual' as const)
|
||||
: ('scheduled' as const),
|
||||
salesCollections: row.salesCollections,
|
||||
openingReceivablesCollections: row.openingReceivablesCollections,
|
||||
openingReceivablesBalance: row.openingReceivablesBalance,
|
||||
otherCollections:
|
||||
row.otherCollections ??
|
||||
formatCents(
|
||||
cents(row.cashCollections) -
|
||||
(row.salesCollections === null
|
||||
? 0n
|
||||
: cents(row.salesCollections)) -
|
||||
cents(row.openingReceivablesCollections),
|
||||
),
|
||||
collections: row.cashCollections,
|
||||
collectionsTotal: row.cashCollections,
|
||||
salesReceivablesBalance: row.salesReceivablesClosing,
|
||||
supplierPayments: row.variableCostPayments,
|
||||
operatingPayments: row.operatingPayments,
|
||||
personnelPayments: row.payrollPayments,
|
||||
interestPayments: row.interestPayment,
|
||||
principalRepayments: row.principalRepayment,
|
||||
netCashFlow: row.netCashFlow,
|
||||
closingCash: row.closingCash,
|
||||
})),
|
||||
notes: [
|
||||
'A classificação fiscal das linhas contabilísticas está pendente; este mapeamento não afirma dedutibilidade.',
|
||||
'Cobranças e pagamentos são fluxos de caixa separados das receitas e despesas reconhecidas.',
|
||||
'Reembolsos de capital aparecem apenas no calendário de caixa e não como despesa contabilística.',
|
||||
'Nenhum imposto, contribuição, retenção ou pagamento fiscal é somado como zero ou estimado nesta ponte.',
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
import { csvCell } from './csv.js';
|
||||
|
||||
export type MonthlyCashflowInput = {
|
||||
openingCash: string;
|
||||
monthlyRevenue: string;
|
||||
monthlyOperatingCosts: string;
|
||||
monthlyDebtService: string;
|
||||
/** Empty/omitted means unknown; enter "0" to explicitly declare zero tax. */
|
||||
monthlyTaxAssessed?: string | null;
|
||||
/** Optional per-period user assumptions; null/blank means unknown for that month. */
|
||||
monthlyTaxSchedule?: (string | null)[];
|
||||
vatCreditEstimated?: string;
|
||||
vatRefundRequested?: string;
|
||||
vatRefundRecognized?: string;
|
||||
vatRefundExpectedReceipt?: string;
|
||||
vatRefundExpectedMonth?: string;
|
||||
currency?: string;
|
||||
periods?: number;
|
||||
};
|
||||
|
||||
function cents(value: string, label: string): bigint {
|
||||
const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(value.trim());
|
||||
if (!match)
|
||||
throw new Error(
|
||||
`${label}: introduza um montante não negativo com até duas casas decimais.`,
|
||||
);
|
||||
return (
|
||||
BigInt(match[1]) * 100n + BigInt((match[2] ?? '').padEnd(2, '0') || '0')
|
||||
);
|
||||
}
|
||||
|
||||
function signedCents(value: string, label: string): bigint {
|
||||
const match = /^(-?\d+)(?:\.(\d{1,2}))?$/.exec(value.trim());
|
||||
if (!match)
|
||||
throw new Error(
|
||||
`${label}: introduza um montante com até duas casas decimais.`,
|
||||
);
|
||||
const sign = match[1].startsWith('-') ? -1n : 1n;
|
||||
return (
|
||||
sign *
|
||||
(BigInt(match[1].replace('-', '')) * 100n +
|
||||
BigInt((match[2] ?? '').padEnd(2, '0') || '0'))
|
||||
);
|
||||
}
|
||||
|
||||
function money(value: bigint): string {
|
||||
const absolute = value < 0n ? -value : value;
|
||||
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** 12-period cashflow. VAT stages are informational except an explicitly assumed receipt month. */
|
||||
export function projectMonthlyCashflow(input: MonthlyCashflowInput) {
|
||||
if (input.currency) {
|
||||
try {
|
||||
if (
|
||||
new Intl.NumberFormat('en', {
|
||||
style: 'currency',
|
||||
currency: input.currency,
|
||||
}).resolvedOptions().maximumFractionDigits !== 2
|
||||
)
|
||||
throw new Error(
|
||||
'Esta ferramenta requer moeda com duas casas decimais.',
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof Error && cause.message.includes('duas casas'))
|
||||
throw cause;
|
||||
throw new Error(
|
||||
'Seleccione uma moeda suportada com duas casas decimais.',
|
||||
);
|
||||
}
|
||||
}
|
||||
const periods = input.periods ?? 12;
|
||||
if (!Number.isSafeInteger(periods) || periods < 1 || periods > 60)
|
||||
throw new Error('O período deve estar entre 1 e 60 meses.');
|
||||
let closingBeforeUnassessedTax = signedCents(
|
||||
input.openingCash,
|
||||
'Saldo inicial',
|
||||
);
|
||||
let closingWithAssessedTax: bigint | null = closingBeforeUnassessedTax;
|
||||
const revenue = cents(input.monthlyRevenue, 'Receita mensal');
|
||||
const costs = cents(input.monthlyOperatingCosts, 'Custos operacionais');
|
||||
const debt = cents(input.monthlyDebtService, 'Serviço da dívida');
|
||||
const scalarTaxKnown =
|
||||
typeof input.monthlyTaxAssessed === 'string' &&
|
||||
input.monthlyTaxAssessed.trim() !== '';
|
||||
if (input.monthlyTaxSchedule !== undefined && scalarTaxKnown)
|
||||
throw new Error(
|
||||
'Use o imposto mensal fixo ou o calendário por mês, não ambos.',
|
||||
);
|
||||
let taxSchedule: (bigint | null)[];
|
||||
if (input.monthlyTaxSchedule !== undefined) {
|
||||
if (
|
||||
!Array.isArray(input.monthlyTaxSchedule) ||
|
||||
input.monthlyTaxSchedule.length !== periods ||
|
||||
input.monthlyTaxSchedule.some(
|
||||
(value) => value !== null && typeof value !== 'string',
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'O calendário do imposto deve conter um valor ou campo vazio para cada mês projectado.',
|
||||
);
|
||||
}
|
||||
taxSchedule = input.monthlyTaxSchedule.map((value, index) =>
|
||||
typeof value === 'string' && value.trim() !== ''
|
||||
? cents(value, `Imposto apurado no mês ${index + 1}`)
|
||||
: null,
|
||||
);
|
||||
} else {
|
||||
const tax = scalarTaxKnown
|
||||
? cents(input.monthlyTaxAssessed as string, 'Imposto apurado')
|
||||
: null;
|
||||
taxSchedule = Array.from({ length: periods }, () => tax);
|
||||
}
|
||||
const hasUnassessedTax = taxSchedule.some((tax) => tax === null);
|
||||
const vatEstimate = cents(
|
||||
input.vatCreditEstimated ?? '0',
|
||||
'Crédito de IVA estimado',
|
||||
);
|
||||
const vatRequested = cents(
|
||||
input.vatRefundRequested ?? '0',
|
||||
'Reembolso de IVA pedido',
|
||||
);
|
||||
const vatRecognized = cents(
|
||||
input.vatRefundRecognized ?? '0',
|
||||
'Reembolso de IVA reconhecido',
|
||||
);
|
||||
const vatReceipt = cents(
|
||||
input.vatRefundExpectedReceipt ?? '0',
|
||||
'Recebimento previsto de IVA',
|
||||
);
|
||||
if (vatReceipt > vatRecognized) {
|
||||
throw new Error(
|
||||
'O recebimento previsto de IVA não pode exceder o montante reconhecido.',
|
||||
);
|
||||
}
|
||||
const receiptMonth = input.vatRefundExpectedMonth
|
||||
? Number(input.vatRefundExpectedMonth)
|
||||
: 0;
|
||||
if (
|
||||
vatReceipt > 0n &&
|
||||
(!Number.isSafeInteger(receiptMonth) ||
|
||||
receiptMonth < 1 ||
|
||||
receiptMonth > periods)
|
||||
) {
|
||||
throw new Error(
|
||||
'Indique o mês previsto do recebimento entre 1 e o horizonte projectado.',
|
||||
);
|
||||
}
|
||||
void vatEstimate;
|
||||
void vatRequested;
|
||||
void vatRecognized;
|
||||
const rows = [];
|
||||
for (let month = 1; month <= periods; month++) {
|
||||
const openingBeforeUnassessedTax = closingBeforeUnassessedTax;
|
||||
const openingWithAssessedTax = closingWithAssessedTax;
|
||||
const refundReceived =
|
||||
vatReceipt > 0n && receiptMonth === month ? vatReceipt : 0n;
|
||||
const tax = taxSchedule[month - 1];
|
||||
const netFlowBeforeUnassessedTax =
|
||||
revenue - costs - debt + refundReceived - (tax ?? 0n);
|
||||
const netFlowWithAssessedTax =
|
||||
tax === null ? null : revenue - costs - debt + refundReceived - tax;
|
||||
closingBeforeUnassessedTax += netFlowBeforeUnassessedTax;
|
||||
if (closingWithAssessedTax !== null) {
|
||||
closingWithAssessedTax =
|
||||
netFlowWithAssessedTax === null
|
||||
? null
|
||||
: closingWithAssessedTax + netFlowWithAssessedTax;
|
||||
}
|
||||
rows.push({
|
||||
month,
|
||||
openingCashBeforeUnassessedTax: money(openingBeforeUnassessedTax),
|
||||
openingCash:
|
||||
openingWithAssessedTax === null
|
||||
? null
|
||||
: money(openingWithAssessedTax),
|
||||
revenue: money(revenue),
|
||||
operatingCosts: money(costs),
|
||||
debtService: money(debt),
|
||||
taxAssessed: tax === null ? null : money(tax),
|
||||
vatRefundExpectedReceipt: money(refundReceived),
|
||||
netFlowBeforeUnassessedTax: money(netFlowBeforeUnassessedTax),
|
||||
closingCashBeforeUnassessedTax: money(closingBeforeUnassessedTax),
|
||||
netFlow:
|
||||
netFlowWithAssessedTax === null
|
||||
? null
|
||||
: money(netFlowWithAssessedTax),
|
||||
closingCash:
|
||||
closingWithAssessedTax === null
|
||||
? null
|
||||
: money(closingWithAssessedTax),
|
||||
});
|
||||
}
|
||||
return {
|
||||
rows,
|
||||
endingCash:
|
||||
closingWithAssessedTax === null
|
||||
? null
|
||||
: money(closingWithAssessedTax),
|
||||
endingCashBeforeUnassessedTax: money(closingBeforeUnassessedTax),
|
||||
firstDeficitMonth:
|
||||
rows.find(
|
||||
(row) =>
|
||||
row.closingCash !== null &&
|
||||
BigInt(row.closingCash.replace('.', '')) < 0n,
|
||||
)?.month ?? null,
|
||||
firstDeficitMonthBeforeUnassessedTax:
|
||||
rows.find(
|
||||
(row) =>
|
||||
BigInt(
|
||||
row.closingCashBeforeUnassessedTax.replace('.', ''),
|
||||
) < 0n,
|
||||
)?.month ?? null,
|
||||
vatCreditEstimated: money(vatEstimate),
|
||||
vatRefundRequested: money(vatRequested),
|
||||
vatRefundRecognized: money(vatRecognized),
|
||||
vatRefundExpectedReceipt: money(vatReceipt),
|
||||
status: hasUnassessedTax
|
||||
? ('incomplete' as const)
|
||||
: ('estimated' as const),
|
||||
};
|
||||
}
|
||||
|
||||
/** CSV contains only assumptions and derived financial rows supplied/calculated in this browser. */
|
||||
export function exportMonthlyCashflowCsv(
|
||||
input: MonthlyCashflowInput,
|
||||
exportedAt = new Date().toISOString(),
|
||||
): string {
|
||||
if (!input.currency)
|
||||
throw new Error('Seleccione a moeda antes de exportar.');
|
||||
const projection = projectMonthlyCashflow(input);
|
||||
const rows = [
|
||||
['Relatório', 'Projecção educativa de tesouraria'],
|
||||
['Versão do modelo', 'monthly-cashflow-v1'],
|
||||
['Data de exportação', exportedAt],
|
||||
['Horizonte', `${projection.rows.length} meses`],
|
||||
['Estado', projection.status],
|
||||
['Moeda', input.currency ?? 'Não seleccionada'],
|
||||
[
|
||||
'Fonte dos pressupostos',
|
||||
'Valores do formulário; os valores pré-preenchidos podem ser exemplos demonstrativos',
|
||||
],
|
||||
['Pressupostos', 'Saldo inicial', input.openingCash],
|
||||
['Pressupostos', 'Receita mensal', input.monthlyRevenue],
|
||||
[
|
||||
'Pressupostos',
|
||||
'Custos operacionais mensais',
|
||||
input.monthlyOperatingCosts,
|
||||
],
|
||||
['Pressupostos', 'Serviço mensal da dívida', input.monthlyDebtService],
|
||||
[
|
||||
'Pressupostos',
|
||||
'Imposto assumido na projecção (saída de caixa)',
|
||||
input.monthlyTaxSchedule === undefined
|
||||
? input.monthlyTaxAssessed?.trim() ||
|
||||
'indeterminado; não informado'
|
||||
: 'Calendário variável; consultar valores mensais abaixo',
|
||||
],
|
||||
...(input.monthlyTaxSchedule === undefined
|
||||
? []
|
||||
: input.monthlyTaxSchedule.map((value, index) => [
|
||||
'Pressuposto mensal de imposto',
|
||||
`Mês ${index + 1}`,
|
||||
value?.trim() || 'indeterminado; não informado',
|
||||
])),
|
||||
[
|
||||
'Informativo; não caixa',
|
||||
'Crédito de IVA estimado',
|
||||
input.vatCreditEstimated ?? '0',
|
||||
],
|
||||
[
|
||||
'Informativo; não caixa',
|
||||
'Pedido de reembolso de IVA',
|
||||
input.vatRefundRequested ?? '0',
|
||||
],
|
||||
[
|
||||
'Informativo; não caixa',
|
||||
'Reembolso de IVA reconhecido',
|
||||
input.vatRefundRecognized ?? '0',
|
||||
],
|
||||
[
|
||||
'Pressuposto condicional de caixa',
|
||||
'Recebimento previsto de reembolso IVA',
|
||||
input.vatRefundExpectedReceipt ?? '0',
|
||||
],
|
||||
[
|
||||
'Pressuposto condicional de caixa',
|
||||
'Mês previsto do recebimento IVA',
|
||||
input.vatRefundExpectedMonth ?? 'não indicado',
|
||||
],
|
||||
[],
|
||||
[
|
||||
'Mês',
|
||||
'Saldo inicial',
|
||||
'Receitas',
|
||||
'Custos operacionais',
|
||||
'Serviço da dívida',
|
||||
'Imposto assumido',
|
||||
'Recebimento IVA previsto',
|
||||
'Fluxo líquido',
|
||||
'Saldo final',
|
||||
'Fluxo conhecido antes de imposto não informado',
|
||||
'Caixa conhecida antes de imposto não informado',
|
||||
],
|
||||
...projection.rows.map((row) => [
|
||||
row.month,
|
||||
row.openingCash ?? 'indeterminado',
|
||||
row.revenue,
|
||||
row.operatingCosts,
|
||||
row.debtService,
|
||||
row.taxAssessed ?? 'indeterminado',
|
||||
row.vatRefundExpectedReceipt,
|
||||
row.netFlow ?? 'indeterminado',
|
||||
row.closingCash ?? 'indeterminado',
|
||||
row.netFlowBeforeUnassessedTax,
|
||||
row.closingCashBeforeUnassessedTax,
|
||||
]),
|
||||
[],
|
||||
[
|
||||
'Nota',
|
||||
'O imposto indicado é pressuposto do utilizador, não cálculo ou confirmação de obrigação fiscal. Meses sem pressuposto deixam o saldo total indeterminado; a caixa conhecida inclui impostos declarados e omite apenas os meses sem valor. Recebimento previsto é pressuposto não garantido. Crédito estimado, pedido e montante reconhecido não entram no caixa. Projecção exclui sazonalidade e movimentos pontuais.',
|
||||
],
|
||||
];
|
||||
return `\uFEFF${rows
|
||||
.map((row) => row.map(csvCell).join(','))
|
||||
.join('\r\n')}`;
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
import {
|
||||
AlignmentType,
|
||||
BorderStyle,
|
||||
Document,
|
||||
Footer,
|
||||
HeadingLevel,
|
||||
ImageRun,
|
||||
Packer,
|
||||
Paragraph,
|
||||
SimpleField,
|
||||
ShadingType,
|
||||
Table,
|
||||
TableCell,
|
||||
TableLayoutType,
|
||||
TableRow,
|
||||
TextRun,
|
||||
WidthType,
|
||||
} from 'docx';
|
||||
import JSZip from 'jszip';
|
||||
import { buildProjectDossierRows, type ProjectDossierRow } from './project-dossier.ts';
|
||||
|
||||
export const dossierReportSections = [
|
||||
{ id: 'summary', title: 'Resumo executivo', private: true },
|
||||
{ id: 'project', title: 'Identificação e descrição do projecto', private: true },
|
||||
{ id: 'market', title: 'Mercado e hipóteses', private: true },
|
||||
{ id: 'location', title: 'Localização', private: true },
|
||||
{ id: 'finance', title: 'Plano financeiro e cálculos', private: true },
|
||||
{ id: 'team', title: 'Equipa, competências e lacunas', private: true },
|
||||
{ id: 'resources', title: 'Recursos e financiamento', private: true },
|
||||
{ id: 'risk', title: 'O que precisa de esclarecer: riscos e respostas', private: true },
|
||||
{ id: 'execution', title: 'Marcos e execução', private: true },
|
||||
{ id: 'sources', title: 'Fontes, pendências e próximos passos', private: true },
|
||||
{ id: 'annexes', title: 'Anexos seleccionados', private: true },
|
||||
] as const;
|
||||
|
||||
export type DossierReportSectionId = (typeof dossierReportSections)[number]['id'];
|
||||
export type DossierReference = {
|
||||
version: number;
|
||||
date: string;
|
||||
checksum: string;
|
||||
};
|
||||
export type DossierCurrentCalculation = {
|
||||
status: string;
|
||||
version: number;
|
||||
updatedAt?: string;
|
||||
snapshot: Record<string, unknown> | null;
|
||||
reportChecksum?: string;
|
||||
};
|
||||
export type DossierAttachment = {
|
||||
file: File;
|
||||
include: boolean;
|
||||
caption: string;
|
||||
};
|
||||
export type DossierAttachmentKind = 'image' | 'csv' | 'text' | 'original-only';
|
||||
export type DossierReportRow = {
|
||||
field: string;
|
||||
value: string;
|
||||
origin: string;
|
||||
classification: string;
|
||||
};
|
||||
export type DossierReportSection = {
|
||||
id: DossierReportSectionId;
|
||||
title: string;
|
||||
private: boolean;
|
||||
paragraphs: string[];
|
||||
rows: DossierReportRow[];
|
||||
};
|
||||
export type DossierReportModel = {
|
||||
title: string;
|
||||
generatedAt: string;
|
||||
version: string;
|
||||
sections: DossierReportSection[];
|
||||
references: DossierReference[];
|
||||
limitations: string[];
|
||||
};
|
||||
|
||||
export const MAX_DOSSIER_ATTACHMENT_COUNT = 10;
|
||||
export const MAX_DOSSIER_ATTACHMENT_BYTES = 15 * 1024 * 1024;
|
||||
export const MAX_DOSSIER_ATTACHMENT_TOTAL_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_EMBEDDED_TEXT_BYTES = 2 * 1024 * 1024;
|
||||
const MAX_EMBEDDED_CSV_ROWS = 250;
|
||||
const MAX_EMBEDDED_CSV_COLUMNS = 16;
|
||||
|
||||
function text(draft: Record<string, string | string[]>, key: string): string {
|
||||
const value = draft[key];
|
||||
if (Array.isArray(value)) return value.filter(Boolean).join(', ');
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function absent(value: string): string {
|
||||
return value.trim() === '' ? 'Não informado' : value;
|
||||
}
|
||||
|
||||
function classification(origin: string): string {
|
||||
const normal = origin.toLocaleLowerCase('pt-MZ');
|
||||
if (normal.includes('não verificada') || normal.includes('nao verificada')) return 'Informação declarada, não verificada';
|
||||
if (normal.includes('estimativa') || normal.includes('estimado')) return 'Estimativa';
|
||||
if (normal.includes('indeterminado') || normal.includes('insuficiente') || normal.includes('não informado')) return 'Indeterminado';
|
||||
if (normal.includes('catálogo') || normal.includes('catalogo')) return 'Referência de catálogo; não equivale a verificação documental';
|
||||
if (normal.includes('utilizador') || normal.includes('declarada') || normal.includes('declarado') || normal.includes('pressuposto')) return 'Informação declarada ou pressuposto';
|
||||
return 'Referência/estado indicado';
|
||||
}
|
||||
|
||||
const rowSection: Record<string, DossierReportSectionId> = {
|
||||
Projecto: 'project',
|
||||
Mercado: 'market',
|
||||
Localização: 'location',
|
||||
'Plano financeiro': 'finance',
|
||||
'Empréstimo educativo': 'finance',
|
||||
'Ponto de equilíbrio': 'finance',
|
||||
Orçamento: 'finance',
|
||||
Equipa: 'team',
|
||||
'Necessidade de negócio': 'resources',
|
||||
Financiamento: 'resources',
|
||||
Risco: 'risk',
|
||||
Execução: 'execution',
|
||||
};
|
||||
|
||||
function makeSections(
|
||||
draft: Record<string, string | string[]>,
|
||||
rows: ProjectDossierRow[],
|
||||
selectedSections: ReadonlySet<DossierReportSectionId>,
|
||||
references: DossierReference[],
|
||||
currentCalculation: DossierCurrentCalculation | null,
|
||||
generatedAt: string,
|
||||
version: string,
|
||||
): DossierReportSection[] {
|
||||
const sections = new Map<DossierReportSectionId, DossierReportSection>();
|
||||
for (const section of dossierReportSections) {
|
||||
if (!selectedSections.has(section.id)) continue;
|
||||
sections.set(section.id, {
|
||||
id: section.id,
|
||||
title: section.title,
|
||||
private: section.private,
|
||||
paragraphs: [],
|
||||
rows: [],
|
||||
});
|
||||
}
|
||||
|
||||
const summary = sections.get('summary');
|
||||
if (summary) {
|
||||
const suppliedSummary = text(draft, 'project_summary');
|
||||
const summaryParts = [
|
||||
suppliedSummary,
|
||||
!suppliedSummary && text(draft, 'project_title') ? `Projecto: ${text(draft, 'project_title')}.` : '',
|
||||
!suppliedSummary && text(draft, 'project_problem') ? `Necessidade abordada: ${text(draft, 'project_problem')}.` : '',
|
||||
!suppliedSummary && text(draft, 'value_proposition') ? `Proposta de valor declarada: ${text(draft, 'value_proposition')}.` : '',
|
||||
!suppliedSummary && text(draft, 'target_customers') ? `Clientes/beneficiários indicados: ${text(draft, 'target_customers')}.` : '',
|
||||
].filter(Boolean);
|
||||
summary.paragraphs.push(summaryParts.length ? summaryParts.join(' ') : 'Resumo executivo pendente: ainda não foram introduzidas informações suficientes no dossier.');
|
||||
summary.rows.push(
|
||||
{ field: 'Projecto', value: absent(text(draft, 'project_title')), origin: 'Informação introduzida no dossier', classification: 'Declarada pelo utilizador' },
|
||||
{ field: 'Data de geração', value: new Date(generatedAt).toLocaleString('pt-MZ'), origin: 'Relógio do dispositivo no momento da exportação', classification: 'Metadado do relatório' },
|
||||
{ field: 'Versão/revisão do dossier', value: version, origin: 'Revisão de rascunho guardada ou impressão digital local', classification: 'Metadado técnico' },
|
||||
);
|
||||
}
|
||||
|
||||
for (const [sectionName, field, value, origin] of rows.slice(1)) {
|
||||
const id = rowSection[sectionName];
|
||||
if (!id) continue;
|
||||
const section = sections.get(id);
|
||||
if (!section) continue;
|
||||
section.rows.push({ field, value: absent(value), origin, classification: classification(origin) });
|
||||
}
|
||||
|
||||
const project = sections.get('project');
|
||||
if (project) {
|
||||
const extra = [
|
||||
['Data prevista de início', text(draft, 'expected_start_date')],
|
||||
['Duração prevista', text(draft, 'project_duration_years')],
|
||||
];
|
||||
for (const [field, value] of extra) {
|
||||
if (!project.rows.some((row) => row.field === field)) project.rows.push({ field, value: absent(value), origin: 'Informação do dossier', classification: value ? 'Declarada pelo utilizador' : 'Indeterminado' });
|
||||
}
|
||||
}
|
||||
|
||||
const location = sections.get('location');
|
||||
if (location) {
|
||||
for (const [field, key] of [
|
||||
['País', 'country_id_label'], ['Província', 'province_id_label'], ['Distrito', 'district_id_label'],
|
||||
['Posto administrativo', 'admin_post_id_label'], ['Localidade', 'locality_id_label'],
|
||||
]) {
|
||||
if (!location.rows.some((row) => row.field === field)) {
|
||||
const value = text(draft, key) || (key === 'country_id_label' && text(draft, 'country_id') === 'MZ' ? 'Moçambique' : '');
|
||||
location.rows.push({ field, value: absent(value), origin: 'Selecção/informação territorial do dossier', classification: value ? 'Selecção declarada; não constitui verificação do local' : 'Indeterminado' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const finance = sections.get('finance');
|
||||
if (finance && currentCalculation) {
|
||||
const snapshot = currentCalculation.snapshot;
|
||||
const result = snapshot && typeof snapshot.result === 'object' && snapshot.result !== null && !Array.isArray(snapshot.result)
|
||||
? snapshot.result as Record<string, unknown>
|
||||
: null;
|
||||
const context = snapshot && typeof snapshot.context === 'object' && snapshot.context !== null && !Array.isArray(snapshot.context)
|
||||
? snapshot.context as Record<string, unknown>
|
||||
: null;
|
||||
const rawValue = result?.value ?? snapshot?.indicative_total;
|
||||
const knownValue = typeof rawValue === 'string' && /^(?:\d+)(?:\.\d+)?$/.test(rawValue) ? rawValue : '';
|
||||
finance.rows.push(
|
||||
{ field: 'Estado da simulação fiscal/aritmética anexada', value: currentCalculation.status === 'completed' ? (result?.status === 'indeterminate' ? 'Indeterminado' : 'Concluída') : 'Não concluída; resultado não incluído como confirmado', origin: 'Execução existente no simulador', classification: currentCalculation.status === 'completed' ? 'Estado da execução; verificar a explicação e o âmbito abaixo' : 'Indeterminado' },
|
||||
{ field: 'Resultado indicativo', value: currentCalculation.status === 'completed' && knownValue ? `${knownValue}${typeof result?.unit === 'string' ? ` ${result.unit}` : ''}` : 'Indeterminado/não disponível', origin: 'Snapshot da execução existente; valor reproduzido sem recalcular', classification: 'Resultado do simulador; não é decisão fiscal nem aconselhamento' },
|
||||
{ field: 'Explicação e dados em falta', value: typeof result?.explanation === 'string' ? result.explanation : 'Não disponível no snapshot', origin: 'Explicação guardada pela execução', classification: 'Informação do resultado do simulador' },
|
||||
{ field: 'Data de referência', value: typeof context?.reference_date === 'string' ? context.reference_date : 'Não identificada', origin: 'Contexto guardado na execução', classification: 'Metadado da simulação' },
|
||||
{ field: 'Versão do motor/cenário', value: `${typeof context?.engine_version === 'string' ? context.engine_version : 'não identificada'} / ${typeof context?.scenario_version === 'number' ? context.scenario_version : currentCalculation.version}`, origin: 'Contexto guardado na execução', classification: 'Metadado técnico' },
|
||||
{ field: 'Fórmula e valores usados', value: snapshot && typeof snapshot.formula_version === 'string' ? `Fórmula ${snapshot.formula_version}; base ${String(snapshot.base ?? 'não disponível')}; taxa ${String(snapshot.rate_percent ?? 'não disponível')}%; redução ${String(snapshot.reduction_percent ?? 'não disponível')}%; moeda ${String(snapshot.currency ?? 'não indicada')}` : 'A fórmula não foi identificada no snapshot; ver explicação da execução', origin: 'Snapshot guardado; sem aplicação de regra legal', classification: 'Reutilização do resultado existente' },
|
||||
{ field: 'Revisão do resultado', value: String(currentCalculation.version), origin: currentCalculation.updatedAt ?? 'Data não identificada', classification: 'Versão imutável da execução existente' },
|
||||
...(currentCalculation.reportChecksum ? [{ field: 'Hash SHA-256 do relatório associado', value: currentCalculation.reportChecksum, origin: 'Referência imutável do relatório', classification: 'Integridade técnica; não é fonte legal' }] : []),
|
||||
);
|
||||
}
|
||||
if (finance && !text(draft, 'business_plan_snapshot')) {
|
||||
finance.paragraphs.push('Não existe plano empresarial detalhado guardado neste dossier. Os campos sem valor são indicados como “Não informado”; não se substituem por zero.');
|
||||
}
|
||||
const resources = sections.get('resources');
|
||||
if (resources) {
|
||||
resources.rows.push({ field: 'Pré-elegibilidade de financiamento', value: 'Indeterminada; não há catálogo de produtos e critérios documentados para esta consulta.', origin: 'Limite funcional conhecido', classification: 'Não verificado/não decidido' });
|
||||
const needs = text(draft, 'infrastructure_needs');
|
||||
resources.rows.push({ field: 'Outros recursos declarados', value: absent(needs), origin: 'Informação do dossier', classification: needs ? 'Declarada pelo utilizador' : 'Indeterminado' });
|
||||
}
|
||||
const sources = sections.get('sources');
|
||||
if (sources) {
|
||||
const marketSource = text(draft, 'market_source');
|
||||
sources.rows.push({ field: 'Origem de mercado', value: absent(marketSource), origin: 'Declarada pelo utilizador; não verificada pelo portal', classification: marketSource ? 'Informação declarada, não verificada' : 'Indeterminado' });
|
||||
if (!marketSource) sources.paragraphs.push('Se disponível, registar origem e data da informação de mercado e validar a fonte antes de a usar numa decisão.');
|
||||
if (references.length) {
|
||||
for (const [index, ref] of references.entries()) {
|
||||
sources.rows.push({ field: `Referência de cálculo anexada ${index + 1}`, value: `Versão ${ref.version}; ${new Date(ref.date).toLocaleString('pt-MZ')}; SHA-256 ${ref.checksum}`, origin: 'Simulação matemática anexada ao dossier com consentimento', classification: 'Rasto de cálculo; não é fonte oficial externa' });
|
||||
}
|
||||
} else {
|
||||
sources.rows.push({ field: 'Cálculos de simulação anexados', value: 'Nenhum cálculo externo/anterior anexado ao dossier.', origin: 'Estado actual do dossier', classification: 'Não aplicável' });
|
||||
}
|
||||
const nextSteps = [
|
||||
!text(draft, 'project_summary') && 'Completar o resumo do projecto ou negócio.',
|
||||
!text(draft, 'market_assumption') && 'Descrever, se conhecido, a hipótese de mercado e a sua origem/data.',
|
||||
!text(draft, 'business_plan_snapshot') && 'Registar pressupostos financeiros se forem necessários à decisão.',
|
||||
!text(draft, 'project_team_snapshot') && 'Identificar competências/equipa em falta, caso sejam relevantes.',
|
||||
'Rever os pressupostos e confirmar as fontes antes de tomar decisões.',
|
||||
'Verificar critérios de financiamento em produtos documentados; esta exportação não determina elegibilidade.',
|
||||
].filter((item): item is string => Boolean(item));
|
||||
sources.paragraphs.push(`Próximos passos sugeridos a partir dos campos em falta: ${nextSteps.join(' ')}`);
|
||||
sources.paragraphs.push('Informação não carregada ou não fornecida não é inferida. A exportação não publica nem partilha o dossier.');
|
||||
}
|
||||
return [...sections.values()];
|
||||
}
|
||||
|
||||
export function createProjectDossierReport(
|
||||
draft: Record<string, string | string[]>,
|
||||
options: {
|
||||
selectedSections: ReadonlySet<DossierReportSectionId>;
|
||||
version?: string;
|
||||
references?: DossierReference[];
|
||||
currentCalculation?: DossierCurrentCalculation | null;
|
||||
generatedAt?: string;
|
||||
},
|
||||
): DossierReportModel {
|
||||
const generatedAt = options.generatedAt ?? new Date().toISOString();
|
||||
const references = options.references ?? [];
|
||||
const reportRows = buildProjectDossierRows(draft);
|
||||
const title = absent(text(draft, 'project_title'));
|
||||
return {
|
||||
title,
|
||||
generatedAt,
|
||||
version: options.version?.trim() || 'Rascunho sem revisão guardada',
|
||||
sections: makeSections(draft, reportRows, options.selectedSections, references, options.currentCalculation ?? null, generatedAt, options.version?.trim() || 'Rascunho sem revisão guardada'),
|
||||
references,
|
||||
limitations: [
|
||||
'Conteúdo fornecido pelo utilizador, estimativas matemáticas, selecções de catálogo e referências documentadas estão rotulados separadamente.',
|
||||
'A origem de mercado introduzida pelo utilizador não foi verificada automaticamente.',
|
||||
'Não há pré-aprovação nem confirmação de financiamento nesta exportação.',
|
||||
'O relatório é gerado localmente e não é publicado nem partilhado pelo portal.',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function classifyDossierAttachment(file: Pick<File, 'name' | 'type' | 'size'>): DossierAttachmentKind {
|
||||
const name = file.name.toLocaleLowerCase('en');
|
||||
const type = file.type.toLocaleLowerCase('en');
|
||||
if ((type === 'image/jpeg' || type === 'image/png') && file.size <= MAX_DOSSIER_ATTACHMENT_BYTES) return 'image';
|
||||
if ((type === 'text/csv' || name.endsWith('.csv') || name.endsWith('.tsv')) && file.size <= MAX_EMBEDDED_TEXT_BYTES) return 'csv';
|
||||
if ((type === 'text/plain' || name.endsWith('.txt')) && file.size <= MAX_EMBEDDED_TEXT_BYTES) return 'text';
|
||||
return 'original-only';
|
||||
}
|
||||
|
||||
export function validateDossierAttachments(files: readonly Pick<File, 'size'>[]): string | null {
|
||||
if (files.length > MAX_DOSSIER_ATTACHMENT_COUNT) return `Seleccione no máximo ${MAX_DOSSIER_ATTACHMENT_COUNT} anexos.`;
|
||||
if (files.some((file) => file.size > MAX_DOSSIER_ATTACHMENT_BYTES)) return 'Cada anexo deve ter até 15 MB.';
|
||||
if (files.reduce((total, file) => total + file.size, 0) > MAX_DOSSIER_ATTACHMENT_TOTAL_BYTES) return 'O conjunto de anexos deve ter até 50 MB.';
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseDelimited(textValue: string, delimiter: string): string[][] {
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let cell = '';
|
||||
let quoted = false;
|
||||
for (let index = 0; index < textValue.length; index++) {
|
||||
const char = textValue[index];
|
||||
if (char === '"') {
|
||||
if (quoted && textValue[index + 1] === '"') { cell += '"'; index++; }
|
||||
else quoted = !quoted;
|
||||
} else if (!quoted && char === delimiter) {
|
||||
row.push(cell); cell = '';
|
||||
} else if (!quoted && (char === '\n' || char === '\r')) {
|
||||
if (char === '\r' && textValue[index + 1] === '\n') index++;
|
||||
row.push(cell); rows.push(row); row = []; cell = '';
|
||||
} else cell += char;
|
||||
}
|
||||
if (cell || row.length) { row.push(cell); rows.push(row); }
|
||||
const cleaned = rows.map((values) => values.map((value) => value.replace(/^\uFEFF/, '')));
|
||||
return cleaned.slice(0, MAX_EMBEDDED_CSV_ROWS).map((values) => values.slice(0, MAX_EMBEDDED_CSV_COLUMNS));
|
||||
}
|
||||
|
||||
function csvDelimiter(value: string): string {
|
||||
const first = value.split(/\r?\n/, 1)[0] ?? '';
|
||||
const semicolons = (first.match(/;/g) ?? []).length;
|
||||
const commas = (first.match(/,/g) ?? []).length;
|
||||
const tabs = (first.match(/\t/g) ?? []).length;
|
||||
return tabs > commas && tabs > semicolons ? '\t' : semicolons > commas ? ';' : ',';
|
||||
}
|
||||
|
||||
function safePackageName(name: string, used: Set<string>): string {
|
||||
const basename = name.split(/[\\/]/).pop() ?? 'anexo';
|
||||
const cleaned = basename.normalize('NFKC').replace(/[^\p{L}\p{N}._-]+/gu, '_').replace(/^\.+/, '').slice(0, 120) || 'anexo';
|
||||
let candidate = cleaned;
|
||||
let suffix = 2;
|
||||
while (used.has(candidate.toLocaleLowerCase('en'))) {
|
||||
const dot = cleaned.lastIndexOf('.');
|
||||
candidate = dot > 0 ? `${cleaned.slice(0, dot)}_${suffix}${cleaned.slice(dot)}` : `${cleaned}_${suffix}`;
|
||||
suffix++;
|
||||
}
|
||||
used.add(candidate.toLocaleLowerCase('en'));
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function attachmentStatus(attachment: DossierAttachment, annexesIncluded: boolean): string {
|
||||
if (!attachment.include) return 'Não seleccionado para exportação';
|
||||
if (!annexesIncluded) return 'Original no pacote ZIP; secção de anexos não foi incluída no relatório';
|
||||
const kind = classifyDossierAttachment(attachment.file);
|
||||
if (kind === 'image') return `Fotografia incorporada${attachment.caption ? `; legenda: ${attachment.caption}` : ''}; original também no pacote ZIP`;
|
||||
if (kind === 'csv') return 'Tabela incorporada; original também no pacote ZIP';
|
||||
if (kind === 'text') return 'Texto incorporado; original também no pacote ZIP';
|
||||
return 'Conteúdo não incorporado; original preservado no pacote ZIP';
|
||||
}
|
||||
|
||||
function tableForDocx(headers: string[], data: string[][]): Table {
|
||||
const widths = headers.length === 4 ? [1850, 1850, 3450, 2210] : headers.length === 3 ? [1900, 4400, 3060] : headers.map(() => Math.floor(9360 / headers.length));
|
||||
const tableRows = [headers, ...data].map((values, rowIndex) => new TableRow({
|
||||
tableHeader: rowIndex === 0,
|
||||
cantSplit: true,
|
||||
children: headers.map((_, cellIndex) => new TableCell({
|
||||
width: { size: widths[cellIndex] ?? 1500, type: WidthType.DXA },
|
||||
shading: rowIndex === 0 ? { type: ShadingType.CLEAR, fill: '123B35' } : undefined,
|
||||
margins: { top: 80, bottom: 80, left: 100, right: 100 },
|
||||
children: [new Paragraph({ children: [new TextRun({ text: values[cellIndex] ?? '', bold: rowIndex === 0, color: rowIndex === 0 ? 'FFFFFF' : '17211F', size: 18 })] })],
|
||||
})),
|
||||
}));
|
||||
return new Table({
|
||||
rows: tableRows,
|
||||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||||
columnWidths: widths,
|
||||
layout: TableLayoutType.FIXED,
|
||||
borders: Object.fromEntries(['top', 'bottom', 'left', 'right', 'insideHorizontal', 'insideVertical'].map((side) => [side, { style: BorderStyle.SINGLE, size: 4, color: 'CBD5D1' }])) as never,
|
||||
});
|
||||
}
|
||||
|
||||
function sectionTable(section: DossierReportSection): Table | null {
|
||||
if (!section.rows.length) return null;
|
||||
return tableForDocx(['Campo', 'Conteúdo', 'Classificação / origem'], section.rows.map((row) => [row.field, row.value, `${row.classification}. ${row.origin}`]));
|
||||
}
|
||||
|
||||
async function imageRuns(attachment: DossierAttachment): Promise<(Paragraph | Table)[]> {
|
||||
const file = attachment.file;
|
||||
const type = file.type === 'image/jpeg' ? 'jpg' : 'png';
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
let sourceWidth = 0;
|
||||
let sourceHeight = 0;
|
||||
if (type === 'png') {
|
||||
if (data.length < 24 || data[0] !== 0x89 || data[1] !== 0x50 || data[2] !== 0x4e || data[3] !== 0x47 || data[12] !== 0x49 || data[13] !== 0x48 || data[14] !== 0x44 || data[15] !== 0x52) {
|
||||
throw new Error(`A fotografia ${file.name} não tem um cabeçalho PNG válido.`);
|
||||
}
|
||||
sourceWidth = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(16);
|
||||
sourceHeight = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(20);
|
||||
} else {
|
||||
if (data.length < 4 || data[0] !== 0xff || data[1] !== 0xd8) throw new Error(`A fotografia ${file.name} não tem um cabeçalho JPEG válido.`);
|
||||
const frameMarkers = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
|
||||
for (let offset = 2; offset + 8 < data.length;) {
|
||||
if (data[offset] !== 0xff) { offset++; continue; }
|
||||
while (data[offset] === 0xff) offset++;
|
||||
const marker = data[offset++];
|
||||
if (marker === 0xd9 || marker === 0xda) break;
|
||||
if ([0x01, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7].includes(marker)) continue;
|
||||
const segmentLength = (data[offset] << 8) | data[offset + 1];
|
||||
if (segmentLength < 2 || offset + segmentLength > data.length) break;
|
||||
if (frameMarkers.has(marker)) {
|
||||
sourceHeight = (data[offset + 3] << 8) | data[offset + 4];
|
||||
sourceWidth = (data[offset + 5] << 8) | data[offset + 6];
|
||||
break;
|
||||
}
|
||||
offset += segmentLength;
|
||||
}
|
||||
}
|
||||
if (!sourceWidth || !sourceHeight || sourceWidth * sourceHeight > 40_000_000 || sourceWidth > 12_000 || sourceHeight > 12_000) {
|
||||
throw new Error(`As dimensões da fotografia ${file.name} são inválidas ou excedem o limite de segurança.`);
|
||||
}
|
||||
const scale = Math.min(1, 520 / sourceWidth, 620 / sourceHeight);
|
||||
const width = Math.max(1, Math.round(sourceWidth * scale));
|
||||
const height = Math.max(1, Math.round(sourceHeight * scale));
|
||||
return [
|
||||
new Paragraph({ alignment: AlignmentType.CENTER, children: [new ImageRun({ data, type, transformation: { width, height }, altText: { name: file.name, description: attachment.caption || file.name, title: file.name } })] }),
|
||||
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: attachment.caption || file.name, italics: true, size: 18 })] }),
|
||||
];
|
||||
}
|
||||
|
||||
async function annexDocxBlocks(attachments: DossierAttachment[]): Promise<(Paragraph | Table)[]> {
|
||||
const blocks: (Paragraph | Table)[] = [];
|
||||
for (const attachment of attachments.filter((item) => item.include)) {
|
||||
const kind = classifyDossierAttachment(attachment.file);
|
||||
blocks.push(new Paragraph({ text: attachment.file.name, heading: HeadingLevel.HEADING_3, keepNext: true }));
|
||||
if (kind === 'image') {
|
||||
blocks.push(...await imageRuns(attachment));
|
||||
} else if (kind === 'text') {
|
||||
const contents = (await attachment.file.text()).replace(/^\uFEFF/, '');
|
||||
for (const line of contents.split(/\r?\n/).slice(0, 1000)) blocks.push(new Paragraph({ children: [new TextRun({ text: line || ' ' })] }));
|
||||
} else if (kind === 'csv') {
|
||||
const contents = (await attachment.file.text()).replace(/^\uFEFF/, '');
|
||||
const rows = parseDelimited(contents, csvDelimiter(contents));
|
||||
const headers = rows[0] ?? [];
|
||||
const data = rows.slice(1);
|
||||
if (headers.length) blocks.push(tableForDocx(headers, data));
|
||||
if (contents.split(/\r?\n/).length > MAX_EMBEDDED_CSV_ROWS) blocks.push(new Paragraph('A tabela foi truncada para 250 linhas no relatório; o original completo acompanha o pacote ZIP.'));
|
||||
} else {
|
||||
blocks.push(new Paragraph('Este formato não foi incorporado ao DOCX. Para preservar o original, exporte também o pacote ZIP de anexos com o respectivo índice.'));
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
export async function generateProjectDossierDocx(
|
||||
model: DossierReportModel,
|
||||
attachments: DossierAttachment[],
|
||||
annexesIncluded: boolean,
|
||||
): Promise<Blob> {
|
||||
const children: (Paragraph | Table)[] = [
|
||||
new Paragraph({ text: 'InvestMoz', heading: HeadingLevel.HEADING_2 }),
|
||||
new Paragraph({ text: 'Relatório consolidado do projecto', heading: HeadingLevel.TITLE }),
|
||||
new Paragraph({ children: [new TextRun({ text: model.title, bold: true, size: 30 })] }),
|
||||
new Paragraph({ children: [new TextRun({ text: `Gerado em ${new Date(model.generatedAt).toLocaleString('pt-MZ')} · versão ${model.version}`, color: '52615D', size: 20 })] }),
|
||||
new Paragraph({ children: [new TextRun({ text: 'Documento privado gerado neste dispositivo. A exportação não publica nem partilha o conteúdo.', bold: true, color: '8A4B08' })] }),
|
||||
];
|
||||
for (const section of model.sections) {
|
||||
if (section.id === 'annexes') {
|
||||
children.push(new Paragraph({ text: section.title, heading: HeadingLevel.HEADING_1 }));
|
||||
if (annexesIncluded) children.push(...await annexDocxBlocks(attachments));
|
||||
if (!attachments.some((item) => item.include)) children.push(new Paragraph('Nenhum anexo foi seleccionado.'));
|
||||
if (attachments.some((item) => item.include && classifyDossierAttachment(item.file) === 'original-only')) children.push(new Paragraph('Os ficheiros que não podem ser incorporados de forma legível devem ser exportados também no pacote ZIP, com índice.'));
|
||||
continue;
|
||||
}
|
||||
children.push(new Paragraph({ text: section.title, heading: HeadingLevel.HEADING_1, keepNext: true }));
|
||||
for (const paragraph of section.paragraphs) children.push(new Paragraph({ children: [new TextRun({ text: paragraph })] }));
|
||||
const table = sectionTable(section);
|
||||
if (table) children.push(table);
|
||||
if (!section.rows.length && !section.paragraphs.length) children.push(new Paragraph('Não há informação fornecida nesta secção.'));
|
||||
}
|
||||
const footer = new Footer({ children: [new Paragraph({ alignment: AlignmentType.RIGHT, children: [new TextRun({ text: 'InvestMoz · relatório privado · página ' }), new SimpleField('PAGE')] })] });
|
||||
const doc = new Document({
|
||||
creator: 'InvestMoz',
|
||||
title: `Relatório do projecto — ${model.title}`,
|
||||
description: 'Dossier consolidado exportado localmente a partir do formulário InvestMoz.',
|
||||
styles: {
|
||||
default: { document: { run: { font: 'Aptos', size: 20, color: '17211F' }, paragraph: { spacing: { after: 120, line: 276 } } } },
|
||||
paragraphStyles: [
|
||||
{ id: 'Title', name: 'Title', basedOn: 'Normal', run: { font: 'Aptos Display', size: 34, bold: true, color: '123B35' }, paragraph: { spacing: { before: 200, after: 220 } } },
|
||||
{ id: 'Heading1', name: 'Heading 1', basedOn: 'Normal', next: 'Normal', run: { font: 'Aptos Display', size: 26, bold: true, color: '123B35' }, paragraph: { spacing: { before: 320, after: 150 }, keepNext: true } },
|
||||
{ id: 'Heading2', name: 'Heading 2', basedOn: 'Normal', next: 'Normal', run: { font: 'Aptos', size: 24, bold: true, color: '27675C' }, paragraph: { spacing: { before: 260, after: 120 }, keepNext: true } },
|
||||
{ id: 'Heading3', name: 'Heading 3', basedOn: 'Normal', next: 'Normal', run: { font: 'Aptos', size: 22, bold: true, color: '27675C' }, paragraph: { spacing: { before: 200, after: 100 }, keepNext: true } },
|
||||
],
|
||||
},
|
||||
sections: [{
|
||||
properties: { page: { size: { width: 12240, height: 15840 }, margin: { top: 900, right: 960, bottom: 900, left: 960, footer: 450, header: 450 } } },
|
||||
footers: { default: footer },
|
||||
children,
|
||||
}],
|
||||
});
|
||||
return Packer.toBlob(doc);
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
|
||||
}
|
||||
|
||||
async function fileDataUrl(file: File): Promise<string> {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return `data:${file.type};base64,${btoa(binary)}`;
|
||||
}
|
||||
|
||||
function htmlTable(headers: string[], rows: string[][]): string {
|
||||
return `<table><thead><tr>${headers.map((value) => `<th>${escapeHtml(value)}</th>`).join('')}</tr></thead><tbody>${rows.map((row) => `<tr>${headers.map((_, index) => `<td>${escapeHtml(row[index] ?? '')}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
|
||||
}
|
||||
|
||||
export async function createProjectDossierPrintHtml(
|
||||
model: DossierReportModel,
|
||||
attachments: DossierAttachment[],
|
||||
annexesIncluded: boolean,
|
||||
): Promise<string> {
|
||||
const content: string[] = [];
|
||||
for (const section of model.sections) {
|
||||
content.push(`<section><h2>${escapeHtml(section.title)}</h2>`);
|
||||
for (const paragraph of section.paragraphs) content.push(`<p>${escapeHtml(paragraph)}</p>`);
|
||||
if (section.rows.length) content.push(htmlTable(['Campo', 'Conteúdo', 'Classificação / origem'], section.rows.map((row) => [row.field, row.value, `${row.classification}. ${row.origin}`])));
|
||||
if (section.id === 'annexes') {
|
||||
const selected = attachments.filter((item) => item.include);
|
||||
if (!selected.length) content.push('<p>Nenhum anexo foi seleccionado.</p>');
|
||||
if (!annexesIncluded) content.push('<p>A secção de anexos foi omitida do relatório. Os originais seleccionados continuam no pacote ZIP.</p>');
|
||||
else for (const attachment of selected) {
|
||||
const kind = classifyDossierAttachment(attachment.file);
|
||||
content.push(`<h3>${escapeHtml(attachment.file.name)}</h3>`);
|
||||
if (kind === 'image') content.push(`<figure><img alt="${escapeHtml(attachment.caption || attachment.file.name)}" src="${await fileDataUrl(attachment.file)}"><figcaption>${escapeHtml(attachment.caption || attachment.file.name)}</figcaption></figure>`);
|
||||
else if (kind === 'text') content.push(`<pre>${escapeHtml((await attachment.file.text()).slice(0, MAX_EMBEDDED_TEXT_BYTES))}</pre>`);
|
||||
else if (kind === 'csv') {
|
||||
const source = (await attachment.file.text()).slice(0, MAX_EMBEDDED_TEXT_BYTES);
|
||||
const rows = parseDelimited(source, csvDelimiter(source));
|
||||
content.push(htmlTable(rows[0] ?? [], rows.slice(1)));
|
||||
} else content.push('<p>Conteúdo original não incorporado nesta versão PDF. Para obter o original, exporte também o pacote ZIP com índice.</p>');
|
||||
}
|
||||
}
|
||||
if (!section.rows.length && !section.paragraphs.length && section.id !== 'annexes') content.push('<p>Não há informação fornecida nesta secção.</p>');
|
||||
content.push('</section>');
|
||||
}
|
||||
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}*{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}th:first-child,td:first-child{width:22%}th:last-child,td:last-child{width:32%;font-size:9pt;color:#40524d}.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 print{a{color:inherit;text-decoration:none}.no-print{display:none}}
|
||||
</style></head><body><h1>InvestMoz<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>InvestMoz · Relatório privado · ${escapeHtml(model.version)}</small></footer><script>window.addEventListener('load',()=>setTimeout(()=>window.print(),350));</script></body></html>`;
|
||||
}
|
||||
|
||||
export async function generateProjectDossierPackage(
|
||||
docxBlob: Blob,
|
||||
attachments: DossierAttachment[],
|
||||
annexesIncluded: boolean,
|
||||
): Promise<Blob> {
|
||||
const zip = new JSZip();
|
||||
zip.file('Relatorio/relatorio-projecto-investmoz.docx', docxBlob);
|
||||
const usedNames = new Set<string>();
|
||||
const selected = attachments.filter((item) => item.include);
|
||||
const index = ['ÍNDICE DO PACOTE DE RELATÓRIO INVESTMOZ', '', 'O relatório e os anexos são privados e foram seleccionados localmente pelo utilizador.', ''].join('\n');
|
||||
const records: string[] = [];
|
||||
for (const attachment of selected) {
|
||||
const filename = safePackageName(attachment.file.name, usedNames);
|
||||
zip.file(`Anexos/${filename}`, attachment.file, { binary: true });
|
||||
records.push(`Ficheiro: ${filename}\nTamanho: ${attachment.file.size} bytes\nTipo: ${attachment.file.type || 'desconhecido'}\nSituação: ${attachmentStatus(attachment, annexesIncluded)}\nLegenda: ${attachment.caption || 'Não indicada'}\n`);
|
||||
}
|
||||
zip.file('indice-anexos.txt', `${index}${records.length ? records.join('\n') : 'Não foram seleccionados anexos.\n'}`);
|
||||
return zip.generateAsync({ type: 'blob', mimeType: 'application/zip', compression: 'DEFLATE', compressionOptions: { level: 6 } });
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { csvCellWithDelimiter } from './csv.js';
|
||||
import {
|
||||
calculateFinancialTools,
|
||||
restoreFinancialToolsSnapshot,
|
||||
} from './financial-calculators.ts';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
restoreBusinessPlanSnapshot,
|
||||
} from './business-financial-plan.ts';
|
||||
import { getProjectReadiness, readPlannedRiskResponses } from './project-readiness.ts';
|
||||
|
||||
export type TeamNeed = {
|
||||
competency: string;
|
||||
state: 'available' | 'gap' | 'unknown';
|
||||
action: string;
|
||||
estimated_cost: string;
|
||||
due_date: string;
|
||||
};
|
||||
|
||||
export type ProjectMilestone = {
|
||||
title: string;
|
||||
due_date: string;
|
||||
status: 'planned' | 'in_progress' | 'completed';
|
||||
planned_amount: string;
|
||||
actual_amount: string;
|
||||
};
|
||||
|
||||
export function readRows<T>(value: string, allowed: readonly string[]): T[] {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value || '[]');
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((row): row is T =>
|
||||
Boolean(row && typeof row === 'object' && !Array.isArray(row) &&
|
||||
allowed.every((key) => typeof (row as Record<string, unknown>)[key] === 'string')),
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export type ProjectDossierRow = [section: string, field: string, value: string, origin: string];
|
||||
|
||||
export function buildProjectDossierRows(draft: Record<string, string | string[]>): ProjectDossierRow[] {
|
||||
const rows: ProjectDossierRow[] = [
|
||||
['Secção', 'Campo', 'Valor', 'Origem / estado'],
|
||||
['Projecto', 'Título', String(draft.project_title ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Versão do questionário', String(draft.project_questionnaire_version ?? 'legacy-unversioned'), 'Metadado do questionário; não altera resultados guardados'],
|
||||
['Projecto', 'Resumo', String(draft.project_summary ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Problema', String(draft.project_problem ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Clientes/beneficiários', String(draft.target_customers ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Proposta de valor', String(draft.value_proposition ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Tipo de projecto', String(draft.project_type_label ?? draft.project_type ?? ''), 'Declarado/seleccionado pelo utilizador'],
|
||||
['Projecto', 'Sector', String(draft.sector_id_label ?? draft.sector_id ?? ''), 'Selecção declarada pelo utilizador'],
|
||||
['Projecto', 'Actividade económica', String(draft.activity_id_label ?? draft.activity_id ?? ''), 'Selecção declarada pelo utilizador'],
|
||||
['Projecto', 'Produtos e serviços', String(draft.products_services ?? ''), 'Declarado pelo utilizador'],
|
||||
['Projecto', 'Fase de maturidade', String(draft.maturity_stage_label ?? draft.maturity_stage ?? ''), 'Declarada pelo utilizador'],
|
||||
['Projecto', 'Data prevista de início', String(draft.expected_start_date ?? ''), 'Declarada pelo utilizador; data não verificada'],
|
||||
['Projecto', 'Duração prevista', draft.project_duration_years ? `${draft.project_duration_years} anos` : '', 'Declarada pelo utilizador'],
|
||||
['Mercado', 'Hipótese', String(draft.market_assumption ?? ''), 'Informação declarada, não verificada'],
|
||||
['Mercado', 'Fonte e data', String(draft.market_source ?? ''), 'Opcional; não verificada'],
|
||||
['Mercado', 'Concorrência e alternativas', String(draft.competitor_assumption ?? ''), 'Hipótese declarada; não verificada'],
|
||||
['Mercado', 'Canal de venda', String(draft.sales_channel_assumption ?? ''), 'Planeamento declarado; não confirmado'],
|
||||
['Mercado', 'Acções de divulgação', String(draft.marketing_approach ?? ''), 'Planeamento declarado; não confirmado'],
|
||||
['Localização', 'Província', String(draft.province_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Distrito', String(draft.district_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Posto administrativo', String(draft.admin_post_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Localidade', String(draft.locality_id_label ?? ''), 'Selecção de catálogo territorial'],
|
||||
['Localização', 'Critérios e pontos a confirmar', String(draft.location_rationale ?? ''), 'Declaração do utilizador; não confirma disponibilidade'],
|
||||
['Plano financeiro', 'Estado do plano detalhado', draft.business_plan_snapshot ? 'Snapshot versionado disponível; usar também a exportação do plano financeiro' : 'Sem plano empresarial detalhado preenchido', 'Pressupostos declarados; não é demonstração contabilística'],
|
||||
['Equipa', 'Nota anterior sobre competências', String(draft.skills_needed ?? ''), 'Texto declarado existente'],
|
||||
['Execução', 'Nota anterior sobre marcos', String(draft.project_milestones ?? ''), 'Texto declarado existente'],
|
||||
['Financiamento', 'Estado de pré-elegibilidade', 'Informação insuficiente', 'Sem catálogo documentado de produtos e critérios'],
|
||||
['Necessidade de negócio', 'Descrição', String(draft.opportunity_description ?? ''), 'Declarado pelo utilizador'],
|
||||
['Necessidade de negócio', 'Infra-estrutura necessária', (Array.isArray(draft.infrastructure_needs) ? draft.infrastructure_needs : []).join(', '), 'Declarado/seleccionado pelo utilizador'],
|
||||
['Financiamento', 'Montante pretendido', String(draft.opportunity_value ?? ''), 'Declarado pelo utilizador; ver moeda separada'],
|
||||
['Financiamento', 'Moeda do montante', String(draft.opportunity_currency_label ?? draft.opportunity_currency ?? ''), 'Declarada/seleccionada; sem avaliação de produto'],
|
||||
];
|
||||
const plannedResponses = readPlannedRiskResponses(draft);
|
||||
for (const item of getProjectReadiness(draft)) {
|
||||
const response = plannedResponses.find((entry) => entry.risk_id === item.id);
|
||||
const responseText = response
|
||||
? [response.action, response.owner ? `Responsável: ${response.owner}` : '', response.estimated_cost ? `Custo previsto: ${response.estimated_cost} ${String(draft.currency ?? '')}` : '', response.due_date ? `Prazo: ${response.due_date}` : ''].filter(Boolean).join(' · ')
|
||||
: 'Resposta ainda não registada';
|
||||
rows.push(['Risco', item.title, `${item.origin} ${item.affected} Consequência possível: ${item.consequence} Acção: ${item.nextAction} Resposta planeada: ${responseText}`, 'Derivado das respostas e campos em falta; estimativa qualitativa, sem probabilidade ou gravidade atribuída']);
|
||||
}
|
||||
const finance = restoreFinancialToolsSnapshot(String(draft.financial_tools_snapshot ?? ''));
|
||||
if (finance) {
|
||||
const calculation = calculateFinancialTools({
|
||||
loan: {
|
||||
principal: finance.loan.principal,
|
||||
annualRatePercent: finance.loan.rate,
|
||||
rateType: finance.loan.rateType,
|
||||
termMonths: Number(finance.loan.months),
|
||||
periodMonths: Number(finance.loan.periodMonths),
|
||||
gracePeriods: Number(finance.loan.gracePeriods),
|
||||
upfrontFee: finance.loan.upfrontFee,
|
||||
recurringFee: finance.loan.recurringFee,
|
||||
},
|
||||
breakEven: {
|
||||
fixedCosts: finance.breakEven.fixed,
|
||||
unitPrice: finance.breakEven.price,
|
||||
variableCostPerUnit: finance.breakEven.variable,
|
||||
},
|
||||
funding: {
|
||||
totalInvestment: finance.funding.total,
|
||||
securedFunding: finance.funding.secured,
|
||||
},
|
||||
incomes: finance.incomes.map((row) => row.amount),
|
||||
expenses: finance.expenses.map((row) => row.amount),
|
||||
});
|
||||
const currency = String(draft.currency ?? '') || 'moeda não indicada';
|
||||
const source = 'Estimativa matemática baseada em pressupostos declarados; não é oferta de crédito nem resultado oficial';
|
||||
rows.push(
|
||||
['Plano financeiro', 'Periodicidade do orçamento', finance.budgetPeriod, 'Declarada pelo utilizador'],
|
||||
['Empréstimo educativo', 'Capital pressuposto', `${finance.loan.principal} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Empréstimo educativo', 'Taxa anual pressuposta', `${finance.loan.rate}% (${finance.loan.rateType})`, 'Declarada pelo utilizador; não é taxa de produto'],
|
||||
['Empréstimo educativo', 'Prazo pressuposto', `${finance.loan.months} meses`, 'Declarado pelo utilizador'],
|
||||
['Empréstimo educativo', 'Método e pressupostos substituídos', `Saldo decrescente; capital ${finance.loan.principal}; taxa ${finance.loan.rate}% ${finance.loan.rateType}; ${finance.loan.months} meses; período ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods}; comissão inicial ${finance.loan.upfrontFee}; comissão periódica ${finance.loan.recurringFee}`, 'Cronograma do simulador; taxa declarada, sem correspondência a produto'],
|
||||
['Empréstimo educativo', 'Prestação do primeiro período', calculation.loan.value?.schedule[0]?.totalPayment ? `${calculation.loan.value.schedule[0].totalPayment} ${currency}` : 'Indeterminado', source],
|
||||
['Empréstimo educativo', 'Juros totais estimados', calculation.loan.value?.totalInterest ? `${calculation.loan.value.totalInterest} ${currency}` : 'Indeterminado', source],
|
||||
['Empréstimo educativo', 'Estado/erro do cálculo', calculation.loan.error ?? (calculation.loan.value ? 'Calculado pelo cronograma do simulador' : 'Indeterminado'), source],
|
||||
['Ponto de equilíbrio', 'Fórmula e valores substituídos', `${finance.breakEven.fixed} / (${finance.breakEven.price} − ${finance.breakEven.variable}); unidades arredondadas para cima`, 'Custos fixos ÷ margem de contribuição unitária; pressupostos declarados'],
|
||||
['Ponto de equilíbrio', 'Unidades estimadas', calculation.breakEven.value?.breakEvenUnits ?? 'Indeterminado', source],
|
||||
['Ponto de equilíbrio', 'Vendas correspondentes', calculation.breakEven.value?.breakEvenRevenue ? `${calculation.breakEven.value.breakEvenRevenue} ${currency}` : 'Indeterminado', source],
|
||||
['Ponto de equilíbrio', 'Estado/erro do cálculo', calculation.breakEven.error ?? (calculation.breakEven.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
['Financiamento', 'Investimento total pressuposto', `${finance.funding.total} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Financiamento', 'Montante já mobilizado pressuposto', `${finance.funding.secured} ${currency}`, 'Declarado pelo utilizador'],
|
||||
['Financiamento', 'Fórmula e valores substituídos', `${finance.funding.total} − ${finance.funding.secured}`, 'Investimento total declarado − financiamento mobilizado declarado'],
|
||||
['Financiamento', 'Diferença por financiar', calculation.funding.value?.gap ? `${calculation.funding.value.gap} ${currency}` : calculation.funding.value?.gap === '0.00' ? `0.00 ${currency}` : 'Indeterminado', source],
|
||||
['Financiamento', 'Estado/erro do cálculo', calculation.funding.error ?? (calculation.funding.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
['Orçamento', 'Fórmula e valores substituídos', `${calculation.budget.value?.incomeTotal ?? 'Não informado'} − ${calculation.budget.value?.expenseTotal ?? 'Não informado'}`, 'Receitas declaradas − despesas declaradas; valores ausentes não são zero'],
|
||||
['Orçamento', 'Receitas declaradas', calculation.budget.value?.incomeTotal ? `${calculation.budget.value.incomeTotal} ${currency}` : 'Indeterminado', 'Declarado pelo utilizador'],
|
||||
['Orçamento', 'Despesas declaradas', calculation.budget.value?.expenseTotal ? `${calculation.budget.value.expenseTotal} ${currency}` : 'Indeterminado', 'Declarado pelo utilizador'],
|
||||
['Orçamento', 'Saldo operacional estimado', calculation.budget.value?.operatingBalance ? `${calculation.budget.value.operatingBalance} ${currency}` : 'Indeterminado', source],
|
||||
['Orçamento', 'Estado/erro do cálculo', calculation.budget.error ?? (calculation.budget.value ? 'Calculado pelo simulador' : 'Indeterminado'), source],
|
||||
);
|
||||
for (const income of finance.incomes) {
|
||||
rows.push(['Orçamento', `Receita declarada: ${income.label}`, `${income.amount} ${currency}`, 'Declarado pelo utilizador']);
|
||||
}
|
||||
for (const expense of finance.expenses) {
|
||||
rows.push(['Orçamento', `Despesa declarada: ${expense.label}`, `${expense.amount} ${currency}`, 'Declarado pelo utilizador']);
|
||||
}
|
||||
}
|
||||
const businessPlan = restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot ?? ''));
|
||||
if (businessPlan) {
|
||||
try {
|
||||
const forecast = forecastBusinessPlan(businessPlan);
|
||||
const source = 'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
|
||||
rows.push(
|
||||
['Plano financeiro', 'Moeda do plano', businessPlan.currency, 'Declarada pelo utilizador'],
|
||||
['Plano financeiro', 'Horizonte', `${businessPlan.periods ?? 12} meses`, 'Pressuposto declarado'],
|
||||
['Plano financeiro', 'Facturação no horizonte', `${forecast.totalRevenue} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Fórmula e valores substituídos', `Facturação: quantidade mensal × preço unitário por produto; caixa final: saldo de abertura + cobranças e fontes − pagamentos. Horizonte: ${businessPlan.periods ?? 12} meses; moeda: ${businessPlan.currency}.`, 'Métodos do plano financeiro; agendas e pressupostos declarados no snapshot'],
|
||||
['Plano financeiro', 'Cobranças no horizonte', `${forecast.totalCashCollections} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Pagamentos no horizonte', `${forecast.totalPayments} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Resultado antes de impostos', `${forecast.totalProfitBeforeTax} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Caixa final projectada', `${forecast.endingCash} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Reconciliação do financiamento', forecast.fundingStatus, 'Comparação calculada entre usos e fontes declarados'],
|
||||
['Plano financeiro', 'Diferença entre usos e fontes', `${forecast.fundingGap} ${businessPlan.currency}`, source],
|
||||
['Plano financeiro', 'Taxa de câmbio de apresentação', businessPlan.fxRate ? `${businessPlan.fxRate}; ${businessPlan.fxDate ?? 'data não informada'}; ${businessPlan.fxSource ?? 'fonte não informada'}` : 'Não utilizada', businessPlan.fxRate ? 'Pressuposto de planeamento declarado pelo utilizador; não verificado' : 'Sem conversão'],
|
||||
);
|
||||
} catch {
|
||||
rows.push(['Plano financeiro', 'Estado do cálculo', 'Indeterminado', 'Snapshot inválido ou pressupostos incompatíveis; reveja o plano antes de exportar']);
|
||||
}
|
||||
}
|
||||
for (const [index, need] of readRows<TeamNeed>(String(draft.project_team_snapshot ?? ''), ['competency', 'state', 'action', 'estimated_cost', 'due_date']).entries()) {
|
||||
rows.push(['Equipa', `Necessidade ${index + 1}`, `${need.competency}; ${need.state}; resposta: ${need.action}; custo: ${need.estimated_cost}; prazo: ${need.due_date}`, 'Declarado pelo utilizador; sem certificação ou correspondência']);
|
||||
}
|
||||
for (const [index, milestone] of readRows<ProjectMilestone>(String(draft.project_execution_snapshot ?? ''), ['title', 'due_date', 'status', 'planned_amount', 'actual_amount']).entries()) {
|
||||
rows.push(['Execução', `Marco ${index + 1}`, `${milestone.title}; ${milestone.status}; prazo: ${milestone.due_date}; planeado: ${milestone.planned_amount}; realizado: ${milestone.actual_amount}`, 'Planeado/realizado declarado pelo utilizador']);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function exportProjectDossierCsv(draft: Record<string, string | string[]>): string {
|
||||
const rows = buildProjectDossierRows(draft);
|
||||
// Semicolon is the active list separator in the target Excel locale (pt-MZ).
|
||||
return `\uFEFF${rows.map((row) => row.map((value) => csvCellWithDelimiter(value, ';')).join(';')).join('\r\n')}`;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
export type ProjectReadinessKind = 'missing' | 'unverified' | 'risk';
|
||||
|
||||
export type ProjectReadinessItem = {
|
||||
id: string;
|
||||
kind: ProjectReadinessKind;
|
||||
title: string;
|
||||
origin: string;
|
||||
affected: string;
|
||||
consequence: string;
|
||||
nextAction: string;
|
||||
fieldKey: string;
|
||||
};
|
||||
|
||||
export type PlannedRiskResponse = {
|
||||
risk_id: string;
|
||||
action: string;
|
||||
owner: string;
|
||||
estimated_cost: string;
|
||||
due_date: string;
|
||||
};
|
||||
|
||||
export type ReadinessDraft = Record<string, string | string[]>;
|
||||
|
||||
function value(draft: ReadinessDraft, key: string): string {
|
||||
const current = draft[key];
|
||||
return typeof current === 'string' ? current.trim() : '';
|
||||
}
|
||||
|
||||
function rows(draft: ReadinessDraft, key: string): Array<Record<string, string>> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value(draft, key) || '[]');
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item): item is Record<string, string> =>
|
||||
Boolean(item && typeof item === 'object' && !Array.isArray(item)),
|
||||
)
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getProjectReadiness(
|
||||
draft: ReadinessDraft,
|
||||
): ProjectReadinessItem[] {
|
||||
const items: ProjectReadinessItem[] = [];
|
||||
const customers = value(draft, 'target_customers');
|
||||
const market = value(draft, 'market_assumption');
|
||||
const marketSource = value(draft, 'market_source');
|
||||
const costs = value(draft, 'business_plan_snapshot') ||
|
||||
value(draft, 'financial_tools_snapshot') ||
|
||||
value(draft, 'annual_operating_costs');
|
||||
const territory = ['province_id', 'district_id', 'locality_id'].some((key) => value(draft, key));
|
||||
const locationReason = value(draft, 'location_rationale');
|
||||
const team = rows(draft, 'project_team_snapshot');
|
||||
const identifiedGap = team.some((item) => item.state === 'gap');
|
||||
const sought = Number(value(draft, 'sought_amount') || value(draft, 'opportunity_value') || 0);
|
||||
const secured = Number(value(draft, 'secured_amount') || value(draft, 'own_capital') || 0);
|
||||
const benefits = value(draft, 'claimed_benefits');
|
||||
const customerStatus = value(draft, 'customer_validation_status');
|
||||
const costStatus = value(draft, 'cost_estimate_status');
|
||||
const locationStatus = value(draft, 'location_assessment_status');
|
||||
const fundingStatus = value(draft, 'funding_status');
|
||||
const collectionStatus = value(draft, 'receivables_timing_status');
|
||||
|
||||
if (!customers && customerStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'customers', kind: 'missing', title: 'Clientes ainda pouco definidos',
|
||||
origin: customerStatus ? `Estado declarado: ${customerStatus}. Não foi indicada uma descrição de clientes ou beneficiários.` : 'Não foi indicada uma descrição de clientes ou beneficiários.',
|
||||
affected: 'Procura e receitas previstas.',
|
||||
consequence: 'As vendas planeadas podem não corresponder à procura real.',
|
||||
nextAction: 'Indique quem poderá comprar, onde está e que necessidade procura resolver.',
|
||||
fieldKey: 'target_customers',
|
||||
});
|
||||
} else if (customers && ((!marketSource && market) || ['no', 'partial', 'unknown'].includes(customerStatus))) {
|
||||
items.push({
|
||||
id: 'market-source', kind: 'unverified', title: 'Hipótese de mercado sem fonte ou data',
|
||||
origin: `Foi registada informação de mercado sem origem/data confirmada${customerStatus ? `; estado declarado da conversa com clientes: ${customerStatus}` : ''}.`,
|
||||
affected: 'Procura, preço e projecções de vendas.',
|
||||
consequence: 'A hipótese pode não representar informação actual ou verificável.',
|
||||
nextAction: 'Registe a origem e a data, ou marque-a como uma hipótese ainda por testar.',
|
||||
fieldKey: 'market_source',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!costs || ['no', 'partial', 'unknown'].includes(costStatus)) && costStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'costs', kind: 'missing', title: 'Custos do projecto por detalhar',
|
||||
origin: costStatus ? `Estado declarado: ${costStatus}. ${costs ? 'Os custos detalhados não cobrem ainda todos os elementos.' : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.'}` : 'Não há plano financeiro, custos operacionais ou snapshot de custos preenchido.',
|
||||
affected: 'Investimento necessário, margem e tesouraria.',
|
||||
consequence: 'O capital necessário pode estar subestimado.',
|
||||
nextAction: 'Registe os principais custos, moeda e periodicidade no plano financeiro.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if ((value(draft, 'business_plan_snapshot') || value(draft, 'annual_revenue'))
|
||||
&& ['no', 'partial', 'unknown', ''].includes(collectionStatus)
|
||||
&& collectionStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'receivables', kind: collectionStatus === 'no' || collectionStatus === 'partial' ? 'risk' : 'missing',
|
||||
title: 'Prazo de recebimentos por esclarecer',
|
||||
origin: collectionStatus ? `Estado declarado sobre o prazo de recebimento: ${collectionStatus}.` : 'Existe um plano/valor de vendas, mas não foi indicado se o prazo de recebimento é conhecido.',
|
||||
affected: 'Fluxo de caixa e capital de giro.',
|
||||
consequence: 'A tesouraria pode ficar abaixo do necessário mesmo quando há vendas previstas.',
|
||||
nextAction: 'Registe os prazos previstos de cobrança no plano de fluxo de caixa e confirme-os com os clientes.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!territory || !locationReason || ['no', 'partial', 'unknown'].includes(locationStatus)) && locationStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'location', kind: territory && locationReason ? 'unverified' : 'missing', title: 'Adequação da localização por esclarecer',
|
||||
origin: `Estado declarado: ${locationStatus || 'não indicado'}. ${territory ? 'Há uma localização seleccionada.' : 'Não foi seleccionada uma localização territorial.'} ${locationReason ? '' : 'Falta explicar os critérios considerados.'}`,
|
||||
affected: 'Acesso a clientes, fornecedores, transporte, infra-estruturas e custos.',
|
||||
consequence: 'Podem existir limitações logísticas ou custos locais ainda não considerados.',
|
||||
nextAction: 'Registe por que escolheu o local e quais recursos precisam de confirmação.',
|
||||
fieldKey: 'location_rationale',
|
||||
});
|
||||
}
|
||||
|
||||
if (identifiedGap || team.length === 0) {
|
||||
items.push({
|
||||
id: 'team', kind: identifiedGap ? 'risk' : 'missing', title: identifiedGap ? 'Competência em falta identificada' : 'Equipa e competências por detalhar',
|
||||
origin: identifiedGap ? 'O plano de equipa assinala pelo menos uma competência como lacuna.' : 'Ainda não há necessidades de equipa registadas.',
|
||||
affected: 'Preparação e execução das actividades.',
|
||||
consequence: 'A execução pode atrasar ou exigir apoio e custos adicionais.',
|
||||
nextAction: 'Registe a competência, a resposta planeada, o responsável e o prazo.',
|
||||
fieldKey: 'team',
|
||||
});
|
||||
}
|
||||
|
||||
if ((sought > secured || ['in_process', 'not_started', 'unknown'].includes(fundingStatus) || (fundingStatus === 'confirmed' && sought === 0 && secured === 0)) && fundingStatus !== 'not_applicable') {
|
||||
items.push({
|
||||
id: 'funding', kind: 'risk', title: 'Financiamento ainda não confirmado',
|
||||
origin: sought > secured ? 'O montante indicado como necessário excede os recursos declarados como mobilizados.' : `Estado do financiamento declarado: ${fundingStatus || 'não indicado'}; os montantes e condições não permitem confirmar recursos disponíveis.`,
|
||||
affected: 'Calendário de investimento e implementação.',
|
||||
consequence: 'Os recursos podem não estar disponíveis quando forem necessários.',
|
||||
nextAction: 'Identifique a fonte, o estado, as condições e uma alternativa de financiamento.',
|
||||
fieldKey: 'financial',
|
||||
});
|
||||
}
|
||||
|
||||
if (benefits) {
|
||||
items.push({
|
||||
id: 'benefits', kind: 'unverified', title: 'Benefício fiscal carece de validação',
|
||||
origin: 'Foram indicados benefícios para validação no dossier.',
|
||||
affected: 'Impostos e retorno financeiro estimado.',
|
||||
consequence: 'O retorno pode estar sobrestimado se as condições não forem satisfeitas.',
|
||||
nextAction: 'Confirme a regra, vigência, regime e documentação numa fonte oficial; mantenha o benefício fora do cenário base até confirmação.',
|
||||
fieldKey: 'tax',
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
export function readPlannedRiskResponses(draft: ReadinessDraft): PlannedRiskResponse[] {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value(draft, 'project_risk_responses_snapshot') || '[]');
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((item): item is PlannedRiskResponse => Boolean(
|
||||
item && typeof item === 'object' && !Array.isArray(item) &&
|
||||
typeof item.risk_id === 'string' && typeof item.action === 'string' &&
|
||||
typeof item.owner === 'string' && typeof item.estimated_cost === 'string' &&
|
||||
typeof item.due_date === 'string',
|
||||
));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function serializePlannedRiskResponses(responses: PlannedRiskResponse[]): string {
|
||||
return JSON.stringify(responses.slice(0, 30));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { isApiErrorV1 } from './simulation-contract.ts';
|
||||
|
||||
export type SimulationApiChoice = { id: string; label: string };
|
||||
|
||||
function scalar(value: unknown): string {
|
||||
return typeof value === 'string' ||
|
||||
(typeof value === 'number' && Number.isFinite(value))
|
||||
? String(value)
|
||||
: '';
|
||||
}
|
||||
|
||||
/** Parse API bodies without leaking JSON parser errors into the public form. */
|
||||
export async function readSimulationApiJson(
|
||||
response: Response,
|
||||
): Promise<unknown> {
|
||||
try {
|
||||
return await response.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer field validation details, falling back to the shared API message. */
|
||||
export function simulationApiErrorMessage(value: unknown): string | undefined {
|
||||
if (!isApiErrorV1(value)) return undefined;
|
||||
const validationMessages = Object.values(value.errors ?? {}).flat();
|
||||
return validationMessages.length
|
||||
? validationMessages.join(' ')
|
||||
: value.message;
|
||||
}
|
||||
|
||||
/** Explain a failed status check without implying the accepted job was lost. */
|
||||
export function simulationPollingFailureMessage(value: unknown): string {
|
||||
return (
|
||||
simulationApiErrorMessage(value) ??
|
||||
'O cenário foi recebido, mas não foi possível confirmar o estado do cálculo. Consulte o histórico antes de tentar novamente.'
|
||||
);
|
||||
}
|
||||
|
||||
/** Validate and normalize the public reference catalog envelope. */
|
||||
export function simulationCatalogChoices(
|
||||
value: unknown,
|
||||
): SimulationApiChoice[] {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value) ||
|
||||
!Array.isArray((value as Record<string, unknown>).data)
|
||||
)
|
||||
throw new Error('O servidor devolveu opções com formato inválido.');
|
||||
|
||||
return (value as { data: unknown[] }).data.flatMap((row) => {
|
||||
if (!row || typeof row !== 'object' || Array.isArray(row)) return [];
|
||||
const record = row as Record<string, unknown>;
|
||||
const choice = {
|
||||
id: scalar(record.id ?? record.value),
|
||||
label: scalar(record.label ?? record.name),
|
||||
};
|
||||
return choice.id && choice.label ? [choice] : [];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
/** Shared vocabulary for simulator values. Decimal amounts stay strings at API boundaries. */
|
||||
export type DecimalString = string;
|
||||
|
||||
export type ResultStatus =
|
||||
| 'calculated'
|
||||
| 'estimated'
|
||||
| 'indeterminate'
|
||||
| 'not_applicable';
|
||||
export const fiscalComponentCodes = [
|
||||
'IRPS',
|
||||
'INSS',
|
||||
'IVA',
|
||||
'IRPC',
|
||||
'ISPC',
|
||||
'RETENCOES',
|
||||
] as const;
|
||||
export type FiscalComponentCode = (typeof fiscalComponentCodes)[number];
|
||||
|
||||
export type SimulationContext = {
|
||||
contractVersion: 1;
|
||||
referenceDate: string;
|
||||
currency: string | null;
|
||||
currencyFractionDigits: number | null;
|
||||
scenarioId: string;
|
||||
engineVersion: string;
|
||||
rulesetVersion: string | null;
|
||||
};
|
||||
|
||||
export type SimulationResult<TValue = DecimalString> = {
|
||||
status: ResultStatus;
|
||||
value: TValue | null;
|
||||
unit: string | null;
|
||||
explanation: string;
|
||||
missingInputs: string[];
|
||||
sourceIds: string[];
|
||||
};
|
||||
|
||||
/** Exact JSON envelope returned by the v1 API (wire keys stay snake_case). */
|
||||
export type ApiSimulationResultV1 = {
|
||||
status: ResultStatus;
|
||||
value: DecimalString | null;
|
||||
unit: string | null;
|
||||
explanation: string;
|
||||
missing_inputs: string[];
|
||||
source_ids: string[];
|
||||
};
|
||||
|
||||
export type ApiSimulationResultContextV1 = {
|
||||
reference_date: string;
|
||||
currency: string | null;
|
||||
currency_fraction_digits: number | null;
|
||||
scenario_id: string;
|
||||
scenario_version: number;
|
||||
engine_version: string;
|
||||
ruleset_version: string | null;
|
||||
};
|
||||
|
||||
export type ApiSimulationResultSnapshotV1 = {
|
||||
contract_version: 1;
|
||||
context: ApiSimulationResultContextV1;
|
||||
result: ApiSimulationResultV1;
|
||||
indicative_total: DecimalString | null;
|
||||
legal_interpretation: false;
|
||||
formula_version: string;
|
||||
};
|
||||
|
||||
const apiDecimalPattern = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/;
|
||||
const uuidPattern =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
/** Runtime guard for untrusted API JSON; zero remains a valid decimal value. */
|
||||
export function isApiSimulationResultSnapshotV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationResultSnapshotV1 {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
return false;
|
||||
const snapshot = value as Record<string, unknown>;
|
||||
const context = snapshot.context;
|
||||
const result = snapshot.result;
|
||||
if (
|
||||
snapshot.contract_version !== 1 ||
|
||||
snapshot.legal_interpretation !== false ||
|
||||
typeof snapshot.formula_version !== 'string' ||
|
||||
!snapshot.formula_version.trim() ||
|
||||
!(
|
||||
snapshot.indicative_total === null ||
|
||||
(typeof snapshot.indicative_total === 'string' &&
|
||||
apiDecimalPattern.test(snapshot.indicative_total))
|
||||
) ||
|
||||
!context ||
|
||||
typeof context !== 'object' ||
|
||||
Array.isArray(context) ||
|
||||
!result ||
|
||||
typeof result !== 'object' ||
|
||||
Array.isArray(result)
|
||||
)
|
||||
return false;
|
||||
|
||||
const meta = context as Record<string, unknown>;
|
||||
const output = result as Record<string, unknown>;
|
||||
const currencyValid =
|
||||
meta.currency === null ||
|
||||
(typeof meta.currency === 'string' && /^[A-Z]{3}$/.test(meta.currency));
|
||||
const currencyDigitsValid =
|
||||
meta.currency_fraction_digits === null ||
|
||||
(Number.isInteger(meta.currency_fraction_digits) &&
|
||||
Number(meta.currency_fraction_digits) >= 0 &&
|
||||
Number(meta.currency_fraction_digits) <= 6);
|
||||
if (
|
||||
!isIsoDate(meta.reference_date) ||
|
||||
!uuidPattern.test(String(meta.scenario_id)) ||
|
||||
!Number.isSafeInteger(meta.scenario_version) ||
|
||||
Number(meta.scenario_version) < 1 ||
|
||||
typeof meta.engine_version !== 'string' ||
|
||||
!meta.engine_version.trim() ||
|
||||
!(
|
||||
meta.ruleset_version === null ||
|
||||
typeof meta.ruleset_version === 'string'
|
||||
) ||
|
||||
!currencyValid ||
|
||||
!currencyDigitsValid ||
|
||||
(meta.currency === null) !== (meta.currency_fraction_digits === null) ||
|
||||
![
|
||||
'calculated',
|
||||
'estimated',
|
||||
'indeterminate',
|
||||
'not_applicable',
|
||||
].includes(String(output.status)) ||
|
||||
!(
|
||||
output.value === null ||
|
||||
(typeof output.value === 'string' &&
|
||||
apiDecimalPattern.test(output.value))
|
||||
) ||
|
||||
output.value !== snapshot.indicative_total ||
|
||||
!(output.unit === null || typeof output.unit === 'string') ||
|
||||
typeof output.explanation !== 'string' ||
|
||||
!output.explanation.trim() ||
|
||||
!Array.isArray(output.missing_inputs) ||
|
||||
!output.missing_inputs.every(
|
||||
(item) => typeof item === 'string' && item.length > 0,
|
||||
) ||
|
||||
!Array.isArray(output.source_ids) ||
|
||||
!output.source_ids.every(
|
||||
(item) => typeof item === 'string' && item.length > 0,
|
||||
)
|
||||
)
|
||||
return false;
|
||||
|
||||
if (
|
||||
(output.status === 'calculated' || output.status === 'estimated') &&
|
||||
output.value === null
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
output.status === 'indeterminate' &&
|
||||
(output.value !== null || output.missing_inputs.length === 0)
|
||||
)
|
||||
return false;
|
||||
if (output.status === 'not_applicable' && output.value !== null)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export const apiSimulationExecutionStatuses = [
|
||||
'queued',
|
||||
'running',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
] as const;
|
||||
export type ApiSimulationExecutionStatus =
|
||||
(typeof apiSimulationExecutionStatuses)[number];
|
||||
|
||||
/** Minimum execution fields consumed by the public form and result reader. */
|
||||
export type ApiSimulationExecutionV1 = {
|
||||
id: string;
|
||||
status: ApiSimulationExecutionStatus;
|
||||
version_no: number;
|
||||
result_snapshot?: Record<string, unknown> | null;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export function isApiSimulationExecutionV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationExecutionV1 {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
return false;
|
||||
const execution = value as Record<string, unknown>;
|
||||
const hasSnapshot = Object.prototype.hasOwnProperty.call(
|
||||
execution,
|
||||
'result_snapshot',
|
||||
);
|
||||
const snapshot = execution.result_snapshot;
|
||||
const snapshotValid =
|
||||
snapshot === undefined || snapshot === null
|
||||
? execution.status !== 'completed'
|
||||
: !!snapshot &&
|
||||
typeof snapshot === 'object' &&
|
||||
!Array.isArray(snapshot) &&
|
||||
(isApiSimulationResultSnapshotV1(snapshot) ||
|
||||
(typeof (snapshot as Record<string, unknown>)
|
||||
.indicative_total === 'string' &&
|
||||
/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(
|
||||
(snapshot as Record<string, string>).indicative_total,
|
||||
) &&
|
||||
!Object.prototype.hasOwnProperty.call(
|
||||
snapshot,
|
||||
'contract_version',
|
||||
)));
|
||||
|
||||
return (
|
||||
typeof execution.id === 'string' &&
|
||||
uuidPattern.test(execution.id) &&
|
||||
apiSimulationExecutionStatuses.includes(
|
||||
execution.status as ApiSimulationExecutionStatus,
|
||||
) &&
|
||||
Number.isSafeInteger(execution.version_no) &&
|
||||
Number(execution.version_no) > 0 &&
|
||||
snapshotValid &&
|
||||
(execution.status !== 'completed' || hasSnapshot)
|
||||
);
|
||||
}
|
||||
|
||||
export type ApiSimulationCreateResponseV1 = {
|
||||
data: ApiSimulationExecutionV1;
|
||||
replayed: boolean;
|
||||
access_token?: string;
|
||||
};
|
||||
|
||||
export function isApiSimulationCreateResponseV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationCreateResponseV1 {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
return false;
|
||||
const response = value as Record<string, unknown>;
|
||||
return (
|
||||
isApiSimulationExecutionV1(response.data) &&
|
||||
typeof response.replayed === 'boolean' &&
|
||||
(response.access_token === undefined ||
|
||||
(typeof response.access_token === 'string' &&
|
||||
response.access_token.length >= 32 &&
|
||||
response.access_token.length <= 256))
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationReadResponseV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationExecutionV1 } {
|
||||
return (
|
||||
!!value &&
|
||||
typeof value === 'object' &&
|
||||
!Array.isArray(value) &&
|
||||
isApiSimulationExecutionV1((value as Record<string, unknown>).data)
|
||||
);
|
||||
}
|
||||
|
||||
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
const isIsoDateTime = (value: unknown): value is string =>
|
||||
typeof value === 'string' &&
|
||||
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(
|
||||
value,
|
||||
) &&
|
||||
Number.isFinite(Date.parse(value));
|
||||
|
||||
const isIsoDate = (value: unknown): value is string =>
|
||||
typeof value === 'string' &&
|
||||
(() => {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
||||
if (!match) return false;
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
if (year < 1 || month < 1 || month > 12 || day < 1) return false;
|
||||
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
||||
const daysInMonth = [
|
||||
31,
|
||||
leap ? 29 : 28,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
];
|
||||
return day <= daysInMonth[month - 1];
|
||||
})();
|
||||
|
||||
export function isApiErrorV1(value: unknown): value is {
|
||||
message?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
[key: string]: unknown;
|
||||
} {
|
||||
if (!isPlainObject(value)) return false;
|
||||
if (value.message !== undefined && typeof value.message !== 'string')
|
||||
return false;
|
||||
if (value.errors !== undefined) {
|
||||
if (!isPlainObject(value.errors)) return false;
|
||||
if (
|
||||
!Object.values(value.errors).every(
|
||||
(messages) =>
|
||||
Array.isArray(messages) &&
|
||||
messages.every((message) => typeof message === 'string'),
|
||||
)
|
||||
)
|
||||
return false;
|
||||
}
|
||||
return typeof value.message === 'string' || value.errors !== undefined;
|
||||
}
|
||||
|
||||
export function isApiQuestionnaireReadResponseV1(value: unknown): value is {
|
||||
data: {
|
||||
id: string;
|
||||
code: string;
|
||||
version_no: number;
|
||||
locale: 'pt-MZ';
|
||||
schema_snapshot: Record<string, unknown>;
|
||||
status: 'published';
|
||||
valid_from: string | null;
|
||||
valid_to: string | null;
|
||||
};
|
||||
} {
|
||||
if (!isPlainObject(value) || !isPlainObject(value.data)) return false;
|
||||
const data = value.data;
|
||||
return (
|
||||
typeof data.id === 'string' &&
|
||||
uuidPattern.test(data.id) &&
|
||||
typeof data.code === 'string' &&
|
||||
/^[a-z0-9][a-z0-9-]{0,79}$/.test(data.code) &&
|
||||
Number.isSafeInteger(data.version_no) &&
|
||||
Number(data.version_no) > 0 &&
|
||||
data.locale === 'pt-MZ' &&
|
||||
isPlainObject(data.schema_snapshot) &&
|
||||
data.status === 'published' &&
|
||||
(data.valid_from === null || isIsoDate(data.valid_from)) &&
|
||||
(data.valid_to === null || isIsoDate(data.valid_to))
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationReportReadResponseV1(value: unknown): value is {
|
||||
data: {
|
||||
id: string;
|
||||
simulation_id: string;
|
||||
version_no: number;
|
||||
status: 'queued' | 'ready' | 'failed';
|
||||
report_snapshot: Record<string, unknown> | null;
|
||||
report_sha256: string | null;
|
||||
};
|
||||
} {
|
||||
if (!isPlainObject(value) || !isPlainObject(value.data)) return false;
|
||||
const data = value.data;
|
||||
const shapeValid =
|
||||
typeof data.id === 'string' &&
|
||||
uuidPattern.test(data.id) &&
|
||||
typeof data.simulation_id === 'string' &&
|
||||
uuidPattern.test(data.simulation_id) &&
|
||||
Number.isSafeInteger(data.version_no) &&
|
||||
Number(data.version_no) > 0 &&
|
||||
(data.status === 'queued' ||
|
||||
data.status === 'ready' ||
|
||||
data.status === 'failed') &&
|
||||
(data.report_snapshot === null ||
|
||||
isPlainObject(data.report_snapshot)) &&
|
||||
(data.report_sha256 === null ||
|
||||
(typeof data.report_sha256 === 'string' &&
|
||||
/^[a-f0-9]{64}$/i.test(data.report_sha256)));
|
||||
if (!shapeValid) return false;
|
||||
if (data.status === 'ready') {
|
||||
return (
|
||||
isPlainObject(data.report_snapshot) &&
|
||||
typeof data.report_sha256 === 'string' &&
|
||||
/^[a-f0-9]{64}$/i.test(data.report_sha256)
|
||||
);
|
||||
}
|
||||
|
||||
return data.report_snapshot === null && data.report_sha256 === null;
|
||||
}
|
||||
|
||||
export type ApiSimulationJobV1 = {
|
||||
id: string;
|
||||
simulation_id: string;
|
||||
job_type: 'execute' | 'report';
|
||||
status: 'pending' | 'running' | 'succeeded' | 'failed';
|
||||
attempts: number;
|
||||
available_at: string;
|
||||
started_at: string | null;
|
||||
finished_at: string | null;
|
||||
error_code: string | null;
|
||||
};
|
||||
|
||||
export function isApiSimulationJobsReadResponseV1(value: unknown): value is {
|
||||
data: ApiSimulationJobV1[];
|
||||
} {
|
||||
if (!isPlainObject(value) || !Array.isArray(value.data)) return false;
|
||||
return value.data.every((job: unknown) => {
|
||||
if (!isPlainObject(job)) return false;
|
||||
return (
|
||||
typeof job.id === 'string' &&
|
||||
uuidPattern.test(job.id) &&
|
||||
typeof job.simulation_id === 'string' &&
|
||||
uuidPattern.test(job.simulation_id) &&
|
||||
(job.job_type === 'execute' || job.job_type === 'report') &&
|
||||
(job.status === 'pending' ||
|
||||
job.status === 'running' ||
|
||||
job.status === 'succeeded' ||
|
||||
job.status === 'failed') &&
|
||||
Number.isSafeInteger(job.attempts) &&
|
||||
Number(job.attempts) >= 0 &&
|
||||
Number(job.attempts) <= 3 &&
|
||||
isIsoDateTime(job.available_at) &&
|
||||
(job.started_at === null || isIsoDateTime(job.started_at)) &&
|
||||
(job.finished_at === null || isIsoDateTime(job.finished_at)) &&
|
||||
(job.error_code === null || typeof job.error_code === 'string')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export type ApiSimulationHistoryEntryV1 = {
|
||||
id: string;
|
||||
scope: 'personal' | 'organization';
|
||||
organization_name: string | null;
|
||||
status: ApiSimulationExecutionStatus;
|
||||
version_no: number;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
has_ready_report: boolean;
|
||||
};
|
||||
|
||||
export type ApiSimulationHistoryResponseV1 = {
|
||||
data: ApiSimulationHistoryEntryV1[];
|
||||
meta: {
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
};
|
||||
};
|
||||
|
||||
export function isApiSimulationHistoryResponseV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationHistoryResponseV1 {
|
||||
if (
|
||||
!isPlainObject(value) ||
|
||||
!Array.isArray(value.data) ||
|
||||
!isPlainObject(value.meta)
|
||||
)
|
||||
return false;
|
||||
const meta = value.meta;
|
||||
if (
|
||||
![meta.current_page, meta.last_page, meta.per_page, meta.total].every(
|
||||
(item) => Number.isSafeInteger(item) && Number(item) >= 0,
|
||||
) ||
|
||||
Number(meta.current_page) < 1 ||
|
||||
Number(meta.last_page) < 1 ||
|
||||
Number(meta.per_page) < 1
|
||||
)
|
||||
return false;
|
||||
|
||||
return value.data.every((entry: unknown) => {
|
||||
if (!isPlainObject(entry)) return false;
|
||||
return (
|
||||
typeof entry.id === 'string' &&
|
||||
uuidPattern.test(entry.id) &&
|
||||
(entry.scope === 'personal' || entry.scope === 'organization') &&
|
||||
(entry.organization_name === null ||
|
||||
typeof entry.organization_name === 'string') &&
|
||||
apiSimulationExecutionStatuses.includes(
|
||||
entry.status as ApiSimulationExecutionStatus,
|
||||
) &&
|
||||
Number.isSafeInteger(entry.version_no) &&
|
||||
Number(entry.version_no) > 0 &&
|
||||
(entry.created_at === null || isIsoDateTime(entry.created_at)) &&
|
||||
(entry.updated_at === null || isIsoDateTime(entry.updated_at)) &&
|
||||
typeof entry.has_ready_report === 'boolean'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export type ApiSimulationDraftV1 = {
|
||||
id: string;
|
||||
version_no: number;
|
||||
snapshot_sha256: string;
|
||||
personal_snapshot: Record<string, unknown> | [];
|
||||
economic_snapshot: Record<string, unknown>;
|
||||
simulation_sources: ApiSimulationSourceV1[];
|
||||
updated_at: string | null;
|
||||
expires_at?: string | null;
|
||||
};
|
||||
|
||||
export type ApiSimulationDraftSummaryV1 = {
|
||||
id: string;
|
||||
title: string;
|
||||
updated_at: string | null;
|
||||
expires_at: string | null;
|
||||
version_no: number;
|
||||
};
|
||||
|
||||
export type ApiSimulationSourceV1 = {
|
||||
simulation_id: string;
|
||||
source_version_no: number;
|
||||
result_snapshot: Record<string, unknown>;
|
||||
report_sha256: string;
|
||||
consented_at: string;
|
||||
};
|
||||
|
||||
function isApiSimulationSourceV1(
|
||||
value: unknown,
|
||||
): value is ApiSimulationSourceV1 {
|
||||
if (!isPlainObject(value)) return false;
|
||||
return (
|
||||
typeof value.simulation_id === 'string' &&
|
||||
uuidPattern.test(value.simulation_id) &&
|
||||
Number.isSafeInteger(value.source_version_no) &&
|
||||
Number(value.source_version_no) > 0 &&
|
||||
isPlainObject(value.result_snapshot) &&
|
||||
typeof value.report_sha256 === 'string' &&
|
||||
/^[a-f0-9]{64}$/i.test(value.report_sha256) &&
|
||||
isIsoDateTime(value.consented_at)
|
||||
);
|
||||
}
|
||||
|
||||
function isApiSimulationDraftV1(value: unknown): value is ApiSimulationDraftV1 {
|
||||
if (!isPlainObject(value)) return false;
|
||||
return (
|
||||
typeof value.id === 'string' &&
|
||||
uuidPattern.test(value.id) &&
|
||||
Number.isSafeInteger(value.version_no) &&
|
||||
Number(value.version_no) > 0 &&
|
||||
typeof value.snapshot_sha256 === 'string' &&
|
||||
/^[a-f0-9]{64}$/i.test(value.snapshot_sha256) &&
|
||||
(isPlainObject(value.personal_snapshot) ||
|
||||
(Array.isArray(value.personal_snapshot) &&
|
||||
value.personal_snapshot.length === 0)) &&
|
||||
isPlainObject(value.economic_snapshot) &&
|
||||
Array.isArray(value.simulation_sources) &&
|
||||
value.simulation_sources.every(isApiSimulationSourceV1) &&
|
||||
(value.updated_at === null || isIsoDateTime(value.updated_at)) &&
|
||||
(value.expires_at === undefined || value.expires_at === null || isIsoDateTime(value.expires_at))
|
||||
);
|
||||
}
|
||||
|
||||
function isApiSimulationDraftSummaryV1(value: unknown): value is ApiSimulationDraftSummaryV1 {
|
||||
return isPlainObject(value) && typeof value.id === 'string' && uuidPattern.test(value.id) &&
|
||||
typeof value.title === 'string' &&
|
||||
(value.updated_at === null || isIsoDateTime(value.updated_at)) &&
|
||||
(value.expires_at === null || isIsoDateTime(value.expires_at)) &&
|
||||
Number.isSafeInteger(value.version_no) && Number(value.version_no) > 0;
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftListResponseV1(value: unknown): value is { data: ApiSimulationDraftSummaryV1[] } {
|
||||
return isPlainObject(value) && Array.isArray(value.data) && value.data.every(isApiSimulationDraftSummaryV1);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftClaimPreviewV1(value: unknown): value is { data: ApiSimulationDraftSummaryV1 | null } {
|
||||
return isPlainObject(value) && (value.data === null || isApiSimulationDraftSummaryV1(value.data));
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftReadResponseV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationDraftV1 | null } {
|
||||
if (!isPlainObject(value)) return false;
|
||||
return value.data === null || isApiSimulationDraftV1(value.data);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftWriteResponseV1(value: unknown): value is {
|
||||
data: { id: string; version_no: number; replayed?: boolean };
|
||||
expires_at?: string | null;
|
||||
} {
|
||||
if (!isPlainObject(value) || !isPlainObject(value.data)) return false;
|
||||
const data = value.data;
|
||||
return (
|
||||
typeof data.id === 'string' &&
|
||||
uuidPattern.test(data.id) &&
|
||||
Number.isSafeInteger(data.version_no) &&
|
||||
Number(data.version_no) > 0 &&
|
||||
(value.expires_at === undefined || value.expires_at === null || isIsoDateTime(value.expires_at)) &&
|
||||
(data.replayed === undefined || typeof data.replayed === 'boolean')
|
||||
);
|
||||
}
|
||||
|
||||
export function isApiSimulationDraftAttachResponseV1(
|
||||
value: unknown,
|
||||
): value is { data: ApiSimulationDraftV1; replayed: boolean } {
|
||||
return (
|
||||
isPlainObject(value) &&
|
||||
isApiSimulationDraftV1(value.data) &&
|
||||
typeof value.replayed === 'boolean'
|
||||
);
|
||||
}
|
||||
|
||||
export function indeterminateFiscalComponent(
|
||||
component: FiscalComponentCode,
|
||||
referenceDate: string,
|
||||
): SimulationResult<DecimalString> & {
|
||||
component: FiscalComponentCode;
|
||||
referenceDate: string;
|
||||
} {
|
||||
return {
|
||||
component,
|
||||
referenceDate,
|
||||
status: 'indeterminate',
|
||||
value: null,
|
||||
unit: null,
|
||||
explanation: `A componente ${component} não tem regra oficial aprovada e vigente associada neste simulador.`,
|
||||
missingInputs: [
|
||||
'approved_rule',
|
||||
'effective_parameters',
|
||||
'applicable_classification',
|
||||
],
|
||||
sourceIds: [],
|
||||
};
|
||||
}
|
||||
|
||||
export type SimulationSnapshot = {
|
||||
personal_snapshot: Record<string, unknown>;
|
||||
economic_snapshot: Record<string, unknown>;
|
||||
context: SimulationContext;
|
||||
};
|
||||
|
||||
const intl = Intl as unknown as {
|
||||
supportedValuesOf?: (key: 'currency') => string[];
|
||||
};
|
||||
export function simulationCurrencyFractionDigits(value: string): number | null {
|
||||
try {
|
||||
const digits = new Intl.NumberFormat('en', {
|
||||
style: 'currency',
|
||||
currency: value,
|
||||
}).resolvedOptions().maximumFractionDigits;
|
||||
return digits !== undefined && Number.isInteger(digits) ? digits : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export const simulationCurrencyOptions = [
|
||||
...new Set([
|
||||
'MZN',
|
||||
'USD',
|
||||
'EUR',
|
||||
'ZAR',
|
||||
...(intl.supportedValuesOf?.('currency') ?? []),
|
||||
]),
|
||||
]
|
||||
.filter((code) => simulationCurrencyFractionDigits(code) === 2)
|
||||
.sort();
|
||||
export const isSimulationCurrency = (value: string): boolean =>
|
||||
simulationCurrencyOptions.includes(value);
|
||||
|
||||
/** Rejects contradictory states so missing/unknown values cannot silently become zero. */
|
||||
export function validateSimulationResult<TValue>(
|
||||
result: SimulationResult<TValue>,
|
||||
): string[] {
|
||||
const errors: string[] = [];
|
||||
if (!result.explanation.trim()) errors.push('explanation');
|
||||
if (result.status === 'calculated' && result.value === null)
|
||||
errors.push('calculated_value');
|
||||
if (
|
||||
result.status === 'indeterminate' &&
|
||||
(result.value !== null || result.missingInputs.length === 0)
|
||||
)
|
||||
errors.push('indeterminate_inputs');
|
||||
if (result.status === 'not_applicable' && result.value !== null)
|
||||
errors.push('not_applicable_value');
|
||||
if (result.status === 'estimated' && result.value === null)
|
||||
errors.push('estimated_value');
|
||||
return errors;
|
||||
}
|
||||
+1852
-179
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user