commit melhorias compras6
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
@@ -0,0 +1,215 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\RequisitionWorkflow;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'reserveLandedCosts')) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
$this->f = receiptFixture();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($this->finance);
$this->budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->f['r']->cost_center_id,
'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Explicit synthetic landed-cost budget']);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer)->approve($this->budget);
$this->actingAs($this->finance);
$this->engine = app(CommonBudget::class)->for($this->finance);
$this->key = (string) Str::uuid();
$this->documents = $this->components = [];
foreach ([['supplier_invoice', 'goods', 10000, 1600], ['carrier_invoice', 'freight', 1000, 160], ['customs_assessment', 'duty', 2000, 0]] as $index => [$kind, $component, $base, $tax]) {
$money = ['subtotal_minor' => $base, 'tax_minor' => $tax, 'total_minor' => $base + $tax,
'reference_subtotal_minor' => $base, 'reference_tax_minor' => $tax, 'reference_total_minor' => $base + $tax];
// Contract-only native source declarations; native invoice integration is tested separately.
$this->documents['source-'.$index] = ['kind' => $kind, 'id' => $index + 1, 'source_key' => 'native:'.$index, 'source_version' => 1,
'creditor_key' => 'creditor:'.$index, 'currency' => 'MZN', 'revision' => hash('sha256', (string) $index), ...$money];
$this->components[] = ['component_key' => 'component-'.$index, 'kind' => $component, 'origin' => 'source-'.$index, ...$money];
}
});
test('landed reserve commit and consume affect only the additional native origin exactly once', function () {
$operation = (string) Str::uuid();
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation);
expect($reserved['total_reference_minor'])->toBe(14760)->and($reserved['additional_amount_minor'])->toBe(2000)
->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(2000);
expect($this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation)['replayed'])->toBeTrue();
$committed = $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid());
expect($committed['phase'])->toBe('committed')->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(0)
->and($this->engine->balance($this->budget)['committed_minor'])->toBe(2000);
$consume = (string) Str::uuid();
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume);
expect($this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume)['replayed'])->toBeTrue();
expect($this->engine->balance($this->budget))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 2000, 'available_minor' => 18000])
->and(DB::table('budget_landed_commands')->count())->toBe(3)->and(DB::table('budget_landed_entries')->count())->toBe(3)
->and(DB::table('budget_landed_entries')->where('source_kind', '!=', 'customs_assessment')->count())->toBe(0)
->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
test('landed operation mismatch stale versions and repeated transition fail without changing the balance', function () {
$operation = (string) Str::uuid();
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation);
expect(fn () => $this->engine->reserveLandedCosts($this->key, 3, $this->budget, $this->components, $this->documents, $operation))->toThrow(BudgetFailure::class);
expect(fn () => $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'commit', (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid());
expect(fn () => $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_commands')->count())->toBe(2)->and($this->engine->balance($this->budget)['committed_minor'])->toBe(2000);
});
test('a native origin cannot be reserved under another plan even after its budget cancellation', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'cancel', (string) Str::uuid());
expect($this->engine->balance($this->budget)['available_minor'])->toBe(20000);
expect(fn () => $this->engine->reserveLandedCosts((string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_commands')->count())->toBe(2);
});
test('consumed customs costs cannot be cancelled or consumed a second time', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['commit', 'consume'] as $kind) {
$this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], $kind, (string) Str::uuid());
}
foreach (['cancel', 'consume'] as $kind) {
expect(fn () => $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], $kind, (string) Str::uuid()))->toThrow(BudgetFailure::class);
}
expect($this->engine->balance($this->budget)['consumed_minor'])->toBe(2000);
});
test('failure of the host audit rolls back the entire additional-origin financial command', function () {
$this->mock(RequisitionWorkflow::class, function ($mock) {
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Synthetic landed-cost audit failure'));
});
expect(fn () => $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid()))->toThrow(RuntimeException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0)
->and($this->engine->balance($this->budget)['available_minor'])->toBe(20000);
});
test('only current Finance can reserve and another company cannot inspect the native plan', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->actingAs($this->f['issuer']);
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->reserveLandedCosts((string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid()))->toThrow(HttpException::class);
$other = receiptFixture();
$foreign = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($foreign);
expect(app(CommonBudget::class)->for($foreign)->landedCostState($this->key))->toBeNull();
expect(fn () => app(CommonBudget::class)->for($foreign)->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'commit', (string) Str::uuid()))->toThrow(BudgetFailure::class);
});
test('the landed history cannot be mutated deleted or silently reinstalled', function () {
$this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['budget_landed_commands', 'budget_landed_entries'] as $table) {
$first = DB::table($table)->first();
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $first->id)->update(['tenant_id' => $first->tenant_id])))->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $first->id)->delete()))->toThrow(QueryException::class);
}
expect(fn () => (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up())->toThrow(LogicException::class);
});
test('reviewed actual-cost amendments preserve the original commitment and require new documentary versions', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid());
$before = DB::table('budget_landed_entries')->get()->toArray();
$this->documents['source-2']['subtotal_minor'] = $this->documents['source-2']['total_minor'] = 2100;
$this->documents['source-2']['reference_subtotal_minor'] = $this->documents['source-2']['reference_total_minor'] = 2100;
$this->components[2]['subtotal_minor'] = $this->components[2]['total_minor'] = 2100;
$this->components[2]['reference_subtotal_minor'] = $this->components[2]['reference_total_minor'] = 2100;
expect(fn () => $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->documents['source-2']['id'] = 4;
$this->documents['source-2']['source_version'] = 2;
$this->documents['source-2']['revision'] = hash('sha256', 'Explicit synthetic corrected customs document');
$operation = (string) Str::uuid();
$amended = $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, $operation);
expect($amended['additional_amount_minor'])->toBe(2100)->and($amended['phase'])->toBe('committed')
->and($amended['committed_delta_minor'])->toBe(100)->and($amended['consumed_delta_minor'])->toBe(0)
->and($this->engine->balance($this->budget)['committed_minor'])->toBe(2100)
->and(DB::table('budget_landed_entries')->limit(2)->get()->toArray())->toEqual($before);
expect($this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, $operation)['replayed'])->toBeTrue();
$this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'consume', (string) Str::uuid());
expect($this->engine->balance($this->budget)['consumed_minor'])->toBe(2100)
->and(DB::table('budget_landed_entries')->where('source_version', 1)->count())->toBe(2);
});
test('additional origins reduce funds available to the preserved legacy budget writer', function () {
$this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
expect(fn () => $this->engine->record($this->f['r']->id, $this->f['r']->cost_center_id, 'operating', 'reserve', 19000, 19000))->toThrow(BudgetFailure::class);
expect(DB::table('budget_entries')->count())->toBe(0)->and($this->engine->balance($this->budget)['available_minor'])->toBe(18000);
});
function addLandedContractSource(object $test, string $key = 'native:late', int $amount = 500): void
{
$money = ['subtotal_minor' => $amount, 'tax_minor' => 0, 'total_minor' => $amount,
'reference_subtotal_minor' => $amount, 'reference_tax_minor' => 0, 'reference_total_minor' => $amount];
$test->documents['late'] = ['kind' => 'other_charge', 'id' => 4, 'source_key' => $key, 'source_version' => 1,
'creditor_key' => 'synthetic-other-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Explicit synthetic additional document'), ...$money];
$test->components[] = ['component_key' => 'late', 'kind' => 'other', 'origin' => 'late', ...$money];
}
test('per-origin consumption and release preserve the consumed source and reject stale financial revisions', function () {
addLandedContractSource($this);
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid(), ['native:2'], 1);
$consume = (string) Str::uuid();
$partial = $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume, ['native:2'], 2);
expect($partial)->toMatchArray(['phase' => 'mixed', 'revision' => 3, 'reserved_minor' => 500, 'committed_minor' => 0, 'consumed_minor' => 2000]);
expect(fn () => $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'cancel', (string) Str::uuid(), ['native:late'], 2))->toThrow(BudgetFailure::class);
$released = $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'cancel', (string) Str::uuid(), ['native:late'], 3);
expect($released['reserved_delta_minor'])->toBe(-500)->and($released['consumed_minor'])->toBe(2000)
->and($this->engine->balance($this->budget))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 2000, 'available_minor' => 18000]);
expect(fn () => $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'cancel', (string) Str::uuid(), ['native:2'], 4))->toThrow(BudgetFailure::class);
expect($this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume, ['native:2'], 2)['replayed'])->toBeTrue();
expect(DB::table('budget_landed_commands')->count())->toBe(4);
});
test('a late documentary origin is reserved and consumed without repeating an earlier consumption', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['commit', 'consume'] as $kind) {
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], $kind, (string) Str::uuid());
}
addLandedContractSource($this);
$amended = $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, (string) Str::uuid(), 3);
expect($amended)->toMatchArray(['phase' => 'mixed', 'reserved_minor' => 500, 'committed_minor' => 0, 'consumed_minor' => 2000]);
$this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'commit', (string) Str::uuid());
$final = $this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'consume', (string) Str::uuid());
expect($final)->toMatchArray(['phase' => 'consumed', 'consumed_delta_minor' => 500, 'consumed_minor' => 2500])
->and($this->engine->balance($this->budget)['consumed_minor'])->toBe(2500)
->and(DB::table('budget_landed_entries')->where('source_key', 'native:2')->where('consumed_minor', '>', 0)->count())->toBe(1);
});
test('a corrected consumed source commits only its explicit increment and never reduces the consumed floor', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['commit', 'consume'] as $kind) {
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], $kind, (string) Str::uuid());
}
foreach (['subtotal_minor', 'total_minor', 'reference_subtotal_minor', 'reference_total_minor'] as $field) {
$this->documents['source-2'][$field] = $this->components[2][$field] = 2100;
}
$this->documents['source-2']['id'] = 4;
$this->documents['source-2']['source_version'] = 2;
$this->documents['source-2']['revision'] = hash('sha256', 'Explicit synthetic correction from 2000 to 2100');
$amended = $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, (string) Str::uuid());
expect($amended)->toMatchArray(['reserved_delta_minor' => 100, 'consumed_delta_minor' => 0, 'consumed_minor' => 2000]);
$this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'commit', (string) Str::uuid());
$final = $this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'consume', (string) Str::uuid());
expect($final)->toMatchArray(['consumed_delta_minor' => 100, 'consumed_minor' => 2100]);
$before = DB::table('budget_landed_commands')->count();
foreach (['subtotal_minor', 'total_minor', 'reference_subtotal_minor', 'reference_total_minor'] as $field) {
$this->documents['source-2'][$field] = $this->components[2][$field] = 1900;
}
$this->documents['source-2']['id'] = 5;
$this->documents['source-2']['source_version'] = 3;
$this->documents['source-2']['revision'] = hash('sha256', 'Synthetic lower correction needs separate consumed-cost reconciliation');
expect(fn () => $this->engine->amendLandedCosts($this->key, 4, $amended['plan_hash'], 6, $this->components, $this->documents, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_commands')->count())->toBe($before)->and($this->engine->balance($this->budget)['consumed_minor'])->toBe(2100);
});
@@ -161,8 +161,10 @@ test('cancellation releases only its unconsumed issued part and never replenishe
$control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid());
$key = (string) Str::uuid();
$input = [orderPartsAmount($source, 4000, 1)];
expect($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse()
->and($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue();
$this->actingAs($this->finance);
$cancel = app(CommonBudget::class)->for($this->finance);
expect($cancel->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse()
->and($cancel->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue();
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 0, 'available_minor' => 94000]);
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6001, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 2)], (string) Str::uuid());
@@ -181,8 +183,8 @@ test('consumed orders reject cancellation and over-consumption without changing
$next = orderPartsAmount($source, 5001, 2);
$next['allocations'][0]['order_key'] = $order;
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts(orderPartsInvoice($this, 5001)->id, [$next], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->actingAs($this->f['issuer']);
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->actingAs($this->finance);
expect(fn () => app(CommonBudget::class)->for($this->finance)->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]);
});
@@ -238,8 +240,8 @@ test('bad invoice allocation rolls back every origin and an unconsumed cancelled
$invoice = orderPartsInvoice($this, 25001);
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, $input, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_consumptions')->count())->toBe(0)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->actingAs($this->f['issuer']);
$control->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid());
$this->actingAs($this->finance);
app(CommonBudget::class)->for($this->finance)->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid());
$this->actingAs($this->finance);
$cancelled = orderPartsAmount($a, 100, 2);
$cancelled['allocations'][0]['order_key'] = $order;
@@ -0,0 +1,94 @@
<?php
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
beforeEach(function () {
if (! class_exists(BudgetLandedCostPlan::class)) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
});
/** Explicit synthetic values, not legal rates or real documents. */
function landedCostMoney(int $base, int $tax): array
{
return ['subtotal_minor' => $base, 'tax_minor' => $tax, 'total_minor' => $base + $tax,
'reference_subtotal_minor' => $base, 'reference_tax_minor' => $tax, 'reference_total_minor' => $base + $tax];
}
function landedCostExample(): array
{
$documents = $components = [];
foreach ([['goods', 'supplier_invoice', 10000, 1600], ['freight', 'carrier_invoice', 1000, 160], ['duty', 'customs_assessment', 2000, 0]] as $index => [$kind, $document, $base, $tax]) {
$key = 'source-'.($index + 1);
$documents[$key] = ['kind' => $document, 'id' => $index + 1, 'creditor_key' => 'creditor-'.($index + 1),
'source_key' => 'native:'.($index + 1), 'source_version' => 1,
'currency' => 'MZN', 'revision' => hash('sha256', $key), ...landedCostMoney($base, $tax)];
$components[] = ['component_key' => $kind, 'kind' => $kind, 'origin' => $key, ...landedCostMoney($base, $tax)];
}
return [$components, $documents];
}
test('landed cost reconciles each creditor document and both existing budget tax bases without financial effects', function () {
[$components, $documents] = landedCostExample();
$withTax = BudgetLandedCostPlan::reconcile($components, $documents, true);
$withoutTax = BudgetLandedCostPlan::reconcile($components, $documents, false);
expect($withTax['total_minor'])->toBe(14760)->and($withTax['subtotal_minor'])->toBe(13000)
->and($withTax['budget_amount_minor'])->toBe(14760)->and($withoutTax['budget_amount_minor'])->toBe(13000)
->and($withTax['documents']['source-1']['total_minor'])->toBe(11600)
->and($withTax['documents']['source-2']['total_minor'])->toBe(1160)
->and($withTax['documents']['source-3']['total_minor'])->toBe(2000)
->and($withTax['financial_effects'])->toBeFalse();
expect(BudgetLandedCostPlan::reconcile(array_reverse($components), array_reverse($documents, true), true)['fingerprint'])->toBe($withTax['fingerprint']);
});
test('missing tax and reference values remain unknown instead of becoming zero', function (string $field) {
[$components, $documents] = landedCostExample();
unset($components[2][$field]);
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
})->with(['tax_minor', 'reference_tax_minor', 'reference_total_minor']);
test('an invoice cannot be disguised as a second origin by changing its component role', function () {
[$components, $documents] = landedCostExample();
$documents['source-2']['id'] = $documents['source-1']['id'];
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
test('a balanced grand total cannot compensate amounts between different creditors', function () {
[$components, $documents] = landedCostExample();
$components[0] = [...$components[0], ...landedCostMoney(10001, 1600)];
$components[1] = [...$components[1], ...landedCostMoney(999, 160)];
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
test('multiple customs components reconcile once to one customs principal', function () {
[$components, $documents] = landedCostExample();
$components[2] = [...$components[2], ...landedCostMoney(1200, 0)];
$components[] = ['component_key' => 'ice', 'kind' => 'ice', 'origin' => 'source-3', ...landedCostMoney(800, 0)];
$plan = BudgetLandedCostPlan::reconcile($components, $documents, true);
expect($plan['total_minor'])->toBe(14760)->and($plan['documents'])->toHaveCount(3)->and($plan['components'])->toHaveCount(4);
});
test('customs impositions require a customs origin and MZN cannot acquire a fictitious conversion', function () {
[$components, $documents] = landedCostExample();
$documents['source-3']['kind'] = 'supplier_invoice';
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
[$components, $documents] = landedCostExample();
$documents['source-1']['reference_total_minor']++;
$documents['source-1']['reference_tax_minor']++;
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
test('aggregate values refuse overflow even when every document is individually representable', function () {
[$components, $documents] = landedCostExample();
foreach ($documents as $key => &$document) {
$document = [...$document, ...landedCostMoney(100000000000000, 0)];
}
unset($document);
foreach ($components as &$component) {
$component = [...$component, ...landedCostMoney(100000000000000, 0)];
}
unset($component);
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
+414
View File
@@ -0,0 +1,414 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\ConflictGuard;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportLandedCosts;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
if (! class_exists(BudgetLandedCostPlan::class)) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
config(['import-landed-costs.qa_enabled' => true]);
Storage::fake('local');
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($this->f['issuer']);
$this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic QA jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Explicit synthetic test regime',
]));
// Existing explicit organisation membership makes raw role fields insufficient.
$this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($this->finance, ['finance']);
supplyGrant($this->reviewer, ['finance']);
$this->actingAs($this->finance);
$this->budget = Budget::query()->create(['tenant_id' => $this->finance->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'amount_minor' => 100000, 'includes_tax' => true, 'created_by' => $this->finance->id,
'approved_by' => $this->reviewer->id, 'reason' => 'Synthetic documentary preparation only']);
$this->input = ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment', 'reference' => 'CUSTOMS-QA-01',
'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic customs authority', 'currency' => 'MZN',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null,
'reason' => 'Explicit synthetic document; not a legal rate.'];
$this->file = UploadedFile::fake()->createWithContent('customs.pdf', "%PDF-1.4\nSynthetic QA evidence only\n%%EOF");
});
function importCostSelection(object $test, SupplyRecord $document): array
{
return ['budget_id' => $test->budget->id, 'documents' => [['origin' => 'customs', 'kind' => 'customs_assessment', 'id' => $document->id]],
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000]]];
}
test('technical inspection detects private import evidence loss alteration and orphans without repairing facts', function () {
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$path = $document->snapshot['evidence']['path'];
$original = Storage::disk('local')->get($path);
$facts = DB::table('supply_records')->orderBy('id')->get()->toJson();
$this->assertThrows(fn () => app(ImportCostDocumentHealth::class)->inspect(), HttpException::class);
auth()->logout();
$health = app(ImportCostDocumentHealth::class);
expect($health->inspect()['ok'])->toBeTrue();
$changed = $original;
$changed[10] = $changed[10] === 'x' ? 'y' : 'x';
Storage::disk('local')->put($path, $changed);
expect($health->inspect()['altered'])->toBe(1);
Storage::disk('local')->delete($path);
expect($health->inspect()['missing'])->toBe(1);
Storage::disk('local')->put($path, 'Altered synthetic evidence');
Storage::disk('local')->put('import-costs/unreferenced.pdf', 'Synthetic orphan');
Storage::disk('local')->put('unrelated.txt', 'Not part of this inspection');
$result = $health->inspect();
expect($result['altered'])->toBe(1)->and($result['unreferenced'])->toBe(1)->and($result['files_checked'])->toBe(2)
->and($health->inspect(1)['complete'])->toBeFalse()
->and(json_encode($result))->not->toContain($path, $this->input['creditor_reference'], $document->record_key)
->and(DB::table('supply_records')->orderBy('id')->get()->toJson())->toBe($facts);
Storage::disk('local')->put($path, $original);
Storage::disk('local')->assertExists('import-costs/unreferenced.pdf');
});
test('cost to item references are frozen in reviewed preparations without stock valuation or financial effects', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$selection = [...importCostSelection($this, $document), 'item_references' => [
['component_key' => 'duty', 'purchase_order_item_ids' => [$this->f['line']->id]],
]];
$stock = DB::table('stock_movements')->get()->toJson();
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null,
'version' => 0, 'action' => 'save', 'reason' => 'Synthetic explicit item reference only', 'data' => $selection]);
$this->actingAs($this->reviewer);
$approved = $service->save($this->reviewer, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => 1, 'action' => 'approve', 'reason' => 'Independent synthetic item reference review', 'data' => []]);
expect($approved->snapshot['plan']['item_references']['duty'])->toBe([$this->f['line']->only(['id', 'description', 'unit', 'quantity'])])
->and($service->workspace($this->reviewer, $this->import)['orderItems']->pluck('id')->all())->toBe([$this->f['line']->id])
->and(DB::table('stock_movements')->get()->toJson())->toBe($stock)
->and(DB::table('budget_landed_commands')->count())->toBe(0);
$this->actingAs($this->finance);
$selection['item_references'] = [];
$next = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => 2, 'action' => 'save', 'reason' => 'Remove reference only in the next synthetic version', 'data' => $selection]);
expect($next->snapshot['plan']['item_references'])->toBe([])
->and($approved->fresh()->snapshot['plan']['item_references']['duty'][0]['id'])->toBe($this->f['line']->id);
});
test('cost item references reject foreign items repeated items and unknown components', function () {
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$foreign = receiptFixture();
$this->actingAs($this->finance);
foreach ([
['component_key' => 'duty', 'purchase_order_item_ids' => [$foreign['line']->id]],
['component_key' => 'duty', 'purchase_order_item_ids' => [$this->f['line']->id, $this->f['line']->id]],
['component_key' => 'missing', 'purchase_order_item_ids' => [$this->f['line']->id]],
] as $reference) {
expect(fn () => $service->preview($this->finance, $this->import, [...importCostSelection($this, $document), 'item_references' => [$reference]]))->toThrow(HttpException::class);
}
expect(SupplyRecord::query()->where('kind', 'import_cost_plan')->count())->toBe(0);
});
test('a customs document and reviewed preparation preserve one native source and create no invoice or budget effect', function () {
$service = app(ImportLandedCosts::class);
$before = DB::table('budget_entries')->get()->toJson();
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
expect($service->recordDocument($this->finance, $this->import, $this->input, $this->file)->id)->toBe($document->id);
Storage::disk('local')->assertExists($document->snapshot['evidence']['path']);
$selection = importCostSelection($this, $document);
$preview = $service->preview($this->finance, $this->import, $selection);
expect($preview['total_minor'])->toBe(2000)->and($preview['financial_effects'])->toBeFalse();
$save = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'reason' => 'Prepare the synthetic documentary cost', 'data' => $selection];
$draft = $service->save($this->finance, $this->import, $save);
expect($service->save($this->finance, $this->import, $save)->id)->toBe($draft->id);
$approve = ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1, 'action' => 'approve',
'reason' => 'Independent synthetic documentary review', 'data' => []];
expect(fn () => $service->save($this->finance, $this->import, $approve))->toThrow(HttpException::class);
$this->actingAs($this->reviewer);
$approved = $service->save($this->reviewer, $this->import, $approve);
expect($approved->state)->toBe('approved')->and($approved->version)->toBe(2)
->and($approved->snapshot['plan'])->toBe($preview)->and($draft->fresh()->state)->toBe('draft')
->and(Invoice::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before)
->and(DB::table('budget_consumptions')->count())->toBe(0);
});
test('changed content cannot reuse an operation or duplicate its documentary identity', function () {
$service = app(ImportLandedCosts::class);
$service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$changed = [...$this->input, 'subtotal_minor' => 2001, 'total_minor' => 2001];
expect(fn () => $service->recordDocument($this->finance, $this->import, $changed, $this->file))->toThrow(HttpException::class);
$changed['operation_key'] = (string) Str::uuid();
expect(fn () => $service->recordDocument($this->finance, $this->import, $changed, $this->file))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'import_cost_doc')->count())->toBe(1)
->and(Storage::disk('local')->allFiles())->toHaveCount(1);
});
test('frozen explicit foreign rates preserve original currency and never average customs costs', function () {
$input = [...$this->input, 'currency' => 'USD', 'subtotal_minor' => 3, 'tax_minor' => 1, 'total_minor' => 4,
'exchange_basis' => ['rate' => '63.125', 'quoted_on' => today()->toDateString(), 'source' => 'Explicit synthetic Finance rate']];
$document = app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $input, $this->file);
expect($document->data['currency'])->toBe('USD')->and($document->data['total_minor'])->toBe(4)
->and($document->snapshot['reference_amounts'])->toBe(['subtotal_minor' => 189, 'tax_minor' => 63, 'total_minor' => 252]);
$changed = [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $document->record_key, 'version' => 1,
'exchange_basis' => [...$input['exchange_basis'], 'rate' => '64.00']];
expect(fn () => app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $changed, $this->file))->toThrow(HttpException::class);
expect($document->fresh()->data['exchange_basis']['rate'])->toBe('63.125');
});
test('changed evidence blocks approval while an independent return remains possible', function () {
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Synthetic recoverable preparation', 'data' => importCostSelection($this, $document)]);
Storage::disk('local')->put($document->snapshot['evidence']['path'], 'Altered synthetic bytes');
$this->actingAs($this->reviewer);
$decision = ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Independent review of changed evidence', 'data' => []];
expect(fn () => $service->save($this->reviewer, $this->import, $decision))->toThrow(HttpException::class);
$decision['action'] = 'return';
expect($service->save($this->reviewer, $this->import, $decision)->state)->toBe('returned');
});
test('a stale import and disabled operational runtime cannot write documentary costs', function () {
$service = app(ImportLandedCosts::class);
$this->actingAs($this->f['issuer']);
app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic dispatch evidence', 'event_date' => today()->toDateString()], 'transit', $this->import));
$this->actingAs($this->finance);
expect(fn () => $service->recordDocument($this->finance, $this->import, $this->input, $this->file))->toThrow(HttpException::class);
config(['import-landed-costs.qa_enabled' => false]);
expect($service->ready())->toBeFalse();
expect(fn () => $service->recordDocument($this->finance, $this->import, $this->input, $this->file))->toThrow(HttpException::class);
expect(Storage::disk('local')->allFiles())->toBe([]);
});
test('withdrawn Finance authority and foreign company sources fail before a document is stored', function () {
$service = app(ImportLandedCosts::class);
$other = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
// This account has no active Finance membership in this organisation.
$this->actingAs($other);
expect(fn () => $service->recordDocument($other, $this->import, $this->input, $this->file))->toThrow(HttpException::class);
$this->actingAs($this->finance);
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($foreign['issuer']);
$foreignImport = app(SupplyPlanning::class)->save($foreign['issuer'], 'import', supplyInput([
'purchase_order_id' => $foreign['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Other synthetic entity',
'origin_country' => 'Other A', 'dispatch_country' => 'Other B', 'regime' => 'Other synthetic regime',
]));
$this->actingAs($this->finance);
expect(fn () => $service->recordDocument($this->finance, $foreignImport, $this->input, $this->file))->toThrow(ModelNotFoundException::class);
expect(Storage::disk('local')->allFiles())->toBe([]);
});
test('failure after private storage rolls back the native source and removes only its new blob', function () {
$this->mock(RequisitionWorkflow::class, function ($mock) {
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Synthetic failure after document storage'));
});
expect(fn () => app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $this->input, $this->file))->toThrow(RuntimeException::class);
expect(SupplyRecord::query()->where('kind', 'import_cost_doc')->count())->toBe(0)
->and(Storage::disk('local')->allFiles())->toBe([]);
});
test('the authenticated multipart route stores exact cents and the workspace never exposes private storage paths', function () {
$this->withoutVite(); // HTTP contract only; the new page is compiled separately in a private candidate.
$url = '/compras/importacoes/'.$this->import->id.'/custos';
$this->post($url.'/documentos', [...$this->input, 'subtotal_minor' => '2000', 'tax_minor' => '0', 'total_minor' => '2000', 'file' => $this->file])->assertRedirect($url);
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->sole();
expect($document->data['total_minor'])->toBe(2000);
$page = $this->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === 'supply/import-costs' && $page['encryptHistory'] === true);
expect($page->headers->get('Cache-Control'))->toContain('no-store');
expect($page->getContent())->not->toContain($document->snapshot['evidence']['path']);
$this->get($url.'/documentos/'.$document->id)->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
$this->actingAs($this->f['issuer'])->get($url)->assertForbidden();
});
test('a native validated goods invoice keeps its original principal and budget consumption when included in landed cost', function () {
$this->actingAs($this->f['issuer']);
$event = ['evidence' => 'Explicit synthetic logistics document', 'event_date' => today()->toDateString()];
$transit = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput($event, 'transit', $this->import));
$arrived = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput($event, 'arrive', $transit));
supplyGrant($this->f['receiver'], ['warehouse', 'import_customs']);
$this->actingAs($this->f['receiver']);
$this->import = app(SupplyPlanning::class)->save($this->f['receiver'], 'import', supplyInput($event, 'release', $arrived));
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->actingAs($this->finance);
DB::transaction(function () {
app(ConflictGuard::class)->lockCompany($this->finance);
app(BudgetWorkflow::class)->record($this->finance, $this->f['r'], 'reserve', 10000, 10000);
app(BudgetWorkflow::class)->record($this->finance, $this->f['r'], 'commit', 10000, 10000);
});
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $this->f['order'], [
'number' => 'NATIVE-IMPORT-GOODS-QA', 'issued_on' => today()->toDateString(), 'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00',
'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '1.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']],
]);
$this->actingAs($this->reviewer);
app(InvoiceWorkflow::class)->validate($this->reviewer, $invoice);
$before = DB::table('budget_consumptions')->get()->toJson();
$this->actingAs($this->finance);
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$selection = importCostSelection($this, $document);
$selection['documents'][] = ['origin' => 'goods', 'kind' => 'supplier_invoice', 'id' => $invoice->id];
$selection['components'][] = ['component_key' => 'goods', 'kind' => 'goods', 'origin' => 'goods',
'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000,
'reference_subtotal_minor' => 10000, 'reference_tax_minor' => 0, 'reference_total_minor' => 10000];
$plan = $service->preview($this->finance, $this->import, $selection);
expect($plan['total_minor'])->toBe(12000)->and($plan['documents']['goods']['total_minor'])->toBe(10000)
->and($plan['document_details']['goods']['financial_authority'])->toBe('native_invoice')
->and(Invoice::query()->count())->toBe(1)->and($invoice->fresh()->total_minor)->toBe(10000)
->and(DB::table('budget_consumptions')->get()->toJson())->toBe($before);
});
test('a documentary correction preserves both original bytes and values and invalidates an older preparation', function () {
$service = app(ImportLandedCosts::class);
$first = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$input = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1,
'subtotal_minor' => 2100, 'total_minor' => 2100, 'reason' => 'Explicit correction in a new documentary version'];
$second = $service->recordDocument($this->finance, $this->import, $input, $this->file);
expect($second->version)->toBe(2)->and($second->record_key)->toBe($first->record_key)->and($first->fresh()->data['total_minor'])->toBe(2000)
->and($second->data['total_minor'])->toBe(2100)->and($second->snapshot['supersedes'])->toBe($first->id)
->and(Storage::disk('local')->allFiles())->toHaveCount(2);
expect($service->evidence($this->finance, $this->import, $first->id)->id)->toBe($first->id);
expect(fn () => $service->preview($this->finance, $this->import, importCostSelection($this, $first)))->toThrow(HttpException::class);
expect(fn () => $service->recordDocument($this->finance, $this->import, [...$input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
});
test('the native independently reviewed cost plan reserves commits and consumes the additional origin once', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Synthetic additional-origin budget preparation', 'data' => importCostSelection($this, $document)]);
$operation = ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0, 'reason' => 'Reserve the independently reviewed synthetic customs cost'];
expect(fn () => $service->financial($this->finance, $this->import, $draft, $operation))->toThrow(HttpException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(0);
$this->actingAs($this->reviewer);
$approved = $service->save($this->reviewer, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Independent native review before additional budget effects', 'data' => []]);
$this->actingAs($this->finance);
$receipt = $service->financial($this->finance, $this->import, $approved, $operation);
expect($receipt->state)->toBe('reserved')->and($receipt->snapshot['common_result']['additional_amount_minor'])->toBe(2000);
expect($service->financial($this->finance, $this->import, $approved, $operation)->id)->toBe($receipt->id);
foreach (['commit', 'consume'] as $index => $action) {
$input = ['operation_key' => (string) Str::uuid(), 'action' => $action, 'financial_revision' => $index + 1, 'reason' => 'Explicit synthetic additional-origin '.$action];
$this->post('/compras/importacoes/'.$this->import->id.'/custos/'.$approved->id.'/orcamento', $input)->assertRedirect();
}
$state = $service->workspace($this->finance, $this->import)['financialState'];
expect($state['phase'])->toBe('consumed')->and($state['additional_amount_minor'])->toBe(2000)
->and(DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0)
->and(DB::table('budget_landed_entries')->sum('committed_minor'))->toBe(0)
->and((string) DB::table('budget_landed_entries')->sum('consumed_minor'))->toBe('2000')
->and(SupplyRecord::query()->where('kind', 'import_cost_event')->count())->toBe(3)
->and(Invoice::query()->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
/** Native documentary preparation; synthetic evidence is deliberately not a statutory assessment. */
function approvedImportCostPreparation(object $test): array
{
$test->actingAs($test->finance);
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($test->finance, $test->import, $test->input, $test->file);
$draft = $service->save($test->finance, $test->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Explicit synthetic documentary cost preparation', 'data' => importCostSelection($test, $document)]);
$test->actingAs($test->reviewer);
$approved = $service->save($test->reviewer, $test->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Independent review of the synthetic cost sources', 'data' => []]);
$test->actingAs($test->finance);
return [$document, $approved];
}
test('logistics progression does not revoke a reviewed cost preparation or require another financial approval', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
[, $approved] = approvedImportCostPreparation($this);
$service = app(ImportLandedCosts::class);
$service->financial($this->finance, $this->import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0,
'reason' => 'Reserve the reviewed synthetic documentary cost']);
$this->actingAs($this->f['issuer']);
$transit = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic dispatch record', 'event_date' => today()->toDateString()], 'transit', $this->import));
$this->actingAs($this->finance);
$event = $service->financial($this->finance, $transit, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'commit', 'financial_revision' => 1,
'reason' => 'The logistics event did not change the approved financial sources']);
expect($event->state)->toBe('committed')->and(SupplyRecord::query()->where('kind', 'import_cost_plan')->count())->toBe(2)
->and($service->workspace($this->finance, $transit)['importRecord']['context_changed'])->toBeFalse();
expect(fn () => $service->financial($this->finance, $transit, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'consume', 'financial_revision' => 1,
'reason' => 'A stale financial action must retain its preparation']))->toThrow(HttpException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(2);
});
test('a failed native financial receipt rolls back the common journal and its audit together', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
[, $approved] = approvedImportCostPreparation($this);
if (DB::getDriverName() === 'pgsql') {
DB::unprepared("CREATE FUNCTION reject_synthetic_import_cost_receipt() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.kind = 'import_cost_event' THEN RAISE EXCEPTION 'Synthetic receipt failure'; END IF; RETURN NEW; END $$;
CREATE TRIGGER reject_synthetic_import_cost_receipt BEFORE INSERT ON supply_records FOR EACH ROW EXECUTE FUNCTION reject_synthetic_import_cost_receipt();");
} else {
DB::unprepared("CREATE TRIGGER reject_synthetic_import_cost_receipt BEFORE INSERT ON supply_records WHEN NEW.kind = 'import_cost_event' BEGIN SELECT RAISE(ABORT, 'Synthetic receipt failure'); END;");
}
expect(fn () => app(ImportLandedCosts::class)->financial($this->finance, $this->import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve',
'financial_revision' => 0, 'reason' => 'Synthetic failure after the common financial command']))->toThrow(QueryException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0)
->and(DB::table('audit_logs')->where('action', 'budget.landed_reserve')->count())->toBe(0)
->and(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('state', 'approved')->count())->toBe(1);
});
test('an import with retained cost evidence cannot be silently moved to another order', function () {
app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $this->input, $this->file);
// A separate, internally consistent already-issued synthetic target; no claim of a new approval execution.
$request = $this->f['r']->replicate();
$request->number = 'REQ-TARGET-'.Str::random(8);
$request->save();
$requested = $this->f['r']->items()->sole()->replicate();
$requested->requisition_id = $request->id;
$requested->save();
$oldAward = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id);
$quote = Quotation::query()->findOrFail($oldAward->quotation_id)->replicate();
$quote->requisition_id = $request->id;
$quote->reference = 'SYNTHETIC-TARGET';
$quote->save();
$quote->items()->create(['tenant_id' => $request->tenant_id, 'requisition_item_id' => $requested->id,
...$this->f['line']->only(['description', 'quantity', 'unit', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor'])]);
$award = $oldAward->replicate();
$award->requisition_id = $request->id;
$award->quotation_id = $quote->id;
$award->save();
$order = $this->f['order']->replicate();
$order->requisition_id = $request->id;
$order->purchase_award_id = $award->id;
$order->number = 'OC-TARGET-'.Str::random(8);
$order->save();
$line = $this->f['line']->replicate();
$line->purchase_order_id = $order->id;
$line->requisition_item_id = $requested->id;
$line->save();
$this->actingAs($this->f['issuer']);
expect(fn () => app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
...$this->import->data, 'purchase_order_id' => $order->id], 'save', $this->import)))->toThrow(ValidationException::class);
expect(SupplyRecord::query()->where('kind', 'import')->count())->toBe(1)
->and($this->import->fresh()->purchase_order_id)->toBe($this->f['order']->id);
});
+101
View File
@@ -0,0 +1,101 @@
<?php
use App\Models\SupplyRecord;
use App\Services\ImportTariffCodes;
use Illuminate\Database\Eloquent\ModelNotFoundException;
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/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['import-tariffs.qa_enabled' => true]);
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->lineId = $this->f['r']->items()->sole()->id;
});
function tariffInput(string $action, array $data = []): array
{
return [...['operation_key' => (string) Str::uuid(), 'action' => $action, 'version' => 0,
'reason' => 'Synthetic classification; no legal rate or customs declaration.'], ...$data];
}
test('native tariff master reuse and buyer deviation preserve proposals versions approvals and financial facts', function () {
supplyGrant($this->f['issuer'], ['procurement', 'requester']);
$service = app(ImportTariffCodes::class);
$order = $this->f['order']->fresh()->getAttributes();
$stock = $this->f['stock']->fresh()->getAttributes();
$master = $service->save($this->f['issuer'], $this->f['r'], tariffInput('master', ['stock_item_id' => $this->f['stock']->id,
'code' => '1234.56', 'source_reference' => 'Synthetic source v1; not a legal classification']));
$proposalInput = tariffInput('propose', ['requisition_item_id' => $this->lineId, 'master_id' => $master->id,
'code' => $master->data['code'], 'source_reference' => $master->data['source_reference']]);
$proposal = $service->save($this->f['issuer'], $this->f['r'], $proposalInput);
expect($service->save($this->f['issuer'], $this->f['r'], $proposalInput)->id)->toBe($proposal->id);
$confirmation = $service->save($this->f['issuer'], $this->f['r'], tariffInput('confirm', ['version' => 1,
'requisition_item_id' => $this->lineId, 'code' => '1234.57', 'source_reference' => 'Synthetic buyer source v2',
'reason' => 'Synthetic buyer explains why the proposed code is changed.']));
expect($confirmation->state)->toBe('confirmed')->and($confirmation->data['deviation'])->toBeTrue()
->and($confirmation->data['proposed_code'])->toBe('1234.56')->and($confirmation->data['confirmed_code'])->toBe('1234.57')
->and($confirmation->snapshot['master']['version'])->toBe(1)->and($confirmation->snapshot['calculations_activated'])->toBeFalse()
->and($proposal->fresh()->state)->toBe('proposed')->and($this->f['order']->fresh()->getAttributes())->toBe($order)
->and($this->f['stock']->fresh()->getAttributes())->toBe($stock)->and(DB::table('budget_consumptions')->count())->toBe(0);
$service->save($this->f['issuer'], $this->f['r'], tariffInput('master', ['version' => 1, 'stock_item_id' => $this->f['stock']->id,
'code' => '1234.58', 'source_reference' => 'Synthetic later material source']));
expect($confirmation->fresh()->data['confirmed_code'])->toBe('1234.57');
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$proposalInput, 'operation_key' => (string) Str::uuid(), 'version' => 2]))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'import_tariff')->count())->toBe(2);
});
test('unknown proposed code remains unknown and a requester cannot confirm or edit the material master', function () {
supplyGrant($this->f['issuer'], ['requester']);
$service = app(ImportTariffCodes::class);
$proposal = $service->save($this->f['issuer'], $this->f['r'], tariffInput('propose', ['requisition_item_id' => $this->lineId]));
expect($proposal->data['proposed_code'])->toBeNull()->and($proposal->state)->toBe('proposed');
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], tariffInput('confirm', ['version' => 1,
'requisition_item_id' => $this->lineId, 'code' => '1234', 'source_reference' => 'Synthetic source'])))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], tariffInput('master', ['stock_item_id' => $this->f['stock']->id,
'code' => '1234', 'source_reference' => 'Synthetic source'])))->toThrow(HttpException::class);
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['canConfirm'])->toBeFalse()->and($workspace['masters']->total())->toBe(0)->and($workspace['stockItems']->total())->toBe(0);
});
test('tariff classification rejects stale versions reused operations foreign items and a disabled capability', function () {
supplyGrant($this->f['issuer'], ['procurement']);
$service = app(ImportTariffCodes::class);
$input = tariffInput('propose', ['requisition_item_id' => $this->lineId, 'code' => '1234', 'source_reference' => 'Synthetic source']);
$service->save($this->f['issuer'], $this->f['r'], $input);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'code' => '5678']))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$foreign = receiptFixture();
$foreignItemId = $foreign['r']->items()->sole()->id;
$this->actingAs($this->f['issuer']);
expect(fn () => $service->workspace($this->f['issuer'], $foreign['r']))->toThrow(ModelNotFoundException::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], tariffInput('propose', ['requisition_item_id' => $foreignItemId])))->toThrow(ModelNotFoundException::class);
config(['import-tariffs.qa_enabled' => false]);
expect(fn () => $service->workspace($this->f['issuer'], $this->f['r']))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'import_tariff')->count())->toBe(1);
});
test('authenticated classification forms use private encrypted history and paginated native sources', function () {
supplyGrant($this->f['issuer'], ['procurement']);
$url = '/requisicoes/'.$this->f['r']->id.'/classificacao-pautal';
$this->post($url, tariffInput('master', ['stock_item_id' => $this->f['stock']->id, 'code' => '1234.56', 'source_reference' => 'Synthetic source']))->assertRedirect();
$this->get($url.'?search=1234')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->component('supply/import-tariffs')->where('canConfirm', true)
->where('masters.total', 1)->where('masters.data.0.data.code', '1234.56')->where('history.total', 0));
$this->getJson($url.'?masters_page=0')->assertUnprocessable();
$this->postJson($url, tariffInput('master', ['stock_item_id' => $this->f['stock']->id]))->assertUnprocessable()->assertJsonValidationErrors(['code', 'source_reference']);
});
test('classification revalidates current company permissions rather than trusting the initial buyer identity', function () {
supplyGrant($this->f['issuer'], ['procurement']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
expect(fn () => app(ImportTariffCodes::class)->save($this->f['issuer'], $this->f['r'], tariffInput('master', [
'stock_item_id' => $this->f['stock']->id, 'code' => '1234', 'source_reference' => 'Synthetic source'])))->toThrow(HttpException::class);
expect(SupplyRecord::query()->whereIn('kind', ['stock_tariff', 'import_tariff'])->count())->toBe(0);
});
+1
View File
@@ -42,6 +42,7 @@ test('operational health integrates native inspections without changing facts or
expect($result['schema_version'])->toBe(1)->and($result['ok'])->toBeTrue()->and($result['complete'])->toBeTrue()
->and($result['checks']['replenishment']['result']['work']['total'])->toBe(0)
->and($result['checks']['receipt_documents']['result']['documents_checked'])->toBe(0);
expect($result['checks']['import_cost_documents']['status'])->toBe('passed');
expect($output)->not->toContain($this->temporaryStorage, 'tenant_id', 'password');
expect(File::get(storage_path('framework/replenishment-command-status.json')))->toBe($heartbeat);
foreach ($before as $table => $rows) {
+406 -26
View File
@@ -13,9 +13,11 @@ use App\Models\Department;
use App\Models\Equipment;
use App\Models\EquipmentSparePart;
use App\Models\InvestmentPolicy;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\PurchaseControlPolicy;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\PurchaseRevision;
use App\Models\QualificationSet;
use App\Models\Quotation;
@@ -35,9 +37,12 @@ use App\Services\ConflictGuard;
use App\Services\DocumentaryQualificationWorkflow;
use App\Services\EquipmentWorkflow;
use App\Services\FormalAdmission;
use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
@@ -46,11 +51,13 @@ use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow;
use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Brick\Math\BigDecimal;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -63,6 +70,79 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
config(['import-tariffs.qa_enabled' => true]);
$tariffs = app(ImportTariffCodes::class);
$this->actingAs($this->buyer);
$proposal = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic documentary classification only',
'reason' => 'Proposed synthetic classification without a legal rate.']);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer);
$before = DB::table('budget_entries')->get()->toJson();
expect(fn () => app(PurchaseWorkflow::class)->issue($this->buyer, $award))->toThrow(HttpException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before);
$confirmed = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => $proposal->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic buyer source', 'reason' => 'Buyer confirms the synthetic documentary code.']);
config(['import-tariffs.qa_enabled' => false]);
expect(fn () => app(PurchaseWorkflow::class)->issue($this->buyer, $award))->toThrow(HttpException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before);
config(['import-tariffs.qa_enabled' => true]);
$order = app(PurchaseWorkflow::class)->issue($this->buyer, $award);
expect($order->snapshot['import_tariffs'][$this->item->id]['record_id'])->toBe($confirmed->id);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56')->assertSee('Synthetic buyer source');
$tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => $confirmed->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.57', 'source_reference' => 'Later synthetic proposal', 'reason' => 'Later proposal must preserve the earlier issued classification.']);
expect($order->fresh()->snapshot['import_tariffs'][$this->item->id]['data']['confirmed_code'])->toBe('1234.56');
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56')->assertDontSee('1234.57');
});
test('a partial native order retains its confirmed imported item classification before committing funds', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
}
config(['import-tariffs.qa_enabled' => true]);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->actingAs($this->buyer);
$tariffs = app(ImportTariffCodes::class);
$proposal = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic partial order source', 'reason' => 'Synthetic imported item proposal for a partial order.']);
expect(fn () => app(OrderPartsWorkflow::class)->issue($this->buyer, $input))->toThrow(HttpException::class);
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(PurchaseOrder::query()->count())->toBe(0);
$confirmed = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => $proposal->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic confirmed partial order source', 'reason' => 'Buyer confirms the synthetic partial order classification.']);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->snapshot['import_tariffs'][$this->item->id]['record_id'])->toBe($confirmed->id)
->and($order->total_minor)->toBe(4000)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56');
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
supplyGrant($this->buyer, ['procurement', 'import_prepare']);
supplyGrant($receiver, ['warehouse', 'import_customs']);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'TARIFF-QA', 'name' => 'Synthetic tariff receipt warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'TARIFF-QA', 'name' => 'Synthetic classified material', 'unit' => 'un']);
$payload = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'TARIFF-RECEIPT-QA', 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->sole()->id,
'received_quantity' => '0.400', 'accepted_quantity' => '0.400', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
expect(fn () => app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload))->toThrow(ValidationException::class);
expect(StockMovement::query()->count())->toBe(0);
$this->actingAs($this->buyer);
$planning = app(SupplyPlanning::class);
$import = $planning->save($this->buyer, 'import', supplyInput(['purchase_order_id' => $order->id, 'purpose' => 'internal',
'jurisdiction' => 'Synthetic jurisdiction', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic customs regime']));
$event = ['evidence' => 'Synthetic customs evidence only', 'event_date' => today()->toDateString()];
$transit = $planning->save($this->buyer, 'import', supplyInput($event, 'transit', $import));
$arrived = $planning->save($this->buyer, 'import', supplyInput($event, 'arrive', $transit));
$this->actingAs($receiver);
expect(fn () => app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload))->toThrow(ValidationException::class);
$planning->save($receiver, 'import', supplyInput($event, 'release', $arrived));
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload)->id)->toBe($receipt->id)
->and(StockMovement::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(400);
});
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.');
@@ -640,7 +720,7 @@ test('catalogue origin survives order issue and automatically identifies receive
$this->get('/ordens/'.$order->id.'/recepcoes')->assertInertia(fn (Assert $p) => $p->where('progress.lines.0.stock_item_id', $stock->id));
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertOk()->assertJsonPath('created', false);
expect(StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
expect((string) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe('1000');
});
function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy
@@ -1391,31 +1471,7 @@ test('optional partial-order preparation consolidates two independently approved
$first = selectPurchaseAward($this);
approvePurchaseAward($this, $first);
$this->actingAs($this->buyer);
$secondRequest = $this->r->fresh()->replicate();
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
$secondRequest->save();
$line = $this->item->replicate();
$line->requisition_id = $secondRequest->id;
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
$line->save();
foreach ($this->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->requisition_id = $secondRequest->id;
$copy->save();
}
$quotes = [];
foreach ($this->suppliers as $index => $supplier) {
$this->actingAs($this->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
$quotes[] = $quote;
foreach ([$this->buyer, $this->finance] as $evaluator) {
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
}
}
[$secondRequest, $quotes] = secondNativeOrderPartsOrigin($this);
$this->actingAs($this->buyer);
$second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]);
approvePurchaseAward($this, $second);
@@ -1432,3 +1488,327 @@ test('optional partial-order preparation consolidates two independently approved
->and(array_column($result['sources'], 'exchange_basis'))->toBe([null, null])
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
});
/** Native adjudication/approval fixture; requisition approval itself is the existing synthetic source. */
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null): PurchaseAward
{
$request ??= $test->r;
$quote ??= $test->quotes[0];
if (! DB::getSchemaBuilder()->hasTable('budget_order_commands')) {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
}
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$test->actingAs($test->finance);
if (! DB::table('budgets')->where('tenant_id', $request->tenant_id)->where('cost_center_id', $request->cost_center_id)->exists()) {
$id = app(CommonBudget::class)->for($test->finance)->create(['cost_center_id' => $request->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotacao sintetica de ordens parciais.']);
$test->actingAs($test->admin);
app(CommonBudget::class)->for($test->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = $quote->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id,
'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
$request->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($request, $host->requestLines($request)), 'prepared_by' => $test->owner->id,
'reason' => 'Explicit synthetic source allocation.']])->save();
$test->actingAs($test->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($test->finance, $request, 'reserve', $request->total_minor, $request->subtotal_minor));
$test->actingAs($test->buyer);
$data = [...$test->selection, 'quotation_id' => $quote->id, 'reason' => 'Explicit native award distribution.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'subtotal' => (string) BigDecimal::of($row['subtotal_minor'])->dividedBy(100, 2),
'total' => (string) BigDecimal::of($row['total_minor'])->dividedBy(100, 2)], $allocations)];
$award = app(PurchaseWorkflow::class)->select($test->buyer, $request, $data);
approvePurchaseAward($test, $award);
$test->actingAs($test->buyer);
return $award;
}
function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quantity, int $version): array
{
$quote = Quotation::query()->whereKey($award->quotation_id)->firstOrFail();
$input = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $quote->items()->sole()->id, 'quantity' => $quantity]]]]];
$prepared = app(OrderPartsPreparation::class)->prepare($test->buyer, $input);
$distribution = DB::table('budget_distributions')->where('requisition_id', $award->requisition_id)->first();
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$line = $prepared['sources'][0]['items'][0];
return [...$input, 'order_key' => (string) Str::uuid(), 'operation_key' => (string) Str::uuid(), 'fingerprint' => $prepared['fingerprint'],
'budget_sources' => [['origin' => $award->requisition_id, 'version' => $version, 'plan_hash' => $snapshot['plan_hash'],
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
(new PurchaseOrder)->fill(['number' => 'Unpersisted legacy metadata warmup']);
(new PurchaseOrderItem)->fill(['description' => 'Unpersisted legacy metadata warmup']);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$workflow = app(OrderPartsWorkflow::class);
$first = $workflow->issue($this->buyer, $input);
expect($first->total_minor)->toBe(4000)->and($first->items()->sole()->quantity)->toBe('0.400')
->and($first->items()->sole()->quantity_offset_milli)->toBe(0)
->and($first->hasCompleteDocumentSnapshot())->toBeTrue()
->and($workflow->issue($this->buyer, $input)->id)->toBe($first->id)
->and(DB::table('purchase_order_sources')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
$changed = $input;
$changed['sources'][0]['items'][0]['quantity'] = '0.401';
expect(fn () => $workflow->issue($this->buyer, $changed))->toThrow(HttpException::class);
$second = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
expect($second->total_minor)->toBe(6000)->and($second->items()->sole()->quantity_offset_milli)->toBe(400)
->and(PurchaseOrder::query()->count())->toBe(2)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(10000)
->and($this->r->fresh()->status)->toBe('approved');
expect(fn () => nativeOrderPartsInput($this, $award, '0.001', 2))->toThrow(ValidationException::class);
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['candidates']['data'] === []);
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertConflict();
});
test('native partial-order issuance rolls back the document and all financial effects when its audit fails', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
expect(fn () => app(OrderPartsWorkflow::class)->issue($this->buyer, $input))->toThrow(RuntimeException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('purchase_order_sources')->count())->toBe(0)
->and(DB::table('budget_order_commands')->count())->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(10000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0);
});
test('native partial-order receipts and independent invoice validation consume exact commitments once with one stock movement per receipt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$workflow = app(OrderPartsWorkflow::class);
$first = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$second = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$validator = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'PARTS-QA', 'name' => 'Armazem de ensaio']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'PARTS-QA', 'name' => 'Material de ensaio', 'unit' => 'un']);
foreach ([[$first, '0.400', '40.00'], [$second, '0.600', '60.00']] as [$order, $quantity, $amount]) {
$this->actingAs($receiver);
$line = $order->items()->sole();
$payload = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-PART-'.$order->id, 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => $quantity,
'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload)->id)->toBe($receipt->id)
->and($receipt->items()->sole()->snapshot['source_line']['requisition_item_id'])->toBe($this->item->id);
$this->actingAs($this->finance);
$allocation = $order->snapshot['order_parts']['budget_sources'][0]['allocations'][0];
$data = ['number' => 'FT-PART-'.$order->id, 'issued_on' => today()->toDateString(), 'subtotal' => $amount, 'tax' => '0.00', 'total' => $amount,
'items' => [['purchase_order_item_id' => $line->id, 'quantity' => $quantity]], 'reason' => 'Explicit native Finance allocation.',
'order_part_allocations' => [['origin' => $this->r->id, 'allocation_key' => $allocation['allocation_key'], 'subtotal' => $amount, 'total' => $amount]]];
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, $data);
expect(fn () => app(InvoiceWorkflow::class)->validate($this->finance, $invoice))->toThrow(HttpException::class);
$this->actingAs($validator);
app(InvoiceWorkflow::class)->validate($validator, $invoice);
app(InvoiceWorkflow::class)->validate($validator, $invoice->fresh());
expect($invoice->fresh()->status)->toBe('validated');
}
expect(Invoice::query()->count())->toBe(2)
->and(DB::table('budget_order_consumptions')->count())->toBe(2)
->and(StockMovement::query()->count())->toBe(2)
->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(1000)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(10000)
->and(DB::table('budget_distribution_consumptions')->count())->toBe(0)
->and(DB::table('budget_consumptions')->count())->toBe(0);
});
function secondNativeOrderPartsOrigin(object $test): array
{
$secondRequest = $test->r->fresh()->replicate();
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
if (DB::getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
$secondRequest->budget_distribution_preparation = null;
}
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
$secondRequest->save();
$line = $test->item->replicate();
$line->requisition_id = $secondRequest->id;
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
$line->save();
foreach ($test->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->requisition_id = $secondRequest->id;
$copy->save();
}
$quotes = [];
foreach ($test->suppliers as $index => $supplier) {
$test->actingAs($test->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
$quotes[] = $quote;
foreach ([$test->buyer, $test->finance] as $evaluator) {
$test->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
}
}
return [$secondRequest, $quotes];
}
test('native consolidated order retains both origins and consumes a single invoice without duplicate stock or debt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$first = nativeOrderPartsAward($this);
[$request, $quotes] = secondNativeOrderPartsOrigin($this);
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
$input = [...$a, 'sources' => [...$a['sources'], ...$b['sources']], 'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]];
$input['fingerprint'] = app(OrderPartsPreparation::class)->prepare($this->buyer, $input)['fingerprint'];
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->total_minor)->toBe(30000)->and($order->items()->count())->toBe(2)
->and(DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->count())->toBe(2)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->whereKey($order->id)->exists())->toBeTrue();
$this->withoutVite();
$this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn (array $page) => count($page['props']['orderPartsSources']) === 2);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee($this->r->number)->assertSee($request->number)
->assertSee('Origens desta ordem')->assertSee('Controlo orçamental confirmado para as parcelas emitidas.');
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CONSOL-QA', 'name' => 'Armazem de ensaio']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CONSOL-QA', 'name' => 'Material de ensaio', 'unit' => 'un']);
$lines = $order->items()->orderBy('id')->get();
$receiptData = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-CONSOL-QA', 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000',
'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id])->all()];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptData);
expect($receipt->items()->count())->toBe(2);
$this->actingAs($this->finance);
$data = ['number' => 'FT-CONSOL-QA', 'issued_on' => today()->toDateString(), 'subtotal' => '150.00', 'tax' => '0.00', 'total' => '150.00',
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '0.500'])->all(),
'reason' => 'Explicit allocations for both approved origins.', 'order_part_allocations' => [
['origin' => $first->requisition_id, 'allocation_key' => $a['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '50.00', 'total' => '50.00'],
['origin' => $second->requisition_id, 'allocation_key' => $b['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '100.00', 'total' => '100.00']]];
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, $data);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
expect(Invoice::query()->count())->toBe(1)
->and($invoice->fresh()->total_minor)->toBe(15000)->and($invoice->fresh()->status)->toBe('validated')
->and(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(2)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(15000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(15000)
->and(StockMovement::query()->count())->toBe(2)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(2000);
$this->actingAs($this->owner);
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
$request->forceFill(['requester_id' => $this->head->id])->save();
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
});
test('native partial-order cancellation uses independent Finance and preserves the unissued reservation and requisition', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$issue = app(OrderPartsWorkflow::class);
$order = $issue->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
config(['order_cancellation.enabled' => true]);
$policyFlow = app(OrderCancellationPolicyWorkflow::class);
$admins = [$this->admin, User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]),
User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin])];
$this->actingAs($admins[0]);
$policy = $policyFlow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'reason' => 'Synthetic existing cancellation policy.']);
foreach (array_slice($admins, 1) as $admin) {
$this->actingAs($admin);
$policyFlow->review($admin, $policy, 'approved', 'Independent synthetic policy review.');
}
$this->actingAs($this->buyer);
$flow = app(OrderCancellationWorkflow::class);
$record = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
'reason' => 'Synthetic cancellation before any execution.', 'evidence' => 'Documented synthetic business decision.']);
$this->actingAs($this->finance);
$flow->decide($this->finance, $record, 'approved', 'Independent Finance confirmation.');
$flow->decide($this->finance, $record->fresh(), 'approved', 'Independent Finance confirmation.');
expect($flow->state($order))->toBe('cancelled')->and($this->r->fresh()->status)->toBe('approved')
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and(DB::table('budget_order_commands')->where('kind', 'cancel')->count())->toBe(1);
$this->actingAs($this->owner);
expect($flow->canRevise($this->owner, $record->fresh()))->toBeFalse()
->and(fn () => $flow->revise($this->owner, $record->fresh(), today()->addMonth()->toDateString(), 'No automatic whole-source reissue.'))->toThrow(HttpException::class);
$this->actingAs($this->buyer);
$remaining = $issue->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 2));
expect($remaining->total_minor)->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0);
});
test('native partial-order forms preview without writes and issue through the authenticated encrypted path', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === 'purchases/parts' && $page['encryptHistory'] === true);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$before = DB::table('audit_logs')->count();
$this->post('/ordens/preparar', ['sources' => $input['sources']])->assertOk()
->assertViewHas('page', fn (array $page) => $page['props']['preview']['prepared']['total_minor'] === 4000 && $page['props']['preview']['can_issue'] === true);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('audit_logs')->count())->toBe($before);
$this->post('/ordens/parcelas/emitir', $input)->assertRedirect();
$order = PurchaseOrder::query()->sole();
$this->post('/ordens/parcelas/emitir', $input)->assertRedirect('/ordens/'.$order->id);
expect(PurchaseOrder::query()->count())->toBe(1);
$this->actingAs($this->finance)->get('/ordens/preparar')->assertForbidden();
$this->actingAs($this->buyer);
config(['order-parts.qa_enabled' => false]);
$this->get('/ordens/preparar')->assertServiceUnavailable();
$this->post('/ordens/parcelas/emitir', $input)->assertServiceUnavailable();
expect(PurchaseOrder::query()->count())->toBe(1);
});
test('native explicit adoption keeps the old reserve unchanged and supports replay after a partial order is issued', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$this->actingAs($this->finance);
$id = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic legacy budget before adoption.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($id);
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$old = DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->get()->toArray();
$this->actingAs($this->buyer);
$source = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]]]];
expect(app(OrderPartsWorkflow::class)->preview($this->buyer, $source)['financial'][0]['requires_adoption'])->toBeTrue();
$operation = (string) Str::uuid();
$this->post('/adjudicacoes/'.$award->id.'/parcelas/adoptar', ['operation_key' => $operation])->assertRedirect('/ordens/preparar');
expect(DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->limit(count($old))->get()->toArray())->toEqual($old)
->and((int) DB::table('budget_entries')->sum('reserved_minor') + (int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(10000);
app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$this->post('/adjudicacoes/'.$award->id.'/parcelas/adoptar', ['operation_key' => $operation])->assertRedirect('/ordens/preparar');
expect(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
});