This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$db = Illuminate\Support\Facades\DB::connection();
|
||||
$report = $db->transaction(function () use ($db) {
|
||||
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
return [
|
||||
'generated_at' => date(DATE_ATOM),
|
||||
'target' => $db->selectOne('select current_database() as database, inet_server_port() as port'),
|
||||
'projects' => $db->table('projects')->orderBy('code')->get(),
|
||||
'dossiers' => $db->table('investment_dossiers')->orderBy('title')->get(),
|
||||
'clusters' => $db->table('economic_clusters')->orderBy('code')->get(),
|
||||
'cluster_projects' => $db->table('cluster_projects')->get(),
|
||||
'opportunity_clusters' => $db->table('opportunity_clusters')->get(),
|
||||
'value_chains' => $db->table('value_chains')->get(),
|
||||
'value_chain_links' => $db->table('value_chain_links')->get(),
|
||||
'project_locations' => $db->table('project_locations')->get(),
|
||||
'opportunity_projects' => $db->table('opportunity_projects')->get(),
|
||||
'opportunities' => $db->table('opportunities')->get(),
|
||||
'profiles' => $db->table('opportunity_profiles')->get(),
|
||||
'locations' => $db->table('geo_locations')->get(['id','name','location_type','parent_id','source_system','external_id','data_classification','deleted_at']),
|
||||
'geometries' => $db->table('geo_geometries')->select(['id','geo_location_id','geometry_type','source_system','external_id','data_classification','deleted_at'])->selectRaw('ST_AsGeoJSON(geom) as geometry')->get(),
|
||||
];
|
||||
});
|
||||
$directory = storage_path('app/private/anchor-project-reconciliation');
|
||||
if (! is_dir($directory)) mkdir($directory, 0700, true);
|
||||
$file = $directory.'/inventory-'.date('Ymd-His').'.json';
|
||||
file_put_contents($file, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
echo $file.PHP_EOL;
|
||||
@@ -0,0 +1,35 @@
|
||||
import hashlib, json, pathlib, zipfile, xml.etree.ElementTree as ET
|
||||
|
||||
root = pathlib.Path(r'C:\Mac\Home\Documents\TEMPO\Portal Tempo\Servicos Tempo\portal do investidor')
|
||||
out = pathlib.Path('storage/app/private/anchor-project-reconciliation')
|
||||
ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
|
||||
inventory, extracts = [], []
|
||||
for file in sorted(root.rglob('*')):
|
||||
if not file.is_file(): continue
|
||||
record = {'path':str(file), 'bytes':file.stat().st_size, 'analysis':'not_analysed'}
|
||||
try:
|
||||
data = file.read_bytes()
|
||||
record['sha256'] = hashlib.sha256(data).hexdigest()
|
||||
if zipfile.is_zipfile(file):
|
||||
with zipfile.ZipFile(file) as archive:
|
||||
record['attachments'] = [{'path':e.filename,'bytes':e.file_size,'sha256':hashlib.sha256(archive.read(e)).hexdigest()} for e in archive.infolist() if '/media/' in e.filename or '/embeddings/' in e.filename]
|
||||
if file.suffix.lower()=='.docx':
|
||||
tree=ET.fromstring(archive.read('word/document.xml'))
|
||||
paragraphs=[''.join(p.itertext()) for p in []]
|
||||
paragraphs=[''.join(t.text or '' for t in p.findall('.//w:t',ns)) for p in tree.findall('.//w:p',ns)]
|
||||
text='\n'.join(paragraphs)
|
||||
tables=[[[ '\n'.join(''.join(t.text or '' for t in p.findall('.//w:t',ns)) for p in c.findall('./w:p',ns)) for c in r.findall('./w:tc',ns)] for r in table.findall('./w:tr',ns)] for table in tree.findall('.//w:body/w:tbl',ns)]
|
||||
extracts.append({'path':str(file),'sha256':record['sha256'],'paragraphs':paragraphs,'tables':tables})
|
||||
record['analysis']='text_extracted; relevance_pending'
|
||||
except Exception as error:
|
||||
record['error']=str(error)
|
||||
inventory.append(record)
|
||||
out.mkdir(parents=True,exist_ok=True)
|
||||
(out/'source-files.json').write_text(json.dumps(inventory,ensure_ascii=False,indent=2),encoding='utf8')
|
||||
(out/'source-texts.json').write_text(json.dumps(extracts,ensure_ascii=False,indent=2),encoding='utf8')
|
||||
for doc in extracts:
|
||||
if 'Matriz detalhada' in doc['path'] or 'v5 programacao' in doc['path'] or doc['path'].endswith('projectos.docx'):
|
||||
print(doc['path'])
|
||||
relevant=[(i,p) for i,p in enumerate(doc['paragraphs']) if any(s in p for s in ['A01','A03','A04','A09','6.6','6.1','oportunidades complementares','Oportunidades complementares'])]
|
||||
for i,p in relevant[:24]: print(i, p[:450])
|
||||
print('Files:',len(inventory),'DOCX:',len(extracts))
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Inventory the accessible documentary collection before selecting form sources."""
|
||||
from pathlib import Path
|
||||
import hashlib, json, zipfile
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
roots = [Path(r'C:\Mac\Home\Documents\TEMPO\Portal Tempo\Servicos Tempo'), Path(r'C:\Users\macbook\.codex\attachments')]
|
||||
out = Path('storage/app/private/virtual-desk')
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
inventory = []
|
||||
for root in roots:
|
||||
for path in sorted(root.rglob('*')):
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
item = dict(path=str(path), size=len(raw), sha256=hashlib.sha256(raw).hexdigest(), analysis='not_analysed', attachments=[])
|
||||
if zipfile.is_zipfile(path):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
item['attachments'] = [dict(identifier=n, size=len(archive.read(n)), sha256=hashlib.sha256(archive.read(n)).hexdigest()) for n in archive.namelist() if '/embeddings/' in n or '/media/' in n]
|
||||
inventory.append(item)
|
||||
except OSError as error:
|
||||
inventory.append(dict(path=str(path), availability='unreadable', reason=str(error)))
|
||||
(out/'source-inventory.json').write_text(json.dumps(inventory, ensure_ascii=False, indent=2), encoding='utf8')
|
||||
# Selection starts only after the complete inventory was persisted.
|
||||
selected=[]
|
||||
for item in inventory:
|
||||
path=Path(item['path'])
|
||||
if path.suffix.lower()=='.docx' and not path.name.startswith('~$'):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
root=ET.fromstring(archive.read('word/document.xml'))
|
||||
text='\n'.join(''.join(p.itertext()) for p in root.findall('.//{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t'))
|
||||
if any(word in path.name.lower() for word in ['balcão','balcao','formul','apiex']) or ('APIEX' in text and ('FORMULÁRIO' in text or 'Formulário' in text)):
|
||||
target=out/(item['sha256']+'.txt')
|
||||
target.write_text(text, encoding='utf8')
|
||||
selected.append(dict(**item, extraction=str(target), form_status='source_review_pending'))
|
||||
(out/'selected-sources.json').write_text(json.dumps(selected, ensure_ascii=False, indent=2), encoding='utf8')
|
||||
print(json.dumps(dict(files=len(inventory), selected=[dict(path=i['path'], extraction=i['extraction']) for i in selected]), ensure_ascii=False))
|
||||
@@ -0,0 +1,49 @@
|
||||
const {chromium}=require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const fs=require('node:fs');const assert=require('node:assert/strict');
|
||||
const dir='storage/app/private/anchor-project-reconciliation/';
|
||||
const fixture=JSON.parse(fs.readFileSync(dir+'qa-browser-fixture.json'));
|
||||
const base='http://127.0.0.1:18086';
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true,executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe'});
|
||||
try {
|
||||
const context=await browser.newContext();
|
||||
await context.route('**/*',route=>route.request().url().startsWith(base)||route.request().url().startsWith('data:')?route.continue():route.abort());
|
||||
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
const response=await page.goto(base+'/carteira/'+fixture.project_dossier,{waitUntil:'networkidle'});
|
||||
assert.equal(response.headers()['x-investmoz-qa-target'],fixture.target);assert.equal(response.status(),200);
|
||||
await page.getByRole('heading',{name:'Localização documentada do projecto',exact:true}).waitFor();
|
||||
for(const text of ['QA province','QA district','QA admin_post','QA locality','32.5'])assert((await page.locator('body').innerText()).includes(text),text);
|
||||
await page.getByRole('link',{name:'Synthetic QA linked opportunity',exact:true}).click();
|
||||
await page.getByRole('link',{name:'Voltar ao dossier: Synthetic QA anchor 1',exact:true}).waitFor();
|
||||
await page.getByRole('link',{name:'Voltar ao dossier: Synthetic QA anchor 1',exact:true}).click();
|
||||
await page.getByRole('heading',{name:'Localização documentada do projecto',exact:true}).waitFor();
|
||||
await page.getByRole('link',{name:'Synthetic QA multi-site cluster',exact:true}).first().click();
|
||||
const geography=page.locator(`[aria-labelledby="documented-geography-${fixture.cluster_dossier}"]`);
|
||||
await geography.getByText('Não existe um ponto único atribuído ao cluster.',{exact:false}).waitFor();
|
||||
assert((await geography.innerText()).includes('2 investimentos com coordenadas disponíveis.'));
|
||||
assert((await geography.innerText()).includes('QA production'));
|
||||
assert((await geography.innerText()).includes('QA processing'));
|
||||
assert.equal(await geography.getByRole('link',{name:/QA-ANCHOR-/}).count(),2);
|
||||
for(const width of [1440,390]){
|
||||
await page.setViewportSize({width,height:1000});
|
||||
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
||||
await page.screenshot({path:`docs/investmoz/relationships/cluster-${width}.png`,fullPage:true});
|
||||
}
|
||||
const map=await context.request.get(base+'/api/v1/investment/map?province_id='+fixture.province_id);assert.equal(map.headers()['x-investmoz-qa-target'],fixture.target);
|
||||
const data=await map.json();assert.equal(data.matched_count,1);assert.equal(data.georeferenced_count,1);assert.equal(data.features[0].properties.location_basis,'linked_project_site');
|
||||
const detail=await context.request.get(base+'/api/v1/investment/opportunities/'+fixture.opportunity_slug);
|
||||
assert(detail.ok());const json=await detail.json();assert.equal(json.context.projects.length,1);assert.equal(json.context.clusters.length,1);
|
||||
await page.goto(base+'/login',{waitUntil:'networkidle'});
|
||||
await page.locator('input[type=email]').fill('relationship-qa@example.invalid');await page.locator('input[type=password]').fill('QA-Relationship-2026!');
|
||||
await page.locator('button[type=submit]').click();await page.waitForURL(url=>!url.pathname.startsWith('/login'));
|
||||
await page.goto(base+'/management/relationship-repair',{waitUntil:'networkidle'});
|
||||
await page.getByRole('heading',{name:'Localizações: 28',exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'Aplicar associações fundamentadas',exact:true}).click();
|
||||
await page.getByText(/Associações documentadas aplicadas\.|Este plano já foi aplicado; nenhum duplicado criado\./).waitFor();
|
||||
await page.getByRole('button',{name:'Aplicar associações fundamentadas',exact:true}).click();
|
||||
await page.getByText('Este plano já foi aplicado; nenhum duplicado criado.',{exact:true}).waitFor();
|
||||
assert.deepEqual(errors,[]);
|
||||
fs.writeFileSync('docs/investmoz/relationships/browser-qa.json',JSON.stringify({target:fixture.target,project:fixture.project_dossier,cluster:fixture.cluster_dossier,passed:true,publicNavigation:true,administrativeHierarchy:true,clusterMemberSites:2,clusterSinglePoint:false,territorialMap:true,chainLinks:true,authenticatedPlanApplied:true,replayWithoutDuplicates:true,viewports:[1440,390],errors},null,2));
|
||||
console.log('QA browser passed: public project/cluster/opportunity navigation, hierarchy, two member sites, chains, filters, authenticated 28-location repair and idempotent replay.');
|
||||
}finally{await browser.close();}
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$active = Illuminate\Support\Facades\DB::connection();
|
||||
$identity = $active->selectOne('select current_database() as database, inet_server_port() as port');
|
||||
if ($identity->database !== 'investemoz' || (int) $identity->port !== 5432) throw new RuntimeException('Unexpected active backup target.');
|
||||
$directory = storage_path('app/private/partnership-exchange/backup-'.date('Ymd-His'));
|
||||
mkdir($directory, 0700, true);
|
||||
$dump = $directory.'/database.dump';
|
||||
$qaName = 'partnership_restore_'.date('Ymd_His').'_test';
|
||||
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
|
||||
$run = function (array $command, array $environment = []) {
|
||||
$process = proc_open($command, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, [...getenv(), ...$environment]);
|
||||
if (! is_resource($process)) throw new RuntimeException('Backup process unavailable.');
|
||||
fclose($pipes[0]);
|
||||
$output = stream_get_contents($pipes[1]); fclose($pipes[1]);
|
||||
$errors = stream_get_contents($pipes[2]); fclose($pipes[2]);
|
||||
if (proc_close($process) !== 0) throw new RuntimeException('Backup/restore command failed: '.$errors);
|
||||
return $output;
|
||||
};
|
||||
$proof = $active->transaction(function () use ($active, $run, $bin, $qaName, $dump, $identity) {
|
||||
$active->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
$snapshot = $active->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
||||
$run([$bin.'pg_dump.exe', '-h', $active->getConfig('host'), '-p', '5432', '-U', $active->getConfig('username'), '-d', 'investemoz', '-Fc', '--snapshot='.$snapshot, '-f', $dump], ['PGPASSWORD' => $active->getConfig('password')]);
|
||||
$run([$bin.'createdb.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'postgres', $qaName], ['PGPASSWORD' => '']);
|
||||
$run([$bin.'pg_restore.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'postgres', '-d', $qaName, '--exit-on-error', '--no-owner', '--no-privileges', $dump], ['PGPASSWORD' => '']);
|
||||
config(['database.connections.partnership_restore' => [...config('database.connections.pgsql'), 'host' => '127.0.0.1', 'port' => 55441, 'database' => $qaName, 'username' => 'postgres', 'password' => '', 'url' => null]]);
|
||||
$restore = Illuminate\Support\Facades\DB::connection('partnership_restore');
|
||||
$restored = $restore->selectOne('select current_database() as database, inet_server_port() as port');
|
||||
if ($restored->database !== $qaName || ! str_ends_with($qaName, '_test') || (int) $restored->port !== 55441) throw new RuntimeException('QA identity rejected.');
|
||||
$counts = []; $hashes = [];
|
||||
foreach ($active->select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
|
||||
$name = $table->tablename;
|
||||
$quoted = '"'.str_replace('"', '""', $name).'"';
|
||||
$rows = fn ($connection) => array_map(fn ($row) => $row->value, $connection->select('select row_to_json(t)::text as value from public.'.$quoted.' as t order by row_to_json(t)::text'));
|
||||
$a = $rows($active); $b = $rows($restore);
|
||||
if ($a !== $b) throw new RuntimeException('Restored contents differ: '.$name);
|
||||
$counts[$name] = count($a); $hashes[$name] = hash('sha256', implode("\n", $a));
|
||||
}
|
||||
return ['restore_verified' => true, 'verified_at' => now()->toIso8601String(), 'target' => $identity, 'restored_target' => $restored,
|
||||
'dump_path' => $dump, 'sha256' => hash_file('sha256', $dump), 'table_counts' => $counts, 'table_hashes' => $hashes];
|
||||
});
|
||||
file_put_contents(storage_path('app/private/partnership-exchange/backup-proof.json'), json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
$audit = $active->table('audit_events')->where('source_system', 'documented-relations-repair')->get(['actor_user_id', 'created_at', 'action']);
|
||||
echo json_encode(['restore_verified' => true, 'tables' => count($proof['table_counts']), 'project_locations' => $proof['table_counts']['project_locations'], 'restored_target' => $proof['restored_target'], 'relationship_audit' => $audit], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,86 @@
|
||||
const {chromium}=require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const fs=require('node:fs');const assert=require('node:assert/strict');
|
||||
const base='http://127.0.0.1:18086';
|
||||
const fixture=JSON.parse(fs.readFileSync('storage/app/private/anchor-project-reconciliation/qa-browser-fixture.json'));
|
||||
(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 login(role){const context=await browser.newContext();await context.route('**/*',r=>r.request().url().startsWith(base)?r.continue():r.abort());const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/login');await page.locator('input[type=email]').fill(`partnership-qa-${role}@example.invalid`);await page.locator('input[type=password]').fill('QA-Partnership-2026!');await page.locator('button[type=submit]').click();await page.waitForURL(url=>!url.pathname.startsWith('/login'));return page;}
|
||||
try{
|
||||
const owner=await login('owner'),candidate=await login('candidate'),moderator=await login('moderator');
|
||||
const title='QA browser partnership '+Date.now();
|
||||
await owner.goto(base+'/carteira/'+fixture.project_dossier,{waitUntil:'networkidle'});
|
||||
await owner.getByRole('link',{name:'Propor parceria a partir deste registo',exact:true}).click();
|
||||
await owner.getByLabel('Título',{exact:true}).fill(title);
|
||||
await owner.getByLabel('Tipo de parceria',{exact:true}).selectOption('joint_venture');
|
||||
await owner.getByLabel('Resumo público',{exact:true}).fill('QA partnership: source references and local workflow');
|
||||
await owner.getByLabel('O que oferece',{exact:true}).fill('Synthetic QA production capacity');
|
||||
await owner.getByLabel('O que procura',{exact:true}).fill('Synthetic QA technology partner');
|
||||
await owner.getByLabel(/Autorizo submeter/).check();
|
||||
await owner.getByRole('button',{name:'Guardar rascunho',exact:true}).click();
|
||||
await owner.waitForURL(/\/parcerias\/\d+\/editar$/);
|
||||
const partnershipId=Number(new URL(owner.url()).pathname.split('/')[2]);
|
||||
await owner.reload();assert.equal(await owner.getByLabel('Título',{exact:true}).inputValue(),title);
|
||||
await owner.getByRole('link',{name:'Pré-visualizar e submeter',exact:true}).click();
|
||||
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA source checked and disclosure requested');
|
||||
await owner.getByRole('button',{name:'Submeter para publicação',exact:true}).click();
|
||||
await owner.getByText('Estado: Submetida.',{exact:false}).waitFor();
|
||||
await moderator.goto(base+'/parcerias/'+partnershipId);
|
||||
await moderator.getByLabel('Motivo da ação',{exact:true}).fill('QA reviewed public content; no organization verification presumed');
|
||||
await moderator.getByRole('button',{name:'Publicar',exact:true}).click();
|
||||
await moderator.getByText('Estado: Publicada.',{exact:false}).waitFor();
|
||||
await candidate.goto(base+'/parcerias/'+partnershipId);
|
||||
await candidate.getByLabel('Proposta curta',{exact:true}).fill('QA candidate contribution');
|
||||
await candidate.getByLabel('Capacidade disponível',{exact:true}).fill('Declared synthetic QA capacity');
|
||||
await candidate.getByLabel(/Autorizo a partilha desta candidatura/).check();
|
||||
await candidate.getByRole('button',{name:'Guardar interesse',exact:true}).click();
|
||||
await candidate.getByRole('heading',{name:/Candidatura \d+/}).waitFor();
|
||||
await owner.reload();
|
||||
await owner.getByLabel('Motivo da decisão ou pedido de esclarecimento',{exact:true}).fill('QA shortlist; unknown evidence remains pending');
|
||||
await owner.getByRole('button',{name:'Adicionar à lista curta',exact:true}).click();
|
||||
await owner.getByRole('heading',{name:/Candidatura \d+ · Lista curta/}).waitFor();
|
||||
await owner.getByLabel('Motivo da decisão ou pedido de esclarecimento',{exact:true}).fill('QA private negotiation authorized');
|
||||
await owner.getByRole('button',{name:'Abrir negociação',exact:true}).click();
|
||||
await owner.getByRole('link',{name:'Abrir conexão privada',exact:true}).click();
|
||||
const roomId=Number(new URL(owner.url()).pathname.split('/').pop());
|
||||
await owner.getByLabel('Mensagem privada',{exact:true}).fill('QA private discussion');
|
||||
await owner.getByRole('button',{name:'Enviar mensagem',exact:true}).click();
|
||||
await owner.getByText('QA private discussion',{exact:true}).waitFor();
|
||||
await owner.getByLabel('Título do instrumento',{exact:true}).fill('QA pilot agreement');
|
||||
await owner.getByLabel('Condições e plano de valor',{exact:true}).fill('Parties, deliverables, responsibilities, risk and exit conditions. Synthetic QA only.');
|
||||
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA terms recorded');
|
||||
await owner.getByRole('button',{name:'Registar versão do acordo',exact:true}).click();
|
||||
await owner.getByRole('button',{name:'Confirmar pela minha parte',exact:true}).waitFor();
|
||||
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA proponent acknowledgement');
|
||||
await owner.getByRole('button',{name:'Confirmar pela minha parte',exact:true}).click();
|
||||
await candidate.goto(base+'/parcerias/salas/'+roomId);
|
||||
await candidate.getByText('QA private discussion',{exact:true}).waitFor();
|
||||
await candidate.getByLabel('Motivo da ação',{exact:true}).fill('QA candidate acknowledgement');
|
||||
await candidate.getByRole('button',{name:'Confirmar pela minha parte',exact:true}).click();
|
||||
await candidate.getByRole('button',{name:'Iniciar acompanhamento',exact:true}).waitFor();
|
||||
await owner.reload();
|
||||
await owner.getByLabel('Entregável',{exact:true}).fill('QA pilot delivery');
|
||||
await owner.getByRole('button',{name:'Guardar marco',exact:true}).click();
|
||||
await owner.getByRole('heading',{name:'Atualizar marco',exact:true}).waitFor();
|
||||
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA start monitoring');
|
||||
await owner.getByRole('button',{name:'Iniciar acompanhamento',exact:true}).click();
|
||||
await owner.getByText('Estado da conexão: Em execução.',{exact:false}).waitFor();
|
||||
const update=owner.getByRole('heading',{name:'Atualizar marco',exact:true}).locator('..');
|
||||
await update.getByLabel('Estado',{exact:true}).selectOption('completed');
|
||||
await update.getByLabel('Evidência ou referência do resultado',{exact:true}).fill('Synthetic QA deliverable evidence');
|
||||
await update.getByRole('button',{name:'Guardar marco',exact:true}).click();
|
||||
await owner.getByText('QA pilot delivery · Concluído · Prazo:',{exact:false}).waitFor();
|
||||
assert.equal(await update.getByLabel('Estado',{exact:true}).inputValue(),'completed');
|
||||
for(const width of [1440,390]){await owner.setViewportSize({width,height:1000});assert(await owner.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await owner.screenshot({path:`docs/investmoz/partnerships/room-${width}.png`,fullPage:true});}
|
||||
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA all milestones completed');
|
||||
await owner.getByRole('button',{name:'Concluir após os marcos',exact:true}).click();
|
||||
await owner.getByText('Estado da conexão: Concluída.',{exact:false}).waitFor();
|
||||
await owner.goto(base+'/carteira/'+fixture.project_dossier,{waitUntil:'networkidle'});
|
||||
await owner.getByRole('link',{name:title,exact:true}).waitFor();
|
||||
await candidate.goto(base+'/parcerias?q='+encodeURIComponent(title));
|
||||
await candidate.getByRole('link',{name:title,exact:true}).waitFor();
|
||||
assert.deepEqual(errors,[]);
|
||||
fs.writeFileSync('docs/investmoz/partnerships/browser-qa.json',JSON.stringify({target:'anchor_restore_20261007_test:55441',passed:true,partnershipId,roomId,draftRecovered:true,sourceBacklink:true,moderation:true,interest:true,shortlist:true,privateMessage:true,bilateralAgreement:true,milestoneCompleted:true,roomClosed:true,viewports:[1440,390],errors},null,2));
|
||||
console.log('QA partnership browser passed: real forms, draft recovery, moderation, interest, shortlist, private room, bilateral agreement, milestone and source backlink.');
|
||||
}finally{await browser.close();}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
// Read-only against the active database. Evidence is written only to private files.
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$directory = storage_path('app/private/partnership-exchange');
|
||||
$tests = json_decode(ltrim(file_get_contents($directory.'/qa-tests.json'), "\xEF\xBB\xBF"), true, 512, JSON_THROW_ON_ERROR);
|
||||
$checks = json_decode(ltrim(file_get_contents($directory.'/qa-checks.json'), "\xEF\xBB\xBF"), true, 512, JSON_THROW_ON_ERROR);
|
||||
$browser = json_decode(file_get_contents(base_path('docs/investmoz/partnerships/browser-qa.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (($tests['result'] ?? '') !== 'passed' || ($tests['passed'] ?? 0) < 46 || ! ($browser['passed'] ?? false)
|
||||
|| ($browser['target'] ?? '') !== 'anchor_restore_20261007_test:55441' || ! ($checks['typescript'] ?? false) || ! ($checks['build'] ?? false)) {
|
||||
throw new RuntimeException('QA evidence is incomplete.');
|
||||
}
|
||||
$installer = app(App\Services\PartnershipInstallation::class);
|
||||
$proof = json_decode(file_get_contents($directory.'/backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (! ($proof['restore_verified'] ?? false) || hash_file('sha256', $proof['dump_path']) !== $proof['sha256']) {
|
||||
throw new RuntimeException('Verified restore proof or dump unavailable.');
|
||||
}
|
||||
$evidence = ['passed' => true, 'code_hash' => $installer->fingerprint(), 'database' => 'anchor_restore_20261007_test', 'port' => 55441,
|
||||
'tests' => $tests, 'checks' => $checks, 'browser' => $browser, 'generated_at' => now()->toIso8601String()];
|
||||
file_put_contents($directory.'/qa-evidence.json', json_encode($evidence, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
$preview = $installer->preview();
|
||||
echo json_encode(['target' => $preview['target'], 'installed' => $preview['installed'], 'preserved_records' => count($preview['records']),
|
||||
'backupVerified' => $preview['backupVerified'], 'qaVerified' => $preview['qaVerified'], 'code_hash' => $evidence['code_hash']], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'anchor_restore_20261007_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '', 'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$identity = Illuminate\Support\Facades\DB::selectOne('select current_database() as database, inet_server_port() as port');
|
||||
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
|
||||
throw new RuntimeException('QA database identity rejected');
|
||||
}
|
||||
if (! Illuminate\Support\Facades\Schema::hasTable('partnership_interests')) {
|
||||
Illuminate\Support\Facades\Artisan::call('migrate', ['--path' => 'database/migrations/2026_10_07_160000_extend_internal_partnership_exchange.php', '--force' => true]);
|
||||
}
|
||||
foreach (['owner', 'candidate', 'moderator'] as $role) {
|
||||
$user = App\Models\User::firstOrCreate(['email' => 'partnership-qa-'.$role.'@example.invalid'], ['name' => 'Synthetic QA partnership '.$role, 'password' => Illuminate\Support\Facades\Hash::make('QA-Partnership-2026!')]);
|
||||
$user->forceFill(['email_verified_at' => $role === 'moderator' ? now() : null])->save();
|
||||
}
|
||||
echo "Partnership migration and synthetic users prepared exclusively in isolated restored QA.\n";
|
||||
@@ -0,0 +1,50 @@
|
||||
import fs from 'node:fs';
|
||||
import crypto from 'node:crypto';
|
||||
const dir='storage/app/private/anchor-project-reconciliation/';
|
||||
const inventory=JSON.parse(fs.readFileSync(dir+fs.readdirSync(dir).filter(f=>f.startsWith('inventory')).sort().at(-1),'utf8'));
|
||||
const texts=JSON.parse(fs.readFileSync(dir+'source-texts.json','utf8'));
|
||||
const normalize=s=>s.normalize('NFD').replace(/\p{Diacritic}/gu,'').toLowerCase().trim();
|
||||
const provincePlan={A03:[['Nampula','secondary'],['Cabo Delgado','secondary'],['Niassa','secondary'],['Tete','secondary'],['Zambezia','impact']],A04:[['Nampula','primary']],A05:[['Nampula','secondary'],['Cabo Delgado','secondary']],A06:[['Tete','secondary'],['Manica','secondary'],['Zambezia','secondary'],['Sofala','secondary']],A07:[['Sofala','primary'],['Manica','secondary'],['Tete','secondary']],A08:[['Zambezia','primary']],A09:[['Zambezia','primary']],A10:[['Tete','primary']],A11:[['Tete','secondary'],['Zambezia','secondary']],A12:[['Zambezia','primary']],A13:[['Inhambane','primary']],A14:[['Gaza','primary']],A15:[['Maputo Província','primary']]};
|
||||
const plan={schema:1,target:inventory.target,inventory_file:fs.readdirSync(dir).filter(f=>f.startsWith('inventory')).sort().at(-1),created_at:new Date().toISOString(),locations:[],memberships:[],prepared_opportunities:[],pending:[]};
|
||||
for(const project of inventory.projects.filter(p=>/^A\d{2}$/.test(p.code))){
|
||||
const dossier=inventory.dossiers.find(d=>d.project_id===project.id&&!d.deleted_at);
|
||||
const content=JSON.parse(dossier.content);
|
||||
for(const [name,role]of provincePlan[project.code]??[]){
|
||||
const nodes=inventory.locations.filter(l=>l.location_type==='province'&&!l.deleted_at&&normalize(l.name)===normalize(name));
|
||||
if(nodes.length!==1){plan.pending.push({code:project.code,reason:'Identidade territorial ambígua',name});continue;}
|
||||
const location=nodes[0];
|
||||
plan.locations.push({project_id:project.id,code:project.code,dossier_id:dossier.id,dossier_version:dossier.version_no,geo_location_id:location.id,name:location.name,role,source_reference:dossier.source,source_quote:content.location,reason:role==='impact'?'Referência parcial ao Norte da Zambézia; não representa cobertura integral da província':'Província explicitamente identificada na localização do dossier autorizado',expected_project_version:project.version_no,data_classification:dossier.publication_status==='published'?'public':'internal',existing:inventory.project_locations.some(l=>!l.deleted_at&&l.project_id===project.id&&l.geo_location_id===location.id&&l.role===role)});
|
||||
}
|
||||
if(['A01','A02'].includes(project.code))plan.pending.push({code:project.code,reason:'Âmbito nacional sem implantação individual ou traçado documentado; não atribuir um ponto único.'});
|
||||
plan.pending.push({code:project.code,reason:'Coordenadas, posto administrativo e localidade sem fonte exacta. Cidade/zona não convertida automaticamente em distrito.'});
|
||||
}
|
||||
// Districts expressly called districts in the source; city names and ambiguous settlements remain text.
|
||||
for(const [code,province,districts,role]of [['A15','Maputo Província',['Boane','Moamba','Namaacha'],'impact'],['A11','Zambezia',['Nicoadala'],'secondary']]){
|
||||
const p=inventory.projects.find(p=>p.code===code),d=inventory.dossiers.find(d=>d.project_id===p.id),base=plan.locations.find(l=>l.code===code&&normalize(l.name)===normalize(province));
|
||||
for(const name of districts){const nodes=inventory.locations.filter(l=>l.location_type==='district'&&l.parent_id===base.geo_location_id&&!l.deleted_at&&normalize(l.name)===normalize(name));if(nodes.length!==1){plan.pending.push({code,reason:'Distrito sem correspondência exacta e única',name});continue;}plan.locations.push({...base,geo_location_id:nodes[0].id,name:nodes[0].name,role,reason:'Distrito explicitamente identificado na fonte; sem inferir posto, localidade ou coordenadas.',existing:inventory.project_locations.some(l=>!l.deleted_at&&l.project_id===p.id&&l.geo_location_id===nodes[0].id&&l.role===role)});}
|
||||
}
|
||||
for(const cluster of inventory.clusters){
|
||||
const dossier=inventory.dossiers.find(d=>d.cluster_id===cluster.id&&!d.deleted_at),content=JSON.parse(dossier.content);
|
||||
for(const code of [...new Set(content.anchors.match(/\bA\d{2}\b/g)??[])]){
|
||||
const project=inventory.projects.find(p=>p.code===code&&!p.deleted_at);if(!project){plan.pending.push({code:cluster.code,project:code,reason:'Projecto citado sem cadastro'});continue;}
|
||||
const existing=inventory.cluster_projects.find(l=>l.project_id===project.id&&l.cluster_id===cluster.id&&!l.deleted_at);
|
||||
plan.memberships.push({cluster_id:cluster.id,cluster_code:cluster.code,project_id:project.id,project_code:code,role:'anchor',existing_id:existing?.id??null,existing_version:existing?.version_no??0,dossier_id:dossier.id,dossier_version:dossier.version_no,source_reference:dossier.source,source_quote:content.anchors,reason:'Código exacto do projecto citado no dossier do cluster; relação de planeamento, sem confirmar pertença jurídica',action:existing?'present_existing':'insert_missing'});
|
||||
}
|
||||
plan.pending.push({code:cluster.code,reason:'Área própria de abrangência não individualizada na fonte; locais dos membros não definem o perímetro do cluster.'});
|
||||
if(!inventory.value_chains.some(v=>v.cluster_id===cluster.id&&!v.deleted_at))plan.pending.push({code:cluster.code,reason:'Sem elos cadastrados em value_chains. Actividades e lacunas do dossier permanecem consultáveis; não foram convertidas em cadeias confirmadas.'});
|
||||
}
|
||||
const source=texts.find(t=>t.path.endsWith('projectos.docx'));
|
||||
for(const [index,table]of source.tables.entries()){
|
||||
if(!table[0].includes('Localização'))continue;
|
||||
const anchor=table[1]?.[0]?.trim();
|
||||
const conflict=index<3; // caption/project identifier conflict documented in original, never silently renumbered.
|
||||
for(const [rowIndex,row]of table.entries()){
|
||||
if(rowIndex<2||!row[0]?.trim())continue;
|
||||
const original=row[0].trim(),project=inventory.projects.find(p=>p.code===anchor),ref=original;
|
||||
const existing=inventory.opportunities.find(o=>o.reference===ref);
|
||||
plan.prepared_opportunities.push({reference:ref,source_identifier:row[0],title:row[1],summary:row[3],description:row.map((cell,i)=>`${table[0][i]}: ${cell}`).join('\n'),location_text:row[4],cost_text:row[5],horizon_text:row[6],source_reference:`${source.path}; SHA256 ${source.sha256}; tabela ${index+1}, linha ${rowIndex+1}`,source_sha256:source.sha256,source_table:index+1,source_row:rowIndex+1,source_cells:row,status:'draft',project_id:conflict?null:project?.id??null,project_code:conflict?null:anchor,existing_id:existing?.id??null,identity_status:conflict?'conflict_caption_anchor_code':'explicit_source_code',unknown:['sector_id','promotor confirmado','maturidade','coordenadas','títulos e disponibilidade','interpretação monetária'],reason:conflict?'Código da âncora e legenda da tabela incompatíveis com os dossiers; não associar nem renumerar':'Componente identificado por código exacto na tabela da âncora; preparado sem publicar, sem associação automática aos clusters'});
|
||||
}
|
||||
}
|
||||
plan.pending.push({code:'opportunity_projects',reason:'As seis oportunidades existentes não têm código documental que as associe às âncoras. Nenhuma associação inferida por nome ou sector.'});
|
||||
const data=JSON.stringify(plan,null,2);fs.writeFileSync(dir+'preview.json',data);fs.writeFileSync(dir+'preview.sha256',crypto.createHash('sha256').update(data).digest('hex'));
|
||||
console.log(JSON.stringify({locations:plan.locations.length,projectsWithLocations:new Set(plan.locations.map(l=>l.code)).size,memberships:plan.memberships.length,existingMemberships:plan.memberships.filter(l=>l.existing_id).length,prepared:plan.prepared_opportunities.length,identityConflicts:plan.prepared_opportunities.filter(o=>o.identity_status.startsWith('conflict')).length,pending:plan.pending.length}));
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
// QA-only HTTP harness: fixed isolated restored database; never use artisan serve for this test.
|
||||
$root = dirname(__DIR__);
|
||||
foreach (['APP_ENV'=>'testing','APP_DEBUG'=>'true','DB_CONNECTION'=>'pgsql','DB_HOST'=>'127.0.0.1','DB_PORT'=>'55441',
|
||||
'DB_DATABASE'=>'anchor_restore_20261007_test','DB_USERNAME'=>'postgres','DB_PASSWORD'=>'','DB_URL'=>'',
|
||||
'QUEUE_CONNECTION'=>'sync','SESSION_DRIVER'=>'file','SESSION_COOKIE'=>'anchor_relationship_qa','CACHE_STORE'=>'array',
|
||||
'PORTAL_MANAGER_EMAILS'=>'relationship-qa@example.invalid,partnership-qa-moderator@example.invalid','MAIL_MAILER'=>'array'] as $key=>$value) {
|
||||
putenv($key.'='.$value); $_ENV[$key]=$value; $_SERVER[$key]=$value;
|
||||
}
|
||||
$path=rawurldecode(parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH)?:'/');
|
||||
if ($path!=='/' && is_file($root.'/public'.$path)) return false;
|
||||
require_once $root.'/vendor/autoload.php';
|
||||
$app=require $root.'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$connection=config('database.connections.'.config('database.default'));
|
||||
if (($connection['database']??null)!=='anchor_restore_20261007_test' || (string)($connection['port']??'')!=='55441'
|
||||
|| ($connection['host']??null)!=='127.0.0.1' || !in_array($connection['url']??null,[null,''],true)) {http_response_code(503);exit('QA target rejected');}
|
||||
$identity=Illuminate\Support\Facades\DB::selectOne('select current_database() as database, inet_server_port() as port');
|
||||
if ($identity->database!=='anchor_restore_20261007_test'||(int)$identity->port!==55441){http_response_code(503);exit('QA connected identity rejected');}
|
||||
$planDirectory = getenv('RELATIONSHIP_QA_PLAN') === 'territorial' ? 'qa-territorial-preview' : 'qa-preview';
|
||||
config(['inertia.ssr.enabled'=>false,'session.files'=>$root.'/storage/framework/anchor-qa-sessions',
|
||||
'investment.repair_directory'=>$root.'/storage/app/private/anchor-project-reconciliation/'.$planDirectory]);
|
||||
if(!is_dir(config('session.files')))mkdir(config('session.files'),0700,true);
|
||||
Illuminate\Support\Facades\Vite::useHotFile($root.'/storage/framework/anchor-qa-hot-file');
|
||||
header('X-Investmoz-QA-Target: '.$identity->database.':'.$identity->port);
|
||||
$app->handleRequest(Illuminate\Http\Request::capture());
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
foreach (['APP_ENV'=>'testing','DB_CONNECTION'=>'pgsql','DB_HOST'=>'127.0.0.1','DB_PORT'=>'55441','DB_DATABASE'=>'anchor_restore_20261007_test','DB_USERNAME'=>'postgres','DB_PASSWORD'=>'','DB_URL'=>''] as $key=>$value) {
|
||||
putenv($key.'='.$value); $_ENV[$key]=$value; $_SERVER[$key]=$value;
|
||||
}
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app=require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$db=Illuminate\Support\Facades\DB::connection();
|
||||
if ($db->getDatabaseName()!=='anchor_restore_20261007_test'||(string)$db->getConfig('port')!=='55441'||$db->getConfig('host')!=='127.0.0.1')throw new RuntimeException('QA target rejected before seed.');
|
||||
$identity=$db->selectOne('select current_database() as database,inet_server_port() as port');
|
||||
if($identity->database!=='anchor_restore_20261007_test'||(int)$identity->port!==55441)throw new RuntimeException('QA runtime identity rejected.');
|
||||
$uuid=fn()=>(string)Illuminate\Support\Str::uuid();
|
||||
$manifest=$db->transaction(function()use($db,$uuid){
|
||||
$user=App\Models\User::firstOrCreate(['email'=>'relationship-qa@example.invalid'],['name'=>'Synthetic QA manager','email_verified_at'=>now(),'password'=>Illuminate\Support\Facades\Hash::make('QA-Relationship-2026!')]);
|
||||
$user->forceFill(['email_verified_at'=>now()])->save();
|
||||
$sector=App\Models\Sector::firstOrCreate(['slug'=>'qa-relationship'],['name'=>'Synthetic QA relationship sector','is_active'=>true]);
|
||||
$parent=null;$ids=[];
|
||||
foreach(['country','province','district','admin_post','locality']as$type){
|
||||
$external='qa-relationship-'.$type;
|
||||
$node=$db->table('geo_locations')->where('source_system','cartografia-workbook')->where('code',$external)->first();
|
||||
$id=$node?->id??$uuid();
|
||||
if(!$node)$db->table('geo_locations')->insert(['id'=>$id,'code'=>$external,'name'=>'QA '.$type,'location_type'=>$type,'parent_id'=>$parent,'data_classification'=>'public',
|
||||
'source_system'=>'cartografia-workbook','external_id'=>'964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$external]);
|
||||
$ids[$type]=$id;$parent=$id;
|
||||
}
|
||||
$projects=[];$dossiers=[];
|
||||
foreach([1,2]as$index){
|
||||
$project=App\Models\Project::firstOrCreate(['code'=>'QA-ANCHOR-'.$index],['name'=>'Synthetic QA anchor '.$index,'source_system'=>'qa-relationship','status'=>'planned','data_classification'=>'public']);
|
||||
$dossier=App\Models\InvestmentDossier::firstOrCreate(['project_id'=>$project->id],['title'=>$project->name,'source'=>'Synthetic browser QA fixture; no operational coordinates',
|
||||
'content'=>['location'=>'QA province / district / admin_post / locality','description'=>'Synthetic project with documented QA fixture site'],'publication_status'=>'published','published_at'=>now(),
|
||||
'approval_basis'=>'document_owner','approval_evidence'=>'Synthetic QA disclosure fixture only']);
|
||||
$site=$db->table('geo_locations')->where('code','qa-anchor-site-'.$index)->first();$siteId=$site?->id??$uuid();
|
||||
if(!$site)$db->table('geo_locations')->insert(['id'=>$siteId,'code'=>'qa-anchor-site-'.$index,'name'=>'QA documented site '.$index,'location_type'=>'site','parent_id'=>$parent,'data_classification'=>'public','source_system'=>'qa-relationship']);
|
||||
if(!$db->table('project_locations')->where('project_id',$project->id)->where('geo_location_id',$siteId)->exists())$db->table('project_locations')->insert(['id'=>$uuid(),'project_id'=>$project->id,'geo_location_id'=>$siteId,'role'=>$index===1?'primary':'secondary','data_classification'=>'public','source_system'=>'qa-relationship']);
|
||||
if(!$db->table('geo_geometries')->where('geo_location_id',$siteId)->exists())$db->table('geo_geometries')->insert(['id'=>$uuid(),'geo_location_id'=>$siteId,'geometry_type'=>'point','data_classification'=>'public','source_system'=>'synthetic QA source',
|
||||
'geom'=>Illuminate\Support\Facades\DB::raw('ST_SetSRID(ST_MakePoint('.(32.4+$index/10).','.(-25.8-$index/10).'),4326)')]);
|
||||
$projects[]=$project;$dossiers[]=$dossier;
|
||||
}
|
||||
$cluster=App\Models\EconomicCluster::firstOrCreate(['code'=>'QA-REL-CLU'],['name'=>'Synthetic QA multi-site cluster','sector'=>'QA','status'=>'planned','data_classification'=>'public']);
|
||||
$clusterDossier=App\Models\InvestmentDossier::firstOrCreate(['cluster_id'=>$cluster->id],['title'=>$cluster->name,'source'=>'Synthetic QA member relationship source',
|
||||
'content'=>['anchors'=>'QA-ANCHOR-1, QA-ANCHOR-2; coverage pending','gaps'=>'Synthetic QA chain gaps'],'publication_status'=>'published','published_at'=>now(),
|
||||
'approval_basis'=>'document_owner','approval_evidence'=>'Synthetic QA fixture disclosure only']);
|
||||
foreach($projects as$project)if(!$db->table('cluster_projects')->where('cluster_id',$cluster->id)->where('project_id',$project->id)->exists())$db->table('cluster_projects')->insert(['id'=>$uuid(),'cluster_id'=>$cluster->id,'project_id'=>$project->id,'role'=>'anchor','data_classification'=>'public','source_system'=>'qa-relationship','source_reference'=>'Synthetic documented QA membership','validation_status'=>'pending']);
|
||||
$production=App\Models\ValueChain::firstOrCreate(['cluster_id'=>$cluster->id,'code'=>'QA-PRODUCTION'],['name'=>'QA production','stage'=>'production','data_classification'=>'public']);
|
||||
$processing=App\Models\ValueChain::firstOrCreate(['cluster_id'=>$cluster->id,'code'=>'QA-PROCESSING'],['name'=>'QA processing','stage'=>'processing','data_classification'=>'public']);
|
||||
if(!$db->table('value_chain_links')->where('from_value_chain_id',$production->id)->where('to_value_chain_id',$processing->id)->exists())$db->table('value_chain_links')->insert(['id'=>$uuid(),'from_value_chain_id'=>$production->id,'to_value_chain_id'=>$processing->id,'link_type'=>'supplies','data_classification'=>'public']);
|
||||
$opportunity=App\Models\Opportunity::firstOrCreate(['reference'=>'QA-ANCHOR-OPPORTUNITY'],['sector_id'=>$sector->id,'title'=>'Synthetic QA linked opportunity','slug'=>'qa-anchor-opportunity','summary'=>'Synthetic browser QA fixture','status'=>'published','published_at'=>now()]);
|
||||
$db->table('opportunity_projects')->insertOrIgnore(['opportunity_id'=>$opportunity->id,'project_id'=>$projects[0]->id]);
|
||||
$db->table('opportunity_clusters')->insertOrIgnore(['opportunity_id'=>$opportunity->id,'cluster_id'=>$cluster->id]);
|
||||
return ['target'=>'anchor_restore_20261007_test:55441','project_dossier'=>$dossiers[0]->id,'second_project'=>$projects[1]->id,'cluster_dossier'=>$clusterDossier->id,'opportunity_slug'=>$opportunity->slug,'opportunity_id'=>$opportunity->id,'province_id'=>$ids['province']];
|
||||
});
|
||||
$directory=storage_path('app/private/anchor-project-reconciliation');
|
||||
if(!is_dir($directory.'/qa-preview'))mkdir($directory.'/qa-preview',0700,true);
|
||||
$plan=json_decode(file_get_contents($directory.'/preview.json'),true);$plan['target']=['database'=>'anchor_restore_20261007_test','port'=>55441];
|
||||
file_put_contents($directory.'/qa-preview/preview.json',json_encode($plan,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));
|
||||
$proof=json_decode(file_get_contents($directory.'/backup-proof.json'),true);$proof['target']=$plan['target'];
|
||||
file_put_contents($directory.'/qa-preview/backup-proof.json',json_encode($proof,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
file_put_contents($directory.'/qa-browser-fixture.json',json_encode($manifest,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode($manifest).PHP_EOL;
|
||||
@@ -0,0 +1,43 @@
|
||||
const { chromium } = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const fs = require('node:fs');
|
||||
const assert = require('node:assert/strict');
|
||||
const base = 'http://127.0.0.1:18087';
|
||||
(async () => {
|
||||
const browser = await chromium.launch({headless:true, executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe'});
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
await context.route('**/*', route => route.request().url().startsWith(base) ? route.continue() : route.abort());
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.goto(base+'/login');
|
||||
await page.locator('input[type=email]').fill('relationship-qa@example.invalid');
|
||||
await page.locator('input[type=password]').fill('QA-Relationship-2026!');
|
||||
await page.locator('button[type=submit]').click();
|
||||
await page.waitForURL(url => !url.pathname.startsWith('/login'));
|
||||
const response = await page.goto(base+'/management/relationship-repair', {waitUntil:'networkidle'});
|
||||
assert.equal(response.headers()['x-investmoz-qa-target'], 'anchor_restore_20261007_test:55441');
|
||||
await page.getByRole('heading',{name:'Fundamentadas: 2',exact:true}).waitFor();
|
||||
await page.getByRole('heading',{name:'Pendentes: 1',exact:true}).waitFor();
|
||||
await page.getByRole('heading',{name:'Contraditórias: 1',exact:true}).waitFor();
|
||||
const grounded = page.getByRole('region',{name:'Associações fundamentadas'});
|
||||
for (const text of ['Localização atual','Localização proposta','Documento de origem','Motivo','Sem coordenadas']) assert((await grounded.innerText()).includes(text));
|
||||
await grounded.getByRole('button',{name:'Aplicar esta associação',exact:true}).first().click();
|
||||
await grounded.getByRole('button',{name:'Associação aplicada',exact:true}).waitFor();
|
||||
assert.equal(await grounded.getByRole('button',{name:'Aplicar esta associação',exact:true}).count(),1);
|
||||
await grounded.getByRole('button',{name:'Aplicar esta associação',exact:true}).click();
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-row-id] button').length===4 && [...document.querySelectorAll('[data-row-id] button')].filter(button=>button.textContent==='Associação aplicada').length===2);
|
||||
assert(await page.getByRole('region',{name:'Associações pendentes'}).getByRole('button').isDisabled());
|
||||
assert(await page.getByRole('region',{name:'Associações contraditórias'}).getByRole('button').isDisabled());
|
||||
assert((await page.locator('body').innerText()).includes('Autor:'));
|
||||
assert((await page.locator('body').innerText()).includes('Data:'));
|
||||
for (const width of [1440,390]) {
|
||||
await page.setViewportSize({width,height:1000});
|
||||
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
||||
await page.screenshot({path:`docs/investmoz/relationships/territorial-${width}.png`,fullPage:true});
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
fs.writeFileSync('docs/investmoz/relationships/territorial-browser-qa.json',JSON.stringify({target:'anchor_restore_20261007_test:55441',passed:true,individualApplications:2,pendingRetained:1,contradictoryRetained:1,noCoordinatesAccepted:true,auditAuthorDateSource:true,viewports:[1440,390],errors},null,2));
|
||||
console.log('QA territorial browser passed: two individual applications, conflicts retained, author/date/source, desktop/mobile.');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
// Synthetic preview only, fixed isolated restored QA database; never writes active data.
|
||||
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'anchor_restore_20261007_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => ''] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$identity = Illuminate\Support\Facades\DB::selectOne('select current_database() as database, inet_server_port() as port');
|
||||
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
|
||||
throw new RuntimeException('Isolated QA required');
|
||||
}
|
||||
$root = storage_path('app/private/anchor-project-reconciliation');
|
||||
$fixture = json_decode(file_get_contents($root.'/qa-browser-fixture.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$dossier = Illuminate\Support\Facades\DB::table('investment_dossiers')->where('id', $fixture['project_dossier'])->first();
|
||||
$project = Illuminate\Support\Facades\DB::table('projects')->where('id', $dossier->project_id)->first();
|
||||
if (! str_starts_with($project->code, 'QA-')) {
|
||||
throw new RuntimeException('Synthetic project required');
|
||||
}
|
||||
$site = Illuminate\Support\Facades\DB::table('project_locations')->where('project_id', $project->id)->where('role', 'primary')->first();
|
||||
$nodes = [];
|
||||
$id = $site->geo_location_id;
|
||||
while ($id) {
|
||||
$node = Illuminate\Support\Facades\DB::table('geo_locations')->where('id', $id)->first();
|
||||
$nodes[$node->location_type] = $node;
|
||||
$id = $node->parent_id;
|
||||
}
|
||||
$base = ['project_id' => $project->id, 'code' => $project->code, 'dossier_id' => $dossier->id, 'dossier_version' => $dossier->version_no,
|
||||
'source_reference' => $dossier->source, 'source_quote' => json_decode($dossier->content, true)['location'],
|
||||
'reason' => 'Synthetic QA individual territorial validation', 'expected_project_version' => $project->version_no, 'data_classification' => 'public'];
|
||||
$rows = [];
|
||||
foreach ([['province', 'secondary'], ['district', 'impact'], ['admin_post', 'secondary'], ['locality', 'impact']] as [$type, $role]) {
|
||||
$rows[] = [...$base, 'geo_location_id' => $nodes[$type]->id, 'name' => $nodes[$type]->name, 'role' => $role, 'existing' => false];
|
||||
}
|
||||
$rows[2]['source_quote'] = '';
|
||||
$rows[3]['province_id'] = (string) Illuminate\Support\Str::uuid();
|
||||
$directory = $root.'/qa-territorial-preview';
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
file_put_contents($directory.'/preview.json', json_encode(['target' => ['database' => $identity->database, 'port' => (int) $identity->port],
|
||||
'locations' => $rows, 'memberships' => [], 'prepared_opportunities' => [], 'pending' => []], JSON_THROW_ON_ERROR));
|
||||
copy($root.'/qa-preview/backup-proof.json', $directory.'/backup-proof.json');
|
||||
echo "Synthetic isolated QA territorial preview prepared.\n";
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$active = Illuminate\Support\Facades\DB::connection();
|
||||
if ($active->getDatabaseName() !== 'investemoz' || (string) $active->getConfig('port') !== '5432') throw new RuntimeException('Unexpected active target.');
|
||||
config(['database.connections.anchor_restore' => [...config('database.connections.pgsql'), 'host' => '127.0.0.1', 'port' => '55441',
|
||||
'database' => 'anchor_restore_20261007_test', 'username' => 'postgres', 'password' => '', 'url' => null]]);
|
||||
$restore = Illuminate\Support\Facades\DB::connection('anchor_restore');
|
||||
$identity = $restore->selectOne('select current_database() as database, inet_server_port() as port');
|
||||
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) throw new RuntimeException('Restore verification requires isolated QA.');
|
||||
$report = $active->transaction(function () use ($active, $restore) {
|
||||
$active->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
$counts = [];
|
||||
foreach ($active->select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
|
||||
$name = $table->tablename;
|
||||
$a = $active->table($name)->count();
|
||||
$b = $restore->table($name)->count();
|
||||
if ($a !== $b) throw new RuntimeException('Restore count differs for '.$name);
|
||||
$counts[$name] = $a;
|
||||
}
|
||||
$hashes = [];
|
||||
foreach (['projects','economic_clusters','investment_dossiers','project_locations','cluster_projects','opportunity_projects','opportunity_clusters','value_chains','value_chain_links','opportunities','geo_locations','geo_geometries'] as $table) {
|
||||
$hash = function ($db) use ($table) {
|
||||
$rows = array_map(fn ($row) => $row->value, $db->select('select row_to_json(t)::text as value from public.'.$table.' as t'));
|
||||
sort($rows, SORT_STRING);
|
||||
return hash('sha256', implode("\n", $rows));
|
||||
};
|
||||
$a = $hash($active);
|
||||
if ($a !== $hash($restore)) throw new RuntimeException('Restore data differs for '.$table);
|
||||
$hashes[$table] = $a;
|
||||
}
|
||||
return ['table_counts' => $counts, 'relation_table_hashes' => $hashes];
|
||||
});
|
||||
$directory = storage_path('app/private/anchor-project-reconciliation');
|
||||
$dump = $directory.'/backup-20261007/database.dump';
|
||||
$proof = [...$report, 'restore_verified' => true, 'verified_at' => date(DATE_ATOM), 'target' => ['database'=>'investemoz','port'=>5432],
|
||||
'restored_target' => ['database'=>$identity->database,'port'=>$identity->port], 'dump_path'=>$dump,'sha256'=>hash_file('sha256',$dump)];
|
||||
file_put_contents($directory.'/backup-proof.json',json_encode($proof,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo 'Restore verified: '.count($report['table_counts']).' table counts and '.count($report['relation_table_hashes']).' content hashes.'.PHP_EOL;
|
||||
Reference in New Issue
Block a user