diff --git a/app/Console/Commands/PublishReducedIvaRate.php b/app/Console/Commands/PublishReducedIvaRate.php new file mode 100644 index 00000000..5f590f76 --- /dev/null +++ b/app/Console/Commands/PublishReducedIvaRate.php @@ -0,0 +1,118 @@ +whereKey((string) config('simulation-fiscal-consumer.rule_id')) + ->where('rule_version', (int) config('simulation-fiscal-consumer.rule_version')) + ->where('rule_code', 'IVA-GERAL-BASE-LIQUIDA')->where('status', 'published')->first(); + if (! $general) { + $this->error('A taxa geral publicada e ligada (INVESTMOZ_IVA_CONSUMER_RULE_ID/VERSION) não foi encontrada. Nada foi alterado.'); + + return self::FAILURE; + } + $generalSource = InvestmentLegalSource::query()->findOrFail($general->legal_source_id); + if (! SimulationFiscalSourceAcceptance::eligible($generalSource->toArray(), $general->source_sha256)) { + $this->error('A fonte da taxa geral não está aceite. Nada foi alterado.'); + + return self::FAILURE; + } + $existing = SimulationTaxRuleVersion::query()->where('rule_code', 'IVA-REDUZIDA-17A-BASE-LIQUIDA') + ->whereIn('status', ['draft', 'submitted', 'reviewed', 'approved', 'published'])->first(); + if ($existing) { + $this->warn("Já existe a versão da taxa reduzida ({$existing->status}): {$existing->id} v{$existing->rule_version}. Nada foi alterado."); + $this->envLines($existing); + + return self::SUCCESS; + } + $actor = User::query()->where('email', strtolower((string) $this->argument('email')))->first(); + if (! $actor) { + $this->error('Conta não encontrada. Nada foi alterado.'); + + return self::FAILURE; + } + $evidence = trim((string) $this->option('evidence')); + + $this->line('Vai ser feito, como '.$actor->email.':'); + $this->line("1. Fonte legal: {$generalSource->diploma}, Artigo 17-A — mesmo texto e hash da taxa geral ({$general->source_sha256}), aceite em seu nome."); + $this->line('2. Versão IVA-REDUZIDA-17A-BASE-LIQUIDA v1, taxa 5%, a partir da ficha database/qa/iva-reduced-17a-net-v1.json.'); + $this->line('3. Etapas: rascunho, submissão, revisão, aprovação e publicação, com o fundamento indicado.'); + if (! $this->option('execute')) { + $this->info('Simulação apenas: repita com --execute e --evidence="…" para publicar.'); + + return self::SUCCESS; + } + if (mb_strlen($evidence) < 20) { + $this->error('Indique --evidence com pelo menos 20 caracteres. Nada foi alterado.'); + + return self::FAILURE; + } + + SimulationTaxGovernanceAccess::requireRole($actor, 'editors'); + $rule = DB::transaction(function () use ($actor, $evidence, $general, $generalSource, $governance): SimulationTaxRuleVersion { + // The article 17-A reference of the same official text, accepted by the person running this command. + $source = InvestmentLegalSource::create([ + ...collect($generalSource->getAttributes())->only(['title', 'url', 'diploma', 'competent_entity', 'valid_from', 'valid_until'])->all(), + 'article' => 'Artigo 17-A', 'validation_status' => 'pending', 'owner_id' => $actor->id, 'version_no' => 1, + 'validator_id' => null, 'validated_at' => null, + 'fiscal_acceptance' => $acceptance = ['scope' => 'fiscal_parameters', 'basis' => 'Tempo-official-sources-20261008', + 'responsible_user_id' => $actor->id, 'sha256' => $general->source_sha256, + 'citation' => 'Lei 22/2022 (CIVA republicado), artigo 17-A: taxa de 5% nas operações do artigo 15(10).', + 'official_origin' => (string) $generalSource->url, 'accepted_at' => now()->toISOString(), + 'legal_opinion' => false, 'independent_review' => false], + ]); + DB::table('audit_events')->insert(['source_system' => 'simulation-fiscal-maintenance', + 'entity_type' => 'investment_legal_sources', 'entity_id' => $source->id, 'actor_user_id' => $actor->id, + 'action' => 'official_source_acceptance', 'after_data' => json_encode([ + 'source' => $source->attributesToArray(), 'basis' => $acceptance, 'evidence' => $evidence, + 'sha256' => hash('sha256', $source->toJson()), + ], JSON_THROW_ON_ERROR)]); + $data = json_decode(CheckedFile::read(database_path('qa/iva-reduced-17a-net-v1.json')), true, flags: JSON_THROW_ON_ERROR); + $data['legal_source_id'] = $source->id; + $data['source_sha256'] = $general->source_sha256; + $rule = $governance->create($actor, $data); + foreach (['submit', 'review', 'approve', 'publish'] as $action) { + $rule = $governance->transition($actor, $rule->id, $rule->version_no, $action, $evidence); + } + + return $rule; + }); + + $this->info('Taxa reduzida publicada.'); + $this->envLines($rule); + + return self::SUCCESS; + } + + private function envLines(SimulationTaxRuleVersion $rule): void + { + $this->line('Acrescente ao .env do servidor e limpe a cache de configuração:'); + $this->line("INVESTMOZ_IVA_REDUCED_RULE_ID={$rule->id}"); + $this->line("INVESTMOZ_IVA_REDUCED_RULE_VERSION={$rule->rule_version}"); + } +} diff --git a/tests/Feature/SimulationPublishedFiscalTest.php b/tests/Feature/SimulationPublishedFiscalTest.php index 185ff363..c40d381f 100644 --- a/tests/Feature/SimulationPublishedFiscalTest.php +++ b/tests/Feature/SimulationPublishedFiscalTest.php @@ -147,6 +147,34 @@ class SimulationPublishedFiscalTest extends TestCase $this->postJson('/api/v1/simulations', $this->monthlyInput(['operation' => 'internal_reduced_other']), ['Idempotency-Key' => (string) Str::uuid()])->assertUnprocessable(); } + public function test_the_owner_publishes_the_reduced_rate_with_one_reviewed_command_and_nothing_happens_without_execute(): void + { + $owner = User::factory()->withTwoFactor()->create(); + foreach (['editors', 'reviewers', 'approvers', 'publishers'] as $role) { + config(['simulation-tax-governance.'.$role => [...config('simulation-tax-governance.'.$role, []), strtolower($owner->email)]]); + } + $this->artisan('fiscal:publish-iva-reduced', ['email' => $owner->email])->expectsOutputToContain('Simulação apenas')->assertSuccessful(); + self::assertFalse(SimulationTaxRuleVersion::query()->where('rule_code', 'IVA-REDUZIDA-17A-BASE-LIQUIDA')->exists()); + $this->artisan('fiscal:publish-iva-reduced', ['email' => $owner->email, '--execute' => true, '--evidence' => 'curto'])->assertFailed(); + + $evidence = 'Decisão do proprietário de 04/12/2026: IVA pela actividade, artigo 17-A da Lei 22/2022.'; + $this->artisan('fiscal:publish-iva-reduced', ['email' => $owner->email, '--execute' => true, '--evidence' => $evidence]) + ->expectsOutputToContain('INVESTMOZ_IVA_REDUCED_RULE_ID=')->assertSuccessful(); + $rule = SimulationTaxRuleVersion::query()->where('rule_code', 'IVA-REDUZIDA-17A-BASE-LIQUIDA')->sole(); + self::assertSame('published', $rule->status); + self::assertSame($this->rule->source_sha256, $rule->source_sha256); + $source = InvestmentLegalSource::query()->findOrFail($rule->legal_source_id); + self::assertSame(['Lei 22/2022', 'Artigo 17-A', 'pending'], [$source->diploma, $source->article, $source->validation_status]); + self::assertSame($owner->id, (int) $source->fiscal_acceptance['responsible_user_id']); + $this->artisan('fiscal:publish-iva-reduced', ['email' => $owner->email, '--execute' => true, '--evidence' => $evidence]) + ->expectsOutputToContain('Já existe')->assertSuccessful(); + + config(['simulation-fiscal-consumer.reduced_rule_id' => $rule->id, 'simulation-fiscal-consumer.reduced_rule_version' => 1]); + $id = $this->actingAs($this->consumer)->postJson('/api/v1/simulations', $this->monthlyInput(['operation' => 'internal_reduced_17a_net']), + ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted()->json('data.id'); + self::assertSame('5', $this->finish($id)->result_snapshot['monthly_projection']['rows'][0]['rate']); + } + public function test_monthly_gross_unknown_scope_and_server_rate_protection_do_not_invent_net_sales(): void { foreach (['included', 'unknown'] as $basis) {