feat: integrate opportunity draft management with audited lifecycle
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
// Protected active reader only; no application kernel or migrations.
|
||||
require __DIR__.'/investmoz-v2-territory-audit.php';
|
||||
$dir = dirname(__DIR__).'/storage/app/private/investmoz-v2';
|
||||
$pdo->exec('BEGIN TRANSACTION READ ONLY');
|
||||
$identity = $pdo->query("SELECT current_database() AS database,inet_server_port() AS port,current_setting('transaction_read_only') AS read_only")->fetch(PDO::FETCH_ASSOC);
|
||||
$installed = (bool) $pdo->query("SELECT EXISTS(SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name='opportunities' AND column_name='management_version')")->fetchColumn();
|
||||
$migrationApplied = (int) $pdo->query("SELECT count(*) FROM migrations WHERE migration='2026_10_09_020000_extend_opportunity_management'")->fetchColumn();
|
||||
$classifications = $pdo->query("SELECT DISTINCT ON (after_data->>'opportunity_id') after_data->>'opportunity_id' AS id,after_data->>'classification' AS classification FROM audit_events WHERE source_system='opportunity-origin-review' ORDER BY after_data->>'opportunity_id',occurred_at DESC,id DESC")->fetchAll(PDO::FETCH_ASSOC);
|
||||
$auditCount = (int) $pdo->query("SELECT count(*) FROM audit_events WHERE source_system IN ('opportunity-management','opportunity-management-install')")->fetchColumn();
|
||||
$pdo->exec('ROLLBACK');
|
||||
$result = ['captured_at' => gmdate('c'), 'identity' => $identity, 'installed' => $installed, 'migration_applied' => $migrationApplied, 'classifications' => $classifications, 'management_events' => $auditCount, 'active_writes' => 0];
|
||||
file_put_contents($dir.'/opportunity-management-active-read-only.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result).PHP_EOL;
|
||||
@@ -0,0 +1,25 @@
|
||||
const {chromium}=require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
const base='http://127.0.0.1:18095',dir='storage/app/private/investmoz-v2/';
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true,executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe'});
|
||||
const errors=[];
|
||||
async function session(viewport){const context=await browser.newContext({viewport});await context.route('**/*',r=>r.request().url().startsWith(base)||r.request().url().startsWith('data:')?r.continue():r.abort());const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/login');await page.getByLabel('Email address').fill('opportunity-manager@example.invalid');await page.getByLabel('Password',{exact:true}).fill('Opportunity-QA-2026!');await page.getByRole('button',{name:'Log in',exact:true}).click();await page.waitForURL('**/dashboard');return {context,page};}
|
||||
const desktop=await session({width:1280,height:900}),page=desktop.page;
|
||||
await page.getByRole('link',{name:'Gestão de Oportunidades',exact:true}).click();await page.getByRole('link',{name:'Nova oportunidade',exact:true}).click();
|
||||
await page.getByLabel('Motivo da alteração').fill('Criação incompleta autorizada somente em QA');
|
||||
await page.getByRole('button',{name:'Guardar rascunho',exact:true}).click();await page.waitForURL(/\/management\/opportunities\/\d+\/edit$/);
|
||||
const id=Number(page.url().match(/(\d+)\/edit$/)[1]);assert(id>6);
|
||||
await page.getByLabel('Título oficial').fill('QA browser opportunity recovered from server');await page.getByLabel('Categoria',{exact:true}).selectOption('investment_project');
|
||||
await page.getByLabel('Investimento estimado').fill('-1');await page.getByLabel('Motivo da alteração').fill('Edição financeira inválida para verificar erros QA');
|
||||
await page.getByRole('button',{name:'Guardar rascunho',exact:true}).click();await page.getByText('The estimated investment amount field format is invalid.').waitFor().catch(async()=>{await page.locator('[role="alert"]').first().waitFor();});
|
||||
assert.equal(await page.getByLabel('Título oficial').inputValue(),'QA browser opportunity recovered from server');
|
||||
await page.getByLabel('Investimento estimado').fill('1000.25');await page.getByLabel('Moeda',{exact:true}).selectOption('MZN');await page.getByRole('button',{name:'Guardar rascunho',exact:true}).click();await page.getByText('Rascunho guardado no servidor. Não foi submetido, aprovado ou publicado.',{exact:true}).waitFor();
|
||||
await page.screenshot({path:dir+'opportunity-management-desktop.png',fullPage:true});await desktop.context.close();
|
||||
const mobile=await session({width:390,height:844});await mobile.page.goto(base+`/management/opportunities/${id}/edit`);
|
||||
await mobile.page.evaluate(()=>localStorage.clear());await mobile.page.reload();assert.equal(await mobile.page.getByLabel('Título oficial').inputValue(),'QA browser opportunity recovered from server');assert.equal(await mobile.page.getByLabel('Investimento estimado').inputValue(),'1000.25');
|
||||
await mobile.page.screenshot({path:dir+'opportunity-management-mobile.png',fullPage:true});assert(await mobile.page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
|
||||
await mobile.page.getByLabel('Motivo da alteração').fill('Exclusão lógica do rascunho de demonstração QA');await mobile.page.getByRole('checkbox',{name:/Confirmo a exclusão/}).check();await mobile.page.getByRole('button',{name:'Excluir rascunho',exact:true}).click();await mobile.page.getByRole('button',{name:'Restaurar',exact:true}).waitFor();
|
||||
await mobile.page.getByLabel('Motivo da alteração').fill('Restauração autorizada do rascunho somente QA');await mobile.page.getByRole('checkbox',{name:/Confirmo a restauração/}).check();await mobile.page.getByRole('button',{name:'Restaurar',exact:true}).click();await mobile.page.getByRole('button',{name:'Excluir rascunho',exact:true}).waitFor();assert.equal(await mobile.page.getByLabel('Título oficial').inputValue(),'QA browser opportunity recovered from server');
|
||||
assert.deepEqual(errors,[]);const proof={recorded_at:new Date().toISOString(),id,desktop:true,mobile:true,new_session_recovery:true,field_errors:true,soft_delete_restore:true,errors,active_writes:0};fs.writeFileSync(dir+'opportunity-management-browser.json',JSON.stringify(proof,null,2));console.log(JSON.stringify(proof));await browser.close();
|
||||
})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityManagementInstallation;
|
||||
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__);
|
||||
$dir = $root.'/storage/app/private/investmoz-v2';
|
||||
$backup = json_decode(file_get_contents($dir.'/opportunity-management-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');
|
||||
}
|
||||
foreach (['APP_ENV' => 'testing', 'APP_DEBUG' => 'true', 'APP_URL' => 'http://127.0.0.1:18095', 'APP_KEY' => 'base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441', 'DB_DATABASE' => $target['database'], 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '', 'SESSION_DRIVER' => 'file', 'SESSION_COOKIE' => 'opportunity_management_qa', 'CACHE_STORE' => 'array', 'QUEUE_CONNECTION' => 'sync'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
require $root.'/vendor/autoload.php';
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
if ($identity->database !== $target['database'] || (int) $identity->port !== 55441) {
|
||||
throw new RuntimeException('Refusing non-QA target');
|
||||
}
|
||||
config(['portal.managers' => ['opportunity-manager@example.invalid'], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$sessions = $dir.'/qa-opportunity-management-sessions';
|
||||
if (! is_dir($sessions)) {
|
||||
mkdir($sessions, 0700, true);
|
||||
}
|
||||
config(['session.files' => $sessions]);
|
||||
Vite::useHotFile($root.'/storage/framework/qa-opportunity-management-hot-absent');
|
||||
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'prepare') {
|
||||
$migration = require $root.'/database/migrations/'.OpportunityManagementInstallation::MIGRATION.'.php';
|
||||
$migration->up();
|
||||
$oldColumns = array_keys((array) DB::selectOne('SELECT * FROM opportunities LIMIT 1'));
|
||||
$oldColumns = array_diff($oldColumns, ['management_version', 'opportunity_category', 'management_draft', 'management_creation_key', 'first_submitted_at', 'management_closed_once']);
|
||||
$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/'.OpportunityManagementInstallation::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(OpportunityManagementInstallation::class)->fingerprint(), 'compatibility_verified' => true, 'reversal_verified' => true, 'tables_compared' => count($backup['table_hashes']), 'active_writes' => 0];
|
||||
file_put_contents($dir.'/opportunity-management-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')), ['management_version', 'opportunity_category', 'management_draft', 'management_creation_key', 'first_submitted_at', 'management_closed_once']);
|
||||
$projection = implode(',', array_map(fn ($column) => '"'.$column.'"', $columns));
|
||||
$checks = [];
|
||||
foreach (['opportunities', 'opportunity_projects', 'opportunity_clusters', '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-management')" : $key);
|
||||
$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-management-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(OpportunityManagementInstallation::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-management-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);
|
||||
$app->handleRequest(Request::capture());
|
||||
Reference in New Issue
Block a user