commit correcoes
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,83 @@
|
||||
const { chromium } = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const assert = require('node:assert/strict');
|
||||
const crypto = require('node:crypto');
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const output = path.join(root, 'outputs/demography-20261113');
|
||||
const proof = JSON.parse(fs.readFileSync(path.join(output, 'verification.json'), 'utf8'));
|
||||
const ids = proof.comparison.territories.map(t => t.id);
|
||||
const base = 'http://127.0.0.1:18813';
|
||||
const evidence = { target: 'investmoz_demography_test:55441', checks: [], screenshots: [], errors: [] };
|
||||
let activePage;
|
||||
|
||||
function totp(secret) {
|
||||
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
const bits = [...secret].map(c => alphabet.indexOf(c).toString(2).padStart(5, '0')).join('');
|
||||
const key = Buffer.from(bits.match(/.{8}/g).map(x => parseInt(x, 2)));
|
||||
const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30000)));
|
||||
const hmac = crypto.createHmac('sha1', key).update(counter).digest();
|
||||
return String((hmac.readUInt32BE(hmac[19] & 15) & 0x7fffffff) % 1000000).padStart(6, '0');
|
||||
}
|
||||
|
||||
(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: 1000 }, locale: 'pt-MZ' });
|
||||
const page = await context.newPage();
|
||||
activePage = page;
|
||||
page.on('pageerror', e => evidence.errors.push(e.message));
|
||||
if (!process.argv.includes('--admin-only')) {
|
||||
const params = new URLSearchParams({ start_year: '2026', end_year: '2027', sector: 'industry' });
|
||||
ids.forEach(id => params.append('territories[]', id));
|
||||
const response = await page.goto(`${base}/localizacoes/demografia?${params}`, { waitUntil: 'networkidle' });
|
||||
assert.equal(response.headers()['x-investmoz-qa-target'], evidence.target);
|
||||
await page.getByRole('heading', { name: 'Demografia e viabilidade territorial', exact: true }).waitFor();
|
||||
await page.getByRole('heading', { name: 'Diferenças entre localizações', exact: true }).waitFor();
|
||||
assert.equal(await page.locator('select[multiple] option:checked').count(), 2);
|
||||
assert.equal(await page.locator('table').count(), 2);
|
||||
evidence.checks.push('Public district comparison, values, versions, differences and preserved filters');
|
||||
await page.screenshot({ path: path.join(output, 'comparison-desktop.png'), fullPage: true });
|
||||
evidence.screenshots.push('comparison-desktop.png');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'Mobile page must not overflow');
|
||||
await page.screenshot({ path: path.join(output, 'comparison-mobile.png'), fullPage: true });
|
||||
evidence.screenshots.push('comparison-mobile.png');
|
||||
evidence.checks.push('Mobile layout at 390 pixels without page overflow');
|
||||
if (process.argv.includes('--public-only')) {
|
||||
fs.writeFileSync(path.join(output, 'browser-public-verification.json'), JSON.stringify(evidence, null, 2));
|
||||
return;
|
||||
}
|
||||
}
|
||||
const account = JSON.parse(fs.readFileSync(path.join(root, 'storage/app/private/demography-browser-account.json'), 'utf8'));
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.goto(`${base}/login`, { waitUntil: 'networkidle' });
|
||||
await page.locator('input[name=email]').fill(account.email);
|
||||
await page.locator('input[name=password]').fill(account.password);
|
||||
await page.locator('button[type=submit]').click();
|
||||
await page.waitForURL('**/two-factor-challenge');
|
||||
evidence.phase = 'password accepted; TOTP challenge';
|
||||
await page.locator('input[autocomplete="one-time-code"]').fill(totp(account.secret));
|
||||
await page.locator('button[type=submit]').click();
|
||||
await page.waitForURL(url => !url.pathname.includes('two-factor-challenge'));
|
||||
evidence.phase = 'TOTP accepted';
|
||||
await page.goto(`${base}/management/demography?batch=${proof.imports[0].id}`, { waitUntil: 'networkidle' });
|
||||
await page.getByRole('heading', { name: 'Dados demográficos INE — QA', exact: true }).waitFor();
|
||||
await page.getByText('Erros e advertências', { exact: true }).click();
|
||||
assert((await page.locator('body').innerText()).includes('2031!E204'));
|
||||
assert.equal(await page.locator('select').count(), 13);
|
||||
await page.screenshot({ path: path.join(output, 'administration-desktop.png'), fullPage: true });
|
||||
evidence.screenshots.push('administration-desktop.png');
|
||||
evidence.checks.push('Real password and TOTP login, administrative preview, 13 territorial matches and original inconsistency references');
|
||||
assert.deepEqual(evidence.errors, []);
|
||||
await context.close();
|
||||
} catch (error) {
|
||||
evidence.failure = { message: error.message, url: activePage?.url(), text: (await activePage?.locator('body').innerText())?.slice(-3000) };
|
||||
await activePage?.screenshot({ path: path.join(output, 'browser-diagnostic.png'), fullPage: true });
|
||||
throw error;
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(output, process.argv.includes('--public-only') ? 'browser-public-verification.json' : 'browser-admin-verification.json'), JSON.stringify(evidence, null, 2));
|
||||
await browser.close();
|
||||
}
|
||||
console.log(JSON.stringify({ checks: evidence.checks, screenshots: evidence.screenshots, errors: evidence.errors }));
|
||||
})().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
// The operational database is read-only; restore writes only to the named isolated QA server.
|
||||
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
|
||||
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
ini_set('zend.exception_ignore_args', '1');
|
||||
$root = dirname(__DIR__);
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
(new LoadEnvironmentVariables)->bootstrap($app);
|
||||
(new LoadConfiguration)->bootstrap($app);
|
||||
$c = config('database.connections.'.config('database.default'));
|
||||
throw_unless($c['driver'] === 'pgsql' && empty($c['url']) && $c['host'] === '127.0.0.1' && (int) $c['port'] === 5432 && $c['database'] === 'investemoz', RuntimeException::class, 'Confirmed operational target required.');
|
||||
$source = new PDO('pgsql:host=127.0.0.1;port=5432;dbname=investemoz', $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$source->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$identity = $source->query("SELECT current_database() AS database,inet_server_port() AS port,current_setting('transaction_read_only') AS read_only")->fetch(PDO::FETCH_ASSOC);
|
||||
throw_unless($identity['database'] === 'investemoz' && (int) $identity['port'] === 5432 && $identity['read_only'] === 'on', RuntimeException::class, 'Actual operational identity differs.');
|
||||
$stamp = gmdate('Ymd_His');
|
||||
$clone = 'demography_restore_'.$stamp.'_test';
|
||||
$directory = $root.'/storage/app/private/demography-deployment/'.$stamp;
|
||||
mkdir($directory, 0700, true);
|
||||
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
|
||||
$run = static function (array $args, string $password) use ($directory): void {
|
||||
$process = new Process($args, null, ['PGPASSWORD' => $password]);
|
||||
$process->setTimeout(300);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
file_put_contents($directory.'/failure.json', json_encode(['tool' => basename($args[0]), 'exit' => $process->getExitCode()], JSON_THROW_ON_ERROR));
|
||||
throw new RuntimeException('Backup/restore command failed; private diagnostic retained.');
|
||||
}
|
||||
};
|
||||
$dump = $directory.'/database.dump';
|
||||
$snapshot = $source->query('SELECT pg_export_snapshot()')->fetchColumn();
|
||||
$run([$bin.'pg_dump.exe', '-h', '127.0.0.1', '-p', '5432', '-U', $c['username'], '-d', 'investemoz', '-Fc', '--snapshot='.$snapshot, '-f', $dump], $c['password']);
|
||||
$qa = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=postgres', 'demography_qa', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
throw_unless((int) $qa->query('SELECT inet_server_port()')->fetchColumn() === 55441 && preg_match('/^demography_restore_\d{8}_\d{6}_test$/', $clone) === 1, RuntimeException::class, 'Restore target refused.');
|
||||
$qa->exec('CREATE DATABASE "'.$clone.'"');
|
||||
$run([$bin.'pg_restore.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'demography_qa', '-d', $clone, '--exit-on-error', '--no-owner', '--no-privileges', $dump], '');
|
||||
$restored = new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$clone, 'demography_qa', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$restored->exec('BEGIN READ ONLY');
|
||||
$tables = [];
|
||||
foreach ($source->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC) as $table) {
|
||||
$name = '"'.str_replace('"', '""', $table['schemaname']).'"."'.str_replace('"', '""', $table['tablename']).'"';
|
||||
$sql = 'SELECT row_to_json(t)::text FROM '.$name.' t ORDER BY row_to_json(t)::text';
|
||||
$a = $source->query($sql)->fetchAll(PDO::FETCH_COLUMN);
|
||||
$b = $restored->query($sql)->fetchAll(PDO::FETCH_COLUMN);
|
||||
// PostgreSQL installations have different collations; compare the exact byte multiset.
|
||||
sort($a, SORT_STRING);
|
||||
sort($b, SORT_STRING);
|
||||
throw_unless($a === $b, RuntimeException::class, 'Restored table differs; do not deploy.');
|
||||
$tables[$name] = ['count' => count($a), 'sha256' => hash('sha256', implode("\n", $a))];
|
||||
}
|
||||
$documents = $source->query('SELECT DISTINCT storage_key FROM documents WHERE storage_key IS NOT NULL')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$source->exec('ROLLBACK');
|
||||
$restored->exec('ROLLBACK');
|
||||
$zipPath = $directory.'/files.zip';
|
||||
$zip = new ZipArchive;
|
||||
throw_unless($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::EXCL) === true, RuntimeException::class);
|
||||
$hashes = [];
|
||||
$add = static function (string $file, string $member) use ($zip, &$hashes): void {
|
||||
throw_unless(is_file($file) && $zip->addFile($file, $member), RuntimeException::class, 'Backup source unavailable.');
|
||||
$hashes[$member] = hash_file('sha256', $file);
|
||||
};
|
||||
$privateRoot = realpath($root.'/storage/app/private');
|
||||
foreach ($documents as $relative) {
|
||||
$file = realpath($privateRoot.'/'.$relative);
|
||||
throw_unless($file && str_starts_with(strtolower($file), strtolower($privateRoot.DIRECTORY_SEPARATOR)), RuntimeException::class, 'Document unavailable for recovery.');
|
||||
$add($file, 'private/'.str_replace('\\', '/', substr($file, strlen($privateRoot) + 1)));
|
||||
}
|
||||
foreach (['app', 'routes', 'config', 'database/migrations', 'public/build'] as $folder) {
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root.'/'.$folder, FilesystemIterator::SKIP_DOTS)) as $file) {
|
||||
if ($file->isFile()) {
|
||||
$relative = str_replace('\\', '/', substr($file->getPathname(), strlen($root) + 1));
|
||||
$add($file->getPathname(), 'code/'.$relative);
|
||||
}
|
||||
}
|
||||
}
|
||||
$add($root.'/.env', 'runtime/.env');
|
||||
$zip->close();
|
||||
$read = new ZipArchive;
|
||||
throw_unless($read->open($zipPath) === true, RuntimeException::class);
|
||||
foreach ($hashes as $member => $sha) {
|
||||
$bytes = $read->getFromName($member);
|
||||
throw_unless(is_string($bytes) && hash_equals($sha, hash('sha256', $bytes)), RuntimeException::class, 'File archive verification failed.');
|
||||
$path = $directory.'/files-restored/'.$member;
|
||||
if (! is_dir(dirname($path))) {
|
||||
mkdir(dirname($path), 0700, true);
|
||||
}
|
||||
throw_unless(file_put_contents($path, $bytes) !== false && hash_file('sha256', $path) === $sha, RuntimeException::class, 'File restore verification failed.');
|
||||
}
|
||||
$read->close();
|
||||
$proof = ['target' => ['database' => 'investemoz', 'port' => 5432], 'restore_target' => ['database' => $clone, 'port' => 55441],
|
||||
'backup_at' => gmdate(DATE_ATOM), 'restore_verified' => true, 'files_verified' => true, 'tables' => $tables, 'file_count' => count($hashes),
|
||||
'dump_path' => $dump, 'dump_sha256' => hash_file('sha256', $dump), 'files_path' => $zipPath, 'files_sha256' => hash_file('sha256', $zipPath),
|
||||
'environment_sha256' => hash_file('sha256', $root.'/.env'), 'previous_manifest_sha256' => hash_file('sha256', $root.'/public/build/manifest.json'),
|
||||
'decision' => 'Proprietário, 13/11/2026: homologar e disponibilizar no portal operacional local investemoz:5432, incluindo três ficheiros e Macate/Vanduzi.'];
|
||||
file_put_contents($root.'/storage/app/private/demography-deployment/backup.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['restore_verified' => true, 'files_verified' => true, 'tables' => count($tables), 'files' => count($hashes), 'restore_target' => $clone], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Vite;
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||
$resolved = is_string($requestPath) ? realpath($root.'/public'.$requestPath) : false;
|
||||
if ($resolved && str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $root).'/public/') && is_file($resolved) && in_array(strtolower(pathinfo($resolved, PATHINFO_EXTENSION)), ['js', 'css', 'png', 'jpg', 'jpeg', 'svg', 'ico', 'webp', 'woff', 'woff2'], true)) {
|
||||
return false;
|
||||
}
|
||||
require $root.'/vendor/autoload.php';
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
throw_unless(IsolatedQaDatabase::allowsSchemaChanges() && config('database.connections.pgsql.database') === 'investmoz_demography_test', RuntimeException::class, 'Dedicated demographic QA server only.');
|
||||
config(['portal.managers' => ['demography-qa@example.test'], 'portal.homologation_only' => false, 'session.driver' => 'file', 'session.cookie' => 'demography_qa_session', 'session.secure' => false, 'cache.default' => 'array']);
|
||||
Vite::useBuildDirectory('build-qa-opportunities');
|
||||
Vite::useHotFile(storage_path('framework/demography-qa.hot'));
|
||||
header('X-Investmoz-QA-Target: investmoz_demography_test:55441');
|
||||
$app->handleRequest(Request::capture());
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
// Reproducible homologation on a new, explicitly named QA database only.
|
||||
use App\Models\User;
|
||||
use App\Services\DemographicEvidence;
|
||||
use App\Services\DemographicImport;
|
||||
use App\Support\CheckedFile;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
throw_unless(IsolatedQaDatabase::allowsSchemaChanges() && DB::connection()->getDatabaseName() === 'investmoz_demography_test', RuntimeException::class, 'Dedicated demography QA required.');
|
||||
$snapshot = json_decode(CheckedFile::read(storage_path('app/private/demography-registry-snapshot.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
throw_unless($snapshot['read_only'] === true, RuntimeException::class);
|
||||
DB::transaction(function () use ($snapshot) {
|
||||
foreach ($snapshot['records'] as $row) {
|
||||
DB::table('geo_locations')->insertOrIgnore($row);
|
||||
}
|
||||
});
|
||||
$actor = User::firstOrCreate(['email' => 'demography-qa@example.test'], ['name' => 'Homologação demográfica QA', 'password' => Str::password(40)]);
|
||||
$actor->forceFill(['email_verified_at' => now(), 'two_factor_confirmed_at' => now(), 'two_factor_secret' => Crypt::encrypt('JBSWY3DPEHPK3PXP')])->save();
|
||||
config(['portal.managers' => [$actor->email]]);
|
||||
$root = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Servicos Tempo/portal do investidor/demografia/Provincias';
|
||||
$manicaSha = CheckedFile::sha256($root.'/Manica.xlsx');
|
||||
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Manica')->value('id');
|
||||
foreach (['Macate', 'Vanduzi'] as $name) {
|
||||
// Owner's explicit reply on 13/11/2026: add ONLY in QA, citing the INE workbook.
|
||||
DB::table('geo_locations')->insertOrIgnore(['id' => (string) Str::uuid(), 'parent_id' => $province, 'name' => $name,
|
||||
'location_type' => 'district', 'code' => 'QA-INE-'.strtoupper($name), 'source_system' => 'ine-demography-qa',
|
||||
'external_id' => $manicaSha.':'.$name, 'data_classification' => 'public', 'version_no' => 1]);
|
||||
}
|
||||
$service = app(DemographicImport::class);
|
||||
$proof = ['qa_database' => DB::connection()->getDatabaseName(), 'qa_port' => 55441, 'active_writes' => false,
|
||||
'qa_registry_additions' => ['Macate', 'Vanduzi'], 'imports' => []];
|
||||
foreach (['Manica.xlsx', 'Inhambane.xlsx', 'Dados demograficos.xlsx'] as $name) {
|
||||
$started = microtime(true);
|
||||
$plan = $service->prepare($actor, $root.'/'.$name, $name, 'Exemplar INE fornecido pela Tempo; edição não indicada; SHA256 identifica a versão', $name === 'Dados demograficos.xlsx' ? 2017 : null);
|
||||
$unresolved = array_values(array_filter($plan['matches'], fn ($m) => $m['geo_location_id'] === null));
|
||||
throw_unless($unresolved === [], RuntimeException::class, 'Unresolved territories: '.json_encode($unresolved, JSON_THROW_ON_ERROR));
|
||||
$receipt = $service->confirm($actor, $plan['id'], $plan['sha256'], [], 'Homologação QA: valores e advertências preservados; sem correcção do original.');
|
||||
$replay = $service->confirm($actor, $plan['id'], $plan['sha256'], [], 'Repetição QA para conferir idempotência.');
|
||||
throw_unless($replay['repeated'] && $receipt['records'] === $replay['records'], RuntimeException::class, 'Replay duplicated observations.');
|
||||
$service->transition($actor, $plan['id'], 'approved', 'Aprovação exclusivamente QA para conferir integração, mantendo advertências da fonte.');
|
||||
$proof['imports'][] = ['file' => $name, 'sha256' => $plan['sha256'], 'id' => $plan['id'], 'records' => $receipt['records'],
|
||||
'rejected_numeric_records' => $plan['report']['issue_counts']['invalid_numeric_or_formula'] ?? 0,
|
||||
'territories' => $plan['matches'], 'years' => $plan['report']['years'], 'sheets' => $plan['report']['sheets'],
|
||||
'issue_counts' => $plan['report']['issue_counts'], 'issues' => $plan['report']['issues'], 'scan' => $plan['report']['scan'],
|
||||
'idempotence' => true, 'seconds' => round(microtime(true) - $started, 3)];
|
||||
echo $name.': '.$receipt['records'].' observations; replay preserved.'.PHP_EOL;
|
||||
}
|
||||
$districts = DB::table('geo_locations')->where('location_type', 'district')->where('parent_id', $province)->whereIn('name', ['GONDOLA', 'GURO'])->pluck('id')->all();
|
||||
$analysis = app(DemographicEvidence::class)->analyse($districts, 2017, 2050, 'industry');
|
||||
throw_unless($analysis['state'] === 'available' && count($analysis['territories']) === 2, RuntimeException::class, 'District comparison failed.');
|
||||
$proof['comparison'] = ['state' => $analysis['state'], 'territories' => array_map(fn ($t) => ['id' => $t['id'], 'name' => $t['name'], 'series' => count($t['series'])], $analysis['territories'])];
|
||||
$proof['total_observations'] = DB::table('demographic_observations')->count();
|
||||
$proof['recorded_at'] = gmdate(DATE_ATOM);
|
||||
file_put_contents(base_path('outputs/demography-20261113/verification.json'), json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
echo 'QA proof saved; '.$proof['total_observations'].' exact numeric observations.'.PHP_EOL;
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
// Read only: take public territorial references from the current application, not private data.
|
||||
use App\Services\InvestmentGeography;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::statement('SET TRANSACTION READ ONLY');
|
||||
$records = app(InvestmentGeography::class)->publicReferences()->whereIn('location_type', ['country', 'province', 'district'])
|
||||
->orderByRaw("CASE location_type WHEN 'country' THEN 0 WHEN 'province' THEN 1 ELSE 2 END")
|
||||
->get(['id', 'parent_id', 'name', 'location_type', 'code', 'source_code', 'source_system', 'external_id', 'data_classification', 'version_no']);
|
||||
$path = storage_path('app/private/demography-registry-snapshot.json');
|
||||
file_put_contents($path, json_encode(['read_only' => true, 'captured_at' => gmdate(DATE_ATOM), 'records' => $records], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
echo json_encode(['read_only' => true, 'counts' => $records->countBy('location_type')->all(), 'snapshot_sha256' => hash_file('sha256', $path)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
DB::rollBack();
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
// Publish only the verified frontend. Data/schema remain behind the authenticated installer.
|
||||
use App\Services\DemographicInstallation;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$installation = app(DemographicInstallation::class);
|
||||
throw_unless($installation->activeTarget(), RuntimeException::class, 'Confirmed operational target required.');
|
||||
$directory = $root.'/outputs/demography-20261113';
|
||||
$backup = json_decode(CheckedFile::read(storage_path('app/private/demography-deployment/backup.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
throw_unless($backup['restore_verified'] && $backup['files_verified'], RuntimeException::class, 'Backup/restore evidence required.');
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
throw_unless(CheckedFile::matches($backup[$kind.'_path'], $backup[$kind.'_sha256']), RuntimeException::class, 'Backup integrity changed.');
|
||||
}
|
||||
throw_unless(CheckedFile::matches(base_path('.env'), $backup['environment_sha256']), RuntimeException::class, 'Environment changed.');
|
||||
throw_unless(CheckedFile::matches(public_path('build/manifest.json'), $backup['previous_manifest_sha256']), RuntimeException::class, 'Operational build changed; reconcile before replacing.');
|
||||
$readResult = static function (string $path, int $expected): array {
|
||||
$bytes = CheckedFile::read($path);
|
||||
if (str_starts_with($bytes, "\xFF\xFE")) {
|
||||
$bytes = mb_convert_encoding($bytes, 'UTF-8', 'UTF-16');
|
||||
}
|
||||
$result = json_decode(trim($bytes), true, 512, JSON_THROW_ON_ERROR);
|
||||
throw_unless(($result['result'] ?? '') === 'passed' && ($result['passed'] ?? 0) === $expected, RuntimeException::class, 'Release test did not pass.');
|
||||
|
||||
return $result;
|
||||
};
|
||||
$releaseTests = $readResult($directory.'/installation-tests.log', 5);
|
||||
$regression = $readResult($directory.'/release-regression.log', 11);
|
||||
$mfa = json_decode(CheckedFile::read($directory.'/qa-http-homologation.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
throw_unless($mfa['mfa_authenticated'] && $mfa['administrative_preview_verified'], RuntimeException::class, 'Real QA MFA confirmation required.');
|
||||
$sourceDirectory = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Servicos Tempo/portal do investidor/demografia/Provincias';
|
||||
foreach (DemographicInstallation::FILES as $name => $expected) {
|
||||
throw_unless(CheckedFile::matches($sourceDirectory.'/'.$name, $expected['sha256']), RuntimeException::class, 'Approved original changed.');
|
||||
}
|
||||
$candidate = realpath($directory.'/release-build');
|
||||
$destination = realpath(public_path('build'));
|
||||
throw_unless($candidate && $destination && str_replace('\\', '/', $destination) === str_replace('\\', '/', $root).'/public/build', RuntimeException::class, 'Build destination refused.');
|
||||
$manifest = json_decode(CheckedFile::read($candidate.'/manifest.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach (['resources/js/pages/management/demography-install.tsx', 'resources/js/pages/management/demography.tsx', 'resources/js/pages/investment/demography.tsx'] as $entry) {
|
||||
throw_unless(isset($manifest[$entry]) && is_file($candidate.'/'.$manifest[$entry]['file']), RuntimeException::class, 'Release page missing from build.');
|
||||
}
|
||||
$releaseFiles = [];
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($candidate, FilesystemIterator::SKIP_DOTS)) as $file) {
|
||||
if (! $file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
$relative = str_replace('\\', '/', substr($file->getPathname(), strlen($candidate) + 1));
|
||||
throw_unless(! str_contains($relative, '..') && ! str_contains($relative, ':'), RuntimeException::class, 'Build member refused.');
|
||||
$releaseFiles[$relative] = CheckedFile::sha256($file->getPathname());
|
||||
if ($relative === 'manifest.json') {
|
||||
continue;
|
||||
}
|
||||
$target = $destination.'/'.$relative;
|
||||
if (! is_dir(dirname($target))) {
|
||||
mkdir(dirname($target), 0755, true);
|
||||
}
|
||||
throw_unless(copy($file->getPathname(), $target) && CheckedFile::matches($target, $releaseFiles[$relative]), RuntimeException::class, 'Release asset copy failed.');
|
||||
}
|
||||
File::replace($destination.'/manifest.json', CheckedFile::read($candidate.'/manifest.json'));
|
||||
throw_unless(CheckedFile::matches($destination.'/manifest.json', $releaseFiles['manifest.json']), RuntimeException::class, 'Release manifest verification failed.');
|
||||
$proof = [...$backup, 'code_sha256' => $installation->fingerprint(), 'verified_at' => gmdate(DATE_ATOM),
|
||||
'qa_passed' => true, 'compatibility_verified' => true, 'release_manifest_sha256' => $releaseFiles['manifest.json'],
|
||||
'release_files' => $releaseFiles, 'installation_tests' => $releaseTests, 'regression_tests' => $regression, 'qa_mfa_verified' => true,
|
||||
'operational_data_applied' => false, 'next_action' => 'Existing authorised installation identity must execute with fresh session MFA at /management/demography/install.'];
|
||||
file_put_contents(storage_path('app/private/demography-deployment/readiness.json'), json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$publicProof = ['target' => $target, 'backup_tables' => count($backup['tables']), 'backup_files' => $backup['file_count'],
|
||||
'restore_verified' => true, 'files_verified' => true, 'installation_tests' => $releaseTests, 'regression_tests' => $regression,
|
||||
'release_manifest_sha256' => $releaseFiles['manifest.json'], 'code_sha256' => $proof['code_sha256'],
|
||||
'operational_data_applied' => false, 'installation_url' => rtrim(config('app.url'), '/').'/management/demography/install',
|
||||
'verified_at' => $proof['verified_at']];
|
||||
file_put_contents($directory.'/release-readiness.json', json_encode($publicProof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($publicProof, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use App\Services\DemographicInstallation;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Contracts\Http\Kernel as HttpKernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
throw_unless(app(DemographicInstallation::class)->activeTarget(), RuntimeException::class, 'Operational identity differs.');
|
||||
$installed = Schema::hasTable('demographic_observations');
|
||||
$proof = ['target' => ['database' => 'investemoz', 'port' => 5432], 'installed' => $installed,
|
||||
'observations' => $installed ? DB::table('demographic_observations')->count() : 0,
|
||||
'approved_batches' => $installed ? DB::table('demographic_imports')->where('status', 'approved')->count() : 0,
|
||||
'authenticated_operation_recorded' => DB::table('audit_events')->where('source_system', 'demography-installation')->where('action', 'install_and_import')->exists(),
|
||||
'routes' => [], 'at' => gmdate(DATE_ATOM), 'scope' => 'Application kernel smoke test, not a browser or TLS certification'];
|
||||
foreach (['/management/demography/install', '/localizacoes/demografia', '/api/v1/investment/demography'] as $path) {
|
||||
$request = Request::create('https://portal-investidor.test'.$path, 'GET');
|
||||
if (str_starts_with($path, '/api/')) {
|
||||
$request->headers->set('Accept', 'application/json');
|
||||
}
|
||||
$response = $app->make(HttpKernel::class)->handle($request);
|
||||
$row = ['path' => $path, 'status' => $response->getStatusCode()];
|
||||
if (str_starts_with($path, '/api/')) {
|
||||
$row['state'] = json_decode($response->getContent(), true, 512, JSON_THROW_ON_ERROR)['state'] ?? null;
|
||||
}
|
||||
$proof['routes'][] = $row;
|
||||
throw_unless(in_array($response->getStatusCode(), str_starts_with($path, '/management/') ? [302, 303] : [200], true), RuntimeException::class, 'Published route failed.');
|
||||
}
|
||||
file_put_contents(base_path('outputs/demography-20261113/operational-status.json'), json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($proof, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
// Repair only interpreter resolution; never bypass authentication or write demographic data.
|
||||
use App\Services\DemographicInstallation;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
throw_unless(app(DemographicInstallation::class)->activeTarget() && ! $app->configurationIsCached(), RuntimeException::class, 'Explicit uncached operational target required.');
|
||||
$proofFile = storage_path('app/private/demography-deployment/readiness.json');
|
||||
$proof = json_decode(CheckedFile::read($proofFile), true, 512, JSON_THROW_ON_ERROR);
|
||||
throw_unless(CheckedFile::matches(base_path('.env'), $proof['environment_sha256']) && CheckedFile::matches(public_path('build/manifest.json'), $proof['release_manifest_sha256']), RuntimeException::class, 'Runtime changed; reconcile before repair.');
|
||||
$python = 'C:/Users/macbook/AppData/Local/Python/pythoncore-3.15-arm64/python.exe';
|
||||
throw_unless(is_file($python), RuntimeException::class, 'Verified installed interpreter unavailable.');
|
||||
if (in_array('--refresh-proof', $argv, true)) {
|
||||
throw_unless(config('demography.python') === $python && CheckedFile::matches($python, $proof['runtime_repair']['python_sha256'] ?? ''), RuntimeException::class, 'Configured interpreter changed.');
|
||||
$probe = new Process([$python, '-c', 'import sys; assert sys.version_info >= (3, 9)'], base_path(), timeout: 15);
|
||||
$probe->mustRun();
|
||||
$proof['code_sha256'] = app(DemographicInstallation::class)->fingerprint();
|
||||
$proof['verified_at'] = gmdate(DATE_ATOM);
|
||||
File::replace($proofFile, json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['runtime_ready' => true, 'code_sha256' => $proof['code_sha256'], 'operational_data_applied' => false], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit(0);
|
||||
}
|
||||
$directory = storage_path('app/private/demography-deployment');
|
||||
$source = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Servicos Tempo/portal do investidor/demografia/Provincias/Manica.xlsx';
|
||||
throw_unless(CheckedFile::matches($source, DemographicInstallation::MANICA_SHA256), RuntimeException::class);
|
||||
$started = microtime(true);
|
||||
$output = $directory.'/runtime-probe.json';
|
||||
$process = new Process([$python, base_path('tools/demography_workbook.py'), $source, '--output', $output], base_path(), timeout: 45);
|
||||
$process->mustRun();
|
||||
$report = json_decode(CheckedFile::read($output), true, 512, JSON_THROW_ON_ERROR);
|
||||
throw_unless($report['record_count'] === 71604 && $report['sha256'] === DemographicInstallation::MANICA_SHA256, RuntimeException::class, 'Runtime probe differs from approved source.');
|
||||
$envFile = base_path('.env');
|
||||
$bytes = CheckedFile::read($envFile);
|
||||
throw_unless(preg_match('/^DEMOGRAPHY_PYTHON=/m', $bytes) !== 1, RuntimeException::class, 'Existing interpreter setting must be reconciled, not overwritten.');
|
||||
$before = $directory.'/environment-before-python-'.gmdate('Ymd_His').'.env';
|
||||
File::replace($before, $bytes);
|
||||
$newline = str_contains($bytes, "\r\n") ? "\r\n" : "\n";
|
||||
File::replace($envFile, rtrim($bytes, "\r\n").$newline.'DEMOGRAPHY_PYTHON="'.$python.'"'.$newline);
|
||||
$proof['environment_before_python_sha256'] = $proof['environment_sha256'];
|
||||
$proof['environment_sha256'] = CheckedFile::sha256($envFile);
|
||||
$proof['code_sha256'] = app(DemographicInstallation::class)->fingerprint();
|
||||
$proof['verified_at'] = gmdate(DATE_ATOM);
|
||||
$proof['runtime_repair'] = ['cause' => 'WindowsApps python execution alias in web process', 'python_executable' => $python,
|
||||
'python_sha256' => CheckedFile::sha256($python), 'probe_records' => 71604, 'probe_seconds' => round(microtime(true) - $started, 3),
|
||||
'environment_backup' => $before, 'authentication_changed' => false, 'operational_data_applied' => false];
|
||||
File::replace($proofFile, json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
$receipt = ['interpreter_probe_passed' => true, 'probe_records' => 71604, 'probe_seconds' => $proof['runtime_repair']['probe_seconds'],
|
||||
'code_sha256' => $proof['code_sha256'], 'authentication_changed' => false, 'operational_data_applied' => false, 'verified_at' => $proof['verified_at']];
|
||||
File::replace(base_path('outputs/demography-20261113/runtime-repair.json'), json_encode($receipt, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($receipt, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Reconcile supplied exemplars without merging statistical series or inventing observations."""
|
||||
import argparse
|
||||
from decimal import Decimal
|
||||
import json
|
||||
from pathlib import Path
|
||||
from demography_workbook import parse
|
||||
|
||||
|
||||
def reconcile(directory):
|
||||
national = parse(directory / 'Dados demograficos.xlsx', 2017)
|
||||
comparisons = []
|
||||
for province in ('Manica', 'Inhambane'):
|
||||
annual = parse(directory / (province + '.xlsx'))
|
||||
detail = [r for r in annual['records'] if r['level'] == 'province' and r['year'] == 2017]
|
||||
for baseline in national['records']:
|
||||
if baseline['province'] != province or baseline['indicator'] != 'population':
|
||||
continue
|
||||
age = baseline['age_group']
|
||||
bands = {'all': ['all'], '0-14': ['0-4', '5-9', '10-14'],
|
||||
'15-64': [f'{i}-{i+4}' for i in range(15, 65, 5)], '65+': ['65-69', '70-74', '75-79', '80+']}[age]
|
||||
matches = [r for r in detail if r['age_group'] in bands and r['sex'] == baseline['sex'] and r['residence'] == baseline['residence']]
|
||||
calculated = sum(Decimal(r['numeric_value']) for r in matches) if len(matches) == len(bands) else None
|
||||
difference = calculated - Decimal(baseline['numeric_value']) if calculated is not None else None
|
||||
comparisons.append({'province': province, 'year': 2017, 'age_group': age, 'sex': baseline['sex'], 'residence': baseline['residence'],
|
||||
'national_value': baseline['original_value'], 'national_reference': baseline['sheet'] + '!' + baseline['cell'],
|
||||
'annual_derived_sum': str(calculated), 'annual_references': [r['sheet'] + '!' + r['cell'] for r in matches],
|
||||
'difference': str(difference), 'state': 'matching_within_precision' if difference is not None and abs(difference) <= Decimal('0.000001') else 'divergent_or_incomplete'})
|
||||
return {'method': 'Independent exact decimal sums; tolerance 0.000001 person for Excel storage residues. Derived sums are reconciliation evidence, not new INE observations.',
|
||||
'type_compatibility': 'Annual sheets explicitly say projected; national sheets do not state observed/projected. Matching numbers do not equate statistical versions.',
|
||||
'baseline_year': 'Population sheet has no printed year: 2017 explicitly supplied in import metadata; age/vital sheets state 2017.',
|
||||
'comparisons': comparisons, 'matching': sum(r['state'] == 'matching_within_precision' for r in comparisons),
|
||||
'divergent_or_incomplete': sum(r['state'] != 'matching_within_precision' for r in comparisons)}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
cli = argparse.ArgumentParser()
|
||||
cli.add_argument('directory', type=Path)
|
||||
cli.add_argument('--output', type=Path, required=True)
|
||||
args = cli.parse_args()
|
||||
report = reconcile(args.directory)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps({k: v for k, v in report.items() if k != 'comparisons'}, ensure_ascii=False))
|
||||
@@ -0,0 +1,31 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {combinedCase} from '../tests/frontend/helpers/irpc-investment-combination-case.mjs';
|
||||
import {plan as ppc} from '../tests/frontend/helpers/irpc-ppc-obligation-case.mjs';
|
||||
import {plan as pec} from '../tests/frontend/helpers/irpc-pec-obligation-case.mjs';
|
||||
import {newPecPlan} from '../resources/js/lib/irpc-pec-plan.ts';
|
||||
import {annualAdvanceCashflow,annualBook,annualCurrent,annualHtml,recordAnnual,saveAnnualBook} from '../resources/js/lib/irpc-annual-settlement.ts';
|
||||
import {createProjectDossierReport} from '../resources/js/lib/project-dossier-report.ts';
|
||||
const out=new URL('../outputs/irpc-cashflow-group-20261113/',import.meta.url);fs.mkdirSync(out,{recursive:true});
|
||||
for(const name of ['overlap','distributed','partial','zero']){
|
||||
if(process.argv[2]==='generate'){
|
||||
const {d,b}=combinedCase();const prior=recordAnnual(d,b,'2026-11-13T21:40:00Z');
|
||||
prior.ppcObligation={...ppc(),subjectNuit:b.subjectNuit};
|
||||
prior.pecObligation={...pec(),subjectNuit:b.subjectNuit,plan:{...newPecPlan(),mode:'single',singleMonth:'2026-05',reference:'SYNTHETIC cash hypothesis'}};
|
||||
if(name==='distributed')prior.pecObligation.plan={...newPecPlan(),mode:'three',june:'10000.01',august:'14999.99',october:'15000',reference:'SYNTHETIC explicit allocation'};
|
||||
if(name==='partial')delete prior.pecObligation.plan;
|
||||
if(name==='zero'){prior.ppcObligation.previousTax='0';prior.ppcObligation.previousWithholdings='0';prior.pecObligation.previousPpcPaid='60000';}
|
||||
d.modelo_a_snapshot=saveAnnualBook(d,recordAnnual(d,prior,'2026-11-13T21:41:00Z'));
|
||||
fs.writeFileSync(new URL(name+'.json',out),JSON.stringify(d));
|
||||
}else{
|
||||
const d=JSON.parse(fs.readFileSync(new URL('recovered-'+name+'.json',out),'utf8')),b=annualBook(d),before=JSON.stringify(b),m=annualAdvanceCashflow(b);
|
||||
assert.equal(annualCurrent(d,b),true);assert.equal(b.history.length,1);assert.deepEqual(b.result.model.arithmeticBalance,{numerator:'138',denominator:'1'});assert.equal(JSON.stringify(b),before);
|
||||
assert.deepEqual(m.total,name==='partial'?null:{numerator:name==='zero'?'0':'112000',denominator:'1'});
|
||||
if(name==='overlap')assert.deepEqual(m.rows[0].knownSubtotal,{numerator:'64000',denominator:'1'});
|
||||
if(name==='partial')assert.equal(m.pecKnown,false);
|
||||
const html=annualHtml(d),report=createProjectDossierReport(d,{selectedSections:new Set(['finance']),generatedAt:'2026-11-13T21:42:00Z'});
|
||||
assert.match(html,/Projecção mensal conjunta PPC\/PEC/);assert.match(JSON.stringify(report),/Projecção mensal conjunta PPC\/PEC/);
|
||||
fs.writeFileSync(new URL(name+'-report.html',out),html);fs.writeFileSync(new URL(name+'-verification.json',out),JSON.stringify({synthetic:true,nativeApiRecovery:true,annualCurrent:true,historyPreserved:true,annualBalanceUnchanged:true,report:true,model:m},null,2));
|
||||
}
|
||||
}
|
||||
console.log(process.argv[2]==='generate'?'Generated four synthetic cash projection cases':'Verified four recovered cash projections and dossier reports');
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
if (($argv[1] ?? '') !== 'test' || basename($root) !== 'portal-investidor') {
|
||||
throw new RuntimeException('Explicit isolated QA test operation required');
|
||||
}
|
||||
foreach (['APP_ENV' => 'testing', 'APP_KEY' => 'base64:'.base64_encode(str_repeat('Q', 32)),
|
||||
'APP_CONFIG_CACHE' => $root.'/outputs/irpc-cashflow-group-20261113/no-config.php', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'investmoz_demography_test', 'DB_USERNAME' => 'demography_qa', 'DB_PASSWORD' => '', 'DB_URL' => '', 'DATABASE_URL' => '',
|
||||
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array', 'SUITECRM_ENABLED' => 'false'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$pdo = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=investmoz_demography_test', 'demography_qa', '');
|
||||
$identity = $pdo->query('select current_database(),inet_server_port()')->fetch(PDO::FETCH_NUM);
|
||||
if ($identity !== ['investmoz_demography_test', 55441] && $identity !== ['investmoz_demography_test', '55441']) {
|
||||
throw new RuntimeException('Isolated QA identity required');
|
||||
}
|
||||
$argv = ['phpunit', '-c', 'phpunit.investmoz.xml', '--do-not-cache-result', 'tests/Feature/IrpcAdvanceCashflowDraftTest.php'];
|
||||
$_SERVER['argv'] = $argv;
|
||||
$_SERVER['argc'] = count($argv);
|
||||
require $root.'/vendor/autoload.php';
|
||||
require $root.'/vendor/phpunit/phpunit/phpunit';
|
||||
@@ -0,0 +1,22 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {periodAdvanceCase} from '../tests/frontend/helpers/irpc-advance-period-case.mjs';
|
||||
import {annualAdvanceCashflow,annualAdvancePeriod,annualBook,annualCurrent,annualHtml,recordAnnual,saveAnnualBook} from '../resources/js/lib/irpc-annual-settlement.ts';
|
||||
import {createProjectDossierReport} from '../resources/js/lib/project-dossier-report.ts';
|
||||
const out=new URL('../outputs/irpc-period-consistency-20261113/',import.meta.url);fs.mkdirSync(out,{recursive:true});
|
||||
for(const name of ['ordinary','noncivil','short','start']){
|
||||
if(process.argv[2]==='generate'){
|
||||
const {d,b}=periodAdvanceCase(name);const prior=recordAnnual(d,{...b,ppcObligation:undefined,pecObligation:undefined},'2026-11-13T22:05:00Z');
|
||||
d.modelo_a_snapshot=saveAnnualBook(d,recordAnnual(d,{...prior,ppcObligation:b.ppcObligation,pecObligation:b.pecObligation},'2026-11-13T22:06:00Z'));fs.writeFileSync(new URL(name+'.json',out),JSON.stringify(d));
|
||||
}else{
|
||||
const d=JSON.parse(fs.readFileSync(new URL('recovered-'+name+'.json',out),'utf8')),b=annualBook(d),period=annualAdvancePeriod(d),m=annualAdvanceCashflow(b,period);
|
||||
assert.equal(annualCurrent(d,b),true);assert.equal(b.history.length,1);assert.deepEqual(b.result.model.arithmeticBalance,b.history[0].model.arithmeticBalance);assert.deepEqual(b.result.model.advancePeriod,period);
|
||||
if(name==='ordinary')assert.deepEqual(m.total,{numerator:'112000',denominator:'1'});else{assert.equal(m.total,null);assert.equal(m.rows.length,0);}
|
||||
if(name==='start')assert.equal(m.pecKnown,true);
|
||||
const html=annualHtml(d),report=createProjectDossierReport(d,{selectedSections:new Set(['finance']),generatedAt:'2026-11-13T22:07:00Z'});
|
||||
assert.match(html,/Projecção mensal conjunta PPC\/PEC/);assert.match(JSON.stringify(report),/Projecção mensal conjunta PPC\/PEC/);
|
||||
if(name!=='ordinary'){assert.match(html,/período L6/);assert.ok(!html.includes('Total da projecção: 112000'));}
|
||||
fs.writeFileSync(new URL(name+'-report.html',out),html);fs.writeFileSync(new URL(name+'-verification.json',out),JSON.stringify({synthetic:true,nativeApiRecovery:true,annualCurrent:true,historyPreserved:true,annualCalculationUnchanged:true,report:true,period,model:m},null,2));
|
||||
}
|
||||
}
|
||||
console.log(process.argv[2]==='generate'?'Generated four synthetic period consistency cases':'Verified four recovered period contexts and reports');
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
if (($argv[1] ?? '') !== 'test' || basename($root) !== 'portal-investidor') {
|
||||
throw new RuntimeException('Explicit isolated QA test operation required');
|
||||
}
|
||||
foreach (['APP_ENV' => 'testing', 'APP_KEY' => 'base64:'.base64_encode(str_repeat('Q', 32)),
|
||||
'APP_CONFIG_CACHE' => $root.'/outputs/irpc-period-consistency-20261113/no-config.php', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'investmoz_demography_test', 'DB_USERNAME' => 'demography_qa', 'DB_PASSWORD' => '', 'DB_URL' => '', 'DATABASE_URL' => '',
|
||||
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array', 'SUITECRM_ENABLED' => 'false'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$pdo = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=investmoz_demography_test', 'demography_qa', '');
|
||||
$identity = $pdo->query('select current_database(),inet_server_port()')->fetch(PDO::FETCH_NUM);
|
||||
if ($identity !== ['investmoz_demography_test', 55441] && $identity !== ['investmoz_demography_test', '55441']) {
|
||||
throw new RuntimeException('Isolated QA identity required');
|
||||
}
|
||||
$argv = ['phpunit', '-c', 'phpunit.investmoz.xml', '--do-not-cache-result', 'tests/Feature/IrpcAdvancePeriodDraftTest.php'];
|
||||
$_SERVER['argv'] = $argv;
|
||||
$_SERVER['argc'] = count($argv);
|
||||
require $root.'/vendor/autoload.php';
|
||||
require $root.'/vendor/phpunit/phpunit/phpunit';
|
||||
@@ -0,0 +1,32 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {noncivilCase} from '../tests/frontend/helpers/irpc-annual-noncivil-case.mjs';
|
||||
import {annualAdvanceCashflow,annualAdvancePeriod,annualBook,annualCurrent,annualHtml,recordAnnual,saveAnnualBook} from '../resources/js/lib/irpc-annual-settlement.ts';
|
||||
import {createProjectDossierReport} from '../resources/js/lib/project-dossier-report.ts';
|
||||
const out=new URL('../outputs/irpc-noncivil-20261114/',import.meta.url);
|
||||
fs.mkdirSync(out,{recursive:true});
|
||||
for(const name of ['three','single','missing','changed']){
|
||||
if(process.argv[2]==='generate'){
|
||||
const {d,b}=noncivilCase();
|
||||
if(name==='single')Object.assign(b.pecObligation.plan,{mode:'single',singleMonth:'2026-01'});
|
||||
if(name==='missing')b.advancePeriodDeclaration.previousReference='';
|
||||
if(name==='changed')b.ppcObligation.previousTax='200000';
|
||||
const prior=recordAnnual(d,{...b,ppcObligation:undefined,pecObligation:undefined,advancePeriodDeclaration:undefined},'2026-11-14T08:00:00Z');
|
||||
d.modelo_a_snapshot=saveAnnualBook(d,recordAnnual(d,{...prior,ppcObligation:b.ppcObligation,pecObligation:b.pecObligation,advancePeriodDeclaration:b.advancePeriodDeclaration},'2026-11-14T08:01:00Z'));
|
||||
fs.writeFileSync(new URL(name+'.json',out),JSON.stringify(d));
|
||||
}else{
|
||||
const d=JSON.parse(fs.readFileSync(new URL('recovered-'+name+'.json',out),'utf8')),b=annualBook(d),period=annualAdvancePeriod(d,b),m=annualAdvanceCashflow(b,period);
|
||||
assert.equal(annualCurrent(d,b),true);assert.equal(b.history.length,1);
|
||||
assert.deepEqual(b.result.model.arithmeticBalance,b.history[0].model.arithmeticBalance);
|
||||
assert.deepEqual(b.result.model.advancePeriod,period);
|
||||
if(['three','single'].includes(name))assert.deepEqual(m.total,{numerator:'112000',denominator:'1'});
|
||||
else assert.equal(m.total,null);
|
||||
if(name==='changed'){assert.equal(m.ppcKnown,false);assert.equal(m.pecKnown,true);}
|
||||
const html=annualHtml(d),report=createProjectDossierReport(d,{selectedSections:new Set(['finance']),generatedAt:'2026-11-14T08:02:00Z'});
|
||||
assert.match(html,/Projecção mensal conjunta PPC\/PEC/);assert.match(JSON.stringify(report),/Projecção mensal conjunta PPC\/PEC/);
|
||||
if(['three','single'].includes(name)){assert.match(html,/2025-11/);assert.match(html,/2026-03/);assert.match(JSON.stringify(report),/112000/);}
|
||||
fs.writeFileSync(new URL(name+'-report.html',out),html);
|
||||
fs.writeFileSync(new URL(name+'-verification.json',out),JSON.stringify({synthetic:true,nativeApiRecovery:true,historyPreserved:true,independentAnnualCalculationUnchanged:true,period,model:m},null,2));
|
||||
}
|
||||
}
|
||||
console.log(process.argv[2]==='generate'?'Generated four synthetic annual noncivil cases':'Verified four recovered annual noncivil cases and reports');
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
if (($argv[1] ?? '') !== 'test' || basename($root) !== 'portal-investidor') {
|
||||
throw new RuntimeException('Explicit isolated QA test operation required');
|
||||
}
|
||||
foreach (['APP_ENV' => 'testing', 'APP_KEY' => 'base64:'.base64_encode(str_repeat('Q', 32)),
|
||||
'APP_CONFIG_CACHE' => $root.'/outputs/irpc-noncivil-20261114/no-config.php', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'investmoz_demography_test', 'DB_USERNAME' => 'demography_qa', 'DB_PASSWORD' => '', 'DB_URL' => '', 'DATABASE_URL' => '',
|
||||
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array', 'SUITECRM_ENABLED' => 'false'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$pdo = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=investmoz_demography_test', 'demography_qa', '');
|
||||
$identity = $pdo->query('select current_database(),inet_server_port()')->fetch(PDO::FETCH_NUM);
|
||||
if ($identity !== ['investmoz_demography_test', 55441] && $identity !== ['investmoz_demography_test', '55441']) {
|
||||
throw new RuntimeException('Isolated QA identity required');
|
||||
}
|
||||
$argv = ['phpunit', '-c', 'phpunit.investmoz.xml', '--do-not-cache-result', 'tests/Feature/IrpcAnnualNoncivilDraftTest.php'];
|
||||
$_SERVER['argv'] = $argv;
|
||||
$_SERVER['argc'] = count($argv);
|
||||
require $root.'/vendor/autoload.php';
|
||||
require $root.'/vendor/phpunit/phpunit/phpunit';
|
||||
@@ -0,0 +1,26 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {combinedCase} from '../tests/frontend/helpers/irpc-investment-combination-case.mjs';
|
||||
import {plan} from '../tests/frontend/helpers/irpc-pec-obligation-case.mjs';
|
||||
import {calculatePecObligation} from '../resources/js/lib/irpc-pec-obligation.ts';
|
||||
import {recordAnnual,saveAnnualBook,annualBook,annualCurrent,annualHtml} from '../resources/js/lib/irpc-annual-settlement.ts';
|
||||
import {createProjectDossierReport} from '../resources/js/lib/project-dossier-report.ts';
|
||||
const out=new URL('../outputs/irpc-pec-last-amount-20261113/',import.meta.url);fs.mkdirSync(out,{recursive:true});
|
||||
for(const name of ['documented','missing','positive','excess']){
|
||||
if(process.argv[2]==='generate'){
|
||||
const {d,b}=combinedCase();const prior=recordAnnual(d,b,'2026-11-13T21:10:00Z');
|
||||
prior.pecObligation={...plan(),subjectNuit:b.subjectNuit,previousTurnover:['positive','excess'].includes(name)?'10000000':'0',previousPpcPaid:name==='excess'?'60000':'10000',lastAmount:{version:1,subjectNuit:b.subjectNuit,year:'2024',amount:'42500.25',reference:name==='missing'?'':'SYNTHETIC final PEC already determined;latest applicable annual MZN reference',confirmed:'yes'}};
|
||||
d.modelo_a_snapshot=saveAnnualBook(d,recordAnnual(d,prior,'2026-11-13T21:11:00Z'));
|
||||
fs.writeFileSync(new URL(name+'.json',out),JSON.stringify(d));
|
||||
}else{
|
||||
const d=JSON.parse(fs.readFileSync(new URL('recovered-'+name+'.json',out),'utf8')),b=annualBook(d),m=calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment);
|
||||
assert.equal(annualCurrent(d,b),true);assert.equal(b.history.length,1);assert.deepEqual(b.result.model.arithmeticBalance,{numerator:'138',denominator:'1'});
|
||||
const expected=name==='missing'?null:name==='excess'?{numerator:'0',denominator:'1'}:name==='positive'?{numerator:'40000',denominator:'1'}:{numerator:'170001',denominator:'4'};assert.deepEqual(m.total,expected);
|
||||
if(name==='excess') {assert.deepEqual(m.ppcExcess,{numerator:'10000',denominator:'1'});}
|
||||
assert.equal(m.lastAmountApplied,name==='documented');assert.equal(m.paymentExecuted,false);assert.equal(m.annualDeductionCreated,false);
|
||||
const html=annualHtml(d),report=createProjectDossierReport(d,{selectedSections:new Set(['finance']),generatedAt:'2026-11-13T21:12:00Z'});
|
||||
assert.match(html,/PEC — último montante documentado/);assert.match(JSON.stringify(report),/PEC — último montante documentado/);
|
||||
fs.writeFileSync(new URL(name+'-report.html',out),html);fs.writeFileSync(new URL(name+'-verification.json',out),JSON.stringify({synthetic:true,nativeApiRecovery:true,annualCurrent:true,historyPreserved:true,annualBalanceUnchanged:true,report:true,model:m},null,2));
|
||||
}
|
||||
}
|
||||
console.log(process.argv[2]==='generate'?'Generated four synthetic cases':'Verified four recovered cases and dossier reports');
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
if (($argv[1] ?? '') !== 'test' || basename($root) !== 'portal-investidor') {
|
||||
throw new RuntimeException('Explicit isolated QA test operation required');
|
||||
}
|
||||
foreach (['APP_ENV' => 'testing', 'APP_KEY' => 'base64:'.base64_encode(str_repeat('Q', 32)),
|
||||
'APP_CONFIG_CACHE' => $root.'/outputs/irpc-pec-last-amount-20261113/no-config.php', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'investmoz_demography_test', 'DB_USERNAME' => 'demography_qa', 'DB_PASSWORD' => '', 'DB_URL' => '', 'DATABASE_URL' => '',
|
||||
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array', 'SUITECRM_ENABLED' => 'false'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$pdo = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=investmoz_demography_test', 'demography_qa', '');
|
||||
$identity = $pdo->query('select current_database(),inet_server_port()')->fetch(PDO::FETCH_NUM);
|
||||
if ($identity !== ['investmoz_demography_test', 55441] && $identity !== ['investmoz_demography_test', '55441']) {
|
||||
throw new RuntimeException('Isolated QA identity required');
|
||||
}
|
||||
$argv = ['phpunit', '-c', 'phpunit.investmoz.xml', '--do-not-cache-result', 'tests/Feature/IrpcPecLastAmountDraftTest.php'];
|
||||
$_SERVER['argv'] = $argv;
|
||||
$_SERVER['argc'] = count($argv);
|
||||
require $root.'/vendor/autoload.php';
|
||||
require $root.'/vendor/phpunit/phpunit/phpunit';
|
||||
Reference in New Issue
Block a user