PDO::ERRMODE_EXCEPTION]); $db->beginTransaction(); $db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); if ($db->query("select current_setting('cluster_name')")->fetchColumn() !== 'sgf_modular_regression_'.$match[1]) { throw new LogicException('Wrong analytical verification cluster.'); } $frames = []; foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) { if (in_array($table, ['supply_records', 'audit_logs'], true)) { continue; } // Normal authentication may rehash a synthetic password or rotate a remember token. $query = $table === 'users' ? 'SELECT id,tenant_id,department_id,purchasing_role,name,email,created_at FROM users' : 'SELECT * FROM "'.str_replace('"', '""', $table).'"'; $rows = $db->query('SELECT row_to_json(t)::text FROM ('.$query.') t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN); $frames[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)); } $file = $root.'/analytics-baseline.private.json'; if ($mode === '--capture') { if (is_file($file) || (int) $db->query("SELECT count(*) FROM supply_records WHERE kind='expense_allocation'")->fetchColumn() !== 0) { throw new LogicException('Fresh analytical baseline required.'); } file_put_contents($file, json_encode($frames, JSON_THROW_ON_ERROR)); echo json_encode(['state' => 'captured', 'protected_tables' => count($frames), 'database_read_only' => true], JSON_THROW_ON_ERROR).PHP_EOL; } else { if ($frames !== json_decode(file_get_contents($file), true, 32, JSON_THROW_ON_ERROR)) { throw new LogicException('Native analytical review changed protected source data.'); } $records = $db->query("SELECT data FROM supply_records WHERE kind='expense_allocation' ORDER BY id")->fetchAll(PDO::FETCH_COLUMN); $data = count($records) === 1 ? json_decode($records[0], true, 32, JSON_THROW_ON_ERROR) : []; if (($data['source_type'] ?? null) !== 'common_allocation' || ($data['allocations'] ?? []) !== [ ['category' => 'Material', 'amount_minor' => '1500'], ['category' => 'Serviços', 'amount_minor' => '2500']] || (int) $db->query("SELECT count(*) FROM audit_logs WHERE action='expense.allocation_recorded'")->fetchColumn() !== 1) { throw new LogicException('One exact explicit analytical attribution and audit required.'); } echo json_encode(['state' => 'passed', 'protected_tables' => count($frames), 'database_read_only' => true, 'explicit_category_total_minor' => 4000, 'one_attribution_one_audit' => true, 'no_financial_source_mutation' => true], JSON_THROW_ON_ERROR).PHP_EOL; } $db->commit();