Integrate monthly IVA with projected sales in QA
This commit is contained in:
@@ -776,6 +776,23 @@ function multiplyQuantity(
|
||||
return (quantityMilli * unitPriceCents + 500n) / 1000n;
|
||||
}
|
||||
|
||||
/** Reuses the sales model, without requiring unrelated cost/cash assumptions. Blank is never zero. */
|
||||
export function monthlyProjectedSales(input: BusinessFinancialPlanInput): Array<string | null> {
|
||||
const periods = input.periods ?? 12;
|
||||
if (!Number.isInteger(periods) || periods < 1 || periods > 60) throw new Error('Horizonte de vendas inválido.');
|
||||
return Array.from({ length: periods }, (_, month) => {
|
||||
if (!input.products.length) return null;
|
||||
let total = 0n;
|
||||
for (const product of input.products) {
|
||||
const units = product.monthlyUnitsByPeriod === undefined ? product.monthlyUnits : product.monthlyUnitsByPeriod[month];
|
||||
const price = product.unitPriceByPeriod === undefined ? product.unitPrice : product.unitPriceByPeriod[month];
|
||||
if (typeof units !== 'string' || typeof price !== 'string' || units.trim() === '' || price.trim() === '') return null;
|
||||
total += multiplyQuantity(quantity(units), cents(price, `Preço de ${product.label}`));
|
||||
}
|
||||
return format(total);
|
||||
});
|
||||
}
|
||||
|
||||
function format(centsValue: bigint): string {
|
||||
const absolute = centsValue < 0n ? -centsValue : centsValue;
|
||||
return `${centsValue < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`;
|
||||
|
||||
@@ -19,7 +19,13 @@ export function fiscalQaRows(value: unknown): Array<[string, string]> {
|
||||
typeof item === "string" || typeof item === "number"
|
||||
? String(item)
|
||||
: "não disponível";
|
||||
const monthly = snapshot.monthly_projection as {rows?: Array<Record<string,unknown>>; cash_treatment?: string} | undefined;
|
||||
return [
|
||||
...(monthly?.rows ? [
|
||||
["Projecção mensal", "Vendas tributáveis sem IVA → taxa aplicada → IVA calculado → total com IVA; não é apuramento final"],
|
||||
...monthly.rows.map((row) => [`Mês ${text(row.date)}`, `Vendas declaradas: ${text(row.sales_declared)}; base líquida: ${text(row.net_sales)}; taxa: ${row.rate == null ? 'não aplicada' : `${text(row.rate)}%`}; IVA: ${text(row.vat)}; total com IVA: ${text(row.gross_sales)}; ${row.status === 'calculated' ? 'calculado' : row.status === 'missing_sales' ? 'sem informação de vendas' : row.status === 'unsupported_basis' ? 'base líquida não determinada' : 'enquadramento ou regra indeterminados'}`]),
|
||||
["Tratamento na tesouraria", monthly.cash_treatment ?? "IVA separado; não é custo nem imposto a pagar"],
|
||||
] as Array<[string,string]> : []),
|
||||
["Relatório", published ? "IVA pela versão publicada; ver enquadramento abaixo" : "Pré-visualização fiscal QA de rascunho — sem activação"],
|
||||
[
|
||||
"IVA calculado (exacto; não é saldo a pagar)",
|
||||
@@ -29,7 +35,7 @@ export function fiscalQaRows(value: unknown): Array<[string, string]> {
|
||||
["Base tributável declarada", text(snapshot.base)],
|
||||
["Taxa cadastrada (%)", text(parameters?.IVA_GENERAL_RATE?.value)],
|
||||
["Moeda explícita", text(value.context.currency)],
|
||||
["Data de exigibilidade declarada", value.context.reference_date],
|
||||
[monthly ? "Início da projecção mensal" : "Data de exigibilidade declarada", value.context.reference_date],
|
||||
[
|
||||
"Enquadramento",
|
||||
provenance?.scope_status === "undetermined" ? "Indeterminado: falta declaração do enquadramento" : "Declarado pelo utilizador; não validado juridicamente",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { monthlyProjectedSales, restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
|
||||
import { restoreCashflowDraftSnapshot } from './monthly-cashflow.ts';
|
||||
import { isApiSimulationReadResponseV1, type ApiSimulationExecutionV1 } from './simulation-contract.ts';
|
||||
|
||||
export type MonthlyIvaInput = {
|
||||
scenario_kind: 'fiscal_rule_published';
|
||||
monthly_sales: Array<{ date: string; amount: string | null }>;
|
||||
sales_vat_basis: 'net' | 'included' | 'unknown';
|
||||
currency: string;
|
||||
scope_declared: boolean;
|
||||
};
|
||||
export type MonthlyIvaSettings = { start: string; basis: MonthlyIvaInput['sales_vat_basis']; declared: boolean; auto: boolean };
|
||||
export type MonthlyIvaRecord = { input: MonthlyIvaInput; execution: ApiSimulationExecutionV1 };
|
||||
export function readMonthlyIvaSettings(raw?: string): MonthlyIvaSettings {
|
||||
try { const value = JSON.parse(raw ?? '');
|
||||
if (typeof value.start === 'string' && ['net', 'included', 'unknown'].includes(value.basis) && typeof value.declared === 'boolean' && typeof value.auto === 'boolean') return value;
|
||||
} catch { /* An invalid setting is not an invented business assumption. */ }
|
||||
return {start: '', basis: 'unknown', declared: false, auto: false};
|
||||
}
|
||||
export function monthlySalesFromDraft(draft: Record<string, unknown>): { amounts: Array<string | null>; source: string } {
|
||||
if (draft.business_plan_snapshot) {
|
||||
const plan = restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot));
|
||||
if (!plan) throw new Error('Não foi possível recuperar a projecção de vendas. Os dados guardados não foram substituídos.');
|
||||
return {amounts: monthlyProjectedSales(plan), source: 'Vendas por produto e mês do plano empresarial; mesmos pressupostos e representação monetária da projecção de vendas.'};
|
||||
}
|
||||
if (draft.cashflow_snapshot) {
|
||||
const saved = restoreCashflowDraftSnapshot(String(draft.cashflow_snapshot));
|
||||
if (!saved) throw new Error('Não foi possível recuperar a receita projectada.');
|
||||
return {amounts: Array.from({length: 12}, () => saved.inputs.monthlyRevenue.trim() === '' ? null : saved.inputs.monthlyRevenue), source: 'Receita mensal constante já declarada na projecção de tesouraria; confirme que corresponde a vendas tributáveis.'};
|
||||
}
|
||||
return {amounts: Array.from({length: 12}, () => null), source: 'Sem projecção de vendas guardada. Prepare as vendas no plano empresarial; não é necessário voltar a introduzi-las aqui.'};
|
||||
}
|
||||
export function monthlyIvaInput(draft: Record<string, unknown>, settings: MonthlyIvaSettings): MonthlyIvaInput {
|
||||
const sales = monthlySalesFromDraft(draft);
|
||||
if (!/^2026-(0[1-9]|1[0-2])$/.test(settings.start)) throw new Error('Indique o primeiro mês real da projecção. Este lote abrange apenas 2026.');
|
||||
const start = Number(settings.start.slice(5));
|
||||
if (sales.amounts.length > 12 || start + sales.amounts.length > 13) throw new Error('O horizonte ultrapassa a cobertura de 2026. Esta versão não calcula os meses fora desse período.');
|
||||
return {scenario_kind: 'fiscal_rule_published', monthly_sales: sales.amounts.map((amount, index) => ({date: `2026-${String(start + index).padStart(2, '0')}-01`, amount})),
|
||||
sales_vat_basis: settings.basis, currency: String(draft.currency ?? ''), scope_declared: settings.declared};
|
||||
}
|
||||
export function monthlyIvaKey(input: Omit<MonthlyIvaInput, 'scenario_kind'>): string {
|
||||
return JSON.stringify([input.currency, input.sales_vat_basis, input.scope_declared, input.monthly_sales.map((row) => [row.date, row.amount])]);
|
||||
}
|
||||
export function readMonthlyIvaRecord(raw?: string): MonthlyIvaRecord | null {
|
||||
try { const value = JSON.parse(raw ?? '');
|
||||
if (value?.input?.scenario_kind === 'fiscal_rule_published' && Array.isArray(value.input.monthly_sales) && isApiSimulationReadResponseV1({data: value.execution})) return value;
|
||||
} catch { /* Keep the stored value intact; no fallback fiscal result. */ }
|
||||
return null;
|
||||
}
|
||||
export const monthlyIvaCashTreatment = 'IVA apresentado separadamente: não é somado novamente aos recebimentos declarados nem deduzido como custo ou imposto final a pagar. A tesouraria conserva os recebimentos e pagamentos introduzidos, antes de uma liquidação fiscal não apurada; não se presume cobrança integral das vendas no mesmo mês.';
|
||||
@@ -173,6 +173,7 @@ const rowSection: Record<string, DossierReportSectionId> = {
|
||||
'Ponto de equilíbrio': 'finance',
|
||||
Orçamento: 'finance',
|
||||
Tesouraria: 'finance',
|
||||
'IVA mensal': 'finance',
|
||||
Equipa: 'team',
|
||||
'Necessidade de negócio': 'resources',
|
||||
Financiamento: 'resources',
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { monthlyIvaInput, monthlyIvaKey, readMonthlyIvaRecord, readMonthlyIvaSettings } from './monthly-iva.ts';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { csvCellWithDelimiter } from './csv.js';
|
||||
import {
|
||||
restoreCashflowDraftSnapshot,
|
||||
@@ -608,6 +610,14 @@ export function buildProjectDossierRows(
|
||||
'Planeado/realizado declarado pelo utilizador',
|
||||
]);
|
||||
}
|
||||
if (draft.monthly_iva_snapshot) {
|
||||
const saved = readMonthlyIvaRecord(String(draft.monthly_iva_snapshot));
|
||||
let current = false;
|
||||
try { current = !!saved && monthlyIvaKey(monthlyIvaInput(draft, readMonthlyIvaSettings(String(draft.monthly_iva_settings ?? '')))) === monthlyIvaKey(saved.input); } catch { /* An old fiscal version is never silently made current. */ }
|
||||
rows.push(['IVA mensal', 'Estado da versão', current ? 'Entradas correspondentes à projecção guardada' : 'Histórico desactualizado face às vendas ou pressupostos actuais; não aplicar como resultado actual', 'Execução versionada no servidor; sem apuramento final']);
|
||||
if (saved?.execution.result_snapshot) for (const [label,value] of fiscalQaRows(saved.execution.result_snapshot)) rows.push(['IVA mensal', label, value, 'Snapshot fiscal preservado; sem recálculo na exportação']);
|
||||
else rows.push(['IVA mensal', 'Resultado', 'Indeterminado ou execução ainda não concluída', 'Sem substituição por zero']);
|
||||
}
|
||||
if (draft.cashflow_snapshot) {
|
||||
const saved = restoreCashflowDraftSnapshot(
|
||||
String(draft.cashflow_snapshot),
|
||||
|
||||
Reference in New Issue
Block a user