feat: verify active opportunity management and prepare versioned resources
This commit is contained in:
@@ -7,11 +7,34 @@ $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();
|
||||
$resourceSchemaInstalled = (bool) $pdo->query("SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_name='opportunity_images')")->fetchColumn();
|
||||
$resourceAuditCount = (int) $pdo->query("SELECT count(*) FROM audit_events WHERE source_system IN ('opportunity-resources','opportunity-resources-install')")->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();
|
||||
$installation = $pdo->query("SELECT id,actor_user_id,occurred_at,action,after_data FROM audit_events WHERE source_system='opportunity-management-install' ORDER BY occurred_at,id")->fetchAll(PDO::FETCH_ASSOC);
|
||||
$backup = json_decode(file_get_contents($dir.'/opportunity-management-backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$checks = [];
|
||||
$restored = $backup['restored_target'];
|
||||
if (! str_ends_with($restored['database'], '_test') || (int) $restored['port'] !== 55441) {
|
||||
throw new RuntimeException('Isolated history comparison required');
|
||||
}
|
||||
$baseline = new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$restored['database'], $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$baseline->exec('BEGIN TRANSACTION READ ONLY');
|
||||
$oldEvents = $baseline->query("SELECT id,row_to_json(t)::text AS row FROM audit_events t WHERE source_system IS DISTINCT FROM 'opportunity-management' ORDER BY row_to_json(t)::text")->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
if (hash('sha256', implode("\n", array_values($oldEvents))) !== $backup['table_hashes']['"public"."audit_events"']) {
|
||||
throw new RuntimeException('Historical baseline drift');
|
||||
}
|
||||
$currentEvents = $pdo->query('SELECT id,row_to_json(t)::text AS row FROM audit_events t ORDER BY id')->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||
$missing = $changed = 0;
|
||||
foreach ($oldEvents as $eventId => $row) {
|
||||
if (! isset($currentEvents[$eventId])) {
|
||||
$missing++;
|
||||
} elseif ($currentEvents[$eventId] !== $row) {
|
||||
$changed++;
|
||||
}
|
||||
}
|
||||
$baseline->exec('ROLLBACK');
|
||||
$historicalAudit = ['baseline_events' => count($oldEvents), 'missing' => $missing, 'changed' => $changed, 'additional_events' => count($currentEvents) - count($oldEvents)];
|
||||
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.'"';
|
||||
if ($table === 'opportunities') {
|
||||
@@ -25,6 +48,6 @@ foreach (['opportunities', 'opportunity_projects', 'opportunity_clusters', 'oppo
|
||||
$checks[$table] = ['matches_preinstallation_backup' => hash('sha256', implode("\n", $rows)) === $backup['table_hashes'][$key], 'rows' => count($rows)];
|
||||
}
|
||||
$pdo->exec('ROLLBACK');
|
||||
$result = ['captured_at' => gmdate('c'), 'identity' => $identity, 'installed' => $installed, 'migration_applied' => $migrationApplied, 'classifications' => $classifications, 'management_events' => $auditCount, 'installation_audit' => $installation, 'preservation' => $checks, 'active_writes' => 0];
|
||||
$result = ['captured_at' => gmdate('c'), 'identity' => $identity, 'installed' => $installed, 'migration_applied' => $migrationApplied, 'resource_schema_installed' => $resourceSchemaInstalled, 'resource_events' => $resourceAuditCount, 'classifications' => $classifications, 'management_events' => $auditCount, 'installation_audit' => $installation, 'preservation' => $checks, 'historical_audit' => $historicalAudit, '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,12 @@
|
||||
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'),zlib=require('node:zlib');
|
||||
const base='http://127.0.0.1:18096',dir='storage/app/private/investmoz-v2/';
|
||||
function png(){function crc(bytes){let c=0xffffffff;for(const b of bytes){c^=b;for(let i=0;i<8;i++)c=(c>>>1)^((c&1)?0xedb88320:0);}return (c^0xffffffff)>>>0;}function chunk(name,bytes){const n=Buffer.from(name),body=Buffer.concat([n,bytes]),head=Buffer.alloc(4),tail=Buffer.alloc(4);head.writeUInt32BE(bytes.length);tail.writeUInt32BE(crc(body));return Buffer.concat([head,body,tail]);}const hdr=Buffer.alloc(13);hdr.writeUInt32BE(500,0);hdr.writeUInt32BE(500,4);hdr[8]=8;hdr[9]=2;return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',hdr),chunk('IDAT',zlib.deflateSync(Buffer.alloc(500*1501))),chunk('IEND',Buffer.alloc(0))]);}
|
||||
(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 de recursos somente na cópia QA');await page.getByRole('button',{name:'Guardar rascunho',exact:true}).click();await page.waitForURL(/\/opportunities\/\d+\/edit$/);const id=Number(page.url().match(/(\d+)\/edit$/)[1]);assert(id>6);await page.getByRole('link',{name:'Imagens, documentos e localizações',exact:true}).click();await page.waitForURL('**/resources');
|
||||
await page.getByLabel('Título',{exact:true}).fill('QA production location');await page.getByLabel('Papel da localização',{exact:true}).selectOption('production');const provinceSelect=page.getByLabel('Província',{exact:true});await provinceSelect.locator('option').nth(1).waitFor({state:'attached'});const province=await provinceSelect.locator('option').nth(1).getAttribute('value');await provinceSelect.selectOption(province);const districtSelect=page.getByLabel('Distrito',{exact:true});await districtSelect.locator('option').nth(1).waitFor({state:'attached'});const district=await districtSelect.locator('option').nth(1).getAttribute('value');await districtSelect.selectOption(district);await page.getByLabel('Distribuição (%)',{exact:true}).fill('60');await page.getByLabel('Localização principal',{exact:true}).check();await page.getByLabel('Motivo (20–1000 caracteres)').fill('Localização e distribuição declaradas em QA');await page.getByRole('button',{name:'Guardar recurso',exact:true}).click();await page.locator('article').filter({hasText:'QA production location'}).waitFor();
|
||||
await page.getByLabel('Título',{exact:true}).fill('QA market location');await page.getByLabel('Papel da localização',{exact:true}).selectOption('market');await provinceSelect.selectOption(province);await districtSelect.locator('option').nth(1).waitFor({state:'attached'});await districtSelect.selectOption(district);await page.getByLabel('Distribuição (%)',{exact:true}).fill('40');await page.getByRole('button',{name:'Guardar recurso',exact:true}).click();await page.locator('article').filter({hasText:'QA market location'}).waitFor();assert.equal(await page.locator('article').count(),2);
|
||||
await page.getByRole('button',{name:'Documentos',exact:true}).click();await page.getByLabel('Título',{exact:true}).fill('QA source document');await page.getByLabel('Original / substituir por nova versão').setInputFiles({name:'qa.pdf',mimeType:'application/pdf',buffer:Buffer.from('%PDF-1.7\nSynthetic QA document\n%%EOF')});await page.getByRole('button',{name:'Guardar recurso',exact:true}).click();await page.locator('article').filter({hasText:'QA source document'}).waitFor();
|
||||
await page.getByRole('button',{name:'Imagens',exact:true}).click();await page.getByLabel('Título',{exact:true}).fill('QA synthetic image');await page.getByLabel('Legenda',{exact:true}).fill('Synthetic image only used in isolated QA');await page.getByLabel('Texto alternativo',{exact:true}).fill('Black square generated for isolated QA');await page.getByLabel('Direitos de utilização',{exact:true}).selectOption('owned');await page.getByLabel('Original / substituir por nova versão').setInputFiles({name:'qa.png',mimeType:'image/png',buffer:png()});await page.getByRole('button',{name:'Guardar recurso',exact:true}).click();const imageArticle=page.locator('article').filter({hasText:'QA synthetic image'});await imageArticle.waitFor();await imageArticle.getByRole('button',{name:'Ver / editar / restaurar'}).click();await page.getByRole('button',{name:'Preparar WebP e miniaturas'}).click();await page.getByText(/GD\/WebP não disponível neste processo|Scan do original pendente ou inseguro/).waitFor();assert.equal(await page.getByLabel('Título',{exact:true}).inputValue(),'QA synthetic image');await page.screenshot({path:dir+'opportunity-resources-desktop.png',fullPage:true});await desktop.context.close();
|
||||
const mobile=await session({width:390,height:844}),mp=mobile.page;await mp.goto(base+`/management/opportunities/${id}/resources`);await mp.evaluate(()=>localStorage.clear());await mp.reload();assert.equal(await mp.locator('article').count(),2);await mp.getByRole('button',{name:'Imagens',exact:true}).click();const mi=mp.locator('article').filter({hasText:'QA synthetic image'});await mi.getByRole('button',{name:'Ver / editar / restaurar'}).click();assert.equal(await mp.getByLabel('Texto alternativo',{exact:true}).inputValue(),'Black square generated for isolated QA');await mp.getByLabel('Motivo (20–1000 caracteres)').fill('Exclusão lógica de imagem somente no ensaio QA');await mp.getByLabel('Confirmar exclusão lógica / restauração').check();await mp.getByRole('button',{name:'Excluir recurso logicamente'}).click();await mp.getByText('eliminado logicamente',{exact:false}).first().waitFor();await mi.getByRole('button',{name:'Ver / editar / restaurar'}).click();await mp.getByLabel('Confirmar exclusão lógica / restauração').check();await mp.getByRole('button',{name:'Restaurar recurso'}).click();await mi.getByText(/rascunho/).waitFor();await mp.screenshot({path:dir+'opportunity-resources-mobile.png',fullPage:true});assert(await mp.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));assert.deepEqual(errors,[]);const proof={recorded_at:new Date().toISOString(),id,desktop:true,mobile:true,new_session_recovery:true,multiple_locations:true,documents:true,images:true,scan_failure_visible:true,soft_delete_restore:true,errors,active_writes:0};fs.writeFileSync(dir+'opportunity-resources-browser.json',JSON.stringify(proof,null,2));console.log(JSON.stringify(proof));await browser.close();})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -63,9 +63,14 @@ 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_favourites', 'interest_requests', 'interest_submission_receipts', 'investment_messages', 'tasks', 'project_locations', 'cluster_projects', 'audit_events'] as $table) {
|
||||
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 === '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]) {
|
||||
|
||||
Reference in New Issue
Block a user