Files
compras/tests/Feature/ImportDossierTest.php
T
nala e709d900d1
tests / ci (push) Waiting to run
commit compras 2711
2026-11-27 13:49:31 +02:00

240 lines
17 KiB
PHP

<?php
use App\Enums\PurchasingRole;
use App\Models\ConflictDeclaration;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportDossier;
use App\Services\ImportEvidence;
use App\Services\ImportParties;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Database\QueryException;
use Illuminate\Filesystem\FilesystemAdapter;
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;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportQaIdentity.php';
beforeEach(function () {
config(['import-dossier.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 dossier jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime',
]));
$this->input = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-QA-1',
'issuer_reference' => 'Synthetic supplier', 'issued_on' => today()->toDateString(), 'notes' => 'Synthetic private original.',
'reason' => 'Retain the original synthetic packing list.'];
$this->bytes = "%PDF-1.4\nSynthetic packing list only\n%%EOF";
$this->file = UploadedFile::fake()->createWithContent('packing.pdf', $this->bytes);
});
test('typed import dossier retains originals corrections and replay without financial stock or customs effects', function () {
$service = app(ImportDossier::class);
$before = [DB::table('stock_movements')->count(), DB::table('invoices')->count(), DB::table('budget_entries')->get()->toArray(), $this->import->toArray()];
$first = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
expect($service->record($this->f['issuer'], $this->import, $this->input, $this->file)->id)->toBe($first->id)
->and($first->version)->toBe(1)->and($first->snapshot['financial_effects'])->toBeFalse()
->and($first->snapshot['external_submission'])->toBeFalse();
$correction = $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'reference' => 'PACK-QA-1-CORRECTED'],
UploadedFile::fake()->createWithContent('corrected.pdf', "%PDF-1.4\nSynthetic corrected packing list\n%%EOF"));
expect($correction->version)->toBe(2)->and($correction->snapshot['supersedes'])->toBe($first->id)
->and(app(ImportEvidence::class)->bytes($first))->toBe($this->bytes)
->and($service->record($this->f['issuer'], $this->import, $this->input, $this->file)->id)->toBe($first->id)
->and([DB::table('stock_movements')->count(), DB::table('invoices')->count(), DB::table('budget_entries')->get()->toArray(), $this->import->fresh()->toArray()])->toEqual($before);
$workspace = $service->workspace($this->f['issuer'], $this->import);
expect($workspace['documents']->items()[0]['current'])->toBeTrue()
->and($workspace['documents']->items()[1]['current'])->toBeFalse()
->and(json_encode($workspace, JSON_THROW_ON_ERROR))->not->toContain('import-dossier/'.$first->tenant_id.'/');
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1], $this->file))->toThrow(HttpException::class);
expect(fn () => DB::transaction(fn () => DB::table('supply_records')->where('id', $first->id)->update(['state' => 'approved'])))->toThrow(QueryException::class);
});
test('typed dossier refuses duplicate identities type changes and storage changes', function () {
$service = app(ImportDossier::class);
$record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $record->record_key, 'version' => 1, 'type' => 'payment_evidence'], $this->file))->toThrow(HttpException::class);
$this->withoutVite();
$response = $this->get('/compras/importacoes/'.$this->import->id.'/documentos/'.$record->id)->assertOk()
->assertHeader('X-Content-Type-Options', 'nosniff');
expect($response->getContent())->toBe($this->bytes);
Storage::disk('local')->put($record->snapshot['evidence']['path'], str_repeat('X', strlen($this->bytes)));
expect($response->getContent())->toBe($this->bytes);
$this->get('/compras/importacoes/'.$this->import->id.'/documentos/'.$record->id)->assertConflict();
expect(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(1);
});
test('dossier read and write use current roles tenant isolation and the disabled capability guard', function () {
$service = app(ImportDossier::class);
$record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($finance, ['finance']);
$this->actingAs($finance);
expect($service->workspace($finance, $this->import)['canWrite'])->toBeFalse();
expect(fn () => $service->record($finance, $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
$this->withoutVite();
$url = '/compras/importacoes/'.$this->import->id.'/documentos';
$this->get($url)->assertOk()->assertViewHas('page', fn ($page) => $page['component'] === 'supply/import-dossier' && $page['encryptHistory'] === true && $page['props']['canWrite'] === false);
$other = receiptFixture();
supplyGrant($other['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($other['issuer'])->get($url.'/'.$record->id)->assertNotFound();
$this->actingAs($this->f['issuer']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => true, 'expires_at' => now()->addHour()]);
$this->get($url)->assertForbidden();
config(['import-dossier.qa_enabled' => false]);
expect($service->ready())->toBeFalse();
$this->get($url)->assertServiceUnavailable();
});
test('failed dossier audit removes only the new unconfirmed private file and preserves existing versions', function () {
$service = app(ImportDossier::class);
$record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
$before = Storage::disk('local')->allFiles();
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $record->record_key, 'version' => 1], UploadedFile::fake()->createWithContent('next.pdf', "%PDF-1.4\nUnconfirmed QA version\n%%EOF")))->toThrow(RuntimeException::class);
expect(Storage::disk('local')->allFiles())->toEqual($before)
->and(app(ImportEvidence::class)->bytes($record))->toBe($this->bytes)
->and(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(1);
});
test('aggregate import inspection includes typed dossier originals without exposing or repairing them', function () {
$record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
$path = $record->snapshot['evidence']['path'];
auth()->logout();
$health = app(ImportCostDocumentHealth::class);
expect($health->inspect()['ok'])->toBeTrue();
Storage::disk('local')->put($path, str_repeat('Y', strlen($this->bytes)));
Storage::disk('local')->put('import-dossier/orphan.pdf', 'Synthetic unreferenced file.');
$result = $health->inspect();
expect($result['altered'])->toBe(1)->and($result['unreferenced'])->toBe(1)
->and(json_encode($result, JSON_THROW_ON_ERROR))->not->toContain($path, $this->input['reference']);
Storage::disk('local')->assertExists($path);
});
test('dossier rejects unsupported empty or oversized originals before storing any record', function () {
foreach ([UploadedFile::fake()->createWithContent('script.txt', 'Not an accepted original.'),
UploadedFile::fake()->create('oversized.pdf', 2049, 'application/pdf'),
UploadedFile::fake()->createWithContent('empty.pdf', '')] as $file) {
$this->postJson('/compras/importacoes/'.$this->import->id.'/documentos', [...$this->input, 'file' => $file])->assertUnprocessable();
}
expect(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(0)
->and(Storage::disk('local')->allFiles())->toBe([]);
});
function importDossierPartyFixture(object $test): array
{
$buyer = User::factory()->create(['tenant_id' => $test->f['tenant']->id, 'department_id' => $test->f['department']->id,
'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($buyer, ['procurement', 'import_prepare']);
$test->actingAs($buyer);
$supplier = Supplier::query()->whereKey($test->f['order']->supplier_id)->firstOrFail()->replicate();
$supplier->name = 'Despachante exclusivamente sintético';
$supplier->nuit = '987654321';
$supplier->save();
$instructions = app(ImportDossier::class)->record($buyer, $test->import, [...$test->input, 'operation_key' => (string) Str::uuid(),
'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-QA'], $test->file);
$data = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $supplier->id,
'supplier_version' => $supplier->version, 'instruction_document_id' => $instructions->id,
'reason' => 'Explicit synthetic independent buyer selection.', 'no_conflict' => true];
return [$buyer, $supplier, $instructions, $data];
}
test('broker selection reuses eligible entity and current written instructions preserving history and requester segregation', function () {
[$buyer, $supplier, $instructions, $data] = importDossierPartyFixture($this);
$service = app(ImportParties::class);
$this->actingAs($this->f['issuer']);
expect($service->canSelect($this->f['issuer'], $this->f['order']))->toBeFalse();
expect(fn () => $service->select($this->f['issuer'], $this->import, $data))->toThrow(HttpException::class);
$this->actingAs($buyer);
expect($service->workspace($buyer, $this->import, 'despachante')['suppliers']->pluck('id')->all())->toContain($supplier->id);
$record = $service->select($buyer, $this->import, $data);
expect($record->snapshot['supplier']['id'])->toBe($supplier->id)
->and($record->data['instruction_document_id'])->toBe($instructions->id)
->and($record->snapshot['no_conflict'])->toBeTrue()
->and($service->select($buyer, $this->import, $data)->id)->toBe($record->id);
$this->withoutVite();
$this->get('/compras/importacoes/'.$this->import->id.'/documentos')->assertOk()
->assertViewHas('page', fn ($page) => $page['props']['parties']['canSelect'] === true);
$this->post('/compras/importacoes/'.$this->import->id.'/intervenientes', $data)
->assertRedirect('/compras/importacoes/'.$this->import->id.'/documentos');
$correction = app(ImportDossier::class)->record($buyer, $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $instructions->record_key, 'version' => 1, 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-QA-2'],
UploadedFile::fake()->createWithContent('instructions.pdf', "%PDF-1.4\nNew synthetic instructions\n%%EOF"));
$transit = supplyInput(['event_date' => today()->toDateString(), 'evidence' => 'Synthetic transit evidence.'], 'transit', $this->import);
expect(fn () => app(SupplyPlanning::class)->save($buyer, 'import', $transit))->toThrow(HttpException::class);
$next = $service->select($buyer, $this->import, [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1,
'instruction_document_id' => $correction->id]);
expect($next->version)->toBe(2)->and($next->snapshot['supersedes'])->toBe($record->id)
->and(app(SupplyPlanning::class)->save($buyer, 'import', $transit)->state)->toBe('transit')
->and(SupplyRecord::query()->where('kind', 'import_party')->count())->toBe(2)
->and(DB::table('stock_movements')->count())->toBe(0);
});
test('broker selection refuses stale entity versions missing declarations and conflicts of earlier selectors', function () {
[$buyer, $supplier, $instructions, $data] = importDossierPartyFixture($this);
$service = app(ImportParties::class);
expect(fn () => $service->select($buyer, $this->import, [...$data, 'supplier_version' => $supplier->version + 1]))->toThrow(HttpException::class);
expect(fn () => $service->select($buyer, $this->import, [...$data, 'no_conflict' => false]))->toThrow(ValidationException::class);
$record = $service->select($buyer, $this->import, $data);
ConflictDeclaration::query()->create(['tenant_id' => $buyer->tenant_id, 'user_id' => $buyer->id, 'supplier_id' => $supplier->id,
'has_conflict' => true, 'known_since' => today(), 'declared_at' => now(), 'reason' => 'Synthetic declared broker relationship.']);
$other = User::factory()->create(['tenant_id' => $buyer->tenant_id, 'department_id' => $buyer->department_id, 'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($other, ['procurement', 'import_prepare']);
$this->actingAs($other);
expect(fn () => $service->select($other, $this->import, [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ValidationException::class);
expect(fn () => app(SupplyPlanning::class)->save($other, 'import', supplyInput(['event_date' => today()->toDateString(),
'evidence' => 'Synthetic transit evidence.'], 'transit', $this->import)))->toThrow(HttpException::class);
$workspace = $service->workspace($other, $this->import);
expect($workspace['current'][0]['issues'])->not->toBeEmpty()
->and(SupplyRecord::query()->where('kind', 'import_party')->count())->toBe(1)
->and($record->fresh()->snapshot['supplier']['id'])->toBe($supplier->id);
});
test('a private original lost between metadata and byte reading is refused as a recoverable conflict', function () {
$record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
$disk = Mockery::mock(FilesystemAdapter::class);
$disk->shouldReceive('exists')->once()->andReturnTrue();
$disk->shouldReceive('size')->once()->andReturn(strlen($this->bytes));
$disk->shouldReceive('get')->once()->andReturnNull();
Storage::shouldReceive('disk')->with('local')->andReturn($disk);
try {
app(ImportEvidence::class)->bytes($record);
$this->fail('Missing private bytes must not be returned.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(409);
}
});
test('documentary date is preserved without inferring current validity or forbidding a future original date', function () {
$date = today()->addMonth()->toDateString();
$record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, [...$this->input, 'issued_on' => $date], $this->file);
expect($record->data['issued_on'])->toBe($date)->and($record->state)->toBe('recorded')
->and($record->snapshot['external_submission'])->toBeFalse()->and($record->snapshot['financial_effects'])->toBeFalse();
});
test('sessionless QA actor reset permits inspection without changing any restored user fields', function () {
app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
$before = hash('sha256', DB::table('users')->orderBy('id')->get()->toJson());
clearImportQaIdentity();
expect(auth()->check())->toBeFalse()->and(app(ImportCostDocumentHealth::class)->inspect()['ok'])->toBeTrue()
->and(hash('sha256', DB::table('users')->orderBy('id')->get()->toJson()))->toBe($before);
});