Consolida rastreabilidade territorial e plano autenticado V2

This commit is contained in:
2026-10-09 02:05:44 +02:00
parent 30acdc9934
commit 6a71aa47e3
33 changed files with 2555 additions and 49 deletions
@@ -0,0 +1,275 @@
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const root = path.resolve(__dirname, '..');
const dir = path.join(root, 'storage/app/private/investmoz-v2');
const audit = JSON.parse(
fs.readFileSync(path.join(dir, 'territory-audit.json'), 'utf8'),
);
const reconciliation = JSON.parse(
fs.readFileSync(
path.join(dir, 'territory-source-reconciliation.json'),
'utf8',
),
);
if (
audit.identity.read_only !== 'on' ||
reconciliation.captured_at !== audit.captured_at
)
throw new Error('Matching read-only source reconciliation required');
const plan = {
schema: 1,
prepared_at: new Date().toISOString(),
target: {
database: audit.identity.database,
port: Number(audit.identity.port),
},
code_hash: '',
rows: [],
updates: [],
guards: [],
pending: [],
new_relationships: [],
};
const guardIds = new Set();
const guard = (table, record, fields) => {
const key = table + ':' + record.id;
if (guardIds.has(key)) return;
guardIds.add(key);
plan.guards.push({
table,
id: record.id,
expected: Object.fromEntries(
fields
.filter((field) => field in record)
.map((field) => [field, record[field]]),
),
});
};
const publicDossiers = audit.dossiers.filter(
(d) => d.publication_status === 'published',
);
for (const entity of audit.records) {
const record = entity.record;
const reference = record.code || record.reference || String(record.id);
const source = reconciliation.records.find(
(r) => r.kind === entity.kind && r.id === entity.id,
);
guard(entity.kind, record, [
'version_no',
'territory_version',
'metadata',
'source_evidence',
'validation_status',
'publication_status',
'status',
'primary_territory_id',
'deleted_at',
]);
const dossiers = audit.dossiers.filter(
(d) => d.project_id === record.id || d.cluster_id === record.id,
);
for (const dossier of dossiers)
guard('investment_dossiers', dossier, [
'version_no',
'source',
'content',
'publication_status',
]);
const visible =
entity.kind === 'opportunities'
? record.status === 'published'
: entity.kind === 'investment_zones'
? record.publication_status === 'published'
: dossiers.some((d) => d.publication_status === 'published');
const metadata = JSON.parse(record.metadata || '{}');
const legal = source.legal_source;
if (legal) guard('investment_legal_sources', legal, Object.keys(legal));
const evidence =
source.official_references[0] || source.non_official_references[0];
const row = (association, role, props = {}) => {
plan.rows.push({
key: `${entity.kind}:${entity.id}:${association}:${role}`,
kind: entity.kind,
record_id: entity.id,
reference,
association,
role,
public: visible,
source_reference: legal
? `${legal.diploma} — ${legal.url}`
: evidence
? `${evidence.title} — ${evidence.url}`
: dossiers[0]?.source || null,
source_quote: null,
supports:
evidence?.supports ||
'Origem oficial aceite pelo responsável; ligação ao exemplar a recuperar onde ausente.',
existing_validation: record.validation_status ?? null,
official_source_accepted: Boolean(
legal || source.official_references.length,
),
traceability: source.traceability,
effect: 'Ficha mostra fundamento e pendência específica; identidade, geometria, filtros e validações preservados.',
...props,
});
};
row('registo', 'proveniência');
const locations = entity.relations.own || [];
for (const location of locations) {
if (location.id)
guard(
entity.kind === 'projects'
? 'project_locations'
: 'investment_zone_locations',
location,
Object.keys(location),
);
const saved =
metadata.documented_location_sources?.[
location.geo_location_id + ':' + location.role
];
row(
location.geo_location_id,
location.role || location.scope_type || 'implantação',
{
public_location_id: location.geo_location_id,
source_reference:
saved?.source_reference ||
location.source_reference ||
legal?.url ||
evidence?.url ||
null,
source_quote: saved?.source_quote || null,
supports:
saved?.reason ||
evidence?.supports ||
'Ligação ao documento utilizado por recuperar; dado preservado.',
dossier_id: saved?.dossier_id || null,
},
);
}
if (
record.primary_territory_id &&
!locations.some(
(l) => l.geo_location_id === record.primary_territory_id,
)
)
row(
record.primary_territory_id,
entity.kind === 'opportunities'
? 'implantação cadastrada'
: 'território principal',
{
public_location_id: record.primary_territory_id,
supports:
'Associação já existente; nomes administrativos provenientes do workbook cartografia-moz. Não se atribui automaticamente o PDF INE a este vínculo.',
},
);
for (const coverage of metadata.documented_coverage || [])
row(coverage.id, 'abrangência', {
source_reference: coverage.source_reference || null,
source_quote: coverage.source_quote || null,
public_location_id: coverage.id,
public: visible && coverage.data_classification === 'public',
});
if (entity.kind === 'economic_clusters') {
const dossier = publicDossiers.find((d) => d.cluster_id === record.id);
const content = JSON.parse(dossier?.content || '{}');
for (const member of entity.relations.members || []) {
const project = audit.records.find(
(r) => r.kind === 'projects' && r.id === member.project_id,
);
const quote = content.anchors || '';
const explicit =
project &&
new RegExp(
'(^|[^A-Za-z0-9])' +
project.record.code +
'([^A-Za-z0-9]|$)',
).test(quote);
guard('cluster_projects', member, Object.keys(member));
row(member.project_id, 'contexto — membro ' + member.role, {
association_id: member.id,
dossier_id: dossier?.id || null,
source_reference:
member.source_reference ||
(explicit ? dossier.source : null),
source_quote: explicit ? quote : null,
existing_validation: member.validation_status,
official_source_accepted: false,
traceability: explicit
? 'citação recuperada; ponte ao exemplar oficial por recuperar'
: 'rastreabilidade por recuperar',
effect: 'Citação da relação cluster–projeto passa a ser visível; não muda validação nem cria implantação da oportunidade.',
});
if (
explicit &&
!member.source_reference &&
!member.evidence_reference
)
plan.updates.push({
table: 'cluster_projects',
id: member.id,
reference: `${reference} → ${project.record.code}`,
current: {
source_reference: null,
evidence_reference: null,
},
values: {
source_reference: dossier.source,
evidence_reference: dossier.id,
},
source_quote: quote,
effect: 'Relação existente reutilizada; apenas referências preenchidas.',
});
}
}
if (source.traceability !== 'official_reference_identified')
plan.pending.push({
reference,
reason: 'Ponte ao exemplar oficial não identificada no cadastro revisto; recuperar sem desvalidar.',
});
if (
entity.kind === 'opportunities' &&
!(entity.relations.projects || []).length &&
!(entity.relations.clusters || []).length
)
plan.pending.push({
reference,
reason: 'Sem correspondência documental explícita a uma âncora/cluster nas fontes já reconciliadas; não criar ligação por setor ou proximidade.',
});
}
const files = [
'app/Services/InvestmentTerritorialTraceability.php',
'app/Http/Controllers/InvestmentRelationshipRepairController.php',
'resources/js/components/territorial-traceability-plan.tsx',
'tools/investmoz-v2-prepare-territorial-plan.cjs',
];
plan.code_hash = crypto
.createHash('sha256')
.update(
files
.map((file) =>
crypto
.createHash('sha256')
.update(fs.readFileSync(path.join(root, file)))
.digest('hex'),
)
.join(''),
)
.digest('hex');
fs.writeFileSync(
path.join(dir, 'territory-activation-plan.json'),
JSON.stringify(plan, null, 2),
);
console.log(
JSON.stringify({
records: audit.records.length,
associations: plan.rows.length,
updates: plan.updates.length,
pending: plan.pending.length,
new_relationships: 0,
target: plan.target,
}),
);
@@ -0,0 +1,183 @@
const fs = require('node:fs');
const path = require('node:path');
function reconcile(item, audit) {
const row = item.record;
const metadata = JSON.parse(row.metadata || '{}');
const evidence = JSON.parse(row.source_evidence || '[]');
const legal =
(audit.legal_sources || []).find(
(source) => source.id === row.legal_source_id,
) || null;
const dossiers = audit.dossiers.filter(
(d) => d.project_id === row.id || d.cluster_id === row.id,
);
const officialReferences = evidence.filter((source) =>
['government', 'institutional'].includes(source.source_type),
);
const documentaryRelations = Object.entries(
metadata.documented_location_sources || {},
).map(([key, source]) => ({ key, ...source }));
return {
kind: item.kind,
id: row.id,
reference: row.code || row.reference || String(row.id),
existing_record_validation: row.validation_status ?? null,
existing_legal_validation: legal?.validation_status ?? null,
legal_source: legal,
official_references: officialReferences,
non_official_references: evidence.filter(
(source) =>
!['government', 'institutional'].includes(source.source_type),
),
documentary_relations: documentaryRelations,
dossiers: dossiers.map((d) => ({
id: d.id,
source: d.source,
version: d.version_no,
})),
traceability:
legal || officialReferences.length
? 'official_reference_identified'
: documentaryRelations.length || dossiers.length
? 'documentary_bridge_to_official_source_to_recover'
: 'official_source_link_not_identified_in_records_reviewed',
official_validation_newly_granted: false,
validation_revoked: false,
calculation_activated: false,
};
}
module.exports = { reconcile };
if (require.main === module) {
const root = path.resolve(__dirname, '..');
const privateDir = path.join(root, 'storage/app/private/investmoz-v2');
const audit = JSON.parse(
fs.readFileSync(path.join(privateDir, 'territory-audit.json'), 'utf8'),
);
if (audit.identity.read_only !== 'on')
throw new Error('Read-only audit required');
const records = audit.records.map((item) => reconcile(item, audit));
const acceptancePath = path.join(
root,
'storage/app/private/geo-ine-review-20260928-v2',
);
const acceptanceFile = fs
.readdirSync(acceptancePath)
.find(
(name) =>
name.startsWith('owner-acceptance-') && name.endsWith('.json'),
);
const acceptance = JSON.parse(
fs.readFileSync(path.join(acceptancePath, acceptanceFile), 'utf8'),
);
const crypto = require('node:crypto');
const archiveHash = crypto
.createHash('sha256')
.update(fs.readFileSync(path.join(acceptancePath, 'original.pdf')))
.digest('hex');
if (archiveHash !== acceptance.source_checksums['original.pdf'])
throw new Error(
'Accepted INE archive hash mismatch; do not reuse acceptance',
);
const clean = (s) =>
String(s ?? '')
.replaceAll('|', '\\|')
.replaceAll('\n', ' ');
const lines = [
'# Reconciliação das fontes e validações territoriais',
'',
'Critério do responsável: documentos oficiais são a única fonte de validação oficial. Programação, promotores, testes e leitura do cadastro não substituem esses documentos. Ausência de um campo de fonte/data é uma lacuna de rastreabilidade, não uma decisão de invalidade nem revogação.',
'',
'Esta revisão conserva os estados existentes. Uma referência oficial identificada não significa que todas as afirmações da ficha estejam cobertas: o âmbito da citação deve ser conservado. Não foram concedidas novas validações nem ativados cálculos. A declaração do responsável sobre a origem oficial dos dados em uso é registada; as pontes técnicas ainda incompletas são identificadas abaixo, sem contradizer essa declaração.',
'',
'## Evidência oficial e aceitação já existentes',
'',
`INE — Codificador da Divisão Político-Administrativa: exemplar privado com SHA-256 \`${archiveHash}\`, coincidente com a aceitação de ${acceptance.decision_date}. Decisão preservada: \`${acceptance.validation}\` e \`${acceptance.authenticity}\`, por instrução explícita do responsável. A aceitação não é reaberta. O próprio registo distingue-a da correspondência técnica: \`${acceptance.technical_mapping_status}\`; zero territórios importados por essa decisão. Não se atribui automaticamente esse PDF aos 1 921 nós oriundos do workbook.`,
'',
'As seis fontes de diplomas existentes conservam `validation_status=pending` tal como já estava na base; esse estado não foi imposto por esta entrega. As 14 fichas de zonas com `validated` conservam esse estado, distinguindo validação do cadastro de validação jurídica do diploma associado. Referências de promotores não passam a fonte oficial por a ficha estar validada.',
'',
'## Matriz por registo',
'',
'| Registo | Validação já registada, preservada | Fonte/citação recuperada | Lacuna específica de rastreabilidade |',
'| --- | --- | --- | --- |',
];
for (const r of records) {
const sources = [
...(r.legal_source
? [
`${r.legal_source.diploma}; ${r.legal_source.title}; ${r.legal_source.article}; ${r.legal_source.url}; versão ${r.legal_source.version_no}`,
]
: []),
...r.official_references.map(
(s) => `${s.title}; ${s.url}; âmbito: ${s.supports}`,
),
...r.non_official_references.map(
(s) =>
`Referência ${s.source_type}, não oficial: ${s.title}; ${s.url}`,
),
...r.documentary_relations.map(
(s) =>
`${s.source_reference}; citação: ${s.source_quote}; dossier ${s.dossier_id}; auditoria ${s.applied_at || 'não identificada'}`,
),
...r.dossiers.map(
(d) => `Dossier ${d.id}, versão ${d.version}: ${d.source}`,
),
];
const state = `Cadastro: ${r.existing_record_validation ?? 'campo de validação não existente/não registado nesta entidade'}; fonte legal: ${r.existing_legal_validation ?? 'sem fonte legal ligada'}`;
const gap =
r.traceability === 'official_reference_identified'
? 'Referência oficial recuperada; ligar exemplar/citação ao atributo quando essa ponte não consta do cadastro. Não repetir validação já evidenciada; não alargar o âmbito da fonte.'
: r.traceability ===
'documentary_bridge_to_official_source_to_recover'
? 'Citação e histórico documentais recuperados; recuperar a ponte ao documento oficial utilizado. Não desvalidar a relação aplicada.'
: 'Ligação ao exemplar oficial não identificada nos registos revistos; recuperar proveniência da importação. Ausência de ligação não prova ausência de fonte oficial.';
lines.push(
`| ${clean(r.reference)} | ${clean(state)} | ${clean(sources.join('; ') || 'Sem ponte documental no cadastro revisto')} | ${clean(gap)} |`,
);
}
lines.push(
'',
'## Estados independentes e limites',
'',
'Consulta autorizada permanece independente da completude da referência. Validação oficial deriva apenas da evidência documental oficial no âmbito aceite; o estado cadastral é preservado e apresentado separadamente. Utilização em regras/cálculos permanece inalterada. Não se transforma a data de criação, data de aplicação ou início de vigência em data da fonte.',
'',
'O rótulo histórico de programação v4 foi preservado; a revisão anterior encontrou programação v5 corroborante, sem o exemplar v4. Esta diferença de rótulo é uma questão de proveniência, não uma revogação das 28 relações aplicadas. Programação não substitui o documento oficial na validação oficial.',
'',
'Nenhuma base ativa foi escrita. A matriz integral privada está em `territory-source-reconciliation.json`. Diferença de cobertura do inventário, questões jurídicas realmente não resolvidas, ClamD real e primeiro pedido real continuam separados.',
);
fs.writeFileSync(
path.join(privateDir, 'territory-source-reconciliation.json'),
JSON.stringify(
{
captured_at: audit.captured_at,
policy: 'official_documents_only_for_official_validation',
owner_origin_declaration_preserved: true,
ine_acceptance: acceptance,
records,
},
null,
2,
),
);
fs.writeFileSync(
path.join(
root,
'docs/investmoz/v2/reconciliacao-fontes-territoriais.md',
),
lines.join('\n') + '\n',
);
console.log(
JSON.stringify({
records: records.length,
official_references_identified: records.filter(
(r) => r.traceability === 'official_reference_identified',
).length,
record_validations_preserved: records.filter(
(r) => r.existing_record_validation === 'validated',
).length,
accepted_ine_hash_matches: true,
active_writes: 0,
}),
);
}
@@ -0,0 +1,93 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { reconcile } = require('./investmoz-v2-source-reconciliation.cjs');
test('validated official source and record survive missing citation fields', () => {
const result = reconcile(
{
kind: 'investment_zones',
record: {
id: 'z',
validation_status: 'validated',
legal_source_id: 'l',
},
},
{
dossiers: [],
legal_sources: [
{
id: 'l',
validation_status: 'validated',
diploma: 'QA official fixture',
},
],
},
);
assert.equal(result.existing_record_validation, 'validated');
assert.equal(result.existing_legal_validation, 'validated');
assert.equal(result.validation_revoked, false);
assert.equal(result.traceability, 'official_reference_identified');
});
test('missing source field is a traceability gap, not rejection', () => {
const result = reconcile(
{
kind: 'projects',
record: {
id: 'p',
metadata: JSON.stringify({
documented_location_sources: {
'x:primary': {
source_quote: 'QA quotation',
source_reference: 'QA dossier',
applied_at: '2026-10-07',
},
},
}),
},
},
{ dossiers: [], legal_sources: [] },
);
assert.equal(
result.traceability,
'documentary_bridge_to_official_source_to_recover',
);
assert.equal(result.documentary_relations[0].source_quote, 'QA quotation');
assert.equal(result.validation_revoked, false);
assert.equal(result.calculation_activated, false);
});
test('promoter cannot become official through validated record', () => {
const result = reconcile(
{
kind: 'investment_zones',
record: {
id: 'z',
validation_status: 'validated',
source_evidence: JSON.stringify([
{ source_type: 'promoter', title: 'QA promoter' },
]),
},
},
{ dossiers: [], legal_sources: [] },
);
assert.equal(result.existing_record_validation, 'validated');
assert.equal(result.official_references.length, 0);
assert.equal(result.official_validation_newly_granted, false);
});
test('existing legal pending is preserved without invalidating consultation', () => {
const result = reconcile(
{
kind: 'investment_zones',
record: {
id: 'z',
validation_status: 'validated',
legal_source_id: 'l',
},
},
{
dossiers: [],
legal_sources: [{ id: 'l', validation_status: 'pending' }],
},
);
assert.equal(result.existing_record_validation, 'validated');
assert.equal(result.existing_legal_validation, 'pending');
assert.equal(result.validation_revoked, false);
});
+59
View File
@@ -0,0 +1,59 @@
<?php
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
// Read-only audit: no Laravel kernel, migrations, seeders or data updates.
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
(new LoadEnvironmentVariables)->bootstrap($app);
(new LoadConfiguration)->bootstrap($app);
$c = $app->make('config')->get('database.connections.'.$app->make('config')->get('database.default'));
if (($c['driver'] ?? '') !== 'pgsql' || ! in_array($c['url'] ?? null, [null, ''], true)) {
throw new RuntimeException('Unsupported target');
}
$pdo = new PDO('pgsql:host='.$c['host'].';port='.$c['port'].';dbname='.$c['database'], $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('BEGIN TRANSACTION READ ONLY');
$proof = ['captured_at' => gmdate('c'), '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), 'records' => []];
foreach (['opportunities', 'projects', 'economic_clusters', 'investment_zones'] as $table) {
$rows = $pdo->query('SELECT * FROM '.$table.' WHERE deleted_at IS NULL ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$relations = [];
$queries = match ($table) {
'opportunities' => ['own' => 'SELECT geo_location_id FROM opportunity_locations WHERE opportunity_id=?', 'projects' => 'SELECT project_id FROM opportunity_projects WHERE opportunity_id=?', 'clusters' => 'SELECT cluster_id FROM opportunity_clusters WHERE opportunity_id=?'],
'projects' => ['own' => 'SELECT * FROM project_locations WHERE project_id=? AND deleted_at IS NULL', 'clusters' => 'SELECT * FROM cluster_projects WHERE project_id=? AND deleted_at IS NULL'],
'economic_clusters' => ['members' => 'SELECT * FROM cluster_projects WHERE cluster_id=? AND deleted_at IS NULL'],
'investment_zones' => ['own' => 'SELECT * FROM investment_zone_locations WHERE zone_id=?', 'links' => 'SELECT * FROM investment_zone_links WHERE zone_id=?'],
};
foreach ($queries as $kind => $sql) {
$statement = $pdo->prepare($sql);
$statement->execute([$row['id']]);
$relations[$kind] = $statement->fetchAll(PDO::FETCH_ASSOC);
}
$issues = [];
$own = count($relations['own'] ?? []) + (empty($row['primary_territory_id']) ? 0 : 1);
if ($table === 'opportunities') {
if (! $own) {
$issues[] = ($relations['projects'] || $relations['clusters']) ? 'context_only_not_implantation' : 'insufficient_territorial_information';
}
if ($own > 1) {
$issues[] = 'multiple_links_review_distinct_ids';
}
$issues[] = 'direct_link_source_and_date_not_stored_in_pivot';
}
$proof['records'][] = ['kind' => $table, 'id' => $row['id'], 'record' => $row, 'relations' => $relations, 'findings' => $issues];
}
}
$proof['geography'] = $pdo->query('SELECT g.id,g.name,g.location_type,g.parent_id,g.source_system,g.data_classification,
p.location_type AS parent_type,p.deleted_at AS parent_deleted_at,
(SELECT count(*) FROM geo_geometries s WHERE s.geo_location_id=g.id AND s.deleted_at IS NULL) AS geometry_count
FROM geo_locations g LEFT JOIN geo_locations p ON p.id=g.parent_id WHERE g.deleted_at IS NULL ORDER BY g.id')->fetchAll(PDO::FETCH_ASSOC);
$proof['geometries'] = $pdo->query('SELECT id,geo_location_id,geometry_type,source_system,properties,data_classification,ST_IsValid(geom) AS valid,ST_IsEmpty(geom) AS empty,ST_SRID(geom) AS srid,ST_AsGeoJSON(geom) AS geometry FROM geo_geometries WHERE deleted_at IS NULL ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$proof['dossiers'] = $pdo->query('SELECT id,project_id,cluster_id,title,source,content,version_no,publication_status FROM investment_dossiers WHERE deleted_at IS NULL ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$proof['legal_sources'] = $pdo->query('SELECT id,title,url,diploma,article,competent_entity,validation_status,validated_at,version_no,valid_from,valid_until FROM investment_legal_sources ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$proof['geo_sources'] = $pdo->query('SELECT id,name,responsible_entity,reference,checksum,source_version,status,approval_reference FROM geo_sources ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$proof['geo_profiles'] = $pdo->query('SELECT geo_location_id,source_id,status,valid_from,valid_to FROM geo_territory_profiles ORDER BY geo_location_id')->fetchAll(PDO::FETCH_ASSOC);
$proof['traceability_events'] = $pdo->query("SELECT id,action,occurred_at FROM audit_events WHERE source_system='territory-traceability-v2' ORDER BY occurred_at,id")->fetchAll(PDO::FETCH_ASSOC);
$pdo->exec('ROLLBACK');
file_put_contents(dirname(__DIR__).'/storage/app/private/investmoz-v2/territory-audit.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode(['identity' => $proof['identity'], 'records' => count($proof['records']), 'territories' => count($proof['geography']), 'geometries' => count($proof['geometries'])], JSON_THROW_ON_ERROR).PHP_EOL;
+239
View File
@@ -0,0 +1,239 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const privateDir = path.resolve(
__dirname,
'../storage/app/private/investmoz-v2',
);
const fixture = JSON.parse(
fs.readFileSync(
path.join(privateDir, 'territory-qa-fixtures.json'),
'utf8',
),
);
assert.equal(fixture.database, 'investmoz_v2_20261008_test');
assert.equal(fixture.port, 55441);
(async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const checks = [];
try {
for (const width of [1440, 390]) {
const context = await browser.newContext({
viewport: { width, height: 850 },
});
await context.route('**/*', (route) =>
route.request().url().startsWith('http://127.0.0.1:18092')
? route.continue()
: route.abort(),
);
const page = await context.newPage();
const errors = [];
const writes = [];
page.on('pageerror', (e) => errors.push(e.message));
page.on('request', (r) => {
if (!['GET', 'HEAD'].includes(r.method()))
writes.push(r.method() + ' ' + r.url());
});
for (const [kind, record] of Object.entries(fixture.cases)) {
const response = await page.goto(
'http://127.0.0.1:18092/oportunidades/' + record.slug,
);
assert.equal(response.status(), 200);
assert.match(
response.headers()['x-investmoz-qa-target'] || '',
/investmoz_v2_20261008_test/,
);
try {
await page
.getByRole('heading', {
name: 'Implantação declarada da oportunidade',
})
.waitFor({ timeout: 10000 });
} catch (error) {
fs.writeFileSync(
path.join(
privateDir,
'territory-browser-diagnostic.json',
),
JSON.stringify(
{
url: page.url(),
errors,
body: await page.locator('body').innerText(),
},
null,
2,
),
);
throw error;
}
const map = await page.request.get(
'http://127.0.0.1:18092/api/v1/investment/map?opportunity_id=' +
record.id,
);
const data = await map.json();
const expected =
kind === 'multiple'
? 2
: ['direct', 'context'].includes(kind)
? 1
: 0;
assert.equal(data.features.length, expected);
const section = page
.locator('section')
.filter({
has: page.getByRole('heading', {
name: 'Implantação declarada da oportunidade',
exact: true,
}),
})
.first();
if (['context', 'insufficient'].includes(kind))
assert.match(await section.innerText(), /não documentada/);
if (kind === 'context') {
assert.equal(
data.features[0].properties.location_basis,
'linked_project_site',
);
await page
.getByRole('link', {
name: 'Consultar dossier: Territory QA dossier',
})
.click();
await page.waitForURL('**/carteira/' + fixture.dossier);
await page
.getByRole('link', {
name: record.title || 'Territory QA context',
exact: true,
})
.first()
.click();
await page.waitForURL(
'**/oportunidades/' + record.slug + '**',
);
}
if (kind === 'multiple') {
const buttons = page.getByRole('button', {
name: 'Territory QA multiple',
exact: true,
});
await buttons.first().waitFor();
assert.equal(await buttons.count(), 2);
await buttons.nth(0).click();
await buttons.nth(1).click();
assert.equal(
await buttons.nth(1).getAttribute('aria-pressed'),
'true',
);
assert.equal(
await buttons.nth(0).getAttribute('aria-pressed'),
'false',
);
}
if (kind === 'direct') {
assert.equal(data.areas.length, 1);
await page
.getByText(
/Polígono cadastrado, limites oficiais por verificar/,
)
.first()
.waitFor();
}
if (kind === 'without-point') {
await section
.getByText('Coordenadas não documentadas.')
.waitFor();
await section
.getByRole('link', {
name: 'Pesquisar oportunidades neste território',
})
.click();
await page.waitForURL(
'**/oportunidades?geo_location_id=' + fixture.district,
);
await page
.getByRole('link', {
name: 'Territory QA without-point',
exact: true,
})
.first()
.waitFor();
}
checks.push({
width,
kind,
markers: data.features.length,
areas: data.areas.length,
passed: true,
});
}
await page.goto('http://127.0.0.1:18092/oportunidades');
await page
.getByLabel('Base da relação territorial')
.selectOption('context');
await page
.getByRole('button', { name: 'Aplicar filtros', exact: true })
.click();
await page.waitForURL('**territory_basis=context**');
await page
.getByRole('link', {
name: 'Territory QA context',
exact: true,
})
.first()
.waitFor();
assert.equal(
await page
.getByRole('link', {
name: 'Territory QA direct',
exact: true,
})
.count(),
0,
);
await page
.getByRole('status')
.filter({ hasText: 'locais com coordenadas disponíveis.' })
.first()
.waitFor();
assert.deepEqual(errors, []);
assert.deepEqual(writes, []);
await page.screenshot({
path: path.join(
privateDir,
'territory-browser-' + width + '.png',
),
fullPage: true,
});
await context.close();
}
fs.writeFileSync(
path.join(privateDir, 'territory-browser.json'),
JSON.stringify(
{
database: fixture.database,
port: fixture.port,
external_requests_blocked: true,
checks,
},
null,
2,
),
);
console.log(
JSON.stringify({ passed: true, checks: checks.length, writes: 0 }),
);
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
@@ -0,0 +1,66 @@
<?php
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use App\Models\Project;
use App\Models\Sector;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
foreach (['APP_ENV' => 'testing', 'APP_KEY' => 'base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441', 'DB_DATABASE' => 'investmoz_v2_20261008_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(Kernel::class)->bootstrap();
$connection = DB::connection();
if ($connection->getDatabaseName() !== 'investmoz_v2_20261008_test' || (string) $connection->getConfig('port') !== '55441' || $connection->getConfig('host') !== '127.0.0.1' || ! in_array($connection->getConfig('url'), [null, ''], true)) {
throw new RuntimeException('QA configuration required');
}
$identity = DB::selectOne('SELECT current_database() AS name,inet_server_port() AS port');
if ($identity->name !== 'investmoz_v2_20261008_test' || (int) $identity->port !== 55441) {
throw new RuntimeException('QA identity required');
}
$manifest = DB::transaction(function () {
$nodes = [];
$parent = null;
foreach (['country', 'province', 'district', 'admin_post', 'locality', 'site'] as $type) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'code' => $id, 'name' => 'Territory QA '.$type, 'location_type' => $type, 'parent_id' => $parent, 'data_classification' => 'public',
'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id]);
$nodes[$type] = $id;
$parent = $id;
}
$second = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $second, 'code' => $second, 'name' => 'Territory QA second site', 'location_type' => 'site', 'parent_id' => $nodes['locality'], 'data_classification' => 'public']);
foreach ([$nodes['site'], $second] as $index => $id) {
DB::table('geo_geometries')->insert(['id' => (string) Str::uuid(), 'geo_location_id' => $id, 'geometry_type' => 'point', 'data_classification' => 'public', 'source_system' => 'Synthetic QA coordinates; no real source',
'geom' => DB::raw('ST_SetSRID(ST_MakePoint('.(32.5 + $index / 10).',-25.9),4326)'), 'properties' => json_encode(['source_date' => '2026-10-08'])]);
}
DB::table('geo_geometries')->insert(['id' => (string) Str::uuid(), 'geo_location_id' => $nodes['site'], 'geometry_type' => 'polygon', 'data_classification' => 'public', 'source_system' => 'Synthetic QA boundary; not official',
'geom' => DB::raw("ST_GeomFromText('POLYGON((32 -26,33 -26,33 -25,32 -25,32 -26))',4326)"), 'properties' => json_encode(['source_date' => '2026-10-08'])]);
$project = Project::factory()->create(['name' => 'Territory QA project', 'status' => 'draft', 'data_classification' => 'internal']);
$dossier = InvestmentDossier::create(['project_id' => $project->id, 'title' => 'Territory QA dossier', 'source' => 'Synthetic QA source', 'content' => ['location' => 'Synthetic QA site'], 'publication_status' => 'published', 'published_at' => now()->subMinute(), 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic isolated QA disclosure']);
DB::table('project_locations')->insert(['id' => (string) Str::uuid(), 'project_id' => $project->id, 'geo_location_id' => $nodes['site'], 'role' => 'primary', 'data_classification' => 'public', 'source_system' => 'Synthetic QA source']);
DB::table('project_locations')->insert(['id' => (string) Str::uuid(), 'project_id' => $project->id, 'geo_location_id' => $nodes['district'], 'role' => 'impact', 'data_classification' => 'public', 'source_system' => 'Synthetic QA impact']);
$sector = Sector::firstOrCreate(['slug' => 'territory-qa'], ['name' => 'Territory QA', 'is_active' => true]);
$cases = [];
foreach (['direct', 'context', 'multiple', 'insufficient', 'without-point'] as $kind) {
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'TERR-QA-'.Str::uuid(), 'title' => 'Territory QA '.$kind, 'slug' => 'territory-qa-'.$kind.'-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subMinute()]);
if ($kind === 'context') {
DB::table('opportunity_projects')->insert(['opportunity_id' => $opportunity->id, 'project_id' => $project->id]);
}
foreach (match ($kind) {
'direct' => [$nodes['site']], 'multiple' => [$nodes['site'], $second], 'without-point' => [$nodes['district']], default => []
} as $id) {
DB::table('opportunity_locations')->insert(['opportunity_id' => $opportunity->id, 'geo_location_id' => $id]);
}
$cases[$kind] = ['id' => $opportunity->id, 'slug' => $opportunity->slug];
}
return ['database' => 'investmoz_v2_20261008_test', 'port' => 55441, 'cases' => $cases, 'dossier' => $dossier->id, 'district' => $nodes['district']];
});
file_put_contents(dirname(__DIR__).'/storage/app/private/investmoz-v2/territory-qa-fixtures.json', json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($manifest, JSON_THROW_ON_ERROR).PHP_EOL;
+216
View File
@@ -0,0 +1,216 @@
const fs = require('node:fs');
const path = require('node:path');
const { reconcile } = require('./investmoz-v2-source-reconciliation.cjs');
const root = path.resolve(__dirname, '..');
const audit = JSON.parse(
fs.readFileSync(
path.join(
root,
'storage/app/private/investmoz-v2/territory-audit.json',
),
'utf8',
),
);
if (audit.identity.read_only !== 'on')
throw new Error('Read-only evidence required');
const geo = new Map(audit.geography.map((g) => [g.id, g]));
const clean = (value) =>
String(value ?? '')
.replaceAll('|', '\\|')
.replaceAll('\n', ' ');
const lineage = (id) => {
const visited = new Set();
const nodes = [];
const issues = [];
while (id) {
if (visited.has(id)) {
issues.push('ciclo');
break;
}
visited.add(id);
const g = geo.get(id);
if (!g) {
issues.push('nó/antepassado ausente');
break;
}
nodes.unshift(g);
id = g.parent_id;
}
const ranks = [
'country',
'province',
'district',
'admin_post',
'locality',
'site',
];
for (let i = 1; i < nodes.length; i++) {
if (
nodes[i].location_type !== 'site' &&
ranks.indexOf(nodes[i].location_type) !==
ranks.indexOf(nodes[i - 1].location_type) + 1
)
issues.push('hierarquia incompatível');
}
return { names: nodes.map((g) => g.name).join(' → '), issues };
};
const lines = [
'# Qualidade territorial e relações — entrega V2',
'',
`Leitura protegida em ${audit.captured_at}, base ativa ${audit.identity.database}:${audit.identity.port}, transação READ ONLY terminada por ROLLBACK. Nenhum dado ativo alterado. Evidência completa privada: \`territory-audit.json\`.`,
'',
'## Resultados por registo e propostas de dados',
'',
'Cada linha identifica o estado cadastrado, a fonte consultada, motivo e impacto da proposta. Documentos oficiais são a única fonte de validação oficial. Ausência de campos de fonte/data é uma lacuna de rastreabilidade, não invalidade ou revogação. Estados e aceitações existentes são preservados na [matriz de reconciliação](reconciliacao-fontes-territoriais.md). Sem associação explícita não se cria uma relação por nome semelhante, cluster ou proximidade.',
'',
'| Registo | Relações/localizações cadastradas | Fonte consultada | Proposta, motivo e impacto |',
'| --- | --- | --- | --- |',
];
const result = [];
for (const item of audit.records) {
const r = item.record;
const reconciled = reconcile(item, audit);
const metadata = JSON.parse(r.metadata || '{}');
const own = (item.relations.own || []).map((l) => ({
id: l.geo_location_id,
role: l.role || l.scope_type || 'declarada',
source:
metadata.documented_location_sources?.[
l.geo_location_id + ':' + l.role
]?.source_reference ||
l.source_reference ||
l.source_system ||
null,
}));
if (
r.primary_territory_id &&
!own.some((l) => l.id === r.primary_territory_id)
)
own.unshift({
id: r.primary_territory_id,
role: 'principal cadastrada',
source: r.source_system || null,
});
for (const c of metadata.documented_coverage || [])
own.push({
id: c.id,
role: 'abrangência',
source: c.source_reference || null,
});
const locations = own.map((l) => ({ ...l, ...lineage(l.id) }));
const dossiers = audit.dossiers.filter(
(d) => d.project_id === r.id || d.cluster_id === r.id,
);
const source =
[
...new Set(
[
r.source_system,
...dossiers.map((d) => d.source),
...locations.map((l) => l.source),
].filter(Boolean),
),
].join('; ') ||
'Cadastro da oportunidade; fonte da relação e data ausentes';
const proposed = [];
if (item.kind === 'opportunities')
proposed.push(
'Recuperar a ligação ao documento oficial utilizado e a data/citação no cadastro, sem desvalidar o dado; associações a projetos/clusters ausentes: recuperar a relação documentada, sem criar vínculos automaticamente',
);
if (!own.length)
proposed.push(
'Sem localização estruturada: preservar descrição e obter identificação documental; não estimar ponto',
);
if (locations.some((l) => l.issues.length))
proposed.push(
'Rever hierarquia indicada na evidência; não mudar parent_id automaticamente',
);
if (own.length > 1)
proposed.push(
'Preservar locais/papéis distintos; não selecionar um único local nem calcular centroide',
);
if (item.kind === 'economic_clusters')
proposed.push(
'Abrangência do cluster distinta dos locais dos membros; não deduzir perímetro',
);
if (item.kind === 'investment_zones')
proposed.push(
'Preservar a validação registada e ligar fonte/citação ao atributo no respetivo âmbito; localização/regime não prova outros atributos como disponibilidade ou capacidade',
);
if (!proposed.length)
proposed.push(
'Preservar relação documental e validações existentes; completar a rastreabilidade da evidência/data quando ausente no cadastro',
);
proposed.push(
'Coordenadas/polígonos não cadastrados nesta leitura; ficha continua consultável',
);
const label = r.code || r.reference || String(r.id);
const relations =
locations
.map(
(l) =>
`${l.role}: ${l.names || l.id}${l.issues.length ? ' [' + l.issues.join(', ') + ']' : ''}`,
)
.join('; ') || 'Sem localização estruturada';
const counts = `projetos: ${(item.relations.projects || []).length}; clusters: ${(item.relations.clusters || []).length}; membros: ${(item.relations.members || []).length}; ligações de zona: ${(item.relations.links || []).length}`;
lines.push(
`| ${clean(label)} | ${clean(relations + '; ' + counts)} | ${clean(source + '; cadastro: ' + (reconciled.existing_record_validation ?? 'sem campo/estado registado') + '; fonte legal: ' + (reconciled.existing_legal_validation ?? 'sem ligação no cadastro'))} | ${clean(proposed.join('; '))} |`,
);
result.push({
kind: item.kind,
id: r.id,
reference: label,
locations,
proposals: proposed,
source_reconciliation: reconciled,
});
}
const hierarchy = audit.geography
.map((g) => ({ id: g.id, ...lineage(g.id) }))
.filter((g) => g.issues.length);
lines.push(
'',
'## Hierarquia e cartografia',
'',
`${audit.geography.length} nós administrativos/locais percorridos; ${hierarchy.length} caminhos com inconsistência estrutural identificada por esta verificação. Ausência de inconsistência cadastral não certifica fronteiras oficiais. ${audit.geometries.length} geometrias ativas cadastradas: nenhum ponto, polígono ou centroide gerado.`,
'',
'## Correções de código e QA',
'',
'- Ficha apresenta implantação declarada separada dos locais/impacto dos projetos e abrangência dos clusters; fonte/data ausentes explícitas.',
'- Filtros distinguem implantação declarada de apenas contexto associado; localizações sem coordenadas continuam pesquisáveis.',
'- Mapa mantém vários locais do mesmo investimento e seleção independente; áreas cadastradas são apresentadas com proveniência, sem homologar limites.',
'- Associação existente continua a permitir navegação oportunidade → dossier → oportunidade e território → pesquisa. Permissões e relações revogadas preservadas.',
'',
'Ver resultados de QA no backlog e na matriz de reconciliação. Propostas desta tabela não são alterações aplicadas nem plano de escrita aprovado; não revogam validações documentais existentes.',
'',
'## Pendências independentes',
'',
'Diferença de cobertura do inventário documental, validação jurídica/documental das fontes, ClamD real e primeiro pedido real no Balcão permanecem separados. Nenhum teste territorial conclui essas pendências. Aplicação futura de dados exige backup/restauro confirmado e ação autenticada existente.',
);
fs.writeFileSync(
path.join(root, 'docs/investmoz/v2/qualidade-territorial.md'),
lines.join('\n') + '\n',
);
fs.writeFileSync(
path.join(
root,
'storage/app/private/investmoz-v2/territory-proposals.json',
),
JSON.stringify(
{
captured_at: audit.captured_at,
applied: false,
records: result,
hierarchy,
},
null,
2,
),
);
console.log(
JSON.stringify({
records: result.length,
hierarchy_issues: hierarchy.length,
geometry_count: audit.geometries.length,
}),
);
+7
View File
@@ -0,0 +1,7 @@
<?php
// Reuse the existing read-only active backup and isolated restore procedure.
require __DIR__.'/desk-activation-backup.php';
$proof = json_decode(file_get_contents(dirname(__DIR__).'/storage/app/private/virtual-desk/backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
$proof['reversal_verified'] = false;
file_put_contents(dirname(__DIR__).'/storage/app/private/investmoz-v2/territory-backup-proof.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
+79
View File
@@ -0,0 +1,79 @@
<?php
use App\Services\InvestmentTerritorialTraceability;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
// Only the restored, isolated backup can be mutated by this compatibility rehearsal.
$root = dirname(__DIR__);
$directory = $root.'/storage/app/private/investmoz-v2';
$proofFile = $directory.'/territory-backup-proof.json';
$proof = json_decode(file_get_contents($proofFile), true, 512, JSON_THROW_ON_ERROR);
$target = $proof['restored_target'];
if (! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $target['database']) || (int) $target['port'] !== 55441 || ! $proof['restore_verified']) {
throw new RuntimeException('Verified isolated restoration required.');
}
foreach (['APP_ENV' => 'testing', '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' => '', '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();
$connection = config('database.connections.pgsql');
if (config('database.default') !== 'pgsql' || $connection['host'] !== '127.0.0.1' || (int) $connection['port'] !== 55441 || $connection['database'] !== $target['database'] || ! empty($connection['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 connection.');
}
$qaDirectory = $directory.'/qa-traceability-reversal';
if (! is_dir($qaDirectory)) {
mkdir($qaDirectory, 0700, true);
}
$activeBytes = file_get_contents($directory.'/territory-activation-plan.json');
$activePlan = json_decode($activeBytes, true, 512, JSON_THROW_ON_ERROR);
$plan = $activePlan;
$plan['target'] = $target;
$qaBytes = json_encode($plan, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$qaHash = hash('sha256', $qaBytes);
file_put_contents($qaDirectory.'/territory-activation-plan.json', $qaBytes);
// This fixture authorizes the QA rehearsal only; it is not evidence of a completed reversal.
$qaProof = [...$proof, 'target' => $target, 'reversal_verified' => true, 'plan_hash' => $qaHash, 'code_hash' => $plan['code_hash'], 'fixture_only' => true];
file_put_contents($qaDirectory.'/territory-backup-proof.json', json_encode($qaProof, JSON_THROW_ON_ERROR));
config(['investment.traceability_directory' => $qaDirectory]);
$service = app(InvestmentTerritorialTraceability::class);
$snapshot = fn () => DB::table('cluster_projects')->orderBy('id')->get(['id', 'source_reference', 'evidence_reference', 'validation_status', 'association_type', 'version_no'])->map(fn ($row) => (array) $row)->all();
$before = $snapshot();
$unchangedTables = ['projects', 'opportunities', 'economic_clusters', 'investment_zones', 'investment_legal_sources', 'investment_dossiers', 'project_locations', 'opportunity_projects', 'opportunity_clusters', 'geo_locations', 'geo_geometries'];
$hashes = fn () => array_combine($unchangedTables, array_map(fn ($table) => hash('sha256', json_encode(DB::table($table)->orderByRaw('to_jsonb('.$table.')::text')->get(), JSON_THROW_ON_ERROR)), $unchangedTables));
$beforeHashes = $hashes();
$actor = DB::table('users')->insertGetId(['name' => 'Territory reversal QA', 'email' => 'territory-reversal-'.bin2hex(random_bytes(5)).'@example.invalid', 'password' => password_hash('QA-only', PASSWORD_BCRYPT), 'created_at' => now(), 'updated_at' => now()]);
$applied = $service->apply($qaHash, $actor);
$replayed = $service->apply($qaHash, $actor);
if ($applied['changed'] !== count($plan['updates']) || ! $replayed['replayed'] || $replayed['changed'] !== 0) {
throw new RuntimeException('Application/idempotence failed.');
}
$sources = $service->sources('economic_clusters', $plan['rows'][array_search('economic_clusters', array_column($plan['rows'], 'kind'))]['record_id']);
$reversed = $service->apply($qaHash, $actor, true);
$after = $snapshot();
foreach ($after as $index => $row) {
$expected = $before[$index];
$changed = in_array($row['id'], array_column($plan['updates'], 'id'), true);
$expected['version_no'] += $changed ? 2 : 0;
if ($row !== $expected) {
throw new RuntimeException('Reversal did not preserve values, validation or monotonic version.');
}
}
if ($hashes() !== $beforeHashes || $reversed['changed'] !== count($plan['updates']) || ! $sources) {
throw new RuntimeException('Unrelated data changed or sources not presented.');
}
$evidence = ['verified_at' => gmdate('c'), 'target' => $target, 'plan_hash' => hash('sha256', $activeBytes), 'code_hash' => $plan['code_hash'], 'applied' => $applied, 'replayed' => $replayed, 'reversed' => $reversed, 'source_projection_count' => count($sources), 'unchanged_tables' => $unchangedTables, 'validation_states_preserved' => true, 'versions_monotonic' => true, 'active_writes' => 0];
file_put_contents($directory.'/territory-reversal-evidence.json', json_encode($evidence, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
$proof['reversal_verified'] = true;
$proof['plan_hash'] = $evidence['plan_hash'];
$proof['code_hash'] = $evidence['code_hash'];
$proof['reversal_evidence'] = 'territory-reversal-evidence.json';
file_put_contents($proofFile, json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($evidence, JSON_THROW_ON_ERROR).PHP_EOL;
+180
View File
@@ -0,0 +1,180 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const directory = path.resolve(
__dirname,
'../storage/app/private/investmoz-v2',
);
const plan = JSON.parse(
fs.readFileSync(
path.join(
directory,
'qa-traceability-browser/territory-activation-plan.json',
),
'utf8',
),
);
assert.match(plan.target.database, /^desk_restore_\d{8}_\d{6}_test$/);
assert.equal(plan.target.port, 55441);
const base = 'http://127.0.0.1:18093';
(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({
viewport: { width: 1440, height: 950 },
});
await context.route('**/*', (route) =>
route.request().url().startsWith(base)
? route.continue()
: route.abort(),
);
const page = await context.newPage();
const errors = [];
const writes = [];
page.on('pageerror', (error) => errors.push(error.message));
page.on('request', (request) => {
if (request.method() === 'POST')
writes.push(new URL(request.url()).pathname);
});
const response = await page.goto(base + '/login');
assert.equal(
response.headers()['x-investmoz-qa-target'],
plan.target.database + ':55441',
);
await page
.locator('input[name=email]')
.fill('territory-browser@example.invalid');
await page.locator('input[name=password]').fill('Territory-QA-2026!');
await page.getByRole('button', { name: 'Log in', exact: true }).click();
await page.waitForURL((url) => url.pathname !== '/login');
await page.goto(base + '/management/relationship-repair');
const apply = page.getByRole('button', {
name: 'Aplicar rastreabilidade territorial V2',
exact: true,
});
await apply.waitFor();
assert.equal(await apply.isEnabled(), true);
assert.match(
await page.locator('body').innerText(),
/112 associações\/fontes/,
);
assert.match(
await page.locator('body').innerText(),
/13 atualizações de referências/,
);
await page.screenshot({
path: path.join(directory, 'territory-activation-preview.png'),
});
const post = page.waitForResponse(
(response) =>
response.request().method() === 'POST' &&
response.url().endsWith('/management/relationship-repair'),
);
await apply.click();
assert.equal((await post).status(), 302);
const revert = page.getByRole('button', {
name: 'Reverter este incremento de rastreabilidade',
exact: true,
});
try {
await revert.waitFor({ timeout: 8000 });
} catch (error) {
fs.writeFileSync(
path.join(directory, 'territory-browser-failure.txt'),
await page.locator('body').innerText(),
);
throw error;
}
assert.match(
await page.locator('body').innerText(),
/Rastreabilidade aplicada; validações e dados territoriais preservados/,
);
await page.reload();
await page
.getByRole('button', {
name: 'Reverter este incremento de rastreabilidade',
exact: true,
})
.waitFor();
const row = plan.rows.find(
(row) =>
row.kind === 'economic_clusters' &&
row.dossier_id &&
row.association_id,
);
await page.goto(base + '/carteira/' + row.dossier_id);
await page
.getByRole('heading', {
name: 'Fundamento documental das associações',
exact: true,
})
.waitFor();
assert.match(
await page.locator('body').innerText(),
/citação recuperada; ponte ao exemplar oficial por recuperar/,
);
await page.goto(base + '/management/relationship-repair');
const reversal = page.waitForResponse(
(response) =>
response.request().method() === 'POST' &&
response.url().endsWith('/management/relationship-repair'),
);
await page
.getByRole('button', {
name: 'Reverter este incremento de rastreabilidade',
exact: true,
})
.click();
assert.equal((await reversal).status(), 302);
await page
.getByRole('button', {
name: 'Aplicar rastreabilidade territorial V2',
exact: true,
})
.waitFor();
assert.match(
await page.locator('body').innerText(),
/Rastreabilidade revertida, histórico preservado/,
);
assert.deepEqual(errors, []);
assert.deepEqual(
writes.filter((path) => path !== '/login'),
[
'/management/relationship-repair',
'/management/relationship-repair',
],
);
const evidence = {
recorded_at: new Date().toISOString(),
target: plan.target,
checks: [
'authenticated preview',
'apply exact V2 button',
'HTTP 302 and visible success',
'recovery after reload',
'source per association on public dossier',
'revert exact increment',
'no console errors',
],
writes,
active_writes: 0,
};
fs.writeFileSync(
path.join(directory, 'territory-activation-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,67 @@
<?php
use App\Models\User;
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.'/territory-backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
$target = $proof['restored_target'];
if (! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $target['database']) || (int) $target['port'] !== 55441) {
throw new RuntimeException('Isolated restored QA target required.');
}
foreach (['APP_ENV' => 'testing', 'APP_DEBUG' => 'true', 'APP_URL' => 'http://127.0.0.1:18093', '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' => 'territory_traceability_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 connection.');
}
$qa = $directory.'/qa-traceability-browser';
if (! is_dir($qa.'/sessions')) {
mkdir($qa.'/sessions', 0700, true);
}
config(['session.files' => $qa.'/sessions', 'portal.managers' => ['territory-browser@example.invalid'], 'investment.traceability_directory' => $qa, 'investment.repair_directory' => $qa, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
Vite::useHotFile($root.'/storage/framework/territory-qa-absent-hot');
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'seed') {
$user = User::updateOrCreate(['email' => 'territory-browser@example.invalid'], ['name' => 'Territory browser QA', 'password' => Hash::make('Territory-QA-2026!'), 'email_verified_at' => now()]);
$user->forceFill(['email_verified_at' => now()])->save();
$plan = json_decode(file_get_contents($directory.'/territory-activation-plan.json'), true, 512, JSON_THROW_ON_ERROR);
$plan['target'] = $target;
$plan['prepared_at'] = gmdate('c');
foreach ($plan['guards'] as &$guard) {
if ($guard['table'] === 'cluster_projects') {
$row = DB::table('cluster_projects')->where('id', $guard['id'])->first();
foreach (array_keys($guard['expected']) as $field) {
$guard['expected'][$field] = $row->$field;
}
}
}
unset($guard);
$bytes = json_encode($plan, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
file_put_contents($qa.'/territory-activation-plan.json', $bytes);
file_put_contents($qa.'/territory-backup-proof.json', json_encode([...$proof, 'target' => $target, 'plan_hash' => hash('sha256', $bytes), 'fixture_only' => true], JSON_THROW_ON_ERROR));
file_put_contents($qa.'/preview.json', json_encode(['target' => $target, 'locations' => [], 'memberships' => [], 'pending' => [], 'prepared_opportunities' => []], JSON_THROW_ON_ERROR));
echo json_encode(['target' => $target, 'seeded_qa_user' => $user->id, 'active_writes' => 0]).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());