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

214 lines
16 KiB
PHP

<?php
use App\Enums\PurchasingRole;
use App\Models\Department;
use App\Models\SupplyRecord;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationalOrders;
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 () {
$this->withoutVite();
$this->f = receiptFixture();
$this->admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->policy = ['version' => 0, 'mode' => 'procurement', 'reason' => 'Locais ainda não abrangidos pela aplicação de compras.', 'operation_key' => (string) Str::uuid()];
$this->input = ['type' => 'production', 'reference' => 'OP-SYNTHETIC-001', 'department_id' => $this->f['department']->id,
'utilisation_location' => 'Linha de produção exclusivamente sintética', 'description' => 'Produção fictícia para comprovar a ordem de origem.',
'reason' => 'Registo sintético pelo agente de procurement.', 'policy_version' => 1, 'operation_key' => (string) Str::uuid()];
$this->actingAs($this->admin);
});
test('operational order search retains literal matching pagination and opens the selected native source beyond the first page', function () {
config(['operational-orders.qa_enabled' => true]);
$service = app(OperationalOrders::class);
$service->configure($this->admin, $this->policy);
$this->actingAs($this->f['issuer']);
$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, 'reference' => 'OP-FOUND-OLD']);
foreach (range(1, 17) as $index) {
$service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'reference' => 'OP-PAGE-'.$index]);
}
$literal = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'reference' => 'OP%_LITERAL']);
$sourceRows = SupplyRecord::query()->where('kind', 'op_order')->orderBy('id')->get()->toJson();
$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['operationalOrderSearchAvailable'])->toBeTrue();
return collect($props['groups'])->firstWhere('key', 'operational_orders')['records'];
};
$page = $read('q=OP-PAGE-');
expect($page['total'])->toBe(17)->and($page['data'])->toHaveCount(15)
->and($page['next_page_url'])->toContain('q=OP-PAGE-', 'operational_orders_page=2');
expect($read('q=OP-PAGE-&operational_orders_page=2')['data'])->toHaveCount(2);
$match = $read('q='.urlencode('%_'));
expect($match['total'])->toBe(1)->and($match['data'][0]['id'])->toBe($literal->id)
->and($match['data'][0]['detail'])->toBe('recorded')->and($match['data'][0]['title'])->toContain('Produção OP%_LITERAL', 'v1')
->and(array_keys($match['data'][0]))->toBe(['id', 'title', 'detail', 'href']);
$oldMatch = $read('q=OP-FOUND-OLD')['data'][0];
expect($oldMatch['href'])->toBe('/ordens-operacionais?order_id='.$old->id.'#op-order-'.$old->id);
$this->get($oldMatch['href'])->assertOk()->assertInertia(fn (Assert $page) => $page->has('orders.data', 1)
->where('orders.data.0.id', $old->id)->where('selectedOrderId', $old->id));
$this->get('/ordens-operacionais?order_id='.$old->id.'&page=999')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('orders.current_page', 1)->has('orders.data', 1)->where('orders.data.0.id', $old->id));
$this->get('/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page->has('orders.data', 15)->where('selectedOrderId', null));
$this->getJson('/compras/pesquisa?q=OP&operational_orders_page=0')->assertUnprocessable();
$this->getJson('/ordens-operacionais?order_id=0')->assertUnprocessable();
expect(SupplyRecord::query()->where('kind', 'op_order')->orderBy('id')->get()->toJson())->toBe($sourceRows);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('operational order search and direct source selection retain native departmental tenant and current capability boundaries', function () {
config(['operational-orders.qa_enabled' => true]);
$service = app(OperationalOrders::class);
$service->configure($this->admin, $this->policy);
supplyGrant($this->f['issuer'], ['procurement']);
$this->actingAs($this->f['issuer']);
$own = $service->save($this->f['issuer'], $this->input);
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'code' => 'OP-OTHER', 'name' => 'Outro departamento sintético']);
$other = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'department_id' => $department->id, 'reference' => 'OP-OTHER-SECRET']);
$viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id]);
supplyGrant($viewer, ['production_order_prepare']);
$this->actingAs($viewer);
expect($service->searchQuery($viewer)?->pluck('id')->all())->toBe([$own->id]);
$this->get('/compras/pesquisa?q=OP-OTHER-SECRET')->assertOk()->assertViewHas('page', fn (array $page) => collect($page['props']['groups'])->firstWhere('key', 'operational_orders')['records']['total'] === 0);
$this->get('/ordens-operacionais?order_id='.$other->id)->assertNotFound();
$this->get('/ordens-operacionais?order_id='.$own->id)->assertOk();
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $viewer->id)->pluck('profile_id'))
->update(['permissions' => json_encode(['finance'])]);
$this->get('/compras/pesquisa?q=OP')->assertInertia(fn (Assert $page) => $page->where('operationalOrderSearchAvailable', false)
->where('groups', fn ($groups) => ! collect($groups)->contains('key', 'operational_orders')));
$this->get('/ordens-operacionais?order_id='.$own->id)->assertForbidden();
$foreign = receiptFixture();
$this->actingAs($foreign['issuer']);
expect($service->searchQuery($foreign['issuer'])?->count())->toBe(0)->and($service->searchQuery($this->f['issuer']))->toBeNull();
$this->get('/ordens-operacionais?order_id='.$own->id)->assertNotFound();
config(['operational-orders.qa_enabled' => false]);
expect($service->searchQuery($foreign['issuer']))->toBeNull();
});
test('operational register requires explicit origin mode preserves sources and has no financial or stock effects', function () {
$this->get('/ordens-operacionais')->assertStatus(503);
config(['operational-orders.qa_enabled' => true]);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertForbidden();
$this->actingAs($this->admin)->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais', $this->input)->assertForbidden();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$order = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
expect($order->snapshot['author']['id'])->toBe($this->f['issuer']->id)
->and($order->snapshot['policy']['data']['mode'])->toBe('procurement')
->and(SupplyRecord::query()->where('kind', 'op_order')->count())->toBe(1);
foreach (SupplyRecord::query()->pluck('kind') as $kind) {
expect(strlen($kind))->toBeLessThanOrEqual(20);
}
$this->post('/ordens-operacionais', [...$this->input, 'description' => 'Payload alterado na mesma operação.'])->assertConflict();
$this->post('/ordens-operacionais', [...$this->input, 'operation_key' => (string) Str::uuid()])->assertConflict();
$response = $this->get('/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page->component('requisitions/operational-orders')->has('orders.data', 1));
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('utilisation mode uses explicit production and workshop responsibilities without a procurement fallback', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', [...$this->policy, 'mode' => 'utilisation'])->assertSessionHasNoErrors()->assertRedirect();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertForbidden();
DB::table('organization_access')->insert(['tenant_id' => $this->f['tenant']->id, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
foreach (['production', 'maintenance'] as $type) {
$person = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $person->tenant_id, 'name' => $type, 'permissions' => json_encode([$type.'_order_prepare']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
$membership = DB::table('organization_memberships')->insertGetId(['tenant_id' => $person->tenant_id, 'user_id' => $person->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
$input = [...$this->input, 'type' => $type, 'reference' => 'SYNTHETIC-'.$type, 'operation_key' => (string) Str::uuid()];
$this->actingAs($person)->post('/ordens-operacionais', $input)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais', [...$input, 'type' => $type === 'production' ? 'maintenance' : 'production', 'operation_key' => (string) Str::uuid()])->assertForbidden();
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => now()->subMinute()]);
$this->post('/ordens-operacionais', $input)->assertForbidden();
}
expect(SupplyRecord::query()->where('kind', 'op_order')->count())->toBe(2);
});
test('request links preserve original order and line basis reject stale changes and cannot be changed after submission', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$source = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
$request = $this->f['r'];
$request->update(['status' => 'draft']);
$item = $request->items()->firstOrFail();
$item->update(['category_context' => ['version' => 1, 'category' => 'production_input', 'reason' => null]]);
$service = app(OperationalOrders::class);
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
$input = ['item_id' => $item->id, 'order_id' => $source->id, 'version' => 0, 'reason' => 'Ligação documental à produção solicitada.', 'operation_key' => (string) Str::uuid()];
$url = '/requisicoes/'.$request->id.'/ordens-operacionais';
$this->post($url, $input)->assertSessionHasNoErrors()->assertRedirect();
$this->post($url, $input)->assertSessionHasNoErrors()->assertRedirect();
$service->assertSubmission($this->f['issuer'], $request);
$frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
expect($frozen[$item->id]['snapshot']['source']['id'])->toBe($source->id)
->and($frozen[$item->id]['snapshot']['source']['snapshot']['author']['id'])->toBe($this->f['issuer']->id);
$this->post($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
$item->update(['description' => 'Alteração posterior exige nova ligação.']);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
$this->post($url, [...$input, 'version' => 1, 'operation_key' => (string) Str::uuid()])->assertSessionHasNoErrors()->assertRedirect();
$request->update(['status' => 'pending']);
$this->post($url, [...$input, 'version' => 2, 'operation_key' => (string) Str::uuid()])->assertConflict();
expect(SupplyRecord::query()->where('kind', 'op_order_link')->count())->toBe(2);
config(['operational-orders.qa_enabled' => false]);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
});
test('policy versions and company department isolation are enforced on original orders', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais/configuracao', [...$this->policy, 'operation_key' => (string) Str::uuid()])->assertConflict();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', [...$this->input, 'policy_version' => 2])->assertConflict();
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
$department = Department::query()->create(['tenant_id' => $other->id, 'name' => 'Outra produção']);
$this->post('/ordens-operacionais', [...$this->input, 'department_id' => $department->id])->assertNotFound();
$foreign = User::factory()->create(['tenant_id' => $other->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Procurement]);
$this->actingAs($foreign)->get('/requisicoes/'.$this->f['r']->id.'/ordens-operacionais')->assertNotFound();
expect(SupplyRecord::query()->withoutGlobalScopes()->where('kind', 'op_order')->count())->toBe(0);
});
test('metadata authority never opens the order register and process readers receive only linked origins', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$order = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
$request = $this->f['r'];
$request->update(['status' => 'draft']);
app(OperationalOrders::class)->link($this->f['issuer'], $request, ['item_id' => $request->items()->sole()->id, 'order_id' => $order->id,
'version' => 0, 'reason' => 'Origem sintética ligada para a consulta limitada.', 'operation_key' => (string) Str::uuid()]);
$this->post('/ordens-operacionais', [...$this->input, 'reference' => 'UNLINKED-PRIVATE-ORDER', 'operation_key' => (string) Str::uuid()])->assertSessionHasNoErrors()->assertRedirect();
$request->update(['status' => 'approved']);
$metadata = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($metadata, ['audit_metadata_read']);
supplyGrant($finance, ['finance']);
$this->actingAs($metadata)->get('/ordens-operacionais')->assertForbidden();
$this->get('/requisicoes/'.$request->id.'/ordens-operacionais')->assertNotFound();
$this->actingAs($finance)->get('/ordens-operacionais')->assertForbidden();
$this->get('/requisicoes/'.$request->id.'/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('canLink', false)->has('orders.data', 1)->where('orders.data.0.id', $order->id)->has('links', 1));
});