commit melhorias compras4
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 16:28:03 +02:00
parent efd97e265b
commit 36dcfdf00c
118 changed files with 6042 additions and 92 deletions
@@ -0,0 +1,434 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CostCenter;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\CommonBudget;
use App\Services\InvoiceWorkflow;
use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->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'));
});
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);
});
@@ -0,0 +1,48 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('old pinned runtime refuses partial optional schema even when its source table is absent', function () {
if (method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Recovery boundary requires the unchanged installed artifact.');
}
$f = receiptFixture();
budgetDistributionFixtureSchema();
DB::connection()->getSchemaBuilder()->drop('budget_distributions');
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($actor);
try {
app(CommonBudget::class)->for($actor);
$this->fail('Partial optional schema cannot silently become a legacy balance.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(503);
}
expect(DB::table('budget_entries')->count())->toBe(0);
});
test('old pinned runtime refuses to ignore a distributed origin instead of presenting a false available balance', function () {
if (method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('This recovery boundary exercises the unchanged installed artifact.');
}
$f = receiptFixture();
budgetDistributionFixtureSchema();
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($actor);
DB::table('budget_distributions')->insert(['tenant_id' => $actor->tenant_id, 'requisition_id' => $f['r']->id,
'phase' => 'reserve', 'snapshot' => '{}', 'created_by' => $actor->id, 'created_at' => now(), 'updated_at' => now()]);
try {
app(CommonBudget::class)->for($actor);
$this->fail('An incompatible runtime must fail closed.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(503);
}
expect(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
@@ -0,0 +1,49 @@
<?php
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('optional QA migration installs once explicitly and preserves previous records', function () {
$f = receiptFixture();
$columns = Schema::getColumnListing('requisitions');
$before = DB::table('requisitions')->select($columns)->get()->toJson();
$count = DB::table('migrations')->count();
$path = database_path('qa-migrations/2026_11_22_000004_create_budget_distributions.php');
foreach ([1, 2] as $attempt) {
expect(Artisan::call('migrate', ['--path' => [$path], '--realpath' => true, '--force' => true]))->toBe(0);
expect(DB::table('migrations')->count())->toBe($count + 1)
->and(DB::table('requisitions')->select($columns)->get()->toJson())->toBe($before)
->and(DB::table('budget_distributions')->count())->toBe(0)
->and(DB::table('requisitions')->whereNotNull('budget_distribution_preparation')->count())->toBe(0);
}
$migration = require $path;
expect(fn () => $migration->down())->toThrow(LogicException::class)
->and(Schema::hasTable('budget_distribution_events'))->toBeTrue()
->and(DB::table('requisitions')->where('id', $f['r']->id)->exists())->toBeTrue();
});
test('optional schema failure is atomic and cannot leave a new preparation column', function () {
receiptFixture();
Schema::create('budget_distribution_entries', fn ($table) => $table->id());
$migration = require database_path('qa-migrations/2026_11_22_000004_create_budget_distributions.php');
expect(fn () => $migration->up())->toThrow(QueryException::class)
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse()
->and(Schema::hasTable('budget_distributions'))->toBeFalse()
->and(Schema::hasTable('budget_distribution_events'))->toBeFalse();
});
test('QA migration refuses an operational environment before writing schema', function () {
receiptFixture();
$migration = require database_path('qa-migrations/2026_11_22_000004_create_budget_distributions.php');
app()->instance('env', 'production');
try {
expect(fn () => $migration->up())->toThrow(LogicException::class)
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse();
} finally {
app()->instance('env', 'testing');
}
});
@@ -18,6 +18,15 @@ beforeEach(function () {
]];
});
test('new and existing requisition form history is encrypted without creating a process on read', function () {
$count = Requisition::query()->count();
$this->get('/requisicoes/criar')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect(Requisition::query()->count())->toBe($count);
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$this->get('/requisicoes/'.$r->id.'/editar')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
});
test('incomplete draft persists unknown values without invented amounts and cannot reserve or submit', function () {
$entries = DB::table('budget_entries')->count();
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
@@ -112,6 +112,17 @@ test('autonomous adapter executes shared lifecycle with one request one reserve
$this->get('/requisicoes/'.$r->id)->assertOk();
});
test('one eligible approver completes the level even when another approver is eligible for the same level', function () {
$alternative = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'department_id' => $this->actor->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->postJson('/requisicoes', $this->data)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$this->postJson('/requisicoes/'.$r->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect();
expect($r->fresh()->canDecide($this->head))->toBeTrue()->and($r->fresh()->canDecide($alternative))->toBeTrue();
$this->actingAs($alternative)->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => 2, 'decision' => 'approved'])->assertRedirect();
expect($r->fresh()->status)->toBe('approved')->and($r->steps()->sole()->approver_id)->toBe($alternative->id)
->and($r->fresh()->canDecide($this->head))->toBeFalse()->and($r->steps()->count())->toBe(1);
});
test('source adapter refuses changed replay stale version revoked role and another tenant', function () {
$this->postJson('/requisicoes', $this->data)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
@@ -39,7 +39,25 @@ beforeEach(function () {
$this->actingAs($this->admin);
});
afterEach(function () {
if ($this->committedReportFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Report fixture cleanup requires the disposable PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
test('intelligence settings are independently configurable audited and scoped without rewriting processes', function () {
if (DB::getDriverName() === 'pgsql') {
// The real report opens its own read-only snapshot, outside the test wrapper.
if (! app()->environment('testing') || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Report fixtures require the disposable PostgreSQL test transaction.');
}
DB::commit();
$this->committedReportFixture = true;
}
$before = $this->f['r']->fresh()->toArray();
$body = ['version' => 1, 'procurement_brief' => false, 'people_brief' => true, 'reason' => 'Apresentar sínteses apenas no percurso de Pessoas.'];
$this->postJson($this->base.'/intelligence', $body)->assertRedirect();
@@ -0,0 +1,115 @@
<?php
use App\Models\Requisition;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPayableInsights;
use App\Services\SupplierPayables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
$this->f = paymentFixture();
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'insights-fixture-instance']);
foreach ([$this->f['author'], $this->f['validator']] as $user) {
foreach (['view', 'prepare', 'validate'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $user->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $user->id, 'person' => 'insights-person-'.$user->id, 'action' => $action]);
}
}
$this->actingAs($this->f['author']);
$prepared = app(SupplierPayables::class)->engine($this->f['author'])->command('prepare', $this->f['invoice']->id, 'Preparação sintética para consulta', (string) Str::uuid());
$this->actingAs($this->f['validator']);
app(SupplierPayables::class)->engine($this->f['validator'])->command('validate', $prepared['proposal_id'], 'Conferência sintética independente', (string) Str::uuid());
});
afterEach(function () {
if ($this->committedInsightsFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Read report fixture cleanup requires the disposable database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
test('financial insights use native positions across authorised filtered requests without modifying sources', function () {
$copy = $this->f['invoice']->replicate();
$copy->number = 'UNRECOGNISED-INSIGHTS';
$copy->save();
receiptFixture(); // Another company is never included.
$this->actingAs($this->f['validator']);
if (DB::getDriverName() === 'pgsql') {
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Commit only the disposable report test fixture.');
}
DB::commit();
$this->committedInsightsFixture = true;
}
$tables = ['pa_obligations', 'pa_sources', 'pa_proposals', 'pa_events', 'pa_commands', 'invoices', 'external_payments', 'audit_logs'];
$before = [];
foreach ($tables as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('payableInsights.coverage', ['invoices' => 2, 'recognised' => 1, 'unrecognised' => 1, 'indeterminate' => 0])
->where('payableInsights.currencies.0.currency', 'MZN')->where('payableInsights.currencies.0.principal_minor', '6000')
->where('payableInsights.currencies.0.balance_minor', '6000')->where('payableInsights.currencies.0.confirmed_payments_minor', '0')
->where('payableInsights.currencies.0.allocated_payments_minor', '0')->missing('payableInsights.bank_snapshot'));
$this->get('/relatorios?search=NO-MATCH-INSIGHTS')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('payableInsights.coverage.invoices', 0)->where('payableInsights.currencies', []));
$csv = $this->get('/relatorios/obrigacoes.csv')->assertOk()->assertDownload();
expect($csv->streamedContent())->toContain('MZN;1;6000;0;0;6000')->toContain('2;1;1;0')->not->toContain('bank_snapshot');
$this->actingAs($this->f['issuer'])->get('/relatorios/obrigacoes.csv')->assertForbidden();
foreach ($tables as $table) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($before[$table]);
}
});
test('a divergent native position is counted as indeterminate and never replaced by zero', function () {
DB::table('invoices')->where('id', $this->f['invoice']->id)->update(['total_minor' => 6001]);
$result = app(ProcurementPayableInsights::class)->build($this->f['validator'], Requisition::query()->visibleTo($this->f['validator']));
expect($result['coverage']['indeterminate'])->toBe(1)->and($result['coverage']['recognised'])->toBe(0)->and($result['currencies'])->toBe([]);
});
test('native imported history is counted once and pending payments do not reduce the reported balance', function () {
$f = paymentFixture();
config(['common-payables.history_enabled' => true]);
foreach ([$f['author'], $f['validator']] as $user) {
foreach (['view', 'prepare', 'validate'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $user->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $user->id,
'person' => 'history-insights-'.$user->id, 'action' => $action]);
}
}
$this->actingAs($f['author']);
$payments = app(ExternalPaymentWorkflow::class);
$payment = $payments->register($f['author'], $f['invoice'], [...$f['payment_data'], 'amount' => '30.00']);
$this->actingAs($f['validator']);
$payments->review($f['validator'], $payment, 'confirmed', 'Conferência histórica sintética');
$this->actingAs($f['author']);
$payments->register($f['author'], $f['invoice'], [...$f['payment_data'], 'amount' => '10.00', 'external_reference' => 'INSIGHTS-PENDING']);
$adapter = app(SupplierPayables::class);
$proposal = $adapter->engine($f['author'])->command('prepare_history', $f['invoice']->id, 'Importação histórica sintética', (string) Str::uuid());
$this->actingAs($f['validator']);
$adapter->engine($f['validator'])->command('validate_history', $proposal['proposal_id'], 'Conferência independente do histórico', (string) Str::uuid());
$result = app(ProcurementPayableInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']));
expect($result['coverage']['recognised'])->toBe(1)->and($result['currencies'][0]['principal_minor'])->toBe('6000')
->and($result['currencies'][0]['confirmed_payments_minor'])->toBe('3000')->and($result['currencies'][0]['allocated_payments_minor'])->toBe('0')
->and($result['currencies'][0]['balance_minor'])->toBe('3000');
});
test('read composition rejects commands and revalidates withdrawn native financial access', function () {
$actor = $this->f['validator'];
$engine = app(SupplierPayables::class)->readEngine($actor);
$commands = DB::table('pa_commands')->count();
expect(fn () => $engine->command('prepare', $this->f['invoice']->id, 'Proibido na composição de leitura', (string) Str::uuid()))->toThrow(LogicException::class);
expect(DB::table('pa_commands')->count())->toBe($commands);
DB::table('pa_access')->where('user_id', $actor->id)->where('action', 'view')->delete();
expect(fn () => $engine->positionForSource($this->f['invoice']->id))->toThrow(HttpException::class);
expect(app(ProcurementPayableInsights::class)->build($actor, Requisition::query()->visibleTo($actor)))->toBeNull();
$this->actingAs($this->f['issuer']);
expect(app(ProcurementPayableInsights::class)->build($this->f['issuer'], Requisition::query()->visibleTo($this->f['issuer'])))->toBeNull();
});
+3 -3
View File
@@ -105,10 +105,10 @@ test('optional finance search uses native invoice scope and returns references w
$create(receiptFixture());
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 8)
->where('groups.7.key', 'invoices')->where('groups.7.records.total', 1)->where('groups.7.records.data.0.href', '/facturas?invoice_id='.$ownInvoice->id)
->where('invoiceSearchAvailable', true)->where('groups.7.key', 'invoices')->where('groups.7.records.total', 1)->where('groups.7.records.data.0.href', '/facturas?invoice_id='.$ownInvoice->id)
->missing('groups.7.records.data.0.snapshot')->missing('groups.7.records.data.0.total_minor'));
$this->get('/facturas?invoice_id='.$ownInvoice->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('focusInvoiceId', $ownInvoice->id));
$this->actingAs($f['issuer'])->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 7));
$this->actingAs($f['issuer'])->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->where('invoiceSearchAvailable', false)->has('groups', 7));
config(['procurement_search.finance_metadata_enabled' => false]);
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 7));
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->where('invoiceSearchAvailable', false)->has('groups', 7));
});
+41
View File
@@ -29,6 +29,7 @@ use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\BudgetWorkflow;
use App\Services\CommonBudget;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
use App\Services\DocumentaryQualificationWorkflow;
@@ -43,6 +44,7 @@ use App\Services\ProposalOpeningWorkflow;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow;
use App\Services\QuotationExchange;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
@@ -53,9 +55,48 @@ use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Unpublished common source requires explicit QA selection.');
}
budgetDistributionFixtureSchema();
config(['budget-distributions.qa_enabled' => true]);
$this->withoutVite();
$second = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'QA-SPLIT', 'name' => 'Segundo centro sintético']);
$adapter = app(CommonBudget::class);
foreach ([$this->r->cost_center_id, $second->id] as $centre) {
$this->actingAs($this->finance);
$id = $adapter->for($this->finance)->create(['cost_center_id' => $centre, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true,
'amount_minor' => 20000, 'reason' => 'Dotação sintética do percurso distribuído.']);
$this->actingAs($this->admin);
$adapter->for($this->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = array_map(fn ($centre) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $this->item->id, 'centre_id' => $centre,
'subtotal_minor' => 5000, 'total_minor' => 5000], [$this->r->cost_center_id, $second->id]);
// The approved source is the existing fixture; preparation/submission have their separate native tests.
$this->r->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($this->r, $host->requestLines($this->r)), 'prepared_by' => $this->owner->id, 'reason' => 'Distribuição da fonte sintética aprovada.']])->save();
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$this->selection['reason'] = 'Confirmação explícita das parcelas da proposta seleccionada.';
$this->selection['budget_distribution_preparation'] = array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => '50.00', 'total' => '50.00'], $allocations);
$this->actingAs($this->buyer)->get($this->awardUrl)->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['budget_control']['phase'])->toBe('commit')
->and(DB::table('budget_distribution_entries')->where('kind', 'commit')->count())->toBe(2)
->and(DB::table('budget_entries')->where('requisition_id', $this->r->id)->count())->toBe(0);
$before = DB::table('budget_distribution_entries')->count();
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
expect(DB::table('budget_distribution_entries')->count())->toBe($before)->and(PurchaseOrder::query()->count())->toBe(1);
});
function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $quantity = '1.000', ?string $stockUnit = null): array
{
@@ -0,0 +1,17 @@
<?php
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('older synthetic order remains readable and printable without rewriting its incomplete snapshot', function () {
$f = receiptFixture();
$order = $f['order'];
$before = $order->fresh()->toArray();
$this->actingAs($f['issuer']);
$this->get('/ordens')->assertOk()->assertInertia(fn (Assert $page) => $page->where('orders.data.0.id', $order->id));
$this->get('/ordens/'.$order->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('snapshotComplete', false)->where('order.snapshot', $order->snapshot));
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Documento original incompleto.')->assertSee($order->number)->assertSee('100,00 MZN')->assertDontSee('Matriz de avaliação congelada');
expect($order->fresh()->toArray())->toBe($before);
$this->actingAs(receiptFixture()['issuer'])->get('/ordens/'.$order->id.'/imprimir')->assertNotFound();
});
@@ -0,0 +1,243 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Department;
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionApprovalLevels;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowNotices;
use App\Services\WorkflowTaskInbox;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('approval schema rollback preserves configured plans and frozen routing', function () {
$migration = require database_path('migrations/2026_11_22_000003_add_configured_requisition_levels.php');
$this->f['tenant']->forceFill(['requisition_approval_policy' => ['enabled' => false, 'levels' => []]])->save();
expect(fn () => $migration->down())->toThrow(LogicException::class);
expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBe(['enabled' => false, 'levels' => []]);
$this->f['tenant']->forceFill(['requisition_approval_policy' => null])->save();
$step = $this->f['r']->steps()->create(['tenant_id' => $this->f['tenant']->id, 'position' => 1, 'role' => 'configured_1', 'decision' => 'pending', 'routing' => ['name' => 'QA preserved route']]);
expect(fn () => $migration->down())->toThrow(LogicException::class);
expect($step->fresh()->routing)->toBe(['name' => 'QA preserved route']);
});
test('installed capability is explicitly enabled independently from the isolated QA flag', function () {
config(['requisition_approval.qa_enabled' => false, 'requisition_approval.enabled' => false]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
config(['requisition_approval.enabled' => true]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeTrue();
$this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect();
expect($this->f['tenant']->fresh()->requisition_approval_policy['quorum'])->toBe('one_eligible');
config(['requisition_approval.enabled' => false]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
});
test('approval schema upgrade adds empty fields without rewriting existing company or approval data', function () {
$migration = require database_path('migrations/2026_11_22_000003_add_configured_requisition_levels.php');
$columns = fn ($table) => array_values(array_diff(DB::connection()->getSchemaBuilder()->getColumnListing($table), ['requisition_approval_policy', 'routing']));
$tenantColumns = $columns('tenants');
$stepColumns = $columns('approval_steps');
$beforeTenants = DB::table('tenants')->orderBy('id')->get($tenantColumns)->toJson();
$beforeSteps = DB::table('approval_steps')->orderBy('id')->get($stepColumns)->toJson();
$migration->down();
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
$migration->up();
expect(DB::table('tenants')->orderBy('id')->get($tenantColumns)->toJson())->toBe($beforeTenants)
->and(DB::table('approval_steps')->orderBy('id')->get($stepColumns)->toJson())->toBe($beforeSteps)
->and(DB::table('tenants')->whereNotNull('requisition_approval_policy')->exists())->toBeFalse()
->and(DB::table('approval_steps')->whereNotNull('routing')->exists())->toBeFalse()
->and(app(RequisitionApprovalLevels::class)->ready())->toBeTrue();
});
function approvalLevelProfile(int $tenant, string $name, array $permissions): int
{
return DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => $name, 'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
}
function approvalLevelMember(User $actor, int $profile): void
{
DB::table('organization_memberships')->insert(['tenant_id' => $actor->tenant_id, 'user_id' => $actor->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
}
beforeEach(function () {
$this->withoutVite();
config(['requisition_approval.qa_enabled' => true]);
$this->f = receiptFixture();
$tenant = $this->f['tenant']->id;
$this->admin = $this->f['issuer'];
$this->f['tenant']->update(['first_limit_minor' => 0, 'second_limit_minor' => 0, 'approval_includes_tax' => true, 'rules_provisional' => false]);
$this->head = User::factory()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id, 'purchasing_role' => PurchasingRole::Configured]);
$this->buyer = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]);
$this->financier = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]);
$secondAdmin = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]);
$adminProfile = approvalLevelProfile($tenant, 'Administração QA', ['admin', 'requester']);
approvalLevelMember($this->admin, $adminProfile);
approvalLevelMember($secondAdmin, $adminProfile);
approvalLevelMember($this->head, approvalLevelProfile($tenant, 'Chefia QA', ['department_head']));
approvalLevelMember($this->buyer, approvalLevelProfile($tenant, 'Compras QA', ['procurement']));
approvalLevelMember($this->financier, approvalLevelProfile($tenant, 'Finanças QA', ['finance']));
$this->pool = approvalLevelProfile($tenant, 'Aprovadores adicionais QA', ['requisition_approve']);
$this->approvers = [];
foreach (range(1, 6) as $index) {
$actor = User::factory()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id, 'purchasing_role' => PurchasingRole::Configured]);
approvalLevelMember($actor, $this->pool);
$this->approvers[] = $actor;
}
DB::table('organization_access')->insert(['tenant_id' => $tenant, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
Budget::query()->create(['tenant_id' => $tenant, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 1000000, 'includes_tax' => true, 'reason' => 'Dotação exclusivamente sintética.', 'created_by' => $this->admin->id, 'approved_by' => $this->financier->id]);
$this->plan = ['version' => 1, 'enabled' => true, 'reason' => 'Plano de níveis adicionais para ensaio isolado.', 'levels' => array_map(fn ($number) => ['name' => 'Nível adicional '.$number, 'profile_ids' => [(string) $this->pool], 'scope' => 'company', 'min_amount' => null, 'categories' => [], 'cost_center_ids' => []], range(1, 5))];
$this->body = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade sintética com oito níveis.',
'items' => [['description' => 'Material QA', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']]];
$this->actingAs($this->admin);
});
function submitConfiguredRequest($test): Requisition
{
$test->actingAs($test->admin)->postJson('/administracao/parametrizacao/approval_levels', $test->plan)->assertRedirect();
$test->postJson('/requisicoes', $test->body)->assertRedirect();
$record = Requisition::query()->latest('id')->firstOrFail();
$test->postJson('/requisicoes/'.$record->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect();
return $record->fresh();
}
function configuredDecision($test, User $actor, Requisition $record, string $decision = 'approved'): void
{
$test->actingAs($actor)->postJson('/requisicoes/'.$record->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $record->fresh()->process_version, 'decision' => $decision, 'comment' => 'Fundamento sintético da decisão.'])->assertRedirect();
}
test('native three controls and five configured levels progress sequentially with one eligible person per level', function () {
$r = submitConfiguredRequest($this);
expect($r->steps()->count())->toBe(8)->and($r->approval_snapshot['routing_quorum'])->toBe('one_eligible');
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
$first = $this->approvers[0];
$this->actingAs($first)->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canDecide', true)->where('approvalRouting.label', 'Nível adicional 1'));
expect(collect(app(WorkflowNotices::class)->visible($first))->contains('role_label', 'Nível adicional 1'))->toBeTrue();
$this->get('/facturas')->assertForbidden();
expect(collect(app(WorkflowTaskInbox::class)->build($first, 'procurement'))->contains('reference', $r->number))->toBeTrue();
expect($r->fresh()->canDecide($this->approvers[1]))->toBeTrue();
foreach (array_slice($this->approvers, 0, 5) as $actor) {
configuredDecision($this, $actor, $r);
}
expect($r->fresh()->status)->toBe('approved')->and($r->steps()->where('decision', 'approved')->count())->toBe(8)
->and($r->steps()->where('position', 4)->sole()->approver_id)->toBe($first->id);
expect($r->fresh()->canDecide($this->approvers[5]))->toBeFalse();
});
test('conditions use exact amount category and cost centre and current rules do not rewrite a submitted route', function () {
$this->plan['levels'][0]['min_amount'] = '116.01';
$this->plan['levels'][1]['categories'] = ['Outra categoria'];
$this->plan['levels'][2]['categories'] = ['MATERIAL'];
$this->plan['levels'][2]['cost_center_ids'] = [(string) $this->f['r']->cost_center_id];
$this->plan['levels'][4]['min_amount'] = '116.00';
$r = submitConfiguredRequest($this);
expect($r->steps()->count())->toBe(6)->and($r->steps()->where('role', 'configured_3')->sole()->routing['profile_ids'])->toBe([$this->pool]);
$snapshot = $r->approval_snapshot;
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2, 'enabled' => false])->assertRedirect();
expect($r->fresh()->approval_snapshot)->toBe($snapshot);
foreach ([$this->head, $this->buyer, $this->financier, ...array_slice($this->approvers, 0, 3)] as $actor) {
configuredDecision($this, $actor, $r);
}
expect($r->fresh()->status)->toBe('approved');
});
test('revoked membership and expired maintenance do not approve or expose assigned requests and repeated identity cannot decide two stages', function () {
$r = submitConfiguredRequest($this);
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
configuredDecision($this, $this->approvers[0], $r);
$this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
DB::table('organization_memberships')->where('user_id', $this->approvers[1]->id)->update(['expires_at' => now()->subMinute()]);
$this->actingAs($this->approvers[1])->get('/requisicoes/'.$r->id)->assertForbidden();
$this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
expect($r->fresh()->status)->toBe('pending');
approvalLevelMember($this->approvers[2], approvalLevelProfile($r->tenant_id, 'Solicitação sem poderes de aprovação', ['requester']));
DB::table('organization_memberships')->where('user_id', $this->approvers[2]->id)->where('profile_id', $this->pool)->update(['maintenance' => true]);
$this->actingAs($this->approvers[2])->get('/requisicoes/'.$r->id)->assertNotFound();
});
test('QA capability is opt in and a configured plan never silently falls back when capability is unavailable', function () {
$r = submitConfiguredRequest($this);
config(['requisition_approval.qa_enabled' => false]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
$this->body['operation_key'] = (string) Str::uuid();
$this->postJson('/requisicoes', $this->body)->assertRedirect();
$new = Requisition::query()->latest('id')->firstOrFail();
$before = DB::table('budget_entries')->count();
$this->postJson('/requisicoes/'.$new->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertStatus(503);
expect(DB::table('budget_entries')->count())->toBe($before)->and($new->fresh()->status)->toBe('draft')->and($r->steps()->count())->toBe(8);
});
test('parallel candidates are bound to the version they reviewed and cannot advance another level with an old decision', function () {
$r = submitConfiguredRequest($this);
$this->actingAs($this->head)->postJson('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertUnprocessable();
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
$version = $r->fresh()->process_version;
$this->actingAs($this->approvers[0])->postJson('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertUnprocessable();
configuredDecision($this, $this->approvers[0], $r);
$this->actingAs($this->approvers[1])->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $version, 'decision' => 'approved'])->assertStatus(409);
expect($r->steps()->where('role', 'like', 'configured_%')->where('decision', 'approved')->count())->toBe(1);
});
test('invalid foreign pools and too many levels do not change the plan or its organisation version', function () {
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'levels' => array_fill(0, 6, $this->plan['levels'][0])])->assertUnprocessable();
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'levels' => ['invalid_key' => $this->plan['levels'][0]]])->assertUnprocessable();
$bad = $this->plan;
$bad['levels'][0]['min_amount'] = '-1';
$this->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable();
$bad = $this->plan;
$bad['levels'][0]['profile_ids'] = [approvalLevelProfile($this->admin->tenant_id, 'Consulta sem aprovação', ['requester'])];
$this->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable();
$other = receiptFixture();
$bad['levels'][0]['profile_ids'] = [approvalLevelProfile($other['tenant']->id, 'Perfil de outra empresa', ['requisition_approve'])];
$this->actingAs($this->admin)->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable();
expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBeNull()
->and(DB::table('organization_access')->where('tenant_id', $this->admin->tenant_id)->value('version'))->toBe(1);
});
test('department levels revalidate the department and the request owner never approves an assigned level', function () {
foreach ($this->plan['levels'] as &$level) {
$level['scope'] = 'department';
}
unset($level);
$r = submitConfiguredRequest($this);
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
approvalLevelMember($this->admin, $this->pool);
$this->actingAs($this->admin)->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
$other = Department::query()->create(['tenant_id' => $r->tenant_id, 'name' => 'Outro departamento QA']);
DB::table('users')->where('id', $this->approvers[0]->id)->update(['department_id' => $other->id]);
$this->actingAs($this->approvers[0])->get('/requisicoes/'.$r->id)->assertNotFound();
$this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
expect($r->fresh()->status)->toBe('pending');
});
test('a plan update and its version roll back when audit cannot be recorded', function () {
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->once()->andThrow(new RuntimeException('Injected audit failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->postJson('/administracao/parametrizacao/approval_levels', $this->plan))->toThrow(RuntimeException::class);
expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBeNull()
->and(DB::table('organization_access')->where('tenant_id', $this->admin->tenant_id)->value('version'))->toBe(1);
});
test('an invalid stored plan cannot leave a reservation or partial approval queue behind', function () {
$plan = app(RequisitionApprovalLevels::class)->prepare($this->admin, $this->plan);
$plan['levels'][] = $plan['levels'][0];
$this->f['tenant']->update(['requisition_approval_policy' => $plan]);
$this->postJson('/requisicoes', $this->body)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$before = DB::table('budget_entries')->count();
$this->postJson('/requisicoes/'.$r->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertUnprocessable();
expect($r->fresh()->status)->toBe('draft')->and($r->steps()->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe($before);
});
+12
View File
@@ -12,6 +12,7 @@ use App\Services\WarehouseFulfilment;
use App\Services\WarehouseRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Integration\WarehouseFeed;
use Tempo\Integration\WarehouseInbox;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -50,6 +51,17 @@ function exchangeDeliver($test, string $quantity = '1.500'): WarehouseRequestEve
return exchangeCommand($test, $test->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => $quantity]]]);
}
test('production consumption remains compatible with the unchanged v1 feed while preserving local production details', function () {
$this->r = app(WarehouseRequests::class)->draft($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
'destination' => 'Linha de produção QA', 'reason' => 'Consumo sintético de insumos de produção.', 'priority' => 'normal',
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '4.000', 'use' => 'production', 'equipment_id' => null, 'production_reference' => 'OP-QA-001']]]);
$event = exchangeDeliver($this);
$page = $this->getJson('/stock/integracao/entregas')->assertOk()->assertJsonPath('items.0.lines.0.use', 'internal')->json();
WarehouseFeed::validate($page, $this->f['tenant']->id);
expect($this->r->fresh()->snapshot['lines'][0]['use'])->toBe('production')
->and($event->data['lines'][0]['production']['reference'])->toBe('OP-QA-001');
});
test('warehouse exchange publishes only physical facts with original identifiers and stable replay content', function () {
$url = '/stock/integracao/entregas';
$this->getJson($url)->assertOk()->assertJsonCount(0, 'items');