feat: preparar lote IVA exacto em QA sem activacao
This commit is contained in:
@@ -4,6 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Jobs\RunSimulation;
|
||||
use App\Models\Simulation;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -17,11 +18,27 @@ final class SimulationExecution
|
||||
*/
|
||||
public function create(array $data, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
|
||||
{
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
|
||||
$scope = $actorId !== null ? (string) $actorId : ($tokenHash ?? 'anonymous');
|
||||
$scopeHash = hash('sha256', $scope);
|
||||
$keyHash = hash('sha256', strtolower($key));
|
||||
$payload = ['base' => (string) $data['base'], 'rate' => (string) $data['rate'], 'reduction' => (string) $data['reduction'], 'scenario_kind' => 'custom_planning', 'organization_id' => $organizationId];
|
||||
|
||||
return $this->createPayload($payload, $actorId, $organizationId, $token, $key);
|
||||
}
|
||||
|
||||
public function createFiscalQaPreview(array $snapshot, int $actorId, string $key): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
abort_unless(($snapshot['scenario_kind'] ?? null) === 'fiscal_rule_qa_preview'
|
||||
&& in_array($snapshot['result']['status'] ?? null, ['calculated', 'indeterminate'], true)
|
||||
&& ($snapshot['presentation']['rounding_applied'] ?? null) === false, 422);
|
||||
|
||||
return $this->createPayload(['scenario_kind' => 'fiscal_rule_qa_preview', 'fiscal_preview' => $snapshot, 'organization_id' => null],
|
||||
$actorId, null, null, $key);
|
||||
}
|
||||
|
||||
private function createPayload(array $payload, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
|
||||
{
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
|
||||
$scopeHash = hash('sha256', $actorId !== null ? (string) $actorId : ($tokenHash ?? 'anonymous'));
|
||||
$keyHash = hash('sha256', strtolower($key));
|
||||
ksort($payload);
|
||||
$payloadHash = hash('sha256', json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
|
||||
@@ -44,7 +61,9 @@ final class SimulationExecution
|
||||
$simulation = Simulation::create([
|
||||
'id' => $id, 'questionnaire_version_id' => '61000100-0000-4000-8000-000000000001', 'owner_user_id' => $actorId, 'organization_id' => $organizationId,
|
||||
'anonymous_token_hash' => $tokenHash, 'status' => 'queued', 'version_no' => 1,
|
||||
'input_snapshot' => $payload, 'calculation_snapshot' => ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
|
||||
'input_snapshot' => $payload, 'calculation_snapshot' => $payload['scenario_kind'] === 'fiscal_rule_qa_preview'
|
||||
? ['engine' => 'fiscal-draft-preview-v1', 'mode' => 'qa_draft_only', 'arithmetic' => 'exact_decimal_no_rounding']
|
||||
: ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
|
||||
]);
|
||||
$scenarioId = (string) Str::uuid();
|
||||
DB::table('simulation_scenarios')->insert([
|
||||
@@ -85,6 +104,8 @@ final class SimulationExecution
|
||||
return DB::transaction(function () use ($id, $scenarioId, $data, $request): Simulation {
|
||||
$this->setContext($request->user()?->id, $this->tokenHash($request));
|
||||
$simulation = Simulation::whereNull('deleted_at')->lockForUpdate()->findOrFail($id);
|
||||
abort_if(($simulation->input_snapshot['scenario_kind'] ?? null) === 'fiscal_rule_qa_preview', 422,
|
||||
'Crie uma nova pré-visualização fiscal; este snapshot conserva a regra e as entradas originais.');
|
||||
$this->requireMatch($request, $simulation);
|
||||
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $id)->where('id', $scenarioId)->lockForUpdate()->first();
|
||||
abort_if($scenario === null, 404);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\User;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Brick\Math\BigRational;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Exact operation-level IVA calculation against an explicit QA draft; never a payment/return total. */
|
||||
final class SimulationFiscalQaPreview
|
||||
{
|
||||
public function create(User $actor, string $ruleId, array $input, string $key): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
|
||||
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.');
|
||||
abort_if(collect($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);
|
||||
$version = $rule->attributesToArray();
|
||||
$version['source'] = $source->attributesToArray();
|
||||
$date = $input['reference_date'];
|
||||
$context = ['operation' => $input['operation'], 'currency' => $input['currency']];
|
||||
$missing = [];
|
||||
$resolution = [];
|
||||
$evaluation = null;
|
||||
if ($date < '2026-01-01' || $date > '2026-12-31') {
|
||||
$missing[] = 'demonstrated_coverage';
|
||||
} else {
|
||||
$resolution = app(SimulationTaxParameterResolver::class)->resolveDraftForQa([$version], 'IVA', $date, $date, $context);
|
||||
$rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
|
||||
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']]);
|
||||
}
|
||||
}
|
||||
$exact = ($evaluation['status'] ?? null) === 'determinate'
|
||||
? (string) BigRational::of($evaluation['result'])->toBigDecimal()
|
||||
: null;
|
||||
if ($exact === null && $missing === []) {
|
||||
$missing = $evaluation['missing'] ?? ['eligible_parameter'];
|
||||
}
|
||||
$snapshot = [
|
||||
'contract_version' => 1, 'scenario_kind' => 'fiscal_rule_qa_preview',
|
||||
'base' => $input['base'], 'currency' => $input['currency'], 'indicative_total' => $exact,
|
||||
'legal_interpretation' => false, 'formula_version' => 'investmoz.tax.v1',
|
||||
'context' => [
|
||||
'reference_date' => $date, 'currency' => $input['currency'], 'currency_fraction_digits' => 2,
|
||||
'scenario_id' => null, 'scenario_version' => 1, 'engine_version' => 'fiscal-draft-preview-v1',
|
||||
'ruleset_version' => $rule->rule_code.':'.$rule->rule_version,
|
||||
],
|
||||
'result' => [
|
||||
'status' => $exact === null ? 'indeterminate' : 'calculated', 'value' => $exact, 'unit' => 'MZN',
|
||||
'explanation' => $exact === null
|
||||
? 'IVA indeterminado: o contexto, a fonte ou o período não permitem resolver o parâmetro deste lote QA.'
|
||||
: 'IVA calculado com precisão decimal exacta, sem arredondamento. Ensaio QA de regra em rascunho; enquadramento declarado, não validado. Não é saldo de declaração nem valor a pagar.',
|
||||
'missing_inputs' => $missing, 'source_ids' => [(string) $source->id],
|
||||
],
|
||||
'presentation' => ['value' => $exact, 'currency' => $input['currency'], 'rounding_applied' => false, 'purpose' => 'operation_tax_not_payment'],
|
||||
// Exact rational steps supplement the decimal result; no float conversion.
|
||||
'intermediate' => $evaluation,
|
||||
'fiscal_provenance' => [
|
||||
'mode' => 'qa_draft_only', 'scope_status' => 'user_declared', 'context' => $context,
|
||||
'rounding_policy' => $rule->rounding_policy, 'resolution' => $resolution,
|
||||
'rule' => $version, 'source_acceptance' => 'Fonte oficial aceite pela decisão Tempo de 08/10/2026; não constitui aprovação jurídica desta operação ou publicação da regra.',
|
||||
],
|
||||
];
|
||||
|
||||
return app(SimulationExecution::class)->createFiscalQaPreview($snapshot, $actor->id, $key);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Brick\Math\BigRational;
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -126,14 +127,30 @@ final class SimulationTaxParameterResolver
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function resolveAvailableParameters(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'published');
|
||||
}
|
||||
|
||||
/** Explicit draft preview. Never used by the published-parameter API. */
|
||||
public function resolveDraftForQa(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
|
||||
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'draft');
|
||||
}
|
||||
|
||||
private function resolveWithStatus(array $versions, string $component, string $periodStart, string $periodEnd, array $context, string $requiredStatus): array
|
||||
{
|
||||
$start = $this->date($periodStart);
|
||||
$end = $this->date($periodEnd);
|
||||
if ($end < $start || $start->diff($end)->days > 365) {
|
||||
throw new InvalidArgumentException('Reveja o período de aplicação indicado.');
|
||||
}
|
||||
$groups = [];
|
||||
|
||||
foreach ($versions as $version) {
|
||||
if (($version['component'] ?? null) !== $component
|
||||
|| ($version['status'] ?? null) !== 'published'
|
||||
|| ($version['status'] ?? null) !== $requiredStatus
|
||||
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|
||||
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|
||||
|| ! $this->overlaps($version, $start, $end)
|
||||
|
||||
Reference in New Issue
Block a user