markTestSkipped('Use the dedicated ledger QA runner with the real common schema and isolated non-elevated role.'); } require_once $source.'/bootstrap.php'; LedgerSchema::install(DB::connection()); if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') { require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php'; $this->schemaComposition = integratedPurchasingQaSchema(); } $this->f = receiptFixture(); $this->item = $this->f['r']->items()->firstOrFail(); $this->actingAs($this->f['issuer']); $this->withoutVite(); config(['requisition-accounts.qa_enabled' => true]); $this->account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0, 'code' => 'QA-ONLY-100', 'label' => 'Conta fictícia de movimentos', 'currency' => 'MZN', 'is_movement' => true]); }); test('pinned private runtime refuses source fallback and mismatched composition without effects', function () { if (config('common-finance-bundle.manifest_sha256') !== '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df') { $this->markTestSkipped('This regression requires the exact frozen private composition.'); } $tables = ['gl_accounts', 'gl_journals', 'requisitions', 'budget_entries', 'supply_records', 'audit_logs']; $snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables); $before = $snapshot(); $source = getenv('RQ01_LEDGER_QA_SOURCE'); $settings = ['common-finance-bundle.manifest_sha256' => config('common-finance-bundle.manifest_sha256'), 'common-finance-bundle.root' => config('common-finance-bundle.root'), 'general-ledger.path' => config('general-ledger.path')]; try { foreach (['C:/laragon/www/sgf-tempo/packages/general-ledger', base_path('storage/framework/testing/unapproved-ledger-source')] as $wrong) { putenv('RQ01_LEDGER_QA_SOURCE='.$wrong); expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class); } putenv('RQ01_LEDGER_QA_SOURCE='.$source); foreach (['common-finance-bundle.manifest_sha256' => str_repeat('0', 64), 'common-finance-bundle.root' => base_path('storage/framework/testing/unapproved-ledger-source'), 'general-ledger.path' => 'C:/laragon/www/sgf-tempo/packages/general-ledger'] as $key => $wrong) { config([$key => $wrong]); expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class); config($settings); } } finally { putenv('RQ01_LEDGER_QA_SOURCE='.$source); config($settings); } expect($snapshot())->toBe($before); }); test('minimal purchasing catalogue reads the actual common chart without journals or a second chart', function () { $service = app(RequisitionLedgerAccounts::class); $before = [DB::table('gl_accounts')->get()->toJson(), DB::table('gl_journals')->count(), DB::table('audit_logs')->count()]; $page = $service->options($this->f['issuer']); expect($service->ready())->toBeTrue()->and($page['total'])->toBe(1) ->and(array_keys($page['data'][0]))->toBe(['id', 'code', 'label', 'currency', 'source_hash']) ->and($service->resolve($this->f['issuer'], $this->account, $page['data'][0]['source_hash']))->toBe($page['data'][0]) ->and([DB::table('gl_accounts')->get()->toJson(), DB::table('gl_journals')->count(), DB::table('audit_logs')->count()])->toBe($before); expect($service->options($this->f['issuer'], '%')['total'])->toBe(0); expect($service->options($this->f['issuer'], 'fictícia')['total'])->toBe(1); }); test('chart references reject foreign scope summary accounts and stale hashes', function () { $service = app(RequisitionLedgerAccounts::class); $hash = $service->options($this->f['issuer'])['data'][0]['source_hash']; foreach (['company_id' => 8, 'unit_id' => 9, 'tenant_id' => $this->f['tenant']->id + 100, 'is_movement' => false] as $column => $value) { $other = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0, 'code' => 'QA-EXCLUDED-'.$column, 'label' => 'Referência sintética fora do catálogo', 'currency' => 'MZN', 'is_movement' => true, $column => $value]); expect($service->options($this->f['issuer'])['total'])->toBe(1) ->and(fn () => $service->resolve($this->f['issuer'], $other, $hash))->toThrow(HttpException::class); } expect(fn () => $service->resolve($this->f['issuer'], $this->account, str_repeat('0', 64)))->toThrow(HttpException::class); // Common accounts are append-only: corrections cannot silently rename an accepted source. expect(fn () => DB::transaction(fn () => DB::table('gl_accounts')->where('id', $this->account)->update(['label' => 'Alteração proibida'])))->toThrow(QueryException::class); config(['requisition-accounts.qa_enabled' => false]); expect($service->ready())->toBeFalse()->and(fn () => $service->options($this->f['issuer']))->toThrow(HttpException::class); }); test('native line account assignment conserves exact parcels versions and originals without ledger effects', function () { $request = $this->f['r']; $request->update(['status' => 'draft']); $service = app(RequisitionAccountAssignments::class); expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class); $space = $service->workspace($this->f['issuer'], $request); $account = $space['accounts']['data'][0]; $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Imputação expressa no ensaio sintético', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]]; $before = [DB::table('gl_journals')->count(), DB::table('gl_lines')->count(), DB::table('budget_entries')->count(), DB::table('stock_movements')->count()]; $path = '/requisicoes/'.$request->id.'/contas'; $this->postJson($path, $input)->assertRedirect(); $this->postJson($path, $input)->assertRedirect(); $this->get($path)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page ->component('requisitions/accounts')->where('current.0.version', 1)->where('items.0.total_minor', '10000')->where('canWrite', true)); $first = SupplyRecord::query()->where('kind', 'req_account')->sole(); expect($first->data['allocations'][0]['total_minor'])->toBe('10000') ->and($service->freezeForItems($this->f['issuer'], [$this->item->id])[$this->item->id]['id'])->toBe($first->id); $input['operation_key'] = (string) Str::uuid(); $input['version'] = 1; $input['reason'] = 'Nova conferência documental sintética'; $this->postJson($path, $input)->assertRedirect(); expect(SupplyRecord::query()->where('kind', 'req_account')->count())->toBe(2) ->and($first->fresh()->reason)->toBe('Imputação expressa no ensaio sintético') ->and([DB::table('gl_journals')->count(), DB::table('gl_lines')->count(), DB::table('budget_entries')->count(), DB::table('stock_movements')->count()])->toBe($before); $input['operation_key'] = (string) Str::uuid(); $this->postJson($path, $input)->assertConflict(); $input['version'] = 2; $input['allocations'][0]['total'] = '99.99'; $this->postJson($path, $input)->assertUnprocessable(); $request->items()->whereKey($this->item->id)->update(['description' => 'Linha alterada de forma explícita']); expect(fn () => $service->freezeForItems($this->f['issuer'], [$this->item->id]))->toThrow(HttpException::class); }); test('classified line requires explicit exact account parcels and rejects another operator', function () { $request = $this->f['r']; $request->update(['status' => 'draft']); $this->item->setAttribute('category_context', ['version' => 1, 'category' => 'other', 'reason' => 'Necessidade sintética sem catálogo']); $this->item->save(); $service = app(RequisitionAccountAssignments::class); expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class); $space = $service->workspace($this->f['issuer'], $request); $account = $space['accounts']['data'][0]; $secondId = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0, 'code' => 'QA-ONLY-200', 'label' => 'Segunda conta fictícia', 'currency' => 'MZN', 'is_movement' => true]); $second = app(RequisitionLedgerAccounts::class)->options($this->f['issuer'])['data'][1]; expect($second['id'])->toBe($secondId); $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Duas parcelas explícitas, sem rateio automático', 'allocations' => [ ['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '0.33', 'total' => '0.33'], ['account_id' => $second['id'], 'source_hash' => $second['source_hash'], 'subtotal' => '99.67', 'total' => '99.67']]]; $path = '/requisicoes/'.$request->id.'/contas'; $bad = $input; $bad['allocations'][1]['subtotal'] = '99.66'; $this->postJson($path, $bad)->assertUnprocessable(); $bad = $input; $bad['allocations'][1]['account_id'] = $account['id']; $this->postJson($path, $bad)->assertUnprocessable(); $this->actingAs($this->f['receiver'])->postJson($path, $input)->assertNotFound(); $finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]); $this->actingAs($finance)->postJson($path, $input)->assertForbidden(); $this->actingAs($this->f['issuer'])->postJson($path, $input)->assertRedirect(); $service->assertSubmission($this->f['issuer'], $request); $source = SupplyRecord::query()->where('kind', 'req_account')->sole(); expect(array_column($source->data['allocations'], 'total_minor'))->toBe(['33', '9967']) ->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0); DB::table('audit_logs')->where('action', 'requisition.accounts_assigned')->delete(); expect(fn () => $service->freezeForItems($this->f['issuer'], [$this->item->id]))->toThrow(HttpException::class); }); test('zero monetary line retains its explicit account without invented compensation', function () { $request = $this->f['r']; $request->update(['status' => 'draft', 'subtotal_minor' => 0, 'total_minor' => 0]); $amounts = PurchaseLineAmounts::portion(1, '0', 0, 1); $this->item->update(['quantity' => '0.001', 'unit_price_minor' => 1, ...$amounts]); expect($amounts['total_minor'])->toBe(0); $service = app(RequisitionAccountAssignments::class); $space = $service->workspace($this->f['issuer'], $request); $account = $space['accounts']['data'][0]; $record = $service->save($this->f['issuer'], $request, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Conta preservada para linha arredondada a zero', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '0.00', 'total' => '0.00']]]); expect($record->data['allocations'][0]['total_minor'])->toBe('0') ->and($record->data['allocations'][0]['account']['code'])->toBe('QA-ONLY-100') ->and(DB::table('gl_journals')->count())->toBe(0); $request->update(['total_minor' => null]); expect($service->workspace($this->f['issuer'], $request)['canWrite'])->toBeFalse(); }); test('native office purchase reconciles declared accounts through receipt invoice and confirmed payment', function (bool $machinery, bool $withExpiry, bool $higherLimit = false) { if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') { expect($this->schemaComposition['migrations'])->toHaveCount(5) ->and($this->schemaComposition['verified_tables'])->toHaveCount(12) ->and(config('requisition-expiry.qa_enabled'))->toBeTrue(); } $tenant = $this->f['tenant']->id; $department = $this->f['department']->id; $staff = fn ($role) => User::factory()->create(['tenant_id' => $tenant, 'department_id' => $department, 'purchasing_role' => $role]); if ($higherLimit) { $this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]); } $owner = $staff(PurchasingRole::Requester); $buyer = $staff(PurchasingRole::Procurement); $independentBuyer = $staff(PurchasingRole::Procurement); $head = $staff(PurchasingRole::DepartmentHead); $finance = $staff(PurchasingRole::Finance); $reviewer = $staff(PurchasingRole::Finance); $category = $machinery ? 'Maquinaria QA' : 'Escritório QA'; $description = $machinery ? 'Maquinaria exclusivamente sintética' : 'Material de escritório de ensaio'; $direction = null; if ($machinery) { config(['capital-register.qa_enabled' => true, 'requisition_approval.qa_enabled' => true]); require_once __DIR__.'/../Support/InvestmentFixture.php'; publishInvestmentFixture($tenant, '100.00'); $admin = $staff(PurchasingRole::Admin); foreach (User::query()->where('tenant_id', $tenant)->get() as $person) { $nativeProfile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => 'QA function '.$person->id, 'permissions' => json_encode([$person->purchasing_role->value]), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]); DB::table('organization_memberships')->insert(['tenant_id' => $tenant, 'user_id' => $person->id, 'profile_id' => $nativeProfile, 'maintenance' => false]); } $direction = $staff(PurchasingRole::Configured); $profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => 'QA direction', 'permissions' => json_encode(['requisition_approve']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]); DB::table('organization_memberships')->insert(['tenant_id' => $tenant, 'user_id' => $direction->id, 'profile_id' => $profile, 'maintenance' => false]); DB::table('organization_access')->insert(['tenant_id' => $tenant, 'active' => true, 'version' => 1]); $this->actingAs($admin)->postJson('/administracao/parametrizacao/approval_levels', ['version' => 1, 'enabled' => true, 'reason' => 'Explicit synthetic direction designation for integrated machinery QA', 'levels' => [[ 'name' => 'QA direction', 'profile_ids' => [$profile], 'scope' => 'company', 'min_amount' => null, 'categories' => [], 'procurement_categories' => ['capital_equipment'], 'cost_center_ids' => []]]])->assertRedirect(); } if ($withExpiry) { $policyAuthor = $machinery ? $admin : $staff(PurchasingRole::Admin); $this->actingAs($policyAuthor); app(RequisitionExpiry::class)->savePolicy($policyAuthor, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement', 'finance', 'configured_1']), 'reason' => 'Explicitly synthetic expiry policy for the fully integrated purchase lifecycle']); } $this->actingAs($finance); $budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $this->f['r']->cost_center_id, 'year' => (int) now()->year, 'kind' => $machinery ? 'investment' : 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação sintética de ensaio: '.$category]); $this->actingAs($reviewer); app(CommonBudget::class)->for($reviewer)->approve($budget); $this->actingAs($owner)->postJson('/requisicoes', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Compra exclusivamente sintética: '.$category.', taxa ilustrativa zero sem regra fiscal real', 'items' => [['description' => $description, 'category' => $category, 'purchase_type' => $machinery ? 'equipment' : 'consumable', 'production_area' => $machinery ? 'Synthetic production line' : null, 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00', 'procurement_category' => $machinery ? 'capital_equipment' : 'office_equipment', 'category_reason' => 'Justificação exclusivamente sintética de aquisição: '.$category]]])->assertRedirect(); $request = Requisition::query()->where('requester_id', $owner->id)->sole(); $line = $request->items()->sole(); if ($machinery) { $this->actingAs($buyer); $asset = app(CapitalRegister::class)->save($buyer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'type' => 'asset', 'code' => 'MACHINERY-FLOW-QA', 'name' => 'Synthetic machinery destination', 'department_id' => $department, 'reference' => 'Synthetic acquisition only', 'state' => 'active', 'reason' => 'Explicit asset destination before synthetic acquisition']); $this->actingAs($owner); app(CapitalAssignments::class)->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line->id, 'capital_id' => $asset->id, 'reason' => 'Explicit synthetic machinery destination']); $this->actingAs($head); $technical = app(EquipmentWorkflow::class); $technical->review($head, $request, $technical->basis($request), 'approved', 'Independent technical check of synthetic machinery'); $this->actingAs($owner); } $space = app(RequisitionAccountAssignments::class)->workspace($owner, $request); $account = $space['accounts']['data'][0]; $this->postJson('/requisicoes/'.$request->id.'/contas', ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Conta do plano próprio escolhida antes da submissão', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]])->assertRedirect(); $submit = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version]; $this->postJson('/requisicoes/'.$request->id.'/submeter', $submit)->assertRedirect(); $this->postJson('/requisicoes/'.$request->id.'/submeter', $submit)->assertRedirect(); expect(array_key_exists('approval_expiry', $request->fresh()->approval_snapshot))->toBe($withExpiry); $this->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Tentativa própria sem competência'])->assertForbidden(); $this->actingAs($head)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Necessidade sintética conferida pela chefia distinta'])->assertRedirect(); if ($higherLimit) { expect($request->fresh()->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'procurement']); $this->actingAs($independentBuyer)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Independent procurement check of the synthetic request'])->assertRedirect(); } if ($machinery) { expect($request->fresh()->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'finance', 'configured_1']); foreach ([$finance, $direction] as $actor) { $this->actingAs($actor)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Independent synthetic machinery approval'])->assertRedirect(); } $this->actingAs($admin)->postJson('/administracao/parametrizacao/approval_levels', ['version' => 2, 'enabled' => false, 'levels' => [], 'reason' => 'Synthetic future policy change preserves already approved machinery route'])->assertRedirect(); } expect($request->fresh()->status)->toBe('approved'); $quotes = []; foreach ([100, 110, 120] as $index => $price) { $this->actingAs($buyer)->postJson('/fornecedores', ['name' => 'Fornecedor de escritório QA '.($index + 1), 'nuit' => (string) (200000001 + $index), 'contact' => 'Contacto sintético', 'email' => 'office-'.$index.'@example.invalid', 'phone' => '123456789', 'address' => 'Morada sintética', 'category' => $category, 'beneficiaries' => 'Beneficiário sintético', 'document_references' => 'Referências exclusivamente sintéticas', 'diligence_notes' => 'Diligência preparada no ensaio, sem fornecedor real', 'blocked' => false, 'next_review' => today()->addYear()->toDateString()])->assertRedirect(); $supplier = Supplier::query()->where('nuit', (string) (200000001 + $index))->sole(); $this->actingAs($finance)->postJson('/fornecedores/'.$supplier->id.'/validar', ['version' => $supplier->version, 'status' => 'active', 'comment' => 'Conferência financeira independente dos dados sintéticos'])->assertRedirect(); $this->actingAs($buyer)->postJson('/requisicoes/'.$request->id.'/cotacoes', ['currency' => 'MZN', 'supplier_id' => $supplier->id, 'reference' => 'OFFICE-QA-'.($index + 1), 'delivery_days' => 5, 'valid_until' => today()->addMonth()->toDateString(), 'payment_terms' => 'Condições sintéticas de trinta dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => $price.'.00', 'discount_type' => 'none', 'discount_value' => '0.00']]])->assertRedirect(); $quote = Quotation::query()->where('requisition_id', $request->id)->where('supplier_id', $supplier->id)->sole(); foreach ([$head, $reviewer] as $evaluator) { $this->actingAs($evaluator)->postJson('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '5', 'history' => '5', 'payment' => '5', 'comment' => 'Avaliação independente e exclusivamente sintética', 'no_conflict' => true])->assertRedirect(); } $quotes[] = $quote; } $comparison = app(ProposalComparison::class)->inspect($request->fresh()); expect($comparison['ready'])->toBeTrue()->and($comparison['top_ids'])->toBe([$quotes[0]->id]); $this->actingAs($buyer)->postJson('/requisicoes/'.$request->id.'/adjudicacao', ['quotation_id' => $quotes[0]->id, 'justification' => 'Escolha sintética da proposta com maior pontuação pelo circuito vigente', 'delivery_date' => today()->addWeek()->toDateString(), 'delivery_location' => 'Armazém de ensaio'])->assertRedirect(); $award = PurchaseAward::query()->where('requisition_id', $request->id)->sole(); $approvers = ['department_head' => $head, 'procurement' => $independentBuyer, 'finance' => $reviewer]; foreach ($award->approvals()->orderBy('position')->get() as $step) { if ($step->role === 'procurement') { $this->actingAs($buyer)->postJson('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved', 'comment' => 'Selector must not approve their own award, even with procurement authority'])->assertForbidden(); expect($award->fresh()->status)->toBe('pending'); } $this->actingAs($approvers[$step->role])->postJson('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved', 'comment' => 'Conferência sintética do valor final'])->assertRedirect(); } $this->actingAs($buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect(); $this->postJson('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect(); $order = PurchaseOrder::query()->where('purchase_award_id', $award->id)->sole(); expect($order->total_minor)->toBe(10000)->and($order->snapshot['account_assignments'][$line->id]['data']['allocations'][0]['account']['id'])->toBe($account['id']); $receiver = $this->f['receiver']; $this->actingAs($receiver); $stock = StockItem::query()->create(['tenant_id' => $tenant, 'created_by' => $receiver->id, 'code' => 'OFFICE-FLOW-QA', 'name' => $description, 'unit' => 'un']); $orderLine = $order->items()->sole(); $receiptInput = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'OFFICE-DELIVERY-QA', 'received_on' => today()->toDateString(), 'warehouse_id' => $this->f['warehouse']->id, 'items' => [['purchase_order_item_id' => $orderLine->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]; $receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptInput); expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptInput)->id)->toBe($receipt->id); if ($machinery) { $this->actingAs($admin)->postJson('/equipamentos/categorias', ['code' => 'FLOW-QA', 'name' => 'Synthetic criticality', 'criteria' => 'Synthetic machinery registration only', 'is_critical' => false])->assertRedirect(); $criticality = CriticalityLevel::query()->where('code', 'FLOW-QA')->sole(); $this->actingAs($buyer)->postJson('/equipamentos/activos', ['code' => 'MACHINERY-FLOW-QA', 'description' => 'Synthetic received machinery', 'area' => 'Synthetic production line', 'serial_number' => 'SYNTHETIC-ONLY', 'status' => 'active', 'department_id' => $department, 'stock_item_id' => $stock->id, 'criticality_level_id' => $criticality->id])->assertRedirect(); $equipment = Equipment::query()->where('code', 'MACHINERY-FLOW-QA')->sole(); $updatedAsset = app(CapitalRegister::class)->save($buyer, [...$asset->data, 'operation_key' => (string) Str::uuid(), 'record_key' => $asset->record_key, 'version' => 1, 'state' => 'active', 'equipment_id' => $equipment->id, 'reason' => 'Link the actual synthetic received machinery without changing original acquisition']); expect($updatedAsset->version)->toBe(2) ->and($order->fresh()->snapshot['capital_assignments'][$line->id]['snapshot']['source']['version'])->toBe(1) ->and($order->fresh()->snapshot['capital_assignments'][$line->id]['snapshot']['source']['data']['equipment_id'])->toBeNull(); $this->get('/equipamentos/'.$equipment->id)->assertOk()->assertInertia(fn (Assert $page) => $page ->where('capitalReference.record_key', $asset->record_key)->where('capitalReference.version', 2)); $this->get('/projectos-imobilizado?history='.$asset->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page ->where('trace.orders.data.0.order_number', $order->number)->where('trace.receipts.data.0.receipt_id', $receipt->id)); } $this->actingAs($finance); $invoice = app(InvoiceWorkflow::class)->register($finance, $order, ['number' => 'OFFICE-INVOICE-QA', 'issued_on' => today()->toDateString(), 'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00', 'items' => [['purchase_order_item_id' => $orderLine->id, 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]); $this->postJson('/facturas/'.$invoice->id.'/validar')->assertForbidden(); expect($invoice->fresh()->status)->toBe('pending'); $this->actingAs($reviewer); app(InvoiceWorkflow::class)->validate($reviewer, $invoice); $supplier = $quotes[0]->supplier; $this->actingAs($buyer); $bank = app(SupplierBankWorkflow::class)->propose($buyer, $supplier, ['account_key' => (string) Str::uuid(), 'previous_id' => 0, 'bank_name' => 'Banco estritamente sintético', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Titular sintético', 'account_identifier' => 'OFFICE-ACCOUNT-QA', 'evidence_reference' => 'Evidência bancária apenas para teste', 'reason' => 'Registo de conta fictícia para o ensaio']); foreach ([$finance, $reviewer] as $bankReviewer) { $this->actingAs($bankReviewer); app(SupplierBankWorkflow::class)->review($bankReviewer, $bank, 'approved', 'Conferência independente de evidência fictícia'); } config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'office-process-qa', 'expense-allocations.qa_enabled' => true]); foreach ([$finance, $reviewer] as $reader) { DB::table('pa_access')->insert(['tenant_id' => $tenant, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $reader->id, 'person' => 'office-qa-'.$reader->id, 'action' => 'view']); } $this->actingAs($finance); $payments = app(ExternalPaymentWorkflow::class); $paymentInput = ['supplier_bank_detail_id' => $bank->id, 'amount' => '40.00', 'paid_on' => today()->toDateString(), 'external_reference' => 'OFFICE-PAYMENT-QA', 'evidence_reference' => 'Evidência exclusivamente sintética de pagamento parcial']; $payment = $payments->register($finance, $invoice, $paymentInput); expect($payments->register($finance, $invoice, $paymentInput)->id)->toBe($payment->id); $this->postJson('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'independently_verified' => true, 'reason' => 'Tentativa própria de conferência no ensaio'])->assertForbidden(); expect($payment->fresh()->status)->toBe('pending'); $this->actingAs($reviewer); $allocations = app(ExpenseAllocations::class); expect(fn () => $allocations->source($reviewer, $payment->id))->toThrow(HttpException::class); $payments->review($reviewer, $payment, 'confirmed', 'Confirmação independente de pagamento externo fictício'); $this->actingAs($finance); expect(fn () => $payments->register($finance, $invoice, [...$paymentInput, 'external_reference' => 'OFFICE-OVERPAY-QA', 'amount' => '60.01'])) ->toThrow(ValidationException::class); $this->actingAs($reviewer); $source = $allocations->source($reviewer, $payment->id); $financialRows = []; foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'budget_consumptions', 'stock_movements', 'gl_journals', 'gl_lines', 'pa_commands'] as $table) { $financialRows[$table] = DB::table($table)->orderBy('id')->get()->toJson(); } $allocation = $allocations->save($reviewer, $payment->id, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'], 'reason' => 'Imputação expressa do pagamento pela função de Finanças', 'allocations' => [['category' => $category, 'amount' => '40.00']]]); $insights = app(ProcurementPaymentInsights::class)->build($reviewer, Requisition::query()->whereKey($request->id), null, null); $balance = app(CommonBudget::class)->for($reviewer)->balance($budget); expect($balance['reserved_minor'])->toBe(0)->and($balance['committed_minor'])->toBe(0) ->and($balance['consumed_minor'])->toBe(10000)->and($balance['available_minor'])->toBe(90000); expect($receipt->items()->sole()->accepted_milli)->toBe(1000)->and($invoice->fresh()->status)->toBe('validated') ->and($payment->fresh()->status)->toBe('confirmed')->and($payments->outstanding($invoice))->toBe(6000) ->and($allocation->data['allocations'])->toBe([['category' => $category, 'amount_minor' => '4000']]) ->and($insights['currencies'][0]['amount_minor'])->toBe('4000')->and($insights['category_attribution']['groups']['data'][0]['amount_minor'])->toBe('4000') ->and((int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000) ->and(DB::table('gl_journals')->count())->toBe(0); foreach ($financialRows as $table => $rows) { expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows); } $this->actingAs($finance); $finalPayment = $payments->register($finance, $invoice, [...$paymentInput, 'external_reference' => 'OFFICE-FINAL-PAYMENT-QA', 'amount' => '60.00']); $this->actingAs($reviewer); $payments->review($reviewer, $finalPayment, 'confirmed', 'Confirmação independente do saldo externo estritamente sintético'); $finalSource = $allocations->source($reviewer, $finalPayment->id); $allocations->save($reviewer, $finalPayment->id, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $finalSource['fingerprint'], 'reason' => 'Imputação explícita do pagamento final por Finanças', 'allocations' => [['category' => $category, 'amount' => '60.00']]]); $settled = app(ProcurementPaymentInsights::class)->build($reviewer, Requisition::query()->whereKey($request->id), null, null); $settledBudget = app(CommonBudget::class)->for($reviewer)->balance($budget); expect($payments->outstanding($invoice))->toBe(0)->and($settled['currencies'][0]['amount_minor'])->toBe('10000') ->and($settled['coverage']['confirmed_payments'])->toBe(2)->and($settled['category_attribution']['coverage']['allocated'])->toBe(2) ->and($settled['category_attribution']['groups']['data'][0]['amount_minor'])->toBe('10000') ->and($settledBudget)->toBe($balance)->and($allocation->fresh()->data['allocations'])->toBe([['category' => $category, 'amount_minor' => '4000']]) ->and((int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000); $this->actingAs($owner)->get('/requisicoes/'.$request->id.'/processo')->assertOk() ->assertInertia(fn (Assert $page) => $page->where('stages.7.state', 'restricted')->where('stages.8.state', 'restricted') ->missing('invoices')->missing('payments')->missing('bank_snapshot')); if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') { expect(DB::table('budget_requisition_cycles')->where('requisition_id', $request->id)->count())->toBe($withExpiry ? 1 : 0) ->and(DB::table('budget_order_commands')->count())->toBe(0) ->and(DB::table('budget_landed_entries')->count())->toBe(0) ->and(DB::table('budget_distribution_entries')->count())->toBe(0); } })->with(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1' ? ['office_without_expiry_policy' => [false, false], 'office_with_explicit_expiry_policy' => [false, true], 'machinery_without_expiry_policy' => [true, false], 'machinery_with_explicit_expiry_policy' => [true, true], 'office_with_independent_procurement' => [false, true, true]] : ['office' => [false, false], 'machinery' => [true, false]]); test('native submission requires account reference before reserve and approval', function () { $owner = $this->f['issuer']; $finance = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Finance]); $admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]); $head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]); $this->actingAs($finance); $budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $this->f['r']->cost_center_id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação exclusivamente sintética para submissão']); $this->actingAs($admin); app(CommonBudget::class)->for($admin)->approve($budget); $this->actingAs($owner); $request = app(RequisitionWorkflow::class)->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Pedido sintético de conferência da conta antes da reserva', 'items' => [['description' => 'Material sintético novo', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00', 'procurement_category' => 'other', 'category_reason' => 'Necessidade de texto livre fundamentada no ensaio']]]); $path = '/requisicoes/'.$request->id; $submit = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version]; $this->postJson($path.'/submeter', $submit)->assertUnprocessable()->assertJsonValidationErrors('account_assignment'); expect($request->fresh()->status)->toBe('draft')->and($request->steps()->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0); $space = app(RequisitionAccountAssignments::class)->workspace($owner, $request); $line = $space['items'][0]; $account = $space['accounts']['data'][0]; $this->postJson($path.'/contas', ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação explícita anterior à submissão', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]])->assertRedirect(); $this->postJson($path.'/submeter', $submit)->assertRedirect(); $this->postJson($path.'/submeter', $submit)->assertRedirect(); expect($request->fresh()->status)->toBe('pending')->and($request->steps()->count())->toBe(1) ->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(10000) ->and(DB::table('gl_journals')->count())->toBe(0); $this->actingAs($head)->postJson($path.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Decisão sintética pelo aprovador distinto'])->assertRedirect(); expect($request->fresh()->status)->toBe('approved'); });