Files
Investidor-V2/tools/opportunity-resources-qa.php
T
nala 6ddafc95ba
tests / ci (push) Canceled after 0s
oportunidades 4
2026-10-10 07:03:59 +02:00

122 lines
8.3 KiB
PHP

<?php
use App\Models\User;
use App\Services\OpportunityResourceInstallation;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Vite;
$root = dirname(__DIR__);
require_once $root.'/tools/portal-qa-environment.php';
$dir = $root.'/storage/app/private/investmoz-v2';
$backup = json_decode(file_get_contents($dir.'/opportunity-resources-backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
$target = $backup['restored_target'];
if (! $backup['restore_verified'] || ! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $target['database']) || (int) $target['port'] !== 55441) {
throw new RuntimeException('QA target required');
}
$target = portalQaEnvironment('file');
require $root.'/vendor/autoload.php';
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
config(['investor-path.enabled' => true]);
config(['geometry-import.enabled' => true]);
$identity = portalQaAssertTarget($target);
config(['portal.qa_synthetic_accounts_only' => true]);
require_once $root.'/tools/portal-qa-account-selection.php';
// Only expose the non-secret identity; passwords, TOTP secrets and recovery codes remain private.
\Laravel\Fortify\Fortify::loginView(fn (Request $request) => \Inertia\Inertia::render('auth/login', [
'canResetPassword' => \Laravel\Fortify\Features::enabled(\Laravel\Fortify\Features::resetPasswords()),
'status' => $request->session()->get('status'),
'qaAccount' => ['id' => 18, 'email' => User::findOrFail(18)->email],
]));
\Laravel\Fortify\Fortify::twoFactorChallengeView(function (Request $request) {
$actor = User::findOrFail($request->session()->get('login.id'));
return \Inertia\Inertia::render('auth/two-factor-challenge', ['qaAccount' => ['id' => $actor->id, 'email' => $actor->email]]);
});
config(['portal.managers' => ['opportunity-manager@example.invalid', 'geo-manager-qa@example.invalid'], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
$sessions = $dir.'/qa-opportunity-resources-sessions';
if (! is_dir($sessions)) {
mkdir($sessions, 0700, true);
}
config(['session.files' => $sessions]);
Vite::useHotFile($root.'/storage/framework/qa-opportunity-resources-hot-absent');
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'prepare') {
$migration = require $root.'/database/migrations/'.OpportunityResourceInstallation::MIGRATION.'.php';
$migration->up();
$oldColumns = array_keys((array) DB::selectOne('SELECT * FROM opportunities LIMIT 1'));
$oldColumns = array_diff($oldColumns, []);
$projection = implode(',', array_map(fn ($column) => '"'.$column.'"', $oldColumns));
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM (SELECT '.$projection.' FROM opportunities) t ORDER BY row_to_json(t)::text');
if (hash('sha256', implode("\n", array_column($rows, 'row'))) !== $backup['table_hashes']['"public"."opportunities"']) {
throw new RuntimeException('Existing opportunity values changed');
}
$migration->down();
foreach ($backup['table_hashes'] as $table => $hash) {
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM '.$table.' t ORDER BY row_to_json(t)::text');
if (hash('sha256', implode("\n", array_column($rows, 'row'))) !== $hash) {
throw new RuntimeException('Restore/rollback comparison failed: '.$table);
}
}
Artisan::call('migrate', ['--path' => 'database/migrations/'.OpportunityResourceInstallation::MIGRATION.'.php', '--force' => true]);
$user = User::updateOrCreate(['email' => 'opportunity-manager@example.invalid'], ['name' => 'QA opportunity manager', 'password' => Hash::make('Opportunity-QA-2026!')]);
$user->forceFill(['email_verified_at' => now()])->save();
$proof = ['target' => $target, 'code_hash' => app(OpportunityResourceInstallation::class)->fingerprint(), 'compatibility_verified' => true, 'reversal_verified' => true, 'tables_compared' => count($backup['table_hashes']), 'active_writes' => 0];
file_put_contents($dir.'/opportunity-resources-compatibility.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($proof).PHP_EOL;
exit;
}
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'verify') {
$columns = array_diff(array_keys((array) DB::selectOne('SELECT * FROM opportunities LIMIT 1')), []);
$projection = implode(',', array_map(fn ($column) => '"'.$column.'"', $columns));
$checks = [];
foreach (['opportunities', 'opportunity_projects', 'opportunity_clusters', 'opportunity_locations', 'geo_locations', 'documents', 'opportunity_favourites', 'interest_requests', 'interest_submission_receipts', 'investment_messages', 'tasks', 'project_locations', 'cluster_projects', 'audit_events'] as $table) {
$key = '"public"."'.$table.'"';
$query = $table === 'opportunities' ? '(SELECT '.$projection.' FROM opportunities WHERE management_creation_key IS NULL)' : ($table === 'audit_events' ? "(SELECT * FROM audit_events WHERE source_system IS DISTINCT FROM 'opportunity-resources' AND source_system IS DISTINCT FROM 'opportunity-management')" : $key);
if ($table === 'audit_events' && isset($backup['audit_event_ids'])) {
// Compare every original event by identity; new QA actions must not hide or replace history.
$originalIds = array_map(fn ($id) => DB::connection()->getPdo()->quote($id), $backup['audit_event_ids']);
$query = '(SELECT * FROM audit_events WHERE id IN ('.($originalIds ? implode(',', $originalIds) : 'NULL').'))';
}
if ($table === 'documents') {
$oldDocumentColumns = array_diff(array_keys((array) DB::selectOne('SELECT * FROM documents LIMIT 1')), ['storage_encryption']);
$documentProjection = implode(',', array_map(fn ($column) => '"'.$column.'"', $oldDocumentColumns));
$query = '(SELECT '.$documentProjection." FROM documents WHERE source_system NOT IN ('opportunity-resources','opportunity-image-derivatives'))";
}
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM '.$query.' t ORDER BY row_to_json(t)::text');
$checks[$table] = hash('sha256', implode("\n", array_column($rows, 'row'))) === $backup['table_hashes'][$key];
if (! $checks[$table]) {
throw new RuntimeException('Baseline data changed: '.$table);
}
}
$browser = json_decode(file_get_contents($dir.'/opportunity-resources-browser.json'), true, 512, JSON_THROW_ON_ERROR);
$draft = DB::table('opportunities')->where('id', $browser['id'])->first();
if ($draft->status !== 'draft' || $draft->deleted_at !== null) {
throw new RuntimeException('Browser cycle not restored');
}
$proof = ['target' => $target, 'code_hash' => app(OpportunityResourceInstallation::class)->fingerprint(), 'preserved' => $checks, 'browser_draft_id' => $draft->id, 'browser_draft_restored' => true, 'origin_classifications' => DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->count(), 'active_writes' => 0];
file_put_contents($dir.'/opportunity-resources-preservation.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($proof).PHP_EOL;
exit;
}
$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
$asset = realpath($root.'/public'.$path);
$public = realpath($root.'/public');
if ($path !== '/' && $asset && $public && str_starts_with($asset, $public.DIRECTORY_SEPARATOR) && is_file($asset)) {
return false;
}
header('X-Investmoz-QA-Target: '.$identity->database.':'.$identity->port);
header('X-Investmoz-QA-Key-Fingerprint: '.hash('sha256', app('encrypter')->getKey()));
header('X-Investmoz-QA-Config-Cache: bypassed');
require_once $root.'/tools/portal-qa-auth-trace.php';
$httpKernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
$httpKernel->prependMiddleware(PortalQaAuthTrace::class);
$httpKernel->appendMiddlewareToGroup('web', PortalQaSessionTrace::class);
$httpKernel->addToMiddlewarePriorityAfter(\Illuminate\Session\Middleware\StartSession::class, PortalQaSessionTrace::class);
$httpKernel->appendMiddlewareToGroup('web', PortalQaAccountSelection::class);
$httpKernel->addToMiddlewarePriorityAfter(PortalQaSessionTrace::class, PortalQaAccountSelection::class);
$app->handleRequest(Request::capture());