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