From 2b9b6c367dd370f37b012f58ce12283b3b1ed066 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 00:42:51 +0200 Subject: [PATCH] =?UTF-8?q?IVA=20pela=20actividade:=205%=20do=20artigo=201?= =?UTF-8?q?7-A=20para=20sa=C3=BAde=20e=20ensino,=2016%=20para=20as=20resta?= =?UTF-8?q?ntes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decisão do proprietário de 04/12/2026: o investidor não escolhe a taxa de IVA; ela decorre da actividade (CAE) do plano. Saúde privada (CAE 86), ensino privado reconhecido e formação profissional usam a taxa reduzida do artigo 17-A da Lei 22/2022; as restantes actividades usam a taxa geral. O IVA mensal das vendas mostra a taxa, a base legal e as condições da lei para o investidor confirmar. A taxa reduzida é uma versão governada própria (IVA-REDUZIDA-17A-BASE-LIQUIDA), com ficha em database/qa, registo QA por fiscal:qa-register-iva --reduced, pré-visualização QA e ligação por INVESTMOZ_IVA_REDUCED_RULE_ID/VERSION. Enquanto não estiver publicada, o IVA das actividades a 5% fica por determinar e nunca usa a taxa geral em substituição. Os resultados anteriores à taxa geral continuam actuais. Decisões e pendências da sessão registadas no manual existente. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM --- .../Commands/RegisterFiscalQaDraft.php | 13 ++- .../SimulationTaxRuleGovernanceController.php | 2 +- app/Http/Requests/StoreSimulationRequest.php | 3 +- app/Services/SimulationFiscalQaPreview.php | 9 +- app/Services/SimulationPublishedFiscal.php | 48 +++++++--- config/simulation-fiscal-consumer.php | 3 + database/qa/iva-reduced-17a-net-v1.json | 62 ++++++++++++ .../js/components/simulation-monthly-iva.tsx | 83 +++++++++++++--- resources/js/lib/iva-activity.ts | 48 ++++++++++ resources/js/lib/monthly-iva.ts | 16 ++++ .../Feature/SimulationPublishedFiscalTest.php | 33 +++++++ tests/frontend/iva-activity.test.mjs | 96 +++++++++++++++++++ 12 files changed, 379 insertions(+), 37 deletions(-) create mode 100644 database/qa/iva-reduced-17a-net-v1.json create mode 100644 resources/js/lib/iva-activity.ts create mode 100644 tests/frontend/iva-activity.test.mjs diff --git a/app/Console/Commands/RegisterFiscalQaDraft.php b/app/Console/Commands/RegisterFiscalQaDraft.php index 326489d4..fbf78a53 100644 --- a/app/Console/Commands/RegisterFiscalQaDraft.php +++ b/app/Console/Commands/RegisterFiscalQaDraft.php @@ -14,18 +14,23 @@ use Illuminate\Console\Command; /** Explicit registration: never run during migration, deployment or document import. */ class RegisterFiscalQaDraft extends Command { - protected $signature = 'fiscal:qa-register-iva {actor : Existing QA editor ID} {source : Existing accepted legal source UUID}'; + protected $signature = 'fiscal:qa-register-iva {actor : Existing QA editor ID} {source : Existing accepted legal source UUID} + {--reduced : Taxa reduzida do artigo 17-A (5%) em vez da taxa geral}'; - protected $description = 'Cadastrar apenas o rascunho IVA do primeiro lote numa base QA isolada, sem publicação'; + protected $description = 'Cadastrar apenas o rascunho IVA (taxa geral ou, com --reduced, taxa do artigo 17-A) numa base QA isolada, sem publicação'; public function handle(SimulationTaxRuleGovernance $governance): int { abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 403, 'O cadastro deste lote só é permitido na base QA isolada.'); $actor = User::findOrFail($this->argument('actor')); $source = InvestmentLegalSource::findOrFail($this->argument('source')); + $reduced = (bool) $this->option('reduced'); + $article = $reduced ? 'Artigo 17-A' : 'Artigo 17(1)'; abort_unless($source->validation_status === 'validated' && $source->diploma === 'Lei 22/2022' - && $source->article === 'Artigo 17(1)', 422, 'Seleccione a referência aceite da taxa geral, Lei 22/2022, artigo 17(1).'); - $payload = json_decode(CheckedFile::read(database_path('qa/iva-general-net-v1.json')), true, flags: JSON_THROW_ON_ERROR); + && $source->article === $article, 422, $reduced + ? 'Seleccione a referência aceite da taxa reduzida, Lei 22/2022, artigo 17-A.' + : 'Seleccione a referência aceite da taxa geral, Lei 22/2022, artigo 17(1).'); + $payload = json_decode(CheckedFile::read(database_path($reduced ? 'qa/iva-reduced-17a-net-v1.json' : 'qa/iva-general-net-v1.json')), true, flags: JSON_THROW_ON_ERROR); $actualHash = CheckedFile::sha256(base_path('docs/investmoz/simulations/source-archive/Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf')); abort_unless(hash_equals($payload['source_sha256'], $actualHash), 422, 'O exemplar não corresponde ao hash da ficha.'); $payload['legal_source_id'] = (string) $source->id; diff --git a/app/Http/Controllers/SimulationTaxRuleGovernanceController.php b/app/Http/Controllers/SimulationTaxRuleGovernanceController.php index be22df54..370f8d4e 100644 --- a/app/Http/Controllers/SimulationTaxRuleGovernanceController.php +++ b/app/Http/Controllers/SimulationTaxRuleGovernanceController.php @@ -38,7 +38,7 @@ class SimulationTaxRuleGovernanceController extends Controller 'base' => ['required', 'string', 'max:40', 'regex:/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/D'], 'reference_date' => ['required', 'date_format:Y-m-d'], 'currency' => ['required', 'in:MZN'], - 'operation' => ['required', 'in:internal_general_net'], + 'operation' => ['required', 'in:internal_general_net,internal_reduced_17a_net'], ]); $result = $preview->create($request->user(), $id, $input, $key); $simulation = $result['simulation']; diff --git a/app/Http/Requests/StoreSimulationRequest.php b/app/Http/Requests/StoreSimulationRequest.php index 9c673ca7..e6cbf0eb 100644 --- a/app/Http/Requests/StoreSimulationRequest.php +++ b/app/Http/Requests/StoreSimulationRequest.php @@ -52,6 +52,7 @@ class StoreSimulationRequest extends FormRequest 'monthly_sales.*.date' => ['required', 'date_format:Y-m-d', 'regex:/^2026-\d{2}-01$/D', 'distinct'], 'monthly_sales.*.amount' => ['present', 'nullable', 'string', 'max:40', 'regex:/^\d+(?:\.\d+)?$/D'], 'sales_vat_basis' => ['required', 'in:net,included,unknown'], + 'operation' => ['sometimes', 'in:internal_general_net,internal_reduced_17a_net'], 'currency' => ['required', 'in:MZN'], 'scope_declared' => ['required', 'boolean'], 'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'], @@ -65,7 +66,7 @@ class StoreSimulationRequest extends FormRequest 'base' => ['required', 'string', 'max:40', 'regex:/^\d+(?:\.\d+)?$/'], 'currency' => ['required', 'in:MZN'], 'reference_date' => ['required', 'date_format:Y-m-d'], - 'operation' => ['required', 'in:internal_general_net'], + 'operation' => ['required', 'in:internal_general_net,internal_reduced_17a_net'], 'scope_declared' => ['required', 'boolean'], 'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'], 'rate' => ['prohibited'], 'reduction' => ['prohibited'], diff --git a/app/Services/SimulationFiscalQaPreview.php b/app/Services/SimulationFiscalQaPreview.php index 0b94c344..79f8a049 100644 --- a/app/Services/SimulationFiscalQaPreview.php +++ b/app/Services/SimulationFiscalQaPreview.php @@ -23,8 +23,9 @@ final class SimulationFiscalQaPreview return DB::transaction(function () use ($actor, $ruleId, $input, $key): array { $rule = app(SimulationTaxRuleGovernance::class)->show($actor, $ruleId); - abort_unless($rule->status === 'draft' && $rule->rule_code === 'IVA-GERAL-BASE-LIQUIDA', 422, - 'Seleccione o rascunho do primeiro lote fiscal.'); + $binding = SimulationPublishedFiscal::OPERATIONS[$input['operation']] ?? null; + abort_unless($binding && $rule->status === 'draft' && $rule->rule_code === $binding['rule_code'], 422, + 'Seleccione o rascunho do lote fiscal correspondente à operação.'); abort_if(collect(StructuredData::collectionItems($rule->rule_definition['nodes'] ?? []))->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422, 'Este percurso preserva o valor exacto e não aplica arredondamento automático.'); $source = InvestmentLegalSource::findOrFail($rule->legal_source_id); @@ -39,12 +40,12 @@ final class SimulationFiscalQaPreview $missing[] = 'demonstrated_coverage'; } else { $resolution = app(SimulationTaxParameterResolver::class)->resolveDraftForQa([$version], 'IVA', $date, $date, $context); - $rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE'); + $rate = collect($resolution)->firstWhere('parameter_code', $binding['parameter']); if (($rate['status'] ?? null) !== 'resolved' || ($rate['unit'] ?? null) !== 'percent') { $missing[] = 'eligible_parameter'; } else { $evaluation = app(SimulationTaxRuleExpression::class)->evaluate($rule->rule_definition, - ['base_tributavel' => $input['base']], ['iva_general_rate' => $rate['value']]); + ['base_tributavel' => $input['base']], [$binding['expression_key'] => $rate['value']]); } } $snapshot = app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing); diff --git a/app/Services/SimulationPublishedFiscal.php b/app/Services/SimulationPublishedFiscal.php index 78e9df8e..8b2fe810 100644 --- a/app/Services/SimulationPublishedFiscal.php +++ b/app/Services/SimulationPublishedFiscal.php @@ -16,6 +16,18 @@ use Illuminate\Support\Str; /** Admission freezes eligibility without granting the public consumer governance write access. */ final class SimulationPublishedFiscal { + /** + * Published IVA versions this consumer may use, one per operation. The reduced rate is the one of artigo 17-A, + * Lei 22/2022 (CIVA republicado), for the operations of artigo 15(10): private health, recognised private + * education, private vocational training and personal lessons. + */ + public const OPERATIONS = [ + 'internal_general_net' => ['config' => '', 'rule_code' => 'IVA-GERAL-BASE-LIQUIDA', 'scope_key' => 'mz.internal-general-net.mzn', + 'parameter' => 'IVA_GENERAL_RATE', 'expression_key' => 'iva_general_rate', 'label' => 'IVA geral sobre base líquida'], + 'internal_reduced_17a_net' => ['config' => 'reduced_', 'rule_code' => 'IVA-REDUZIDA-17A-BASE-LIQUIDA', 'scope_key' => 'mz.internal-reduced-17a-net.mzn', + 'parameter' => 'IVA_REDUCED_17A_RATE', 'expression_key' => 'iva_reduced_17a_rate', 'label' => 'IVA à taxa reduzida do artigo 17-A sobre base líquida'], + ]; + /** * @return array */ @@ -23,25 +35,29 @@ final class SimulationPublishedFiscal { $enabled = (bool) config('simulation-fiscal-consumer.enabled'); $eligible = $enabled && $this->boundRule()->where('status', 'published')->exists(); + $reduced = $enabled && $this->boundRule('internal_reduced_17a_net')->where('status', 'published')->exists(); - return ['enabled' => $eligible, 'coverage_start' => '2026-01-01', 'coverage_end' => '2026-12-31', + return ['enabled' => $eligible, 'reduced_enabled' => $reduced, 'coverage_start' => '2026-01-01', 'coverage_end' => '2026-12-31', 'message' => $eligible ? 'IVA geral sobre base líquida disponível; enquadramento declarado.' - : 'O cálculo de IVA geral sobre base líquida está indisponível para novas execuções. Os históricos mantêm-se acessíveis.']; + : 'O cálculo de IVA geral sobre base líquida está indisponível para novas execuções. Os históricos mantêm-se acessíveis.', + 'reduced_message' => $reduced ? 'IVA à taxa reduzida de 5% (artigo 17-A) disponível; enquadramento declarado.' + : 'O IVA à taxa reduzida de 5% (artigo 17-A) ainda não está publicado para novas execuções.']; } /** * @return Builder */ - private function boundRule(): Builder + private function boundRule(string $operation = 'internal_general_net'): Builder { - if (! Str::isUuid((string) config('simulation-fiscal-consumer.rule_id')) || config('simulation-fiscal-consumer.rule_version') < 1) { + $binding = self::OPERATIONS[$operation] ?? null; + $ruleId = $binding ? (string) config('simulation-fiscal-consumer.'.$binding['config'].'rule_id') : ''; + $version = $binding ? (int) config('simulation-fiscal-consumer.'.$binding['config'].'rule_version') : 0; + if (! Str::isUuid($ruleId) || $version < 1) { return SimulationTaxRuleVersion::query()->whereRaw('false'); } - return SimulationTaxRuleVersion::query()->whereKey(config('simulation-fiscal-consumer.rule_id')) - ->where('rule_version', config('simulation-fiscal-consumer.rule_version')) - ->where('rule_code', 'IVA-GERAL-BASE-LIQUIDA')->where('component', 'IVA') - ->where('scope_key', 'mz.internal-general-net.mzn'); + return SimulationTaxRuleVersion::query()->whereKey($ruleId)->where('rule_version', $version) + ->where('rule_code', $binding['rule_code'])->where('component', 'IVA')->where('scope_key', $binding['scope_key']); } /** @@ -57,8 +73,11 @@ final class SimulationPublishedFiscal abort_unless(DB::transactionLevel() > 0, 500); abort_unless(config('simulation-fiscal-consumer.enabled'), 503, 'O cálculo de IVA está temporariamente indisponível. Os dados e históricos foram preservados.'); - DB::select('select pg_advisory_xact_lock_shared(261021, hashtext(?))', [(string) config('simulation-fiscal-consumer.rule_id')]); - $rule = $this->boundRule()->first(); + $operation = (string) ($input['operation'] ?? 'internal_general_net'); + $binding = self::OPERATIONS[$operation] ?? null; + abort_unless($binding, 422, 'Operação de IVA não suportada. As entradas foram preservadas.'); + DB::select('select pg_advisory_xact_lock_shared(261021, hashtext(?))', [(string) config('simulation-fiscal-consumer.'.$binding['config'].'rule_id')]); + $rule = $this->boundRule($operation)->first(); abort_unless($rule && $rule->status === 'published', 503, 'A versão autorizada de IVA não está disponível para novas execuções. Os históricos foram preservados.'); abort_if($input['reference_date'] < '2026-01-01' || $input['reference_date'] > '2026-12-31', 422, @@ -77,7 +96,7 @@ final class SimulationPublishedFiscal ])); $resolution = app(SimulationTaxParameterResolver::class)->resolvePublishedForPeriod('IVA', $input['reference_date'], $input['reference_date'], ['currency' => $input['currency'], 'operation' => $input['operation']]); - $rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE'); + $rate = collect($resolution)->firstWhere('parameter_code', $binding['parameter']); $missing = []; if ($missingBase) { $missing[] = 'taxable_sales'; @@ -93,7 +112,7 @@ final class SimulationPublishedFiscal } if ($missing === []) { $evaluation = app(SimulationTaxRuleExpression::class)->evaluate($rule->rule_definition, - ['base_tributavel' => $input['base']], ['iva_general_rate' => $rate['value']]); + ['base_tributavel' => $input['base']], [$binding['expression_key'] => $rate['value']]); } return app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing, true); @@ -115,11 +134,12 @@ final class SimulationPublishedFiscal $previous = $sale['date']; $known = $sale['amount'] !== null && $sale['amount'] !== ''; $net = $input['sales_vat_basis'] === 'net'; + $operation = (string) ($input['operation'] ?? 'internal_general_net'); $month = $this->admit(['base' => $known && $net ? $sale['amount'] : null, 'currency' => $input['currency'], 'reference_date' => $sale['date'], - 'operation' => 'internal_general_net', 'scope_declared' => $input['scope_declared']], ! $known || ! $net); + 'operation' => $operation, 'scope_declared' => $input['scope_declared']], ! $known || ! $net); $snapshot ??= $month; - $rate = collect(StructuredData::collectionItems($month['fiscal_provenance']['resolution']))->firstWhere('parameter_code', 'IVA_GENERAL_RATE'); + $rate = collect(StructuredData::collectionItems($month['fiscal_provenance']['resolution']))->firstWhere('parameter_code', self::OPERATIONS[$operation]['parameter']); $vat = $month['result']['value']; $status = ! $known ? 'missing_sales' : (! $net ? 'unsupported_basis' : ($vat === null ? 'indeterminate' : 'calculated')); $rows[] = ['date' => $sale['date'], 'sales_declared' => $sale['amount'], diff --git a/config/simulation-fiscal-consumer.php b/config/simulation-fiscal-consumer.php index 8480badb..c3301a56 100644 --- a/config/simulation-fiscal-consumer.php +++ b/config/simulation-fiscal-consumer.php @@ -5,4 +5,7 @@ return [ 'enabled' => env('INVESTMOZ_IVA_CONSUMER_ENABLED', false), 'rule_id' => env('INVESTMOZ_IVA_CONSUMER_RULE_ID'), 'rule_version' => (int) env('INVESTMOZ_IVA_CONSUMER_RULE_VERSION', 0), + // Reduced rate of artigo 17-A (5%): its own published version, bound separately. + 'reduced_rule_id' => env('INVESTMOZ_IVA_REDUCED_RULE_ID'), + 'reduced_rule_version' => (int) env('INVESTMOZ_IVA_REDUCED_RULE_VERSION', 0), ]; diff --git a/database/qa/iva-reduced-17a-net-v1.json b/database/qa/iva-reduced-17a-net-v1.json new file mode 100644 index 00000000..b364ab5a --- /dev/null +++ b/database/qa/iva-reduced-17a-net-v1.json @@ -0,0 +1,62 @@ +{ + "rule_code": "IVA-REDUZIDA-17A-BASE-LIQUIDA", + "rule_version": 1, + "component": "IVA", + "scope_key": "mz.internal-reduced-17a-net.mzn", + "valid_from": "2023-01-01", + "valid_until": null, + "source_sha256": "ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53", + "rule_definition": { + "language": "investmoz.tax.v1", + "nodes": { + "base": { + "op": "input", + "key": "base_tributavel" + }, + "rate": { + "op": "parameter", + "key": "iva_reduced_17a_rate" + }, + "hundred": { + "op": "literal", + "value": "100" + }, + "product": { + "op": "multiply", + "args": [ + "base", + "rate" + ] + }, + "intermediate": { + "op": "divide", + "args": [ + "product", + "hundred" + ] + } + }, + "result": "intermediate" + }, + "parameters": { + "IVA_REDUCED_17A_RATE": { + "value": "5", + "unit": "percent", + "conditions": { + "operation": "internal_reduced_17a_net", + "currency": "MZN" + } + } + }, + "rounding_policy": { + "status": "not_applied", + "precision": "exact_decimal", + "method": "none", + "ties": "not_applicable_without_rounding", + "aggregation": "single_declared_taxable_base", + "purpose": "operation_tax_not_payment", + "evidence": "Mesma orientação do lote IVA geral (sem arredondamento automático); taxa do artigo 17-A, Lei 22/2022 (CIVA republicado), operações do artigo 15(10)", + "coverage_start": "2026-01-01", + "coverage_end": "2026-12-31" + } +} diff --git a/resources/js/components/simulation-monthly-iva.tsx b/resources/js/components/simulation-monthly-iva.tsx index 720bcf84..3c683ff8 100644 --- a/resources/js/components/simulation-monthly-iva.tsx +++ b/resources/js/components/simulation-monthly-iva.tsx @@ -21,6 +21,7 @@ import { readMonthlyIvaSettings, recoverMonthlyIvaRecord, monthlyIvaCashTreatment, + monthlyIvaTreatment, type MonthlyIvaInput, type MonthlyIvaSettings, } from '@/lib/monthly-iva'; @@ -70,6 +71,11 @@ export function SimulationMonthlyIva({ const [retry, setRetry] = useState(0); const [error, setError] = useState(''); const [available, setAvailable] = useState(null); + const [reducedAvailable, setReducedAvailable] = useState( + null, + ); + const treatment = monthlyIvaTreatment(draft); + const reduced = treatment.operation === 'internal_reduced_17a_net'; const attempt = useRef(''); const mounted = useRef(true); const latestSnapshot = useRef(draft.monthly_iva_snapshot); @@ -118,7 +124,9 @@ export function SimulationMonthlyIva({ .then(async (response) => { if (!response.ok) throw new Error(); const payload = await response.json(); - if (active) setAvailable(payload?.data?.enabled === true); + if (!active) return; + setAvailable(payload?.data?.enabled === true); + setReducedAvailable(payload?.data?.reduced_enabled === true); }) .catch(() => { if (active) @@ -134,7 +142,10 @@ export function SimulationMonthlyIva({ if (!settings.auto || busy || attempt.current === actionKey) return; if ( !pendingRecord && - (!input || input.currency !== 'MZN' || !available || completed) + (!input || + input.currency !== 'MZN' || + !(reduced ? reducedAvailable : available) || + completed) ) return; const request = pendingRecord?.input ?? input!; @@ -177,7 +188,17 @@ export function SimulationMonthlyIva({ })(); }, 700); return () => window.clearTimeout(timer); - }, [actionKey, key, settings.auto, busy, available, completed, retry]); + }, [ + actionKey, + key, + settings.auto, + busy, + available, + reducedAvailable, + reduced, + completed, + retry, + ]); const snapshot = record?.execution.result_snapshot; const projection = snapshot?.monthly_projection as @@ -205,10 +226,36 @@ export function SimulationMonthlyIva({ />

IVA mensal das vendas projectadas

{source}

+
+

+ Taxa pela actividade do plano: {treatment.rate}% —{' '} + {treatment.label} ({treatment.article}) +

+ {!treatment.fromActivity && ( +

+ Sem actividade (CAE) escolhida no plano financeiro, + aplica-se a taxa geral. Escolha a actividade no plano + para confirmar a taxa. +

+ )} + {reduced && ( + <> +

Condições da lei para a taxa de 5%:

+
    + {treatment.conditions.map((condition) => ( +
  • {condition}
  • + ))} +
+ + )} +

+ A taxa não é escolhida neste formulário: segue a actividade + e o servidor usa a versão publicada correspondente. +

+

Declare se os preços projectados são sem IVA ou com IVA - incluído. Nenhuma taxa é fixada neste formulário; o servidor - selecciona a versão publicada. + incluído.

- Sem importações, taxas reduzidas, isenções, regimes especiais, - deduções, reembolsos ou apuramento final. Valores com IVA - incluído permanecem indeterminados neste lote; não se aplica a - taxa ao preço bruto. + Sem importações, isenções, regimes especiais, deduções, + reembolsos ou apuramento final. Valores com IVA incluído + permanecem indeterminados neste lote; não se aplica a taxa ao + preço bruto.

{monthlyIvaCashTreatment}

{!!draft.currency && draft.currency !== 'MZN' && ( @@ -272,7 +320,14 @@ export function SimulationMonthlyIva({ A consultar a disponibilidade da versão publicada…

)} - {available === false && ( + {reduced && reducedAvailable === false && ( +

+ A taxa de 5% (artigo 17-A) ainda não está publicada neste + ambiente. O IVA destas vendas fica por determinar; não se + usa a taxa geral em substituição. +

+ )} + {!reduced && available === false && (

A versão publicada de IVA está indisponível neste ambiente para novas execuções. Os pressupostos e históricos @@ -308,7 +363,9 @@ export function SimulationMonthlyIva({ disabled={ busy || (!pendingRecord && - (!available || !input || input.currency !== 'MZN')) + (!(reduced ? reducedAvailable : available) || + !input || + input.currency !== 'MZN')) } onClick={() => { attempt.current = ''; diff --git a/resources/js/lib/iva-activity.ts b/resources/js/lib/iva-activity.ts new file mode 100644 index 00000000..53c2a33b --- /dev/null +++ b/resources/js/lib/iva-activity.ts @@ -0,0 +1,48 @@ +import { operationTreatments } from './iva-operations.ts'; + +export type IvaActivityOperation = + | 'internal_general_net' + | 'internal_reduced_17a_net'; + +export type IvaActivityTreatment = { + operation: IvaActivityOperation; + rate: 16 | 5; + label: string; + article: string; + conditions: string[]; + /** True when the plan has a documented activity; otherwise the general rate is only the default. */ + fromActivity: boolean; +}; + +const treatment = ( + id: string, + operation: IvaActivityOperation, + fromActivity: boolean, +): IvaActivityTreatment => { + const row = operationTreatments.find((item) => item.id === id)!; + return { + operation, + rate: operation === 'internal_general_net' ? 16 : 5, + label: row.label, + article: row.article, + conditions: [...row.conditions], + fromActivity, + }; +}; + +/** + * IVA follows the activity, not a choice of rate (owner decision 04/12/2026). + * CAE-Rev.2 subclasses that are the operations of artigo 15(10) take the + * reduced rate of artigo 17-A; every other activity takes the general rate. + * The conditions of the law are shown for the investor to confirm. + */ +export function ivaTreatmentForCae(code?: string | null): IvaActivityTreatment { + const cae = (code ?? '').trim(); + if (/^86\d{3}$/.test(cae)) + return treatment('private_health', 'internal_reduced_17a_net', true); + if (cae === '85492') + return treatment('private_training', 'internal_reduced_17a_net', true); + if (/^85(1\d{2}|2[12]\d|300)$/.test(cae)) + return treatment('private_education', 'internal_reduced_17a_net', true); + return treatment('general', 'internal_general_net', cae !== ''); +} diff --git a/resources/js/lib/monthly-iva.ts b/resources/js/lib/monthly-iva.ts index a8bf93fd..b5120d37 100644 --- a/resources/js/lib/monthly-iva.ts +++ b/resources/js/lib/monthly-iva.ts @@ -1,4 +1,5 @@ import { inputText } from './input-text.ts'; +import { ivaTreatmentForCae } from './iva-activity.ts'; import { monthlyProjectedSales, restoreBusinessPlanSnapshot, @@ -18,6 +19,8 @@ export type MonthlyIvaInput = { 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; @@ -117,8 +120,19 @@ export function monthlyIvaInput( 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) { + const plan = draft.business_plan_snapshot + ? restoreBusinessPlanSnapshot(inputText(draft.business_plan_snapshot)) + : null; + return ivaTreatmentForCae(plan?.economicClassification?.code); +} export function monthlyIvaKey( input: Omit, ): string { @@ -127,6 +141,8 @@ export function monthlyIvaKey( 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 { diff --git a/tests/Feature/SimulationPublishedFiscalTest.php b/tests/Feature/SimulationPublishedFiscalTest.php index 17ac377a..185ff363 100644 --- a/tests/Feature/SimulationPublishedFiscalTest.php +++ b/tests/Feature/SimulationPublishedFiscalTest.php @@ -28,6 +28,9 @@ class SimulationPublishedFiscalTest extends TestCase private InvestmentLegalSource $source; + /** @var array */ + private array $actors = []; + protected function setUp(): void { parent::setUp(); @@ -39,6 +42,7 @@ class SimulationPublishedFiscalTest extends TestCase config(['simulation-tax-governance.'.$role => [$actors[$role]->email]]); } $this->publisher = $actors['publishers']; + $this->actors = $actors; $this->source = InvestmentLegalSource::create([ 'title' => 'Synthetic QA fixture, not a homologation publication', 'url' => 'https://www.inm.gov.mz/', 'diploma' => 'Lei 22/2022', 'article' => 'Artigo 17(1)', 'competent_entity' => 'Assembleia da República', @@ -114,6 +118,35 @@ class SimulationPublishedFiscalTest extends TestCase self::assertSame(2, Simulation::where('owner_user_id', $this->consumer->id)->count()); } + public function test_reduced_rate_of_article_17a_is_its_own_published_version_and_never_borrows_the_general_rate(): void + { + // Owner decision 04/12/2026: IVA follows the activity; health and education at 5% (Lei 22/2022, artigo 17-A). + $input = $this->monthlyInput(['operation' => 'internal_reduced_17a_net']); + $this->actingAs($this->consumer)->postJson('/api/v1/simulations', $input, ['Idempotency-Key' => (string) Str::uuid()])->assertStatus(503); + $this->getJson('/api/v1/fiscal-consumer')->assertOk()->assertJsonPath('data.reduced_enabled', false); + + $source = InvestmentLegalSource::create([...collect($this->source->getAttributes())->only(['title', 'url', 'diploma', 'competent_entity', 'valid_from', 'valid_until', 'validation_status', 'owner_id', 'version_no', 'validator_id', 'validated_at'])->all(), 'article' => 'Artigo 17-A']); + $data = json_decode(file_get_contents(database_path('qa/iva-reduced-17a-net-v1.json')), true, flags: JSON_THROW_ON_ERROR); + $data['legal_source_id'] = $source->id; + $gov = app(SimulationTaxRuleGovernance::class); + $rule = $gov->create($this->actors['editors'], $data); + foreach (['submit' => 'editors', 'review' => 'reviewers', 'approve' => 'approvers', 'publish' => 'publishers'] as $action => $role) { + $rule = $gov->transition($this->actors[$role], $rule->id, $rule->version_no, $action, 'Synthetic isolated QA fixture for the reduced rate consumer.'); + } + config(['simulation-fiscal-consumer.reduced_rule_id' => $rule->id, 'simulation-fiscal-consumer.reduced_rule_version' => 1]); + $this->getJson('/api/v1/fiscal-consumer')->assertOk()->assertJsonPath('data.reduced_enabled', true); + + $id = $this->postJson('/api/v1/simulations', $input, ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted()->json('data.id'); + $rows = $this->finish($id)->result_snapshot['monthly_projection']['rows']; + self::assertSame('5', $rows[0]['rate']); + self::assertSame('50.0015', $rows[0]['vat']); + self::assertSame($rule->id, $rows[0]['rule_id']); + + $general = $this->postJson('/api/v1/simulations', $this->monthlyInput(), ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted()->json('data.id'); + self::assertSame('16', $this->finish($general)->result_snapshot['monthly_projection']['rows'][0]['rate']); + $this->postJson('/api/v1/simulations', $this->monthlyInput(['operation' => 'internal_reduced_other']), ['Idempotency-Key' => (string) Str::uuid()])->assertUnprocessable(); + } + public function test_monthly_gross_unknown_scope_and_server_rate_protection_do_not_invent_net_sales(): void { foreach (['included', 'unknown'] as $basis) { diff --git a/tests/frontend/iva-activity.test.mjs b/tests/frontend/iva-activity.test.mjs new file mode 100644 index 00000000..e440e468 --- /dev/null +++ b/tests/frontend/iva-activity.test.mjs @@ -0,0 +1,96 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { serializeBusinessPlanSnapshot } from '../../resources/js/lib/business-financial-plan.ts'; +import { ivaTreatmentForCae } from '../../resources/js/lib/iva-activity.ts'; +import { + monthlyIvaInput, + monthlyIvaKey, + monthlyIvaTreatment, +} from '../../resources/js/lib/monthly-iva.ts'; + +const settings = { start: '2026-01', basis: 'net', declared: true, auto: true }; +function draftWith(cae) { + const zero = Object.fromEntries( + [ + 'openingCash', + 'monthlyCollections', + 'monthlyVariableCostPayments', + 'monthlyInventoryPurchases', + 'monthlyOperatingExpenses', + 'monthlyOperatingPayments', + 'monthlyPayrollExpense', + 'monthlyPayrollPayments', + 'assetInvestment', + 'inventory', + 'receivables', + 'payables', + 'equity', + 'shareholderLoans', + 'bankLoanProceeds', + 'grants', + 'assetDepreciation', + 'monthlyInterestExpense', + 'monthlyInterestPayment', + 'monthlyPrincipalRepayment', + ].map((key) => [key, '0']), + ); + return { + currency: 'MZN', + business_plan_snapshot: serializeBusinessPlanSnapshot({ + ...zero, + currency: 'MZN', + periods: 2, + depreciationLifeMonths: 60, + products: [ + { + label: 'Serviço', + monthlyUnits: '10', + unitPrice: '1000', + unitVariableCost: '0', + }, + ], + ...(cae + ? { + economicClassification: { + code: cae, + revision: 'CAE-Rev.2', + sourceSha256: + 'cb3dee56db5b2c3f12e3071615725051828a9e1eba17662aa5e78d5f3356b0fc', + }, + } + : {}), + }), + }; +} + +test('IVA follows the activity: health and education at 5% (artigo 17-A), everything else at 16%', () => { + assert.equal(ivaTreatmentForCae('86201').rate, 5); + assert.match(ivaTreatmentForCae('86201').article, /17-A\(a\)/); + assert.equal(ivaTreatmentForCae('85300').rate, 5); + assert.match(ivaTreatmentForCae('85300').article, /17-A\(b\)/); + assert.match(ivaTreatmentForCae('85492').article, /17-A\(c\)/); + assert.ok( + ivaTreatmentForCae('85300').conditions.some((c) => + /reconhecido/.test(c), + ), + ); + for (const code of ['55111', '01111', '85410']) + assert.equal(ivaTreatmentForCae(code).rate, 16, code); + assert.equal(ivaTreatmentForCae(undefined).fromActivity, false); + assert.equal(ivaTreatmentForCae('55111').fromActivity, true); +}); + +test('the monthly IVA asks the server for the reduced version only for a 17-A activity, and earlier hotel results stay current', () => { + const clinic = monthlyIvaInput(draftWith('86201'), settings); + assert.equal(clinic.operation, 'internal_reduced_17a_net'); + assert.equal(monthlyIvaTreatment(draftWith('86201')).rate, 5); + const hotel = monthlyIvaInput(draftWith('55111'), settings); + assert.equal('operation' in hotel, false); + const unclassified = monthlyIvaInput(draftWith(null), settings); + assert.equal(monthlyIvaKey(hotel), monthlyIvaKey(unclassified)); + assert.notEqual( + monthlyIvaKey(clinic), + monthlyIvaKey(hotel), + 'a change of activity makes the earlier result stale', + ); +});