Files
compras/tests/Feature/CapitalRegisterTest.php
T
nala 448948a487
tests / ci (push) Waiting to run
commit compras1 2911
2026-11-29 05:28:30 +02:00

255 lines
19 KiB
PHP

<?php
use App\Models\CriticalityLevel;
use App\Models\Department;
use App\Models\Equipment;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
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(['capital-register.qa_enabled' => true]);
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'type' => 'project', 'code' => 'PRJ-QA', 'name' => 'Projecto estritamente sintético',
'department_id' => $this->f['department']->id, 'equipment_id' => null,
'reference' => 'Documento fictício para cadastro independente de Compras', 'state' => 'active',
'reason' => 'Preparação de referência sintética para testes de compras'];
});
test('capital search returns current metadata literal matches pagination and native history links without business writes', function () {
$service = app(CapitalRegister::class);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$old = $service->save($this->f['issuer'], [...$this->input, 'name' => 'OLD-CAPITAL-SEARCH']);
$current = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $old->record_key, 'version' => 1, 'name' => 'NEW-CAPITAL%_SEARCH', 'state' => 'archived']);
$read = function (string $query) {
$response = $this->get('/compras/pesquisa?'.$query)->assertOk()
->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$props = $response->viewData('page')['props'];
expect($props['capitalSearchAvailable'])->toBeTrue();
expect($props['capitalRegisterAvailable'])->toBeTrue();
return collect($props['groups'])->firstWhere('key', 'capital')['records'];
};
expect($read('q=OLD-CAPITAL-SEARCH')['total'])->toBe(0);
$literal = $read('q='.urlencode('%_'));
expect($literal['total'])->toBe(1)->and($literal['data'][0]['id'])->toBe($current->id)
->and($literal['data'][0]['detail'])->toBe('archived')
->and($literal['data'][0]['title'])->toContain('NEW-CAPITAL%_SEARCH', 'v2')
->and(array_keys($literal['data'][0]))->toBe(['id', 'title', 'detail', 'href'])
->and($literal['data'][0]['href'])->toBe('/projectos-imobilizado?history='.$old->record_key);
$this->get($literal['data'][0]['href'])->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 2));
foreach (range(1, 17) as $index) {
$service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'code' => 'CAP-PAGE-'.$index]);
}
$firstPage = $read('q=CAP-PAGE-');
expect($firstPage['total'])->toBe(17)->and($firstPage['data'])->toHaveCount(15)
->and($firstPage['next_page_url'])->toContain('q=CAP-PAGE-', 'capital_page=2');
expect($read('q=CAP-PAGE-&capital_page=2')['data'])->toHaveCount(2);
$asset = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'code' => 'CAP-ASSET', 'type' => 'asset']);
expect($read('q=CAP-ASSET')['data'][0]['title'])->toContain('Imobilizado CAP-ASSET');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->getJson('/compras/pesquisa?q=CAP&capital_page=0')->assertUnprocessable();
});
test('capital search retains tenant departmental permission and QA boundaries', function () {
$service = app(CapitalRegister::class);
$own = $this->f;
$service->save($own['issuer'], $this->input);
$foreign = receiptFixture();
$this->actingAs($foreign['issuer']);
expect($service->searchQuery($foreign['issuer'])?->count())->toBe(0)
->and($service->searchQuery($own['issuer']))->toBeNull();
$this->actingAs($own['issuer']);
$department = Department::query()->create(['tenant_id' => $own['tenant']->id, 'code' => 'OTHER-CAP', 'name' => 'Outro departamento QA']);
$service->save($own['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'code' => 'CAP-OTHER', 'department_id' => $department->id]);
$head = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id]);
supplyGrant($head, ['department_head']);
$this->actingAs($head);
expect($service->searchQuery($head)?->count())->toBe(1);
$this->get('/compras/pesquisa?q=CAP-OTHER')->assertOk()->assertViewHas('page', fn (array $page) => collect($page['props']['groups'])->firstWhere('key', 'capital')['records']['total'] === 0);
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $head->id)->pluck('profile_id'))
->update(['permissions' => json_encode(['requester'])]);
$this->get('/compras/pesquisa?q=PRJ')->assertInertia(fn (Assert $page) => $page->where('capitalSearchAvailable', false)->where('capitalRegisterAvailable', false)
->where('groups', fn ($groups) => ! collect($groups)->contains('key', 'capital')));
config(['capital-register.qa_enabled' => false]);
supplyGrant($own['issuer'], ['procurement']);
$this->actingAs($own['issuer'])->get('/compras/pesquisa?q=PRJ')->assertInertia(fn (Assert $page) => $page->where('capitalSearchAvailable', false));
});
test('own project register versions preserves identity and replay without financial or stock effects', function () {
$service = app(CapitalRegister::class);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$first = $service->save($this->f['issuer'], $this->input);
expect($first->version)->toBe(1)->and($first->snapshot['source_system'])->toBe('compras');
expect($service->save($this->f['issuer'], $this->input)->id)->toBe($first->id);
$archive = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'state' => 'archived'];
$second = $service->save($this->f['issuer'], $archive);
expect($second->version)->toBe(2)->and($second->state)->toBe('archived')
->and($first->fresh()->state)->toBe('active')->and(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(2);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
expect(fn () => $service->save($this->f['issuer'], [...$archive, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(ValidationException::class);
});
test('register rejects reused operation content and renaming a permanent code', function () {
$service = app(CapitalRegister::class);
$first = $service->save($this->f['issuer'], $this->input);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'name' => 'Conteúdo diferente']))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'code' => 'OUTRO']))->toThrow(ValidationException::class);
expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
});
test('asset references reuse a physical equipment identity and reject duplicate or removed links', function () {
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(), 'code' => 'QA', 'name' => 'Ensaio', 'criteria' => 'Só fixture sintética', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'code' => 'EQ-QA', 'description' => 'Equipamento físico sintético',
'area' => 'Área sintética', 'status' => 'active', 'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
$input = [...$this->input, 'type' => 'asset', 'code' => 'ASSET-QA', 'equipment_id' => $equipment->id];
$service = app(CapitalRegister::class);
$first = $service->save($this->f['issuer'], $input);
expect($first->snapshot['equipment']['id'])->toBe($equipment->id)->and(Equipment::query()->count())->toBe(1);
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => 'OTHER-QA']))->toThrow(ValidationException::class);
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'equipment_id' => null]))->toThrow(ValidationException::class);
$this->get('/projectos-imobilizado?history='.$first->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 1));
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => ['invalid']]))->toThrow(ValidationException::class);
});
test('equipment backlink revalidates current register access without exposing a reference after revocation', function () {
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(),
'code' => 'LINK-QA', 'name' => 'Ensaio de ligação', 'criteria' => 'Dados sintéticos', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id,
'code' => 'EQ-LINK-QA', 'description' => 'Identidade sintética de equipamento', 'area' => 'Ensaio', 'status' => 'active',
'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
$service = app(CapitalRegister::class);
$source = $service->save($this->f['issuer'], [...$this->input, 'type' => 'asset', 'code' => 'ASSET-LINK-QA', 'equipment_id' => $equipment->id]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment)['record_key'])->toBe($source->record_key);
supplyGrant($this->f['issuer'], ['admin']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => true]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => false]);
DB::table('organization_profiles')->where('tenant_id', $this->f['tenant']->id)->update(['permissions' => json_encode(['requester'])]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
auth()->logout();
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
});
test('native register page is encrypted private paginated and gated off outside QA', function () {
app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$this->get('/projectos-imobilizado')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('equipment/capital-register')
->has('records.data', 1)->where('records.data.0.data.code', 'PRJ-QA')->where('canManage', true));
config(['capital-register.qa_enabled' => false]);
$this->get('/projectos-imobilizado')->assertStatus(503);
});
test('native register revalidates operator and hides foreign department identity without creating versions', function () {
$service = app(CapitalRegister::class);
$first = $service->save($this->f['issuer'], $this->input);
$this->actingAs($this->f['receiver']);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$this->actingAs($this->f['issuer']);
$other = receiptFixture();
$this->actingAs($other['issuer']);
$this->get('/projectos-imobilizado')->assertOk()->assertInertia(fn (Assert $page) => $page->has('records.data', 0));
$this->post('/projectos-imobilizado', [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1])->assertNotFound();
$this->actingAs($this->f['issuer']);
expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
});
test('line destination freezes the chosen project version and preserves it after archival without financial effects', function () {
$register = app(CapitalRegister::class);
$source = $register->save($this->f['issuer'], $this->input);
$this->f['r']->update(['status' => 'draft']);
$item = $this->f['r']->items()->firstOrFail();
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id,
'capital_id' => $source->id, 'reason' => 'Escolha de destino sintético da linha da requisição'];
$service = app(CapitalAssignments::class);
$first = $service->save($this->f['issuer'], $this->f['r'], $input);
expect($first->state)->toBe('linked')->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($first->id);
$register->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $source->record_key, 'version' => 1, 'state' => 'archived', 'name' => 'Designação posterior sintética']);
$frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
expect($frozen[$item->id]['snapshot']['source']['version'])->toBe(1)
->and($frozen[$item->id]['snapshot']['source']['data']['name'])->toBe($this->input['name']);
$this->get('/requisicoes/'.$this->f['r']->id.'/projectos-imobilizado')->assertOk()
->assertInertia(fn (Assert $page) => $page->component('requisitions/capital-assignments')->where('canWrite', true)->has('choices.data', 0)->has('current', 1));
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ModelNotFoundException::class);
expect(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
$item->update(['description' => 'Artigo alterado após a escolha']);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
$cleared = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'capital_id' => null]);
expect($cleared->state)->toBe('cleared')->and($service->freezeForItems($this->f['issuer'], [$item->id]))->toBe([])
->and($first->fresh()->state)->toBe('linked');
});
test('submitted requisitions reject new line destinations and stale versions do not replace choices', function () {
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$item = $this->f['r']->items()->firstOrFail();
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
'reason' => 'Escolha documental sintética preservando decisões anteriores'];
$service = app(CapitalAssignments::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $input))->toThrow(HttpException::class);
$this->f['r']->update(['status' => 'draft']);
$service->save($this->f['issuer'], $this->f['r'], $input);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'capital_id' => null]))->toThrow(HttpException::class);
config(['capital-register.qa_enabled' => false]);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
});
test('revoked requester retains only native historical visibility without new catalogue choices or commands', function () {
supplyGrant($this->f['issuer'], ['procurement', 'requester']);
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$this->f['r']->update(['status' => 'draft']);
$item = $this->f['r']->items()->sole();
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
'reason' => 'Escolha sintética antes da revogação dos acessos'];
$service = app(CapitalAssignments::class);
$service->save($this->f['issuer'], $this->f['r'], $input);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['canWrite'])->toBeFalse()->and($workspace['choices']->total())->toBe(0)->and($workspace['current'])->toHaveCount(1);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(HttpException::class);
});
test('classified machinery cannot submit without a capital destination or create approvals and reservations', function () {
$this->f['r']->update(['status' => 'draft']);
$item = $this->f['r']->items()->sole();
$item->update(['purchase_type' => 'equipment', 'production_area' => 'Área sintética',
'category_context' => ['version' => 1, 'category' => 'capital_equipment', 'reason' => 'Justificação sintética de investimento']]);
$this->postJson('/requisicoes/'.$this->f['r']->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $this->f['r']->process_version])
->assertUnprocessable()->assertJsonValidationErrors('capital_assignment');
expect($this->f['r']->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->count())->toBe(0)
->and($this->f['r']->steps()->count())->toBe(0);
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
app(CapitalAssignments::class)->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $item->id, 'capital_id' => $source->id, 'reason' => 'Destino sintético para maquinaria classificada']);
app(CapitalAssignments::class)->assertSubmission($this->f['issuer'], $this->f['r']);
expect(DB::table('budget_entries')->count())->toBe(0)->and($this->f['r']->steps()->count())->toBe(0);
});