Decisão do proprietário de 04/12/2026. Quando o «IVA mensal das vendas projectadas» está calculado para as vendas actuais (taxa da actividade, 16% ou 5%), o fluxo de caixa do relatório financeiro integral passa a ter «IVA recebido dos clientes», em proporção das vendas efectivamente cobradas, e «IVA entregue ao Estado» no mês seguinte ao da facturação, com a declaração periódica (CIVA, Lei 13/2016, artigos 23(1) e 32(1)(b): até ao último dia do mês seguinte). O balanço mostra o «IVA a entregar ao Estado» e o IVA facturado ainda por cobrar fica nos recebíveis; o balanço continua reconciliado e o resultado não muda, porque o IVA não é receita nem custo. Sem resultado actual e completo, o IVA não entra e o plano diz o que falta calcular. O resumo do dossier soma o IVA às cobranças e aos pagamentos para coincidir com as tabelas. O IVA dedutível nas compras não é considerado. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
231 lines
9.3 KiB
TypeScript
231 lines
9.3 KiB
TypeScript
import { inputText } from './input-text.ts';
|
|
import { ivaTreatmentForCae } from './iva-activity.ts';
|
|
import type { IntegralVat } from './integral-financial-report.ts';
|
|
import {
|
|
monthlyProjectedSales,
|
|
restoreBusinessPlanSnapshot,
|
|
} from './business-financial-plan.ts';
|
|
import {
|
|
cashflowCurrency,
|
|
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;
|
|
/** Present only for the reduced rate of artigo 17-A; absent means the general rate. */
|
|
operation?: 'internal_reduced_17a_net';
|
|
};
|
|
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(
|
|
inputText(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.',
|
|
);
|
|
if (draft.currency && plan.currency && draft.currency !== plan.currency)
|
|
throw new Error(
|
|
`A projecção de vendas está em ${plan.currency}, mas o projecto está em ${inputText(draft.currency)}. Reveja a moeda da projecção; os valores não foram convertidos nem reclassificados.`,
|
|
);
|
|
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(
|
|
inputText(draft.cashflow_snapshot),
|
|
);
|
|
if (!saved)
|
|
throw new Error('Não foi possível recuperar a receita projectada.');
|
|
const origin = cashflowCurrency(saved, inputText(draft.currency ?? ''));
|
|
if (!origin.matchesProject) throw new Error(origin.notice);
|
|
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 {
|
|
if (
|
|
draft.fiscal_period &&
|
|
inputText(draft.fiscal_period) !== settings.start.slice(0, 4)
|
|
)
|
|
throw new Error(
|
|
'O ano escolhido no enquadramento fiscal difere do primeiro mês da projecção. Confira o período; nenhum ano foi alterado automaticamente.',
|
|
);
|
|
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 cálculo dispõe de cobertura apenas para 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: inputText(draft.currency ?? ''),
|
|
scope_declared: settings.declared,
|
|
...(monthlyIvaTreatment(draft).operation === 'internal_reduced_17a_net'
|
|
? { operation: 'internal_reduced_17a_net' as const }
|
|
: {}),
|
|
};
|
|
}
|
|
|
|
/** The IVA of the plan's sales follows the activity declared in the plan (CAE). */
|
|
export function monthlyIvaTreatment(draft: Record<string, unknown>) {
|
|
const plan = draft.business_plan_snapshot
|
|
? restoreBusinessPlanSnapshot(inputText(draft.business_plan_snapshot))
|
|
: null;
|
|
return ivaTreatmentForCae(plan?.economicClassification?.code);
|
|
}
|
|
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]),
|
|
// General-rate keys stay as before, so earlier results remain current.
|
|
...(input.operation ? [input.operation] : []),
|
|
]);
|
|
}
|
|
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;
|
|
}
|
|
/** Read an admitted execution through the existing ownership-protected endpoint; never create one. */
|
|
export async function recoverMonthlyIvaRecord(
|
|
record: MonthlyIvaRecord,
|
|
request: typeof fetch = fetch,
|
|
): Promise<MonthlyIvaRecord> {
|
|
const response = await request(
|
|
`/api/v1/simulations/${encodeURIComponent(record.execution.id)}`,
|
|
{ credentials: 'same-origin', headers: { Accept: 'application/json' } },
|
|
);
|
|
const value: unknown = await response.json();
|
|
if (
|
|
!response.ok ||
|
|
!isApiSimulationReadResponseV1(value) ||
|
|
value.data.id !== record.execution.id
|
|
)
|
|
throw new Error(
|
|
'Não foi possível recuperar a execução mensal guardada. Os dados foram preservados e não foi criada uma execução alternativa.',
|
|
);
|
|
return { input: record.input, execution: value.data };
|
|
}
|
|
export const monthlyIvaCashTreatment =
|
|
'IVA apresentado em linhas próprias: não é somado novamente aos recebimentos declarados nem deduzido como custo. No relatório financeiro integral, o IVA recebido com as cobranças das vendas e o IVA entregue ao Estado no mês seguinte (CIVA, artigos 23(1) e 32(1)(b)) entram na tesouraria; não se presume cobrança integral das vendas no mesmo mês.';
|
|
|
|
/**
|
|
* The IVA of the plan's sales for the treasury: only from a completed result
|
|
* that still matches the current sales, activity and basis, with every month
|
|
* determined. Otherwise null, and the treasury says the IVA is not included.
|
|
*/
|
|
export function integralVatFromDraft(
|
|
draft: Record<string, unknown>,
|
|
): IntegralVat | null {
|
|
const record = readMonthlyIvaRecord(
|
|
inputText(draft.monthly_iva_snapshot ?? ''),
|
|
);
|
|
if (!record || record.execution.status !== 'completed') return null;
|
|
let input: MonthlyIvaInput;
|
|
try {
|
|
input = monthlyIvaInput(
|
|
draft,
|
|
readMonthlyIvaSettings(inputText(draft.monthly_iva_settings ?? '')),
|
|
);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (monthlyIvaKey(record.input) !== monthlyIvaKey(input)) return null;
|
|
const rows = (
|
|
record.execution.result_snapshot?.monthly_projection as
|
|
| { rows?: { vat: string | null; rate: string | null }[] }
|
|
| undefined
|
|
)?.rows;
|
|
if (!rows?.length || rows.some((row) => row.vat === null || !row.rate))
|
|
return null;
|
|
const rate = rows[0].rate!;
|
|
if (rows.some((row) => row.rate !== rate)) return null;
|
|
const treatment = monthlyIvaTreatment(draft);
|
|
return {
|
|
ratePercent: rate,
|
|
billedByMonth: rows.map((row) => centsHalfUp(row.vat!)),
|
|
source: `${treatment.label}, ${treatment.article}; versão publicada aplicada pelo servidor`,
|
|
};
|
|
}
|
|
|
|
/** A non-negative decimal with up to 4 places, rounded half up to cents. */
|
|
function centsHalfUp(value: string): bigint {
|
|
const [whole, fraction = ''] = value.split('.');
|
|
const digits = BigInt(whole + fraction.padEnd(4, '0').slice(0, 4));
|
|
return (digits + 50n) / 100n;
|
|
}
|