markTestSkipped('Unpublished common source requires explicit COMMON_BUDGET_PATH QA selection.'); } $this->f = receiptFixture(); budgetDistributionFixtureSchema(); config(['budget-distributions.qa_enabled' => true]); $this->author = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]); $this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]); $this->centre2 = CostCenter::query()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'code' => 'DISTR-2', 'name' => 'Centro sintético adicional']); $this->actingAs($this->author); $this->budgetIds = []; foreach ([$this->f['r']->cost_center_id, $this->centre2->id] as $centre) { $budget = app(CommonBudget::class)->for($this->author)->create(['cost_center_id' => $centre, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => $centre !== $this->centre2->id, 'amount_minor' => 20000, 'reason' => 'Dotação sintética para contrato comum']); $this->actingAs($this->reviewer); app(CommonBudget::class)->for($this->reviewer)->approve($budget); $this->budgetIds[] = $budget; $this->actingAs($this->author); } // Explicit synthetic host source contract; not a claim of an invoice workflow execution. $this->lines = [12 => ['subtotal_minor' => 10000, 'total_minor' => 11600, 'required_kind' => 'operating']]; $this->plan = [ ['allocation_key' => 'a', 'line_id' => 12, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 5000, 'total_minor' => 5800], ['allocation_key' => 'b', 'line_id' => 12, 'centre_id' => $this->centre2->id, 'subtotal_minor' => 5000, 'total_minor' => 5800], ]; }); function distributedRecord(object $test, string $phase, ?string $key = null, ?array $plan = null): array { return app(CommonBudget::class)->for($test->author)->recordDistribution($test->f['r']->id, $phase, $plan ?? $test->plan, $test->lines, str_repeat('a', 64), $key ?? (string) Str::uuid()); } test('explicit optional contract composition loads the selected standalone source without sibling fallback', function () { $selected = getenv('COMMON_BUDGET_PATH'); expect($selected)->toBeString()->not->toBe('') ->and(realpath((new ReflectionClass(BudgetControl::class))->getFileName()))->toBe(realpath($selected.'/src/BudgetControl.php')); }); test('prepared deployment capability verifies the selected standalone artifact outside QA and remains disabled by default', function () { $proofPath = base_path('docs/proofs/rq01-distribution-artifact.json'); $proof = json_decode(file_get_contents($proofPath), true, 32, JSON_THROW_ON_ERROR); // Only the process which already loaded the frozen artifact can enable this composition. $selected = realpath((new ReflectionClass(BudgetControl::class))->getFileName()); $artifact = base_path($proof['path']); config(['budget-distributions.qa_enabled' => false, 'budget-distributions.enabled' => false]); app()->instance('env', 'local'); try { expect(app(RequisitionBudgetDistributions::class)->ready())->toBeFalse(); config(['budget-distributions.enabled' => true, 'budget-distributions.artifact_manifest' => $proofPath, 'budget-distributions.artifact_manifest_sha256' => hash_file('sha256', $proofPath), 'common-budget.path' => $artifact]); expect(app(RequisitionBudgetDistributions::class)->ready())->toBe($selected === realpath($artifact.'/src/BudgetControl.php')); config(['budget-distributions.artifact_manifest_sha256' => str_repeat('0', 64)]); expect(fn () => app(RequisitionBudgetDistributions::class)->ready())->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_MANIFEST_MISMATCH'); } finally { app()->instance('env', 'testing'); } }); function distributionInvoice(object $test, string $number, int $net, int $gross): Invoice { return Invoice::query()->create(['tenant_id' => $test->author->tenant_id, 'purchase_order_id' => $test->f['order']->id, 'supplier_id' => $test->f['order']->supplier_id, 'created_by' => $test->author->id, 'number' => $number, 'issued_on' => today(), 'status' => 'pending', 'subtotal_minor' => $net, 'tax_minor' => $gross - $net, 'total_minor' => $gross, 'snapshot' => ['synthetic_contract_fixture' => true]]); } function preparedDistributedRequisition(object $test): array { $workflow = app(RequisitionWorkflow::class); $data = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $test->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Pedido sintético com distribuição explícita.', 'items' => [['description' => 'Material sintético distribuído', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']]]; $request = $workflow->save($test->author, $data); $line = $request->items()->firstOrFail(); $preparation = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->getAttribute('process_version'), 'reason' => 'Distribuição explícita pelos centros autorizados.', 'budget_distribution_preparation' => [ ['allocation_key' => (string) Str::uuid(), 'line_id' => $line->id, 'centre_id' => $test->f['r']->cost_center_id, 'subtotal' => '50.00', 'total' => '58.00'], ['allocation_key' => (string) Str::uuid(), 'line_id' => $line->id, 'centre_id' => $test->centre2->id, 'subtotal' => '50.00', 'total' => '58.00'], ]]; $prepared = $workflow->save($test->author, $preparation, $request); return [$prepared, $data, $preparation]; } test('native requisition save and submit reuse the common distributed writer without parallel reservations', function () { [$request, , $preparation] = preparedDistributedRequisition($this); $version = $request->getAttribute('process_version'); $again = app(RequisitionWorkflow::class)->save($this->author, $preparation, $request); expect($again->getAttribute('process_version'))->toBe($version)->and($request->budget_distribution_preparation['prepared_by'])->toBe($this->author->id); app(RequisitionWorkflow::class)->submit($this->author, $request, (string) Str::uuid(), $version); expect($request->fresh()->status)->toBe('pending')->and(DB::table('budget_distributions')->where('requisition_id', $request->id)->value('phase'))->toBe('reserve') ->and(DB::table('budget_distribution_entries')->count())->toBe(2)->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0); }); test('distribution preparation has an encrypted HTTP form and uses native versioned save', function () { $this->withoutVite(); [$request, , $preparation] = preparedDistributedRequisition($this); $this->get('/requisicoes/'.$request->id.'/distribuicoes')->assertOk() ->assertViewHas('page', fn (array $page) => $page['component'] === 'requisitions/distributions' && $page['encryptHistory'] === true); $preparation['operation_key'] = (string) Str::uuid(); $preparation['process_version'] = $request->getAttribute('process_version'); $this->postJson('/requisicoes/'.$request->id.'/distribuicoes', $preparation)->assertRedirect('/requisicoes/'.$request->id); expect($request->fresh()->getAttribute('process_version'))->toBe($preparation['process_version'] + 1) ->and(DB::table('budget_distribution_entries')->count())->toBe(0); $this->actingAs($this->reviewer); $this->get('/requisicoes/'.$request->id.'/distribuicoes')->assertForbidden(); $this->postJson('/requisicoes/'.$request->id.'/distribuicoes', [...$preparation, 'operation_key' => (string) Str::uuid()])->assertForbidden(); config(['budget-distributions.qa_enabled' => false]); $this->actingAs($this->author); $this->get('/requisicoes/'.$request->id.'/distribuicoes')->assertServiceUnavailable(); }); test('explicit amendment action requires current Finance function even when the common command is called directly', function () { distributedRecord($this, 'reserve'); $commit = distributedRecord($this, 'commit'); $this->actingAs($this->reviewer); $changed = [[...$this->plan[0], 'subtotal_minor' => 4999, 'total_minor' => 5799], [...$this->plan[1], 'subtotal_minor' => 5001, 'total_minor' => 5801]]; try { app(CommonBudget::class)->for($this->reviewer)->amendDistribution($this->f['r']->id, $changed, $commit['plan_hash'], 'Administrador sem função financeira explícita.', (string) Str::uuid()); $this->fail('Finance authority is mandatory.'); } catch (HttpException $error) { expect($error->getStatusCode())->toBe(403); } expect(DB::table('budget_distribution_events')->count())->toBe(2); }); test('quotation allocation uses actual changed MZN line amounts and freezes the source before commitment', function () { [$request, , $preparation] = preparedDistributedRequisition($this); app(RequisitionWorkflow::class)->submit($this->author, $request, (string) Str::uuid(), $request->getAttribute('process_version')); $quote = Quotation::query()->create(['tenant_id' => $this->author->tenant_id, 'requisition_id' => $request->id, 'supplier_id' => $this->f['order']->supplier_id, 'created_by' => $this->f['issuer']->id, 'reference' => 'QA-DISTR-QUOTE', 'delivery_days' => 5, 'valid_until' => today()->addWeek(), 'payment_terms' => '30 dias', 'currency' => 'MZN', 'subtotal_minor' => 12000, 'tax_minor' => 1920, 'total_minor' => 13920, 'weights' => []]); $line = $quote->items()->create(['tenant_id' => $this->author->tenant_id, 'requisition_item_id' => $request->items()->firstOrFail()->id, 'description' => 'Proposta sintética com valor alterado', 'quantity' => '2.000', 'unit_price_minor' => 6000, 'tax_rate' => '16.00', 'subtotal_minor' => 12000, 'tax_minor' => 1920, 'total_minor' => 13920]); $this->actingAs($this->f['issuer']); $budget = app(BudgetWorkflow::class); expect(fn () => $budget->record($this->f['issuer'], $request, 'award', 13920, 12000, $quote))->toThrow(ValidationException::class); $input = $preparation; $input['budget_distribution_preparation'] = array_map(fn ($row) => [...$row, 'subtotal' => '60.00', 'total' => '69.60'], $input['budget_distribution_preparation']); DB::transaction(function () use ($request, $quote, $input, $budget) { app(RequisitionBudgetDistributions::class)->prepareQuote($this->f['issuer'], $request, $quote, $input); $budget->record($this->f['issuer'], $request, 'award', 13920, 12000, $quote); }); expect($request->fresh()->budget_distribution_preparation['allocations'][0]['total_minor'])->toBe(5800) ->and($request->fresh()->budget_distribution_preparation['quotation']['allocations'][0]['total_minor'])->toBe(6960); expect(array_key_exists('budget_distribution_preparation', $request->fresh()->toArray()))->toBeFalse(); $this->actingAs($this->author); $this->get('/requisicoes/'.$request->id)->assertOk()->assertViewHas('page', fn (array $page) => ! array_key_exists('budget_distribution_preparation', json_decode(json_encode($page['props']['requisition'], JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR))); $this->actingAs($this->f['issuer']); $line->update(['description' => 'Mesmo valor, descrição posteriormente editada']); // Descriptive edits do not replace monetary source values; actual monetary changes do. $line->update(['subtotal_minor' => 12001]); expect(fn () => $budget->record($this->f['issuer'], $request->fresh(), 'commit', 13920, 12000, $quote))->toThrow(ValidationException::class); expect(DB::table('budget_distributions')->where('requisition_id', $request->id)->value('phase'))->toBe('award'); $line->update(['subtotal_minor' => 12000]); $budget->record($this->f['issuer'], $request->fresh(), 'commit', 13920, 12000, $quote); expect(DB::table('budget_distributions')->where('requisition_id', $request->id)->value('phase'))->toBe('commit'); }); test('changed draft basis requires reconfirmation and disabled distribution never falls back to the old writer', function () { [$request, $data] = preparedDistributedRequisition($this); $changed = app(RequisitionWorkflow::class)->save($this->author, [...$data, 'operation_key' => (string) Str::uuid(), 'process_version' => $request->getAttribute('process_version')], $request); expect(fn () => app(RequisitionWorkflow::class)->submit($this->author, $changed, (string) Str::uuid(), $changed->getAttribute('process_version')))->toThrow(ValidationException::class); expect($changed->fresh()->status)->toBe('draft')->and(DB::table('budget_distribution_entries')->count())->toBe(0); [$another] = preparedDistributedRequisition($this); config(['budget-distributions.qa_enabled' => false]); try { app(RequisitionWorkflow::class)->submit($this->author, $another, (string) Str::uuid(), $another->getAttribute('process_version')); $this->fail('Distribution must not fall back to the legacy writer.'); } catch (HttpException $error) { expect($error->getStatusCode())->toBe(503); } expect($another->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->where('requisition_id', $another->id)->count())->toBe(0); }); test('distributed reservation commitment and partial consumption share native balances and replay exactly once', function () { $key = (string) Str::uuid(); distributedRecord($this, 'reserve', $key); expect(distributedRecord($this, 'reserve', $key)['replayed'])->toBeTrue() ->and(DB::table('budget_distribution_entries')->count())->toBe(2); $engine = app(CommonBudget::class)->for($this->author); expect($engine->balance($this->budgetIds[0])['reserved_minor'])->toBe(5800) ->and($engine->balance($this->budgetIds[1])['reserved_minor'])->toBe(5000); distributedRecord($this, 'award'); distributedRecord($this, 'commit'); $invoice = distributionInvoice($this, 'DISTR-PARTIAL', 1000, 1160); $partial = array_map(fn ($row) => [...$row, 'subtotal_minor' => 500, 'total_minor' => 580], $this->plan); $lines = [12 => ['subtotal_minor' => 1000, 'total_minor' => 1160, 'required_kind' => 'operating']]; $operation = (string) Str::uuid(); $consume = fn () => $engine->consumeDistribution($this->f['r']->id, $invoice->id, $partial, $lines, str_repeat('b', 64), $operation); expect($consume()['replayed'])->toBeFalse()->and($consume()['replayed'])->toBeTrue(); expect($engine->balance($this->budgetIds[0]))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 5220, 'consumed_minor' => 580, 'available_minor' => 14200]); expect($engine->balance($this->budgetIds[1]))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 4500, 'consumed_minor' => 500, 'available_minor' => 15000]); expect(DB::table('budget_distribution_consumptions')->count())->toBe(2) ->and(DB::table('budget_distribution_events')->count())->toBe(4) ->and(fn () => $engine->record($this->f['r']->id, $this->f['r']->cost_center_id, 'operating', 'reserve', 11600, 10000))->toThrow(BudgetFailure::class) ->and(fn () => distributedRecord($this, 'cancel'))->toThrow(BudgetFailure::class); }); test('explicit commitment amendment preserves native totals and history with versioned replay', function () { distributedRecord($this, 'reserve'); $commit = distributedRecord($this, 'commit'); $engine = app(CommonBudget::class)->for($this->author); $changed = [[...$this->plan[0], 'subtotal_minor' => 4999, 'total_minor' => 5799], [...$this->plan[1], 'subtotal_minor' => 5001, 'total_minor' => 5801]]; $operation = (string) Str::uuid(); $amend = fn () => $engine->amendDistribution($this->f['r']->id, $changed, $commit['plan_hash'], 'Reafectação explícita sintética por Finanças.', $operation); $result = $amend(); expect($result['amendment_version'])->toBe(1)->and($amend()['replayed'])->toBeTrue() ->and($engine->balance($this->budgetIds[0])['committed_minor'])->toBe(5799) ->and($engine->balance($this->budgetIds[1])['committed_minor'])->toBe(5001); expect(fn () => $engine->amendDistribution($this->f['r']->id, $this->plan, $commit['plan_hash'], 'Versão desactualizada não pode alterar.', (string) Str::uuid()))->toThrow(BudgetFailure::class); $restored = $engine->amendDistribution($this->f['r']->id, $this->plan, $result['plan_hash'], 'Nova reafectação explícita preservando histórico.', (string) Str::uuid()); expect($restored['amendment_version'])->toBe(2)->and($restored['plan_hash'])->not->toBe($commit['plan_hash']) ->and(DB::table('budget_distribution_events')->count())->toBe(4); $original = json_decode(DB::table('budget_distribution_events')->where('kind', 'commit')->value('snapshot'), true); expect($original['allocations'][0]['total_minor'])->toBe(5800); }); test('amendment cannot erase consumed amounts or exceed an approved destination budget', function () { distributedRecord($this, 'reserve'); $commit = distributedRecord($this, 'commit'); $engine = app(CommonBudget::class)->for($this->author); $invoice = distributionInvoice($this, 'AMEND-USED', 5000, 5800); $engine->consumeDistribution($this->f['r']->id, $invoice->id, [$this->plan[0]], [12 => ['subtotal_minor' => 5000, 'total_minor' => 5800, 'required_kind' => 'operating']], str_repeat('d', 64), (string) Str::uuid()); $changed = [[...$this->plan[0], 'subtotal_minor' => 4999, 'total_minor' => 5799], [...$this->plan[1], 'subtotal_minor' => 5001, 'total_minor' => 5801]]; expect(fn () => $engine->amendDistribution($this->f['r']->id, $changed, $commit['plan_hash'], 'Não reduzir o consumo documental anterior.', (string) Str::uuid()))->toThrow(BudgetFailure::class); $before = DB::table('budget_distribution_entries')->get()->toJson(); $increase = [[...$this->plan[0], 'subtotal_minor' => 5000, 'total_minor' => 5801], [...$this->plan[1], 'subtotal_minor' => 5000, 'total_minor' => 5799]]; // Increase the tax-inclusive first allocation; consumed amounts remain respected. $other = $this->f['r']->replicate(['number']); $other->number = 'QA-AMEND-BALANCE'; $other->save(); $engine->record($other->id, $this->f['r']->cost_center_id, 'operating', 'reserve', 14200, 14200); expect(fn () => $engine->amendDistribution($this->f['r']->id, $increase, $commit['plan_hash'], 'Reafectação sem saldo deve ser integralmente recusada.', (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_distribution_entries')->get()->toJson())->toBe($before) ->and(DB::table('budget_distribution_events')->count())->toBe(3); }); test('explicit reference line reallocation preserves native header totals without automatic cents', function () { // Synthetic reference imputations: one MZN cent shared across two documentary lines. $this->lines = [12 => ['subtotal_minor' => 1, 'total_minor' => 1, 'required_kind' => 'operating'], 13 => ['subtotal_minor' => 0, 'total_minor' => 0, 'required_kind' => 'operating']]; $this->plan = [[...$this->plan[0], 'subtotal_minor' => 1, 'total_minor' => 1], [...$this->plan[1], 'line_id' => 13, 'subtotal_minor' => 0, 'total_minor' => 0]]; distributedRecord($this, 'reserve'); $commit = distributedRecord($this, 'commit'); $next = [[...$this->plan[0], 'subtotal_minor' => 0, 'total_minor' => 0], [...$this->plan[1], 'subtotal_minor' => 1, 'total_minor' => 1]]; $lines = [12 => ['subtotal_minor' => 0, 'total_minor' => 0, 'required_kind' => 'operating'], 13 => ['subtotal_minor' => 1, 'total_minor' => 1, 'required_kind' => 'operating']]; $engine = app(CommonBudget::class)->for($this->author); $invalid = $lines; $invalid[13]['subtotal_minor'] = 2; $invalid[13]['total_minor'] = 2; $wrongPlan = $next; $wrongPlan[1]['subtotal_minor'] = 2; $wrongPlan[1]['total_minor'] = 2; expect(fn () => $engine->amendDistribution($this->f['r']->id, $wrongPlan, $commit['plan_hash'], 'Não alterar os totais nativos congelados.', (string) Str::uuid(), $invalid))->toThrow(BudgetFailure::class); $operation = (string) Str::uuid(); $amend = fn () => $engine->amendDistribution($this->f['r']->id, $next, $commit['plan_hash'], 'Imputação explícita sintética do centavo por Finanças.', $operation, $lines); expect($amend()['replayed'])->toBeFalse()->and($amend()['replayed'])->toBeTrue() ->and($engine->balance($this->budgetIds[0])['committed_minor'])->toBe(0) ->and($engine->balance($this->budgetIds[1])['committed_minor'])->toBe(1); $invoice = distributionInvoice($this, 'EXPLICIT-CENT', 1, 1); $engine->consumeDistribution($this->f['r']->id, $invoice->id, [$next[1]], [13 => $lines[13]], str_repeat('e', 64), (string) Str::uuid()); expect($engine->balance($this->budgetIds[1])['consumed_minor'])->toBe(1); }); test('native partial invoice registration and independent validation use distributed consumption exactly once', function () { $id = $this->f['line']->requisition_item_id; $this->lines = [$id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $this->plan = array_map(fn ($row) => [...$row, 'allocation_key' => (string) Str::uuid(), 'line_id' => $id, 'subtotal_minor' => 5000, 'total_minor' => 5000], $this->plan); distributedRecord($this, 'reserve'); distributedRecord($this, 'commit'); $this->actingAs($this->f['receiver']); app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000')); $this->actingAs($this->author); $data = ['number' => 'DISTR-NATIVE-PARTIAL', 'issued_on' => today()->toDateString(), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00', 'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '0.600']], 'reason' => 'Imputação explícita da factura parcial sintética.', 'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => '30.00', 'total' => '30.00'], $this->plan)]; $invalid = $data; $invalid['budget_distribution_preparation'][0]['allocation_key'] = (string) Str::uuid(); expect(fn () => app(InvoiceWorkflow::class)->register($this->author, $this->f['order'], $invalid))->toThrow(ValidationException::class) ->and(Invoice::query()->count())->toBe(0)->and(DB::table('budget_distribution_consumptions')->count())->toBe(0); $invoice = app(InvoiceWorkflow::class)->register($this->author, $this->f['order'], $data); expect($invoice->snapshot['budget_distribution']['reference']['total_minor'])->toBe(6000) ->and(DB::table('budget_distribution_consumptions')->count())->toBe(0); try { app(InvoiceWorkflow::class)->validate($this->author, $invoice); $this->fail('The invoice author cannot validate their own preparation.'); } catch (HttpException $error) { expect($error->getStatusCode())->toBe(403); } $validator = User::factory()->create(['tenant_id' => $this->author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]); $this->actingAs($validator); app(InvoiceWorkflow::class)->validate($validator, $invoice); app(InvoiceWorkflow::class)->validate($validator, $invoice); expect($invoice->fresh()->status)->toBe('validated')->and(DB::table('budget_distribution_consumptions')->count())->toBe(2) ->and(DB::table('budget_consumptions')->count())->toBe(0) ->and(app(CommonBudget::class)->for($validator)->balance($this->budgetIds[0]))->toMatchArray(['committed_minor' => 2000, 'consumed_minor' => 3000]); $this->get('/requisicoes/'.$this->f['r']->id.'/processo')->assertOk()->assertInertia(fn ($page) => $page->where('stages', fn ($stages) => collect($stages)->firstWhere('label', 'Controlo orçamental')['state'] === 'recorded')); }); test('Finance explicitly versions a foreign order allocation through HTTP without altering its frozen document', function () { $this->withoutVite(); // Synthetic issued-order fixture; no claim of a full adjudication journey. $request = $this->f['r']->replicate(['number']); $request->number = 'QA-FX-DISTR-'.Str::random(8); $request->save(); $requested = $this->f['r']->items()->firstOrFail()->replicate(); $requested->requisition_id = $request->id; $requested->save(); app(QuotationExchange::class)->record($this->author, $request, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.0000000000', 'quoted_on' => today()->toDateString(), 'source' => 'Taxa exclusivamente sintética para teste, sem cotação de mercado.']); $basis = app(QuotationExchange::class)->basis($request, 'USD'); $quote = Quotation::query()->where('requisition_id', $this->f['r']->id)->firstOrFail()->replicate(); $quote->requisition_id = $request->id; $quote->currency = 'USD'; $quote->exchange_basis = $basis; $quote->save(); $award = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id)->replicate(); $award->requisition_id = $request->id; $award->quotation_id = $quote->id; $award->save(); $order = $this->f['order']->replicate(['number']); $order->number = 'QA-OC-FX-'.Str::random(8); $order->requisition_id = $request->id; $order->purchase_award_id = $award->id; $order->currency = 'USD'; $order->snapshot = [...$order->snapshot, 'exchange_basis' => $basis, 'reference_amounts' => ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]]; $order->save(); $line = $this->f['line']->replicate(); $line->purchase_order_id = $order->id; $line->requisition_item_id = $requested->id; $line->save(); $plan = array_map(fn ($row) => [...$row, 'allocation_key' => (string) Str::uuid(), 'line_id' => $requested->id, 'subtotal_minor' => 5000, 'total_minor' => 5000], $this->plan); $lines = [$requested->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $engine = app(CommonBudget::class)->for($this->author); $engine->recordDistribution($request->id, 'reserve', $plan, $lines, str_repeat('f', 64), (string) Str::uuid()); $commit = $engine->recordDistribution($request->id, 'commit', $plan, $lines, str_repeat('f', 64), (string) Str::uuid()); $document = $order->fresh()->getRawOriginal(); $this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true); $input = ['operation_key' => (string) Str::uuid(), 'expected_plan_hash' => $commit['plan_hash'], 'reason' => 'Reafectação explícita sintética para conferência da factura parcial.', 'budget_distribution_preparation' => array_map(fn ($row, $amount) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => $amount, 'total' => $amount], $plan, ['60.01', '39.99'])]; $this->postJson('/ordens/'.$order->id.'/reafectacao', $input)->assertRedirect('/ordens/'.$order->id); $this->postJson('/ordens/'.$order->id.'/reafectacao', $input)->assertRedirect('/ordens/'.$order->id); expect($order->fresh()->getRawOriginal())->toBe($document) ->and(DB::table('budget_distribution_events')->where('distribution_id', $commit['distribution_id'])->count())->toBe(3); $this->actingAs($this->f['issuer']); $this->postJson('/ordens/'.$order->id.'/reafectacao', [...$input, 'operation_key' => (string) Str::uuid()])->assertForbidden(); $this->actingAs($this->f['receiver']); $fixture = [...$this->f, 'r' => $request, 'order' => $order, 'line' => $line]; app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $order, receiptPayload($fixture, '1.000')); $this->actingAs($this->author); $data = ['number' => 'QA-FX-PARTIAL', 'issued_on' => today()->toDateString(), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00', 'items' => [['purchase_order_item_id' => $line->id, 'quantity' => '0.600']], 'reason' => 'Imputação explícita em MZN da factura parcial.', 'budget_distribution_preparation' => array_map(fn ($row) => [...$row, 'subtotal' => '30.00', 'total' => '30.00'], $input['budget_distribution_preparation'])]; $invoice = app(InvoiceWorkflow::class)->register($this->author, $order, $data); $validator = User::factory()->create(['tenant_id' => $this->author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]); $this->actingAs($validator); app(InvoiceWorkflow::class)->validate($validator, $invoice); expect($invoice->fresh()->status)->toBe('validated')->and($invoice->snapshot['exchange_basis'])->toBe($basis) ->and($invoice->snapshot['budget_distribution']['reference']['total_minor'])->toBe(6000); }); test('failure of any destination rolls back the entire distribution and its origin', function () { $centre = CostCenter::query()->create(['tenant_id' => $this->author->tenant_id, 'department_id' => $this->f['department']->id, 'code' => 'DISTR-SMALL', 'name' => 'Dotação insuficiente sintética']); $budget = app(CommonBudget::class)->for($this->author)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100, 'reason' => 'Limite sintético do cenário de falha']); $this->actingAs($this->reviewer); app(CommonBudget::class)->for($this->reviewer)->approve($budget); $this->actingAs($this->author); $plan = $this->plan; $plan[1]['centre_id'] = $centre->id; expect(fn () => distributedRecord($this, 'reserve', null, $plan))->toThrow(BudgetFailure::class); foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries'] as $table) { expect(DB::table($table)->count())->toBe(0); } expect(app(CommonBudget::class)->for($this->author)->balance($this->budgetIds[0])['available_minor'])->toBe(20000); }); test('a same-budget redistribution checks its combined delta instead of rejecting a temporary line ordering', function () { $centre = CostCenter::query()->create(['tenant_id' => $this->author->tenant_id, 'department_id' => $this->f['department']->id, 'code' => 'DISTR-EXACT', 'name' => 'Dotação exacta sintética']); $budget = app(CommonBudget::class)->for($this->author)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 11600, 'reason' => 'Dotação exacta para a distribuição']); $this->actingAs($this->reviewer); app(CommonBudget::class)->for($this->reviewer)->approve($budget); $this->actingAs($this->author); $plan = array_map(fn ($row) => [...$row, 'centre_id' => $centre->id], $this->plan); distributedRecord($this, 'reserve', null, $plan); $changed = [[...$plan[0], 'subtotal_minor' => 9000, 'total_minor' => 10440], [...$plan[1], 'subtotal_minor' => 1000, 'total_minor' => 1160]]; distributedRecord($this, 'award', null, $changed); expect(app(CommonBudget::class)->for($this->author)->balance($budget))->toMatchArray(['reserved_minor' => 11600, 'available_minor' => 0]); }); test('cancellation releases each unused commitment once and cannot restart the distributed process', function () { distributedRecord($this, 'reserve'); distributedRecord($this, 'commit'); $operation = (string) Str::uuid(); expect(distributedRecord($this, 'cancel', $operation)['replayed'])->toBeFalse() ->and(distributedRecord($this, 'cancel', $operation)['replayed'])->toBeTrue(); foreach ($this->budgetIds as $budget) { expect(app(CommonBudget::class)->for($this->author)->balance($budget))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'available_minor' => 20000]); } expect(fn () => distributedRecord($this, 'award'))->toThrow(BudgetFailure::class) ->and(DB::table('budget_distribution_events')->count())->toBe(3); }); test('changed replay and cumulative allocation overspending cannot alter distributed effects', function () { $key = (string) Str::uuid(); distributedRecord($this, 'reserve', $key); $changed = [[...$this->plan[0], 'subtotal_minor' => 6000, 'total_minor' => 6960], [...$this->plan[1], 'subtotal_minor' => 4000, 'total_minor' => 4640]]; expect(fn () => distributedRecord($this, 'reserve', $key, $changed))->toThrow(BudgetFailure::class); distributedRecord($this, 'commit'); $engine = app(CommonBudget::class)->for($this->author); $invoice = distributionInvoice($this, 'DISTR-ONE', 1000, 1160); $partial = array_map(fn ($row) => [...$row, 'subtotal_minor' => 500, 'total_minor' => 580], $this->plan); $engine->consumeDistribution($this->f['r']->id, $invoice->id, $partial, [12 => ['subtotal_minor' => 1000, 'total_minor' => 1160, 'required_kind' => 'operating']], str_repeat('b', 64), (string) Str::uuid()); $invoice2 = distributionInvoice($this, 'DISTR-TOO-MUCH', 5000, 5800); $before = DB::table('budget_distribution_entries')->get()->toJson(); expect(fn () => $engine->consumeDistribution($this->f['r']->id, $invoice2->id, [$this->plan[0]], [12 => ['subtotal_minor' => 5000, 'total_minor' => 5800, 'required_kind' => 'operating']], str_repeat('c', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_distribution_entries')->get()->toJson())->toBe($before); }); test('partial distribution schema fails closed instead of hiding existing financial positions', function () { DB::connection()->getSchemaBuilder()->drop('budget_distribution_events'); expect(app(RequisitionBudgetDistributions::class)->ready())->toBeFalse(); expect(fn () => app(CommonBudget::class)->for($this->author)->balance($this->budgetIds[0]))->toThrow(BudgetFailure::class); });