commit compras1 2811
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-28 07:11:35 +02:00
parent d58b75c87a
commit eb32c74c56
202 changed files with 17463 additions and 1526 deletions
@@ -0,0 +1,52 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Compose already-authorised optional contracts only in the owned non-elevated ledger QA database. */
function integratedPurchasingQaSchema(): array
{
LedgerSchema::assertSynthetic(DB::connection());
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| DB::connection()->getConfig('port') !== '55439'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())) {
throw new LogicException('Integrated purchasing schema requires the dedicated owned QA composition.');
}
$migrations = [
'2026_11_22_000004_create_budget_distributions.php',
'2026_11_22_000007_create_budget_order_parts.php',
'2026_11_22_000008_create_purchase_order_sources.php',
'2026_11_22_000009_create_budget_landed_costs.php',
'2026_11_27_000001_add_requisition_cycles.php',
];
$tables = ['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions',
'budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions',
'purchase_order_sources', 'budget_landed_commands', 'budget_landed_entries', 'budget_requisition_cycles'];
foreach ($tables as $table) {
if (Schema::hasTable($table)) {
throw new LogicException('Never reinstall or repair a partial integrated QA schema implicitly.');
}
}
$columns = ['requisitions' => 'approval_cycle', 'approval_steps' => 'approval_cycle', 'budget_entries' => 'requisition_cycle',
'budget_distributions' => 'requisition_cycle', 'purchase_orders' => 'order_key'];
DB::transaction(function () use ($migrations, $tables, $columns) {
foreach ($migrations as $migration) {
(require base_path('database/qa-migrations/'.$migration))->up();
}
foreach ($tables as $table) {
if (! Schema::hasTable($table)) {
throw new LogicException('An integrated QA contract table was not created.');
}
}
foreach ($columns as $table => $column) {
if (! Schema::hasColumn($table, $column)) {
throw new LogicException('An integrated QA contract column was not created.');
}
}
});
config(['requisition-expiry.qa_enabled' => true]);
return ['migrations' => array_map(fn ($name) => ['name' => $name, 'sha256' => hash_file('sha256', base_path('database/qa-migrations/'.$name))], $migrations),
'verified_tables' => $tables, 'verified_columns' => $columns];
}
+3 -1
View File
@@ -36,11 +36,13 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return true;
}
if (in_array($mode, ['recover-cycles', 'recover-expenses'], true)) {
if (in_array($mode, ['recover-cycles', 'recover-expenses', 'recover-urgent'], true)) {
return $contains(fn ($row) => ($row['cycle_post_extension_all_tables_equal'] ?? false) === true
&& ($row['cycle_native_replays_without_effects'] ?? false) === true && ($row['cycle_history_and_reserve_restored'] ?? false) === true
&& ($row['cycle_reserved_minor'] ?? null) === 12000 && ($row['cycle_pre_extension_all_tables_equal'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true)
&& ($mode !== 'recover-urgent' || $contains(fn ($row) => ($row['urgent_policy_frozen_restored'] ?? false) === true
&& ($row['urgent_expire_seconds_restored'] ?? null) === 300))
&& ($mode !== 'recover-expenses' || $contains(fn ($row) => ($row['expense_versions_restored'] ?? null) === 2
&& ($row['expense_native_sources_verified'] ?? false) === true && ($row['expense_replay_without_effects'] ?? false) === true
&& ($row['expense_explicit_amounts_restored'] ?? null) === ['Material' => '1000', 'Serviços' => '3000']));
@@ -0,0 +1,80 @@
<?php
use App\Models\ExternalPayment;
use App\Models\GoodsReceipt;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrder;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\StockItem;
use App\Models\User;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPaymentInsights;
use Illuminate\Support\Facades\DB;
/** Assertion-only projection; every business mutation in the office journey must use native HTTP. */
function nativeOfficePurchaseState(array $fixture): array
{
$office = $fixture['office_journey'] ?? null;
if (! app()->environment('testing') || getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1' || ! is_array($office)
|| DB::transactionLevel() !== 1 || DB::selectOne('SHOW transaction_read_only')->transaction_read_only !== 'on') {
throw new LogicException('Owned office journey assertions require a top-level read-only transaction.');
}
$tenant = $fixture['tenant_id'];
$actor = User::query()->where('tenant_id', $tenant)->findOrFail($office['actors']['reviewer']['id']);
auth()->guard()->setUser($actor);
config(['common-payables.enabled' => true, 'common-payables.source_instance' => $office['source_instance'], 'expense-allocations.qa_enabled' => true]);
$requests = Requisition::query()->where('requester_id', $office['actors']['owner']['id'])->get();
if ($requests->count() > 1) {
throw new LogicException('The dedicated HTTP requester has more than one synthetic source.');
}
$request = $requests->first();
$budget = DB::table('budgets')->where('tenant_id', $tenant)->where('cost_center_id', $office['cost_center_id'])->where('kind', 'operating')->first();
$quotes = $request ? Quotation::query()->where('requisition_id', $request->id)->orderBy('id')->get() : collect();
$award = $request ? PurchaseAward::query()->where('requisition_id', $request->id)->first() : null;
$order = $award ? PurchaseOrder::query()->where('purchase_award_id', $award->id)->first() : null;
$invoice = $order ? Invoice::query()->where('purchase_order_id', $order->id)->first() : null;
$payments = $invoice ? ExternalPayment::query()->where('invoice_id', $invoice->id)->orderBy('id')->get() : collect();
$stock = StockItem::query()->where('code', 'HTTP-OFFICE-QA')->first();
$bank = $order ? DB::table('supplier_bank_details')->where('tenant_id', $tenant)->where('supplier_id', $order->supplier_id)->orderByDesc('id')->first(['id', 'revision']) : null;
$frames = [];
foreach (DB::select("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename") as $table) {
$name = $table->tablename;
if ($name !== 'budgets' && ! str_starts_with($name, 'budget_') && ! str_starts_with($name, 'gl_') && ! str_starts_with($name, 'pa_')
&& ! in_array($name, ['purchase_orders', 'purchase_order_items', 'purchase_order_sources', 'invoices', 'invoice_items', 'external_payments', 'stock_movements'], true)) {
continue;
}
$quoted = str_replace('"', '""', $name);
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.$quoted.'" t ORDER BY row_to_json(t)::text');
$frames[$name] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($name), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
}
$analytics = $request && $payments->where('status', 'confirmed')->isNotEmpty()
? app(ProcurementPaymentInsights::class)->build($actor, Requisition::query()->whereKey($request->id), null, null) : null;
return [
'budget' => $budget ? ['id' => $budget->id, 'created_by' => $budget->created_by, 'approved_by' => $budget->approved_by] : null,
'request' => $request ? ['id' => $request->id, 'status' => $request->status, 'process_version' => $request->process_version,
'approval_cycle' => $request->approval_cycle, 'total_minor' => $request->total_minor,
'items' => $request->items()->orderBy('id')->get(['id', 'category'])->toArray(),
'steps' => $request->steps()->orderBy('position')->get(['id', 'role', 'decision'])->toArray()] : null,
'suppliers' => DB::table('suppliers')->where('tenant_id', $tenant)->whereIn('nuit', ['300000001', '300000002', '300000003'])
->orderBy('id')->get(['id', 'nuit', 'version'])->map(fn ($row) => (array) $row)->all(),
'quotes' => $quotes->map(fn ($quote) => ['id' => $quote->id, 'supplier_id' => $quote->supplier_id, 'total_minor' => $quote->total_minor])->all(),
'award' => $award ? ['id' => $award->id, 'status' => $award->status,
'steps' => $award->approvals()->orderBy('position')->get(['id', 'role', 'decision'])->toArray()] : null,
'order' => $order ? ['id' => $order->id, 'total_minor' => $order->total_minor,
'items' => $order->items()->orderBy('id')->get(['id', 'quantity'])->toArray(),
'account_assignments' => $order->snapshot['account_assignments'] ?? null,
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->orderBy('id')->get(['id', 'status'])->toArray()] : null,
'stock' => $stock ? ['id' => $stock->id, 'quantity_milli' => (int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'),
'movements' => DB::table('stock_movements')->where('stock_item_id', $stock->id)->count()] : null,
'invoice' => $invoice ? ['id' => $invoice->id, 'status' => $invoice->status, 'total_minor' => $invoice->total_minor,
'outstanding_minor' => app(ExternalPaymentWorkflow::class)->outstanding($invoice)] : null,
'bank' => $bank ? ['id' => $bank->id, 'revision' => $bank->revision,
'approved_reviews' => DB::table('supplier_bank_reviews')->where('supplier_bank_detail_id', $bank->id)->where('decision', 'approved')->count()] : null,
'payments' => $payments->map(fn ($payment) => ['id' => $payment->id, 'amount_minor' => $payment->amount_minor, 'status' => $payment->status])->all(),
'analytics' => $analytics === null ? null : array_intersect_key($analytics, array_flip(['currencies', 'coverage', 'category_attribution'])),
'journals' => DB::table('gl_journals')->count(), 'financial_fingerprint' => hash('sha256', json_encode($frames, JSON_THROW_ON_ERROR)),
];
}
@@ -0,0 +1,259 @@
<?php
use App\Enums\PurchasingRole;
use App\Http\Controllers\AuditMetadataController;
use App\Models\CostCenter;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\UrgentRequisitionReviews;
use App\Services\WarehouseFulfilment;
use App\Services\WarehouseRequests;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Strictly guarded native synthetic composition; no real identities, source data or grants. */
function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $officeJourney = false): array
{
LedgerSchema::install(DB::connection());
$composition = null;
if ($integrated) {
require_once __DIR__.'/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
} else {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
$f = receiptFixture();
$f['tenant']->update(['name' => 'QA isolada de Compras — contas e urgências']);
config(['requisition-expiry.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true,
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
'procurement_search.warehouse_requests_metadata_enabled' => true]);
$people = [];
$profiles = [];
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
if ($officeJourney) {
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
'office_procurement_reviewer' => ['procurement']];
}
foreach ($functions as $key => $permissions) {
$people[$key] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'purchasing_role' => PurchasingRole::Configured, 'name' => 'QA '.$key, 'email' => 'qa-'.$key.'@example.invalid']);
$profiles[$key] = DB::table('organization_profiles')->insertGetId(['tenant_id' => $f['tenant']->id, 'name' => 'QA '.$key,
'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $f['tenant']->id, 'user_id' => $people[$key]->id,
'profile_id' => $profiles[$key], 'maintenance' => false]);
}
DB::table('organization_access')->insert(['tenant_id' => $f['tenant']->id, 'active' => true, 'version' => 1]);
foreach (['QA-100' => 'Materiais de ensaio', 'QA-200' => 'Outras necessidades de ensaio'] as $code => $label) {
DB::table('gl_accounts')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true]);
}
auth()->guard()->setUser($people['finance']);
$budget = app(CommonBudget::class)->for($people['finance'])->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação inteiramente fictícia da revisão nativa isolada']);
auth()->guard()->setUser($people['reviewer']);
app(CommonBudget::class)->for($people['reviewer'])->approve($budget);
app(PurchaseControlPolicyWorkflow::class)->propose($people['reviewer'], ['previous_id' => 0, 'mode' => 'unissued_award',
'enabled' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'reason' => 'Proposta exclusivamente sintética e desactivada para conferir o isolamento de consulta; sem aprovação ou publicação']);
app(RequisitionExpiry::class)->savePolicy($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => [],
'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => null]],
'reason' => 'Prazos explicitamente sintéticos para revisão de apresentação e gravação']);
app(UrgentRequisitionReviews::class)->savePolicy($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
'enabled' => true, 'profile_ids' => [$profiles['reviewer']], 'reason' => 'Designação de identidade inteiramente sintética para a revisão nativa']);
$workflow = app(RequisitionWorkflow::class);
$make = function (User $owner, string $priority, string $description, string $price = '100.00') use ($f, $workflow): array {
auth()->guard()->setUser($owner);
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => $priority,
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Dados inteiramente sintéticos para conferência local do percurso de Compras',
'items' => [['description' => $description, 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un',
'unit_price' => $price, 'tax_rate' => '0.00', 'procurement_category' => 'other', 'category_reason' => 'Texto livre exclusivamente sintético para ensaio de apresentação']]];
return [$workflow->save($owner, $input), $input];
};
$assign = function (User $owner, $request): void {
auth()->guard()->setUser($owner);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($owner, $request);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
$service->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'],
'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação fictícia confirmada antes da submissão nativa',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
'subtotal' => (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2),
'total' => (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2)]]]);
};
[$draft] = $make($people['reviewer'], 'normal', 'Material para conferir a atribuição de contas');
[$approved] = $make($people['requester'], 'urgent', 'Urgência sintética aprovada');
$assign($people['requester'], $approved);
$workflow->submit($people['requester'], $approved, (string) Str::uuid(), $approved->process_version);
$approved->refresh();
auth()->guard()->setUser($people['head']);
$workflow->decide($people['head'], $approved, 'approved', 'Decisão fictícia pelo aprovador independente', (string) Str::uuid(), $approved->process_version);
[$expired, $revision] = $make($people['requester'], 'urgent', 'Urgência original que será expirada');
$assign($people['requester'], $expired);
$workflow->submit($people['requester'], $expired, (string) Str::uuid(), $expired->process_version);
$expired->refresh();
// Fixed synthetic clock keeps this native visual fixture stable across requests.
CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(6));
Carbon::setTestNow(CarbonImmutable::now());
$deadline = app(RequisitionExpiry::class)->deadline($expired);
$workflow->expire($people['requester'], $expired, $deadline['basis_hash'], (string) Str::uuid(), $expired->process_version);
$expired->refresh();
$revision['operation_key'] = (string) Str::uuid();
$revision['process_version'] = $expired->process_version;
$revision['priority'] = 'normal';
$revision['items'][0]['description'] = 'Nova preparação depois da expiração — 120 MZN';
$revision['items'][0]['unit_price'] = '120.00';
$expired = $workflow->save($people['requester'], $revision, $expired);
$assign($people['requester'], $expired);
$workflow->submit($people['requester'], $expired, (string) Str::uuid(), $expired->process_version);
// Separate normal-cycle example: a real first decision remains visible after the second level expires.
auth()->guard()->setUser($people['reviewer']);
$f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
app(RequisitionExpiry::class)->savePolicy($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 1, 'enabled' => true,
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => 10,
'escalation_minutes' => null, 'profile_ids' => [], 'urgent_expire_minutes' => 5,
'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => null], ['department_head', 'procurement']),
'reason' => 'Configuração exclusivamente sintética para conferir autoria e documento dos ciclos anteriores']);
[$historyRequest, $historyInput] = $make($people['requester'], 'normal', 'Documento original do ciclo — 100 MZN');
$assign($people['requester'], $historyRequest);
$workflow->submit($people['requester'], $historyRequest, (string) Str::uuid(), $historyRequest->process_version);
auth()->guard()->setUser($people['head']);
$workflow->decide($people['head'], $historyRequest->fresh(), 'approved', 'Fundamento original da chefia — conferência inteiramente sintética',
(string) Str::uuid(), $historyRequest->fresh()->process_version);
CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(31));
Carbon::setTestNow(CarbonImmutable::now());
auth()->guard()->setUser($people['requester']);
$historyRequest->refresh();
$deadline = app(RequisitionExpiry::class)->deadline($historyRequest);
$workflow->expire($people['requester'], $historyRequest, $deadline['basis_hash'], (string) Str::uuid(), $historyRequest->process_version);
$historyInput['operation_key'] = (string) Str::uuid();
$historyInput['process_version'] = $historyRequest->fresh()->process_version;
$historyInput['items'][0]['description'] = 'Documento da nova submissão — 120 MZN';
$historyInput['items'][0]['unit_price'] = '120.00';
$historyRequest = $workflow->save($people['requester'], $historyInput, $historyRequest->fresh());
$assign($people['requester'], $historyRequest);
$workflow->submit($people['requester'], $historyRequest, (string) Str::uuid(), $historyRequest->process_version);
[$pending] = $make($people['requester'], 'urgent', 'Urgência para conferir os prazos próprios');
$assign($people['requester'], $pending);
$workflow->submit($people['requester'], $pending, (string) Str::uuid(), $pending->process_version);
require_once __DIR__.'/SupplyFixture.php';
auth()->guard()->setUser($people['reviewer']);
$planning = app(SupplyPlanning::class);
$agreement = $planning->save($people['reviewer'], 'agreement', supplyInput([
'stock_item_id' => $f['stock']->id, 'warehouse_id' => $f['warehouse']->id, 'supplier_id' => $f['order']->supplier_id,
'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'QA-VISUAL-AGREEMENT']));
$contract = $planning->save($people['reviewer'], 'contract', supplyInput([
'supplier_id' => $f['order']->supplier_id, 'reference' => 'QA-VISUAL-CONTRACT', 'currency' => 'MZN',
'valid_from' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString(),
'periodicity_days' => 30, 'order_limit_amount' => '100.00', 'lead_days' => 3]));
auth()->guard()->setUser($people['head']);
$agreement = $planning->save($people['head'], 'agreement', supplyInput([], 'approve', $agreement));
$contract = $planning->save($people['head'], 'contract', supplyInput([], 'approve', $contract));
auth()->guard()->setUser($people['reviewer']);
$internal = app(WarehouseRequests::class)->draft($people['reviewer'], ['operation_key' => (string) Str::uuid(),
'warehouse_id' => $f['warehouse']->id, 'cost_center_id' => $f['r']->cost_center_id,
'destination' => 'QA-VISUAL-INTERNAL — destino exclusivamente sintético', 'reason' => 'Ensaio de pesquisa e leitura sem entrega física', 'priority' => 'normal',
'lines' => [['stock_item_id' => $f['stock']->id, 'quantity' => '1.000', 'use' => 'internal', 'equipment_id' => null]]]);
$fulfilment = app(WarehouseFulfilment::class);
$fulfilment->command($people['reviewer'], $internal->id, ['operation_key' => (string) Str::uuid(),
'version' => $fulfilment->progress($internal)['version'], 'action' => 'submit', 'reason' => 'Pedido sintético para conferir a projecção da pesquisa']);
if ($agreement->state !== 'approved' || $contract->state !== 'approved' || $fulfilment->progress($internal)['state'] !== 'submitted') {
throw new LogicException('Native search review fixture did not reach its required states.');
}
$historical = app(RequisitionExpiry::class)->workspace($people['reviewer'], $historyRequest->fresh());
$frozen = $historical['history']->getCollection()->first();
if ($frozen['request']['total_minor'] !== 10000 || $frozen['approval_amount_minor'] !== 10000
|| $frozen['steps'][0]['approver_id'] !== $people['head']->id || $frozen['rules']['first_limit_minor'] !== 5000
|| $historyRequest->fresh()->total_minor !== 12000 || $historical['canExpire']) {
throw new LogicException('Native historical decision fixture did not preserve its original document and independent new cycle.');
}
if (DB::transactionLevel() !== 0) {
throw new LogicException('Audit native review requires top-level native readonly transactions.');
}
$readonlyTransactions = 0;
DB::listen(function ($query) use (&$readonlyTransactions) {
if (str_starts_with($query->sql, 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY')
&& DB::selectOne('SHOW transaction_read_only')->transaction_read_only === 'on') {
$readonlyTransactions++;
}
});
$auditReadBefore = [];
foreach (['audit_logs', 'requisitions', 'approval_steps', 'supply_records', 'budget_entries', 'stock_movements', 'users', 'organization_profiles', 'organization_memberships'] as $table) {
$auditReadBefore[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
foreach (['reviewer' => true, 'auditor' => false] as $key => $canOpen) {
auth()->guard()->setUser($people[$key]);
$query = Request::create('/auditoria/eventos', 'GET', ['request_reference' => $historyRequest->number]);
$query->setUserResolver(fn () => $people[$key]);
$query->headers->set('X-Inertia', 'true');
$response = app(AuditMetadataController::class)->index($query);
$page = json_decode($response->getContent(), true, 64, JSON_THROW_ON_ERROR);
if (($page['props']['requestContext'] !== null) !== $canOpen || $page['props']['events']['total'] < 1) {
throw new LogicException('Audit metadata and native process scope were not kept independent.');
}
foreach ($page['props']['events']['data'] as $event) {
if (array_keys($event) !== ['id', 'created_at', 'action', 'user_id']) {
throw new LogicException('Audit metadata review exposed fields outside its native scope.');
}
}
}
$csvQuery = Request::create('/auditoria/eventos.csv', 'GET', ['request_reference' => $historyRequest->number]);
$csvQuery->setUserResolver(fn () => $people['auditor']);
ob_start();
try {
app(AuditMetadataController::class)->csv($csvQuery)->sendContent();
$csv = ob_get_contents();
} finally {
ob_end_clean();
}
if (! is_string($csv) || ! str_contains($csv, $historyRequest->number) || $readonlyTransactions !== 3 || DB::transactionLevel() !== 0) {
throw new LogicException('Native audit page/CSV did not complete three readonly transactions.');
}
foreach ($auditReadBefore as $table => $rows) {
if (DB::table($table)->orderBy('id')->get()->toJson() !== $rows) {
throw new LogicException('Native audit consultation changed its source rows.');
}
}
auth()->guard()->setUser($people['reviewer']);
$office = null;
if ($officeJourney) {
$centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'code' => 'HTTP-OFFICE-QA', 'name' => 'Centro exclusivamente sintético do percurso HTTP']);
foreach ([$people['finance'], $people['office_finance_reviewer']] as $reader) {
DB::table('pa_access')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $reader->id, 'person' => 'http-office-qa-'.$reader->id, 'action' => 'view']);
}
$office = ['cost_center_id' => $centre->id, 'warehouse_id' => $f['warehouse']->id, 'category' => 'Escritório QA HTTP',
'source_instance' => 'native-http-office-qa', 'actors' => []];
foreach (['owner' => 'office_requester', 'buyer' => 'reviewer', 'head' => 'head', 'finance' => 'finance',
'reviewer' => 'office_finance_reviewer', 'warehouse' => 'office_warehouse', 'procurement_reviewer' => 'office_procurement_reviewer'] as $function => $key) {
$office['actors'][$function] = ['id' => $people[$key]->id, 'email' => $people[$key]->email];
}
}
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
'office_journey' => $office,
'integrated_optional_schema' => $composition,
'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
'audit_request_reference' => $historyRequest->number, 'audit_native_readonly_transactions' => $readonlyTransactions,
'search_agreement' => $agreement->id, 'search_contract' => $contract->id, 'warehouse_search_request' => $internal->id,
'historical_decision_request' => $historyRequest->id, 'historical_decision_verified' => true,
'draft_request' => $draft->id, 'approved_request' => $approved->id, 'expired_request' => $expired->id,
'urgent_pending_request' => $pending->id, 'clock' => CarbonImmutable::now()->toIso8601String(), 'synthetic_only' => true];
}
@@ -0,0 +1,48 @@
<?php
use Illuminate\Support\Facades\DB;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Composition\Bundle;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\Payables\PayablesSchema;
/** Only the canonical QA source or the exact verified private runtime is accepted. */
function requisitionLedgerQaSource(): ?string
{
$source = getenv('RQ01_LEDGER_QA_SOURCE');
if (! is_string($source) || $source === '') {
return null;
}
if ($source === 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
if (config('common-finance-bundle.manifest_sha256') === '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df') {
throw new LogicException('A pinned private composition cannot fall back to the canonical development source.');
}
return $source;
}
$root = base_path('storage/framework/testing/requisition-ledger-runtime-qa-182e10ceec556e12');
$pin = '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df';
$normal = static fn ($value) => is_string($value) && realpath($value) !== false ? str_replace('\\', '/', realpath($value)) : null;
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| DB::connection()->getConfig('port') !== '55439'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())
|| $normal($source) !== $normal($root.'/general-ledger')
|| $normal(config('common-finance-bundle.root')) !== $normal($root)
|| config('common-finance-bundle.manifest_sha256') !== $pin
|| $normal(config('general-ledger.path')) !== $normal($source)) {
throw new LogicException('Only the pinned independently verified private ledger runtime is allowed.');
}
// AppServiceProvider already verified the pinned loader before loading Bundle or Payables.
Bundle::verify($root, $pin);
require_once $source.'/bootstrap.php';
foreach ([LedgerSchema::class => $root.'/general-ledger',
BudgetControl::class => base_path('storage/framework/testing/requisition-cycles-qa-35701ec1614f871e/budget-control'),
PayablesSchema::class => $root.'/payables'] as $class => $boundary) {
$file = (new ReflectionClass($class))->getFileName();
if (! is_string($file) || ! str_starts_with($normal($file) ?? '', ($normal($boundary) ?? 'unavailable').'/')) {
throw new LogicException('A financial class escaped the pinned private composition.');
}
}
return $source;
}
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { test } from 'node:test';
import { createNativeInertiaClient } from '../../scripts/lib/native-inertia-client.mjs';
test('owned native client drains large closed responses while preserving body headers cookies and manual redirects', async () => {
const payload = { synthetic_only: true, content: 'x'.repeat(2 * 1024 * 1024) };
let cookiesSeen = '';
const server = createServer((request, response) => {
response.setHeader('Connection', 'close');
if (request.url === '/cookies') {
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
}
if (request.url === '/empty') { response.writeHead(204); response.end(); return; }
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
cookiesSeen = request.headers.cookie ?? '';
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(payload));
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
const origin = `http://127.0.0.1:${server.address().port}`;
const client = createNativeInertiaClient(origin, assert.ok);
// Deliberately leave the returned body unread, matching status/header-only checks.
const first = await client.request('/large');
assert.equal(first.status, 200);
assert.equal(first.bodyUsed, false);
assert.equal(first.url, origin + '/large');
await client.request('/cookies');
const next = await client.request('/large');
assert.match(cookiesSeen, /QA_SESSION=first/);
assert.match(cookiesSeen, /QA_CONTEXT=second/);
assert.deepEqual(await next.json(), payload);
assert.equal(first.headers.get('Content-Type'), 'application/json');
assert.deepEqual(await first.json(), payload);
const empty = await client.request('/empty');
assert.equal(empty.status, 204);
assert.equal(await empty.text(), '');
const redirect = await client.request('/redirect');
assert.equal(redirect.status, 302);
assert.equal(redirect.headers.get('Location'), '/large');
assert.equal(await redirect.text(), 'Synthetic redirect');
await assert.rejects(client.request('//example.test/foreign'), /External HTTP destination refused/);
} finally {
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
}
});
@@ -0,0 +1,47 @@
<?php
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
$root = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$database = getenv('DB_DATABASE') ?: '';
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
if (getenv('APP_ENV') !== 'testing' || getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $database, $matches)
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_REQUISITION_QA_PORT')
|| $root === false || $boundary === false || str_replace('\\', '/', $root) !== str_replace('\\', '/', $boundary).'/rq01-ledger-qa-'.$matches[1]) {
http_response_code(503);
exit;
}
require __DIR__.'/../../vendor/autoload.php';
$public = $root.'/public';
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$asset = realpath($public.'/'.ltrim(rawurldecode($requestPath), '/'));
$types = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
&& isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
readfile($asset);
exit;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->useStoragePath($root.'/storage');
$app->usePublicPath($root.'/public');
$app->booted(function () use ($root, $database) {
abort_unless(config('database.default') === 'pgsql' && config('database.connections.pgsql.database') === $database, 503);
$fixture = json_decode(file_get_contents($root.'/native-review.json'), true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($fixture['clock']);
CarbonImmutable::setTestNow($fixture['clock']);
config(['requisition-expiry.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true,
'order_cancellation.enabled' => true,
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
'procurement_search.warehouse_requests_metadata_enabled' => true,
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
'session.secure' => false, 'cache.default' => 'array']);
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1') {
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'native-http-office-qa',
'expense-allocations.qa_enabled' => true]);
}
});
$app->handleRequest(Request::capture());