markTestSkipped('Select the authorised unpublished common source for isolated QA.'); } config(['import-estimates.qa_enabled' => true]); $this->withoutVite(); $this->f = receiptFixture(); $this->actingAs($this->f['issuer']); $this->draft = $this->f['r']->replicate(); $this->draft->fill(['number' => 'ESTIMATE-'.Str::random(12), 'status' => 'draft']); $this->draft->save(); $item = $this->f['r']->items()->sole()->replicate(); $item->requisition_id = $this->draft->id; $item->save(); $budgetAuthor = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]); $budgetReviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]); $this->actingAs($budgetAuthor); $budgetId = app(CommonBudget::class)->for($budgetAuthor)->create(['cost_center_id' => $this->draft->cost_center_id, 'year' => (int) now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Orçamento estritamente sintético']); $this->actingAs($budgetReviewer); app(CommonBudget::class)->for($budgetReviewer)->approve($budgetId); $this->budget = Budget::query()->findOrFail($budgetId); $this->actingAs($this->f['issuer']); $this->input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $this->budget->id, 'reason' => 'Preparação de pressupostos estritamente sintéticos', 'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'unknown', 'basis' => 'Valor ainda não disponível', 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)]; }); test('native import cost assumptions reuse exact legal charges once with explicit tax split and immutable source provenance', function () { config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]); Storage::fake('local'); supplyGrant($this->f['issuer'], ['procurement', 'import_customs']); $rules = app(ImportLegalRules::class); $draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [[ 'key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem', 'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => 'Synthetic explicit customs-value basis', ]]]), importLegalQaFile()); $rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic rate publication for native estimate integration']); $legal = app(ImportLegalEstimates::class)->save($this->f['issuer'], $this->draft, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $this->draft->items()->sole()->id, 'rule_id' => $rule->id, 'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27', 'bases' => ['synthetic-duty' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared customs valuation']], 'reason' => 'Synthetic exact charge adoption fixture']); $input = $this->input; foreach ($input['components'] as &$component) { $component['status'] = $component['kind'] === 'duty' ? 'known' : 'not_applicable'; $component['basis'] = 'Explicit synthetic assumptions; other costs do not apply in this test'; if ($component['kind'] === 'duty') { $component['subtotal_minor'] = 750; $component['tax_minor'] = 0; $component['total_minor'] = 750; } } unset($component); $input['legal_sources'] = ['duty' => ['estimate_id' => $legal->id, 'charge_key' => 'synthetic-duty']]; $native = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input); expect($native->snapshot['plan']['budget_amount_minor'])->toBe(10750) ->and($native->snapshot['legal_sources']['duty']['estimate_id'])->toBe($legal->id) ->and($native->snapshot['legal_sources']['duty']['legal_rule']['id'])->toBe($rule->id) ->and(DB::table('budget_entries')->count())->toBe(0); $changed = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]; foreach ($changed['components'] as &$component) { if ($component['kind'] === 'duty') { $component['subtotal_minor'] = 751; $component['total_minor'] = 751; } } unset($component); expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $changed))->toThrow(HttpException::class); $duplicate = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]; $duty = array_values(array_filter($duplicate['components'], fn ($component) => $component['kind'] === 'duty'))[0]; $duplicate['components'][] = [...$duty, 'key' => 'duty-again']; $duplicate['legal_sources']['duty-again'] = $duplicate['legal_sources']['duty']; expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $duplicate))->toThrow(HttpException::class); $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key, 'version' => 2, 'action' => 'withdraw', 'reason' => 'Synthetic withdrawal before native approval requires explicit review']); expect(fn () => app(ImportEstimates::class)->approval($this->draft))->toThrow(HttpException::class); expect(DB::table('budget_entries')->count())->toBe(0)->and($native->fresh()->snapshot['plan']['budget_amount_minor'])->toBe(10750); }); test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () { $service = app(ImportEstimates::class); $before = $this->draft->fresh()->getAttributes(); $record = $service->save($this->f['issuer'], $this->draft, $this->input); expect($record->state)->toBe('incomplete')->and($record->snapshot['plan']['budget_amount_minor'])->toBeNull() ->and($service->save($this->f['issuer'], $this->draft, $this->input)->id)->toBe($record->id) ->and($this->draft->fresh()->getAttributes())->toBe($before)->and(DB::table('budget_entries')->count())->toBe(0); $next = [...$this->input, 'operation_key' => (string) Str::uuid(), 'version' => 1]; foreach ($next['components'] as &$component) { $component['status'] = 'not_applicable'; $component['basis'] = 'Hipótese sintética sem esta componente'; } unset($component); $corrected = $service->save($this->f['issuer'], $this->draft, $next); expect($corrected->version)->toBe(2)->and($corrected->state)->toBe('prepared') ->and($corrected->snapshot['plan']['budget_amount_minor'])->toBe(10000) ->and($record->fresh()->state)->toBe('incomplete'); $this->get('/requisicoes/'.$this->draft->id.'/estimativa-importacao')->assertOk() ->assertInertia(fn (AssertableInertia $page) => $page->component('supply/import-estimate') ->where('latest.version', 2)->where('canPrepare', true)->where('nativeChanged', false)); expect(fn () => $service->save($this->f['issuer'], $this->draft, [...$next, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class); }); test('assumptions cannot rewrite a submitted request or bypass actor and feature isolation', function () { $service = app(ImportEstimates::class); expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $this->input))->toThrow(HttpException::class); $this->actingAs($this->f['receiver']); expect(fn () => $service->save($this->f['receiver'], $this->draft, $this->input))->toThrow(ModelNotFoundException::class); $this->actingAs($this->f['issuer']); config(['import-estimates.qa_enabled' => false]); expect(fn () => $service->save($this->f['issuer'], $this->draft, $this->input))->toThrow(HttpException::class); }); test('native submission approves the full estimate reserves goods and extras once and rejection releases both', function () { (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up(); $this->f['tenant']->update(['first_limit_minor' => 10500, 'second_limit_minor' => 10800]); $input = $this->input; foreach ($input['components'] as &$component) { $component['status'] = 'not_applicable'; } unset($component); $input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000]; $estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input); $workflow = app(RequisitionWorkflow::class); $workflow->submit($this->f['issuer'], $this->draft); $submitted = $this->draft->fresh(); expect($submitted->status)->toBe('pending')->and($submitted->total_minor)->toBe(10000) ->and($submitted->approval_snapshot['approval_basis']['total_minor'])->toBe(11000) ->and($submitted->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'procurement', 'finance']); $this->actingAs($this->f['issuer']); $engine = app(CommonBudget::class)->for($this->f['issuer']); expect((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(10000) ->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(1000) ->and($estimate->fresh()->state)->toBe('prepared'); $head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->draft->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]); $this->actingAs($head); $workflow->decide($head, $submitted, 'rejected', 'Rejeição sintética para conferir a libertação'); expect($this->draft->fresh()->status)->toBe('rejected')->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(0) ->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0); }); test('unknown or stale estimate prevents native submission without partial reservations or approval steps', function () { app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $this->input); try { app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft); $this->fail('Unknown costs cannot be submitted as zero.'); } catch (HttpException $error) { expect($error->getStatusCode())->toBe(422); } expect($this->draft->fresh()->status)->toBe('draft')->and($this->draft->steps()->count())->toBe(0) ->and(DB::table('budget_entries')->count())->toBe(0); $this->draft->items()->firstOrFail()->update(['description' => 'Edição deliberada posterior']); expect(fn () => app(ImportEstimates::class)->approval($this->draft->fresh()))->toThrow(HttpException::class); }); test('identified imported articles require an estimate and insufficient extras roll back the native goods reservation', function () { config(['import-tariffs.qa_enabled' => true]); app(ImportTariffCodes::class)->save($this->f['issuer'], $this->draft, [ 'operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0, 'requisition_item_id' => $this->draft->items()->sole()->id, 'reason' => 'Identificação sintética do artigo importado']); expect(fn () => app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft))->toThrow(HttpException::class); (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up(); $input = $this->input; foreach ($input['components'] as &$component) { $component['status'] = 'not_applicable'; } unset($component); $input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 200000, 'tax_minor' => 0, 'total_minor' => 200000]; app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input); expect(fn () => app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft))->toThrow(ValidationException::class); expect($this->draft->fresh()->status)->toBe('draft')->and($this->draft->steps()->count())->toBe(0) ->and(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0); }); test('native independently reviewed documents reconcile an approved estimate portion and preserve the remaining orders capacity', function () { config(['import-landed-costs.qa_enabled' => true]); Storage::fake('local'); (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up(); $input = $this->input; foreach ($input['components'] as &$component) { $component['status'] = 'not_applicable'; } unset($component); $input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000]; $estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input); app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft); $head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->draft->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]); $this->actingAs($head); app(RequisitionWorkflow::class)->decide($head, $this->draft->fresh(), 'approved', 'Aprovação sintética do custo integral'); // Synthetic issued-order fixture, after actual native approval of this new source. $award = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id)->replicate(); $quote = Quotation::query()->findOrFail($award->quotation_id)->replicate(); $quote->fill(['requisition_id' => $this->draft->id, 'reference' => 'ESTIMATE-QUOTE-'.Str::random(10)]); $quote->save(); $award->fill(['requisition_id' => $this->draft->id, 'quotation_id' => $quote->id]); $award->save(); $order = $this->f['order']->replicate(); $order->fill(['number' => 'ESTIMATE-ORDER-'.Str::random(10), 'requisition_id' => $this->draft->id, 'purchase_award_id' => $award->id]); $order->save(); $line = $this->f['line']->replicate(); $line->purchase_order_id = $order->id; $line->save(); supplyGrant($this->f['issuer'], ['procurement', 'import_prepare', 'requester']); $this->actingAs($this->f['issuer']); $import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([ 'purchase_order_id' => $order->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic QA jurisdiction', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Explicit synthetic regime'])); $finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]); $reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]); supplyGrant($finance, ['finance']); supplyGrant($reviewer, ['finance']); $this->actingAs($finance); $service = app(ImportLandedCosts::class); $document = $service->recordDocument($finance, $import, ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment', 'reference' => 'SYNTHETIC-ESTIMATE-ACTUAL', 'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic authority', 'currency' => 'MZN', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null, 'reason' => 'Documento sintético, sem execução aduaneira'], UploadedFile::fake()->createWithContent('estimate-actual.pdf', "%PDF-1.4\nSynthetic QA only\n%%EOF")); $selection = ['budget_id' => $this->budget->id, 'documents' => [['origin' => 'customs', 'kind' => 'customs_assessment', 'id' => $document->id]], 'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000]]]; $prepared = $service->save($finance, $import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save', 'reason' => 'Preparação documental sintética', 'data' => $selection]); $this->actingAs($reviewer); $approved = $service->save($reviewer, $import, ['operation_key' => (string) Str::uuid(), 'record_key' => $prepared->record_key, 'version' => 1, 'action' => 'approve', 'reason' => 'Conferência independente dos documentos sintéticos', 'data' => []]); $this->actingAs($finance); expect(fn () => $service->financial($finance, $import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0, 'reason' => 'Não duplicar a reserva estimada']))->toThrow(HttpException::class); $this->post('/compras/importacoes/'.$import->id.'/custos/'.$approved->id.'/orcamento?estimates_page=999999', ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0, 'reason' => 'A paginação não altera a protecção financeira'])->assertStatus(409); $command = ['operation_key' => (string) Str::uuid(), 'actual_operation_key' => (string) Str::uuid(), 'action' => 'reconcile_estimate', 'financial_revision' => 0, 'estimate_id' => $estimate->id, 'estimate_revision' => 1, 'estimate_release_minor' => 1000, 'reason' => 'Parcela sintética correspondente a esta ordem; diferença documentada de 1000 MZN centavos']; $this->post('/compras/importacoes/'.$import->id.'/custos/'.$approved->id.'/orcamento', $command)->assertRedirect(); $result = SupplyRecord::query()->where('kind', 'import_cost_event')->where('operation_key', $command['operation_key'])->firstOrFail(); expect($result->snapshot['common_result']['estimate_reconciliation']['reserved_minor'])->toBe(2000) ->and($result->snapshot['common_result']['additional_amount_minor'])->toBe(2000) ->and($service->financial($finance, $import, $approved, $command)->id)->toBe($result->id) ->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(4000) ->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0); $this->get('/compras/importacoes/'.$import->id.'/custos')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page ->where('estimateSources.data.0.reserved_minor', 2000)->where('estimateSources.data.0.revision', 2)); expect(fn () => $service->financial($finance, $import, $approved, [...$command, 'operation_key' => (string) Str::uuid(), 'actual_operation_key' => (string) Str::uuid(), 'financial_revision' => 1]))->toThrow(HttpException::class); config(['import-estimates.qa_enabled' => false]); try { $service->financial($finance, $import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 1, 'reason' => 'A capacidade desligada não permite ignorar a reserva anterior']); $this->fail('The reserved estimate capability must remain available.'); } catch (HttpException $error) { expect($error->getStatusCode())->toBe(503); } });