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
+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);
});