Add audited opportunity origin review and QA separation
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
// Read-only verification in the restored QA database; never connect to the active target.
|
||||
$directory = dirname(__DIR__).'/storage/app/private/investmoz-v2';
|
||||
$proof = json_decode(file_get_contents($directory.'/territory-backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$plan = json_decode(file_get_contents($directory.'/opportunity-association-plan.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$target = $proof['restored_target'];
|
||||
if (! $proof['restore_verified'] || ! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $target['database']) || (int) $target['port'] !== 55441) {
|
||||
throw new RuntimeException('Isolated restored QA required.');
|
||||
}
|
||||
$pdo = new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$target['database'], 'postgres', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$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);
|
||||
if ($identity['database'] !== $target['database'] || (int) $identity['port'] !== 55441 || $identity['read_only'] !== 'on' || $plan['associations'] !== [] || $plan['deletions'] !== []) {
|
||||
throw new RuntimeException('QA identity or review-only plan mismatch.');
|
||||
}
|
||||
$checks = [];
|
||||
foreach ($plan['records'] as $record) {
|
||||
$statement = $pdo->prepare('SELECT reference,title,description FROM opportunities WHERE id=?');
|
||||
$statement->execute([$record['id']]);
|
||||
$current = $statement->fetch(PDO::FETCH_ASSOC);
|
||||
if (! $current || $current['reference'] !== $record['reference'] || $current['title'] !== $record['title'] || $current['description'] !== $record['description']) {
|
||||
throw new RuntimeException('QA record identity differs.');
|
||||
}
|
||||
foreach (['opportunity_projects' => 'project_id', 'opportunity_clusters' => 'cluster_id'] as $table => $column) {
|
||||
$statement = $pdo->prepare('SELECT '.$column.' FROM '.$table.' WHERE opportunity_id=? ORDER BY '.$column);
|
||||
$statement->execute([$record['id']]);
|
||||
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||
$expected = $table === 'opportunity_projects' ? $record['existing_projects'] : $record['existing_clusters'];
|
||||
if ($rows !== $expected) {
|
||||
throw new RuntimeException('Existing relationships differ.');
|
||||
}
|
||||
}
|
||||
if ($record['unequivocal_links'] !== [] || array_filter($record['options'], fn ($option) => $option['relation_proven'])) {
|
||||
throw new RuntimeException('An option was promoted without a decision.');
|
||||
}
|
||||
$checks[] = ['id' => $record['id'], 'identity_matches' => true, 'existing_links_preserved' => true, 'no_option_applied' => true];
|
||||
}
|
||||
$pdo->exec('ROLLBACK');
|
||||
$evidence = ['recorded_at' => gmdate('c'), 'identity' => $identity, 'checks' => $checks, 'plan_has_no_writes' => true, 'active_writes' => 0];
|
||||
file_put_contents($directory.'/opportunity-association-qa.json', json_encode($evidence, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($evidence, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,259 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const dir = path.join(root, 'storage/app/private/investmoz-v2');
|
||||
const read = (file) =>
|
||||
JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
|
||||
const audit = read(path.join(dir, 'territory-audit.json'));
|
||||
if (audit.identity.read_only !== 'on') throw Error('Read-only audit required');
|
||||
const sources = read(
|
||||
path.join(
|
||||
root,
|
||||
'storage/app/private/anchor-project-reconciliation/source-texts.json',
|
||||
),
|
||||
);
|
||||
const master = read(path.join(dir, 'master-paragraphs-reopened.json'));
|
||||
const norm = (text) =>
|
||||
text
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, ' ');
|
||||
const units = sources
|
||||
.flatMap((s) => [
|
||||
...s.paragraphs.map((text, i) => ({
|
||||
source: path.win32.basename(s.path),
|
||||
locator: `parágrafo extraído ${i + 1}`,
|
||||
text,
|
||||
})),
|
||||
...s.tables.flatMap((table, i) =>
|
||||
table.map((cells, j) => ({
|
||||
source: path.win32.basename(s.path),
|
||||
locator: `tabela ${i + 1}, linha ${j + 1}`,
|
||||
text: cells.join(' | '),
|
||||
})),
|
||||
),
|
||||
])
|
||||
.concat(
|
||||
master.map((r) => ({
|
||||
source: 'Documento mestre relido',
|
||||
locator: `w:p ${r.p}`,
|
||||
text: r.text,
|
||||
})),
|
||||
);
|
||||
const decisions = {
|
||||
1: {
|
||||
options: [
|
||||
['A03', 'description'],
|
||||
['CLU-01', 'anchors'],
|
||||
],
|
||||
question:
|
||||
'Qual é a atividade/cultura e o código do componente desta unidade? Integra expressamente o Corredor de Nacala ou apenas o âmbito de processamento do CLU-01? A06 refere a cadeia do arroz no Centro, não identifica esta unidade.',
|
||||
},
|
||||
2: {
|
||||
options: [
|
||||
['A08', 'description'],
|
||||
['CLU-02', 'gaps'],
|
||||
],
|
||||
question:
|
||||
'Qual é o polo produtivo e o código da mini-rede que abastece as 40 unidades? A fonte não identifica se faz parte de Mocuba, de outro parque ou de um projeto independente; geração solar não é identidade com A10 hidroelétrica.',
|
||||
},
|
||||
3: {
|
||||
options: [
|
||||
['A13', 'description'],
|
||||
['CLU-04', 'gaps'],
|
||||
],
|
||||
question:
|
||||
'Qual é o nome/local exato do empreendimento e o componente documental? Está integrado em Vilanculos–Inhassoro–Bazaruto ou é um empreendimento costeiro independente? Inhambane e eco-lodge não demonstram essa integração.',
|
||||
},
|
||||
4: {
|
||||
options: [
|
||||
['A02', 'description'],
|
||||
['A03', 'description'],
|
||||
['A11', 'description'],
|
||||
['CLU-03', 'gaps'],
|
||||
],
|
||||
question:
|
||||
'Qual é o terminal/plataforma, o corredor servido e o código contratual ou documental? A redução de custos logísticos não determina se integra Norte–Sul, Nacala, Macuse–Moatize ou nenhum deles; Sofala não decide a ligação.',
|
||||
},
|
||||
5: {
|
||||
options: [
|
||||
['A12', 'description'],
|
||||
['CLU-04', 'anchors'],
|
||||
],
|
||||
question:
|
||||
'Qual é a unidade de pescado e o componente do programa ao qual pertence? A12 identifica resiliência costeira, mas não esta unidade de processamento. CLU-04 identifica turismo/marinas, não demonstra cadeia fria pesqueira; pode não haver âncora/cluster correspondente no cadastro atual.',
|
||||
},
|
||||
6: {
|
||||
options: [
|
||||
['CLU-08', 'anchors'],
|
||||
['CLU-07', 'anchors'],
|
||||
['CLU-01', 'gaps'],
|
||||
],
|
||||
question:
|
||||
'Qual é o operador/instrumento e a relação assumida: financiamento transversal CLU-08, serviço fintech CLU-07 ou financiamento da cadeia CLU-01? Qual documento identifica esta plataforma e as 300+ empresas? Não atribuir todos os clusters automaticamente.',
|
||||
},
|
||||
};
|
||||
const records = audit.records
|
||||
.filter((r) => r.kind === 'opportunities')
|
||||
.map((entity) => {
|
||||
const opportunity = entity.record;
|
||||
const decision = decisions[opportunity.id];
|
||||
if (!decision)
|
||||
throw Error('New opportunity requires individual review');
|
||||
const hits = units.filter((u) =>
|
||||
[
|
||||
opportunity.reference,
|
||||
opportunity.title,
|
||||
opportunity.description,
|
||||
].some((text) => norm(u.text).includes(norm(text))),
|
||||
);
|
||||
const options = decision.options.map(([code, field]) => {
|
||||
const dossier = audit.dossiers.find(
|
||||
(d) => JSON.parse(d.content).code === code,
|
||||
);
|
||||
if (!dossier) throw Error('Missing dossier ' + code);
|
||||
const content = JSON.parse(dossier.content);
|
||||
return {
|
||||
code,
|
||||
target_id: dossier.project_id || dossier.cluster_id,
|
||||
target_type: dossier.project_id ? 'project' : 'cluster',
|
||||
title: dossier.title,
|
||||
source_reference: dossier.source,
|
||||
dossier_id: dossier.id,
|
||||
quote: content[field],
|
||||
field,
|
||||
relation_proven: false,
|
||||
status: 'option_for_decision_only',
|
||||
};
|
||||
});
|
||||
return {
|
||||
id: opportunity.id,
|
||||
reference: opportunity.reference,
|
||||
title: opportunity.title,
|
||||
description: opportunity.description,
|
||||
existing_projects: entity.relations.projects,
|
||||
existing_clusters: entity.relations.clusters,
|
||||
source_mentions: hits.map((hit) => {
|
||||
const indices = [
|
||||
opportunity.reference,
|
||||
opportunity.title,
|
||||
opportunity.description,
|
||||
]
|
||||
.map((text) =>
|
||||
hit.text.toLowerCase().indexOf(text.toLowerCase()),
|
||||
)
|
||||
.filter((index) => index >= 0);
|
||||
const start = indices.length ? Math.min(...indices) : 0;
|
||||
return {
|
||||
source: hit.source,
|
||||
locator: hit.locator,
|
||||
quote: hit.text.slice(start, start + 240),
|
||||
};
|
||||
}),
|
||||
options,
|
||||
question: decision.question,
|
||||
unequivocal_links: [],
|
||||
status: 'decision_required',
|
||||
};
|
||||
});
|
||||
const plan = {
|
||||
schema: 1,
|
||||
captured_at: audit.captured_at,
|
||||
target: {
|
||||
database: audit.identity.database,
|
||||
port: Number(audit.identity.port),
|
||||
},
|
||||
coverage: {
|
||||
extracted_documents: sources.length,
|
||||
master_paragraphs: master.length,
|
||||
text_units: units.length,
|
||||
full_inventory_review: false,
|
||||
},
|
||||
existing_links_preserved: true,
|
||||
records,
|
||||
associations: [],
|
||||
deletions: [],
|
||||
status: 'decision_required',
|
||||
reason: 'No explicit identification links these six opportunity records to an anchor/cluster in the reviewed extracts. Options are not applied associations.',
|
||||
};
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'opportunity-association-plan.json'),
|
||||
JSON.stringify(plan, null, 2),
|
||||
);
|
||||
const lines = [
|
||||
'# Oportunidades — correspondências e plano único',
|
||||
'',
|
||||
`Leitura protegida: ${audit.captured_at}, ${plan.target.database}:${plan.target.port}. Consulta das extrações de ${sources.length} documentos e ${master.length} parágrafos do mestre relido; não é revisão integral dos ficheiros do inventário. A aceitação das fontes oficiais não foi reaberta.`,
|
||||
'',
|
||||
'**Resultado:** zero ligações inequívocas recuperadas para as seis oportunidades existentes. As opções abaixo são alternativas para decisão, não correspondências confirmadas. O trecho documenta o projeto/cluster candidato; não identifica automaticamente a oportunidade como seu componente.',
|
||||
'',
|
||||
'As referências de programação e os exemplos de código descrevem registos e funções. Não são reinterpretados como identidade institucional, promotor ou relação oficial. As correspondências continuam pendências específicas, independentes da cobertura do inventário, questões jurídicas, ClamD e primeiro pedido real.',
|
||||
];
|
||||
lines.push(
|
||||
'',
|
||||
'## Origem e perguntas ao responsável',
|
||||
'',
|
||||
'Ver [a conferência do seeder, a auditoria disponível e o plano condicional de separação](origem-oportunidades-e-separacao.md). Os registos coincidem com dados de código; isto não comprova investimentos reais nem autoriza classificá-los automaticamente como exemplos. Antes de decidir os pares, esclarecer projeto/polo dos IDs 1–3, localização/corredor do ID 4, integração em A12 ou independência do ID 5 e pertença versus serviço financeiro do ID 6. Nenhum contacto foi enviado e nenhuma decisão foi inventada.',
|
||||
);
|
||||
for (const r of records) {
|
||||
lines.push(
|
||||
'',
|
||||
`## ID ${r.id} — ${r.title}`,
|
||||
'',
|
||||
`Referência: \`${r.reference}\`. Descrição atual: ${r.description}`,
|
||||
'',
|
||||
`Relações já cadastradas: ${r.existing_projects.length} projetos, ${r.existing_clusters.length} clusters.`,
|
||||
'',
|
||||
'### Opções documentadas, sem associação automática',
|
||||
'',
|
||||
);
|
||||
for (const option of r.options)
|
||||
lines.push(
|
||||
`- **${option.code} — ${option.title}**, ID \`${option.target_id}\`. Fonte: ${option.source_reference}, dossier \`${option.dossier_id}\`, campo \`${option.field}\`. Trecho: «${option.quote}». **Não prova a relação com a oportunidade ${r.id}.**`,
|
||||
);
|
||||
lines.push(
|
||||
'',
|
||||
`**Dúvida concreta:** ${r.question}`,
|
||||
'',
|
||||
`**Identificação no acervo revisto:** ${
|
||||
r.source_mentions.length
|
||||
? r.source_mentions
|
||||
.slice(0, 3)
|
||||
.map(
|
||||
(hit) =>
|
||||
`${hit.source}, ${hit.locator}: «${hit.quote.replace(/\s+/g, ' ')}»`,
|
||||
)
|
||||
.join('; ') +
|
||||
'. Ocorrência de exemplo/código não constitui ligação a uma âncora.'
|
||||
: 'Não foi encontrada menção exata da referência/título/descrição nas extrações revistas. Não implica invalidade da fonte ou do registo.'
|
||||
}`,
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'## Plano único de novas ligações',
|
||||
'',
|
||||
'1. Preservar todas as relações existentes, incluindo as 28 associações territoriais e 13 relações cluster–projeto já conferidas.',
|
||||
'2. Decidir os pares dos seis registos acima e o âmbito da relação, podendo optar por nenhuma correspondência. Não exigir outra fonte para revalidar origem oficial aceite.',
|
||||
'3. Adicionar ao mesmo plano apenas pares identificados explicitamente, com trecho ou decisão de correspondência do proprietário; verificar os IDs atuais e excluir os pares já cadastrados.',
|
||||
'4. Preparar os pares decididos na base QA isolada, testar idempotência e os filtros/fichas/mapa, sem converter contexto em implantação.',
|
||||
'5. Atualizar backup/restauro, verificar reversão das inserções específicas e apresentar uma única pré-visualização autenticada antes da aplicação ativa.',
|
||||
'',
|
||||
'**Plano atual: zero inserções e zero eliminações.** Não existe um lote inequívoco para aplicar em QA ou na base ativa. A prova QA confirma que não houve associação automática nem alteração das relações existentes. Não reutilizar o botão de rastreabilidade das 13 referências como se aplicasse estas novas correspondências.',
|
||||
'',
|
||||
'Matriz e plano completos privados: `opportunity-association-plan.json`. As opções não vão para `opportunity_projects`/`opportunity_clusters` enquanto permanecerem indeterminadas.',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(root, 'docs/investmoz/v2/oportunidades-correspondencias.md'),
|
||||
lines.join('\n') + '\n',
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
records: records.length,
|
||||
associations: 0,
|
||||
sources: sources.length,
|
||||
text_units: units.length,
|
||||
decision_required: records.length,
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
// Reuse the protected reader; no seeder, Laravel kernel or write to the active database.
|
||||
require __DIR__.'/investmoz-v2-territory-audit.php';
|
||||
$directory = dirname(__DIR__).'/storage/app/private/investmoz-v2';
|
||||
$audit = json_decode(file_get_contents($directory.'/territory-audit.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$source = file_get_contents(dirname(__DIR__).'/database/seeders/OpportunitySeeder.php');
|
||||
preg_match_all("/'reference' => '([^']+)', 'title' => '([^']+)', 'province' => '([^']+)', 'maturity' => ([0-9]+), 'amount' => ([0-9]+), 'financing' => '([^']+)', 'impact' => '([^']+)'/", $source, $matches, PREG_SET_ORDER);
|
||||
if (count($matches) !== 6) {
|
||||
throw new RuntimeException('Seeder format changed; individual review required.');
|
||||
}
|
||||
$comparisons = [];
|
||||
foreach ($audit['records'] as $entity) {
|
||||
if ($entity['kind'] !== 'opportunities') {
|
||||
continue;
|
||||
}
|
||||
$record = $entity['record'];
|
||||
$seed = array_values(array_filter($matches, fn ($match) => $match[1] === $record['reference']))[0] ?? null;
|
||||
if (! $seed) {
|
||||
throw new RuntimeException('Opportunity not covered by reviewed seeder.');
|
||||
}
|
||||
$fields = ['reference' => $seed[1], 'title' => $seed[2], 'province' => $seed[3], 'maturity_level' => (int) $seed[4], 'estimated_investment_amount' => $seed[5], 'financing_modality' => $seed[6], 'description' => $seed[7], 'promoter_name' => 'Promotor em validação'];
|
||||
$checks = [];
|
||||
foreach ($fields as $field => $value) {
|
||||
$checks[$field] = $field === 'estimated_investment_amount' ? (float) $record[$field] === (float) $value : (string) $record[$field] === (string) $value;
|
||||
}
|
||||
$comparisons[] = ['id' => $record['id'], 'reference' => $record['reference'], 'title' => $record['title'], 'created_at' => $record['created_at'], 'status' => $record['status'], 'checks' => $checks, 'code_origin' => 'database/seeders/OpportunitySeeder.php', 'real_world_status' => 'not_established_by_seeder', 'classification_decision' => 'pending_responsible'];
|
||||
}
|
||||
$pdo->exec('BEGIN TRANSACTION READ ONLY');
|
||||
$events = $pdo->query("SELECT action,source_system,actor_user_id,occurred_at,after_data->>'reference' AS reference,after_data->>'opportunity_id' AS opportunity_id FROM audit_events WHERE entity_type IN ('opportunity','opportunities') OR after_data->>'reference' IN ('INV-MZ-AGR-001','INV-MZ-ENE-002','INV-MZ-TUR-003','INV-MZ-INF-004','INV-MZ-BLUE-005','INV-MZ-FIN-006') ORDER BY occurred_at,id")->fetchAll(PDO::FETCH_ASSOC);
|
||||
$importTables = $pdo->query("SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog','information_schema') AND (table_name ILIKE '%import%' OR table_name ILIKE '%seed%') ORDER BY table_schema,table_name")->fetchAll(PDO::FETCH_ASSOC);
|
||||
$classificationEvents = (int) $pdo->query("SELECT count(*) FROM audit_events WHERE source_system='opportunity-origin-review'")->fetchColumn();
|
||||
$pdo->exec('ROLLBACK');
|
||||
$proof = ['captured_at' => $audit['captured_at'], 'identity' => $audit['identity'], 'seeder_sha256' => hash('sha256', $source), 'comparisons' => $comparisons, 'available_opportunity_audit_events' => $events, 'import_registry_tables_found' => $importTables, 'active_classification_events' => $classificationEvents, 'creation_execution_proven' => false, 'official_origin_revalidation' => false, 'active_writes' => 0];
|
||||
file_put_contents($directory.'/opportunity-origin-confirmation.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['matching_records' => count($comparisons), 'matched_fields' => count(array_filter($comparisons, fn ($record) => ! in_array(false, $record['checks'], true))), 'available_audit_events' => count($events), 'real_world_status' => 'requires_responsible_confirmation', 'active_writes' => 0], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,170 @@
|
||||
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/investmoz-v2/';
|
||||
const backup = JSON.parse(
|
||||
fs.readFileSync(dir + 'opportunity-origin-backup-proof.json'),
|
||||
);
|
||||
const audit = JSON.parse(fs.readFileSync(dir + 'territory-audit.json'));
|
||||
const record = audit.records.find(
|
||||
(r) => r.kind === 'opportunities' && r.id === 1,
|
||||
).record;
|
||||
const base = 'http://127.0.0.1:18094';
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath:
|
||||
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
|
||||
});
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.route('**/*', (route) =>
|
||||
route.request().url().startsWith(base)
|
||||
? route.continue()
|
||||
: route.abort(),
|
||||
);
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(e.message));
|
||||
const response = await page.goto(base + '/login');
|
||||
assert.equal(
|
||||
response.headers()['x-investmoz-qa-target'],
|
||||
backup.restored_target.database + ':55441',
|
||||
);
|
||||
await page
|
||||
.locator('input[name=email]')
|
||||
.fill('origin-browser@example.invalid');
|
||||
await page.locator('input[name=password]').fill('Origin-QA-2026!');
|
||||
await page.getByRole('button', { name: 'Log in', exact: true }).click();
|
||||
await page.waitForURL((url) => url.pathname !== '/login');
|
||||
await page.goto(base + '/management/opportunity-origin');
|
||||
await page
|
||||
.getByRole('heading', {
|
||||
name: 'ID 1 — ' + record.title,
|
||||
exact: true,
|
||||
})
|
||||
.waitFor();
|
||||
assert.equal(await page.locator('article').count(), 6);
|
||||
const article = page.locator('article').first();
|
||||
const statusBeforePreview = (
|
||||
await page.request.get(
|
||||
base + '/api/v1/opportunities/' + record.slug,
|
||||
)
|
||||
).status();
|
||||
await article
|
||||
.getByLabel('Classificação', { exact: true })
|
||||
.selectOption('example');
|
||||
await article
|
||||
.getByLabel('Fundamento da decisão')
|
||||
.fill(
|
||||
'Declaração sintética QA: separar exemplo, sem classificar o registo ativo.',
|
||||
);
|
||||
await article
|
||||
.getByRole('button', { name: 'Pré-visualizar decisão' })
|
||||
.click();
|
||||
await article
|
||||
.getByRole('region', { name: 'Pré-visualização da classificação' })
|
||||
.waitFor();
|
||||
const apply = article.getByRole('button', {
|
||||
name: 'Aplicar decisão de classificação',
|
||||
});
|
||||
assert.equal(await apply.isEnabled(), false);
|
||||
assert.equal(
|
||||
(
|
||||
await page.request.get(
|
||||
base + '/api/v1/opportunities/' + record.slug,
|
||||
)
|
||||
).status(),
|
||||
statusBeforePreview,
|
||||
);
|
||||
await page.screenshot({ path: dir + 'opportunity-origin-preview.png' });
|
||||
await article
|
||||
.getByLabel('Confirmo esta decisão de classificação')
|
||||
.check();
|
||||
await apply.click();
|
||||
await article.getByRole('status').waitFor();
|
||||
await page.reload();
|
||||
await page
|
||||
.getByText(
|
||||
'Exemplo de demonstração — não constitui oportunidade real.',
|
||||
{ exact: false },
|
||||
)
|
||||
.waitFor();
|
||||
assert.equal(
|
||||
(
|
||||
await page.request.get(
|
||||
base + '/api/v1/opportunities/' + record.slug,
|
||||
)
|
||||
).status(),
|
||||
404,
|
||||
);
|
||||
const listing = await page.request.get(
|
||||
base + '/api/v1/opportunities/search',
|
||||
);
|
||||
assert.equal(listing.status(), 200);
|
||||
const map = await page.request.get(
|
||||
base + '/api/v1/investment/map?opportunity_id=1',
|
||||
);
|
||||
assert.equal(map.status(), 200);
|
||||
assert.equal((await map.json()).matched_count, 0);
|
||||
await article
|
||||
.getByLabel('Classificação', { exact: true })
|
||||
.selectOption('undetermined');
|
||||
await article
|
||||
.getByLabel('Fundamento da decisão')
|
||||
.fill(
|
||||
'QA: restituir classificação indeterminada, preservando auditoria.',
|
||||
);
|
||||
await article
|
||||
.getByRole('button', { name: 'Pré-visualizar decisão' })
|
||||
.click();
|
||||
await article
|
||||
.getByRole('region', { name: 'Pré-visualização da classificação' })
|
||||
.waitFor();
|
||||
await article
|
||||
.getByLabel('Confirmo esta decisão de classificação')
|
||||
.check();
|
||||
await article
|
||||
.getByRole('button', { name: 'Aplicar decisão de classificação' })
|
||||
.click();
|
||||
await article.getByRole('status').waitFor();
|
||||
await page.reload();
|
||||
await page
|
||||
.getByRole('heading', {
|
||||
name: 'ID 1 — ' + record.title,
|
||||
exact: true,
|
||||
})
|
||||
.waitFor();
|
||||
assert.equal(
|
||||
(
|
||||
await page.request.get(
|
||||
base + '/api/v1/opportunities/' + record.slug,
|
||||
)
|
||||
).status(),
|
||||
200,
|
||||
);
|
||||
assert.deepEqual(errors, []);
|
||||
const evidence = {
|
||||
recorded_at: new Date().toISOString(),
|
||||
target: backup.restored_target,
|
||||
preview_has_no_application: true,
|
||||
explicit_confirmation: true,
|
||||
example_separated_from_api_map: true,
|
||||
authenticated_consultation: true,
|
||||
restored: true,
|
||||
errors,
|
||||
active_writes: 0,
|
||||
};
|
||||
fs.writeFileSync(
|
||||
dir + 'opportunity-origin-browser.json',
|
||||
JSON.stringify(evidence, null, 2),
|
||||
);
|
||||
console.log(JSON.stringify(evidence));
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityOriginReview;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Vite;
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$directory = $root.'/storage/app/private/investmoz-v2';
|
||||
$proof = json_decode(file_get_contents($directory.'/opportunity-origin-backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$target = $proof['restored_target'];
|
||||
if (! $proof['restore_verified'] || ! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $target['database']) || (int) $target['port'] !== 55441) {
|
||||
throw new RuntimeException('Isolated restored QA required.');
|
||||
}
|
||||
foreach (['APP_ENV' => 'testing', 'APP_DEBUG' => 'true', 'APP_URL' => 'http://127.0.0.1:18094', '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' => 'origin_review_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();
|
||||
$c = config('database.connections.pgsql');
|
||||
if (config('database.default') !== 'pgsql' || $c['host'] !== '127.0.0.1' || (int) $c['port'] !== 55441 || $c['database'] !== $target['database'] || ! empty($c['url'])) {
|
||||
throw new RuntimeException('Refusing non-QA configuration.');
|
||||
}
|
||||
$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 database.');
|
||||
}
|
||||
$qa = $directory.'/qa-origin-review';
|
||||
if (! is_dir($qa.'/sessions')) {
|
||||
mkdir($qa.'/sessions', 0700, true);
|
||||
}
|
||||
config(['session.files' => $qa.'/sessions', 'portal.managers' => ['origin-browser@example.invalid'], 'opportunity_origin.proof_path' => $qa.'/proof.json', 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
Vite::useHotFile($root.'/storage/framework/origin-qa-absent-hot');
|
||||
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'seed') {
|
||||
$user = User::updateOrCreate(['email' => 'origin-browser@example.invalid'], ['name' => 'Origin review QA', 'password' => Hash::make('Origin-QA-2026!')]);
|
||||
$user->forceFill(['email_verified_at' => now()])->save();
|
||||
file_put_contents($qa.'/proof.json', json_encode([...$proof, 'target' => $target, 'reversal_verified' => true, 'fixture_only' => true, 'code_hash' => app(OpportunityOriginReview::class)->fingerprint()], JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['target' => $target, 'qa_user' => $user->id, 'code_hash' => app(OpportunityOriginReview::class)->fingerprint(), 'active_writes' => 0]).PHP_EOL;
|
||||
exit;
|
||||
}
|
||||
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'verify') {
|
||||
$hashes = [];
|
||||
foreach (['opportunities', 'opportunity_projects', 'opportunity_clusters', 'opportunity_favourites', 'interest_requests', 'interest_submission_receipts', 'investment_messages', 'tasks', 'project_locations', 'cluster_projects'] as $table) {
|
||||
$qualified = '"public"."'.$table.'"';
|
||||
$rows = DB::select('SELECT row_to_json(t)::text AS row_json FROM '.$qualified.' t ORDER BY row_to_json(t)::text');
|
||||
$hashes[$qualified] = hash('sha256', implode("\n", array_map(fn ($row) => $row->row_json, $rows)));
|
||||
if ($hashes[$qualified] !== $proof['table_hashes'][$qualified]) {
|
||||
throw new RuntimeException('Record/interaction preservation failed: '.$table);
|
||||
}
|
||||
}
|
||||
$events = DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->orderBy('occurred_at')->get();
|
||||
$state = app(OpportunityOriginReview::class)->state(1);
|
||||
if ($state['classification'] !== 'undetermined' || $events->count() !== 2) {
|
||||
throw new RuntimeException('QA classification cycle incomplete.');
|
||||
}
|
||||
$evidence = ['verified_at' => gmdate('c'), 'target' => $target, 'hashes' => $hashes, 'classification_restored' => $state['classification'] === 'undetermined', 'decision_events' => $events->count(), 'code_hash' => app(OpportunityOriginReview::class)->fingerprint(), 'active_writes' => 0];
|
||||
file_put_contents($directory.'/opportunity-origin-reversal-evidence.json', json_encode($evidence, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($evidence, JSON_THROW_ON_ERROR).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