IVA 5%: comando revisto para publicar a taxa do artigo 17-A na produção
tests / ci (push) Waiting to run
tests / ci (push) Waiting to run
fiscal:publish-iva-reduced {email} mostra primeiro o que vai fazer e só
publica com --execute e um fundamento (--evidence, 20 caracteres no
mínimo). Reutiliza o texto oficial e o hash da taxa geral publicada,
regista a referência «Lei 22/2022, Artigo 17-A» aceite em nome de quem o
executa (com evento de auditoria, como a aceitação de fontes fiscais da
gestão), cria a versão IVA-REDUZIDA-17A-BASE-LIQUIDA a partir da ficha e
percorre submissão, revisão, aprovação e publicação. No fim indica as
linhas INVESTMOZ_IVA_REDUCED_RULE_ID/VERSION para o .env. Se a versão já
existir, não altera nada.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\SimulationTaxRuleVersion;
|
||||
use App\Models\User;
|
||||
use App\Services\SimulationFiscalSourceAcceptance;
|
||||
use App\Services\SimulationTaxGovernanceAccess;
|
||||
use App\Services\SimulationTaxRuleGovernance;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Publishes the reduced IVA rate of artigo 17-A (5%) as its own governed version, on the owner's decision of
|
||||
* 04/12/2026. It reuses the accepted source of the published general rate (the same Lei 22/2022 text), registers the
|
||||
* article 17-A reference and runs the usual stages (draft, submission, review, approval, publication) as the named
|
||||
* fiscal maintainer, with the evidence given. Without --execute it only shows what it would do.
|
||||
*/
|
||||
final class PublishReducedIvaRate extends Command
|
||||
{
|
||||
protected $signature = 'fiscal:publish-iva-reduced {email : Responsável pela manutenção fiscal (conta existente)}
|
||||
{--evidence= : Fundamento registado em cada etapa (mínimo 20 caracteres)}
|
||||
{--execute : Executar; sem esta opção apenas mostra o que seria feito}';
|
||||
|
||||
protected $description = 'Publicar a taxa de IVA de 5% do artigo 17-A como versão governada própria (decisão de 04/12/2026)';
|
||||
|
||||
public function handle(SimulationTaxRuleGovernance $governance): int
|
||||
{
|
||||
$general = SimulationTaxRuleVersion::query()->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}");
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user