IVA pela actividade: 5% do artigo 17-A para saúde e ensino, 16% para as restantes
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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'];
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<array-key, mixed>
|
||||
*/
|
||||
@@ -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<SimulationTaxRuleVersion>
|
||||
*/
|
||||
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'],
|
||||
|
||||
Reference in New Issue
Block a user