merge: integrate validated QA 1349952d for authorised public installation
tests / ci (push) Waiting to run
tests / ci (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
// Isolated worktrees share only vendor dependencies, never application sources.
|
||||
$qaRoot = dirname(__DIR__);
|
||||
putenv('APP_BASE_PATH='.$qaRoot);
|
||||
$_ENV['APP_BASE_PATH'] = $_SERVER['APP_BASE_PATH'] = $qaRoot;
|
||||
$loader = require $qaRoot.'/vendor/autoload.php';
|
||||
foreach ($loader->getPrefixesPsr4() as $prefix => $paths) {
|
||||
if (in_array($prefix, ['App\\', 'Tests\\', 'Database\\Factories\\', 'Database\\Seeders\\'], true)) {
|
||||
$directories = ['App\\' => 'app', 'Tests\\' => 'tests', 'Database\\Factories\\' => 'database/factories', 'Database\\Seeders\\' => 'database/seeders'];
|
||||
$loader->setPsr4($prefix, $qaRoot.'/'.$directories[$prefix]);
|
||||
}
|
||||
}
|
||||
$overrides = [];
|
||||
foreach ($loader->getClassMap() as $class => $path) {
|
||||
foreach (['App\\' => 'app', 'Tests\\' => 'tests', 'Database\\Factories\\' => 'database/factories', 'Database\\Seeders\\' => 'database/seeders'] as $prefix => $directory) {
|
||||
if (str_starts_with($class, $prefix)) {
|
||||
$candidate = $qaRoot.'/'.$directory.'/'.str_replace('\\', '/', substr($class, strlen($prefix))).'.php';
|
||||
if (is_file($candidate)) {
|
||||
$overrides[$class] = $candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$loader->addClassMap($overrides);
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Foundation\Vite;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$qaRoot = dirname(__DIR__);
|
||||
$public = $qaRoot.'/public';
|
||||
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||
if ($path !== '/' && is_file($public.$path)) {
|
||||
return false;
|
||||
}
|
||||
$app = require $qaRoot.'/bootstrap/app.php';
|
||||
$app->booted(function () {
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
if (! IsolatedQaDatabase::allowsSchemaChanges() || $identity->name !== 'continuity_20261120_test' || (int) $identity->port !== 55441) {
|
||||
abort(503);
|
||||
}
|
||||
app(Vite::class)->useBuildDirectory('build-qa-opportunities');
|
||||
});
|
||||
$app->handleRequest(Request::capture());
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestorContext;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\VirtualDesk;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
try {
|
||||
// Long-lived synthetic QA. Never run RefreshDatabase suites against this database.
|
||||
$qaDatabase = 'controlled_5f7db7cd_20261120_test';
|
||||
$qaConfigCache = dirname(__DIR__).'/outputs/controlled-5f7db7cd-20261120/no-config.php';
|
||||
putenv('APP_CONFIG_CACHE='.$qaConfigCache);
|
||||
$_ENV['APP_CONFIG_CACHE'] = $_SERVER['APP_CONFIG_CACHE'] = $qaConfigCache;
|
||||
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441', 'DB_DATABASE' => $qaDatabase, 'DB_USERNAME' => 'investmoz_test', 'DB_PASSWORD' => '', 'DB_URL' => '', 'DATABASE_URL' => '', 'CACHE_STORE' => 'array', 'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'BROADCAST_CONNECTION' => 'null', 'SUITECRM_ENABLED' => 'false', 'INVESTMOZ_AI_ENABLED' => 'false', 'INVESTOR_PATH_ENABLED' => 'true'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
if (! IsolatedQaDatabase::allowsSchemaChanges() || $identity->name !== $qaDatabase || (int) $identity->port !== 55441) {
|
||||
throw new RuntimeException('Controlled synthetic QA identity rejected');
|
||||
}
|
||||
if (in_array('--migrate', $argv, true)) {
|
||||
$tables = DB::select("select tablename from pg_tables where schemaname='public' and tablename <> 'spatial_ref_sys'");
|
||||
if ($tables !== []) {
|
||||
throw new RuntimeException('Schema preparation requires a fresh empty QA database; existing state preserved');
|
||||
}
|
||||
Artisan::call('migrate', ['--force' => true]);
|
||||
echo Artisan::output();
|
||||
}
|
||||
if (in_array('--prepare-contexts', $argv, true)) {
|
||||
$fixture = json_decode(file_get_contents(dirname(__DIR__).'/outputs/controlled-5f7db7cd-20261120/synthetic-fixture.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$owner = User::findOrFail($fixture['owner_id']);
|
||||
foreach ($fixture['cases'] as $key => $item) {
|
||||
$case = app(VirtualDesk::class)->case($owner, $item['id']);
|
||||
if ((int) $case->version !== 1) {
|
||||
throw new RuntimeException('Context already edited; preserve deliberate changes');
|
||||
}
|
||||
app(InvestorPath::class)->initialize($owner, $case->id);
|
||||
$case = app(VirtualDesk::class)->case($owner, $case->id);
|
||||
$input = ['version' => $case->version, 'selection' => ['sector' => 'sector:'.$item['sector_id'], 'territory' => 'territory:'.$fixture['geography']['locality']], 'opportunity_choices' => [], 'declarations' => ['project_title' => $key === 'hotel' ? 'Criar Hotel — SINTÉTICO QA' : 'Agronegócio — SINTÉTICO QA', 'products_services' => $key === 'hotel' ? 'Hotel — ensaio sintético' : 'Produção agrícola — ensaio sintético', 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
|
||||
$preview = app(InvestorContext::class)->preview($owner, $case->id, $input);
|
||||
app(InvestorContext::class)->commit($owner, $case->id, [...$input, 'preview_hash' => $preview['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true]);
|
||||
}
|
||||
echo "Two synthetic contexts prepared through the normal preview/commit services.\n";
|
||||
}
|
||||
if (in_array('--seed', $argv, true)) {
|
||||
$existing = DB::table('users')->where('email', 'controlled-investor-20261120@example.invalid')->first();
|
||||
if ($existing) {
|
||||
throw new RuntimeException('Synthetic actor already exists; preserve it and its history');
|
||||
}
|
||||
$fixture = DB::transaction(function () {
|
||||
$owner = User::factory()->create(['name' => 'Investidor sintético QA controlado', 'email' => 'controlled-investor-20261120@example.invalid']);
|
||||
$parent = null;
|
||||
$geography = [];
|
||||
foreach (['country', 'province', 'district', 'admin_post', 'locality'] as $type) {
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SINTÉTICO QA '.$type, 'code' => $id, 'location_type' => $type, 'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
|
||||
$geography[$type] = $id;
|
||||
$parent = $id;
|
||||
}
|
||||
$cases = [];
|
||||
foreach (['hotel' => 'Turismo sintético QA', 'agro' => 'Agronegócio sintético QA'] as $key => $name) {
|
||||
$sector = Sector::create(['name' => $name, 'slug' => 'controlled-qa-'.$key, 'is_active' => true, 'published_at' => now()]);
|
||||
$case = app(VirtualDesk::class)->createCase($owner, ['title' => $name, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true]);
|
||||
$cases[$key] = ['id' => $case->id, 'sector_id' => $sector->id];
|
||||
}
|
||||
|
||||
return ['synthetic' => true, 'restoration_of_previous_qa' => false, 'owner_id' => $owner->id, 'cases' => $cases, 'geography' => $geography];
|
||||
});
|
||||
$directory = dirname(__DIR__).'/outputs/controlled-5f7db7cd-20261120';
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
file_put_contents($directory.'/synthetic-fixture.json', json_encode($fixture, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
|
||||
echo "New synthetic QA fixture recorded; no prior history restored.\n";
|
||||
}
|
||||
echo json_encode(['database' => $identity->name, 'port' => $identity->port, 'users' => DB::table('users')->count(), 'cases' => DB::table('desk_cases')->count(), 'baseline' => '5f7db7cd', 'restoration' => false], JSON_THROW_ON_ERROR)."\n";
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, 'QA action rejected: '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
// Read-only comparison of QA observations with exact INE slices.
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
throw_unless($identity->name === 'continuity_20261120_test' && (int) $identity->port === 55441, RuntimeException::class, 'Isolated QA only');
|
||||
$slices = json_decode(file_get_contents(dirname(__DIR__).'/outputs/demography-d01-d06-20261120/source-slices.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$checked = 0;
|
||||
foreach ($slices as $slice) {
|
||||
$batch = DB::table('demographic_imports')->where('sha256', $slice['sha256'])->first();
|
||||
throw_unless($batch && $batch->file_name === $slice['file'], RuntimeException::class, 'Original provenance missing');
|
||||
foreach ($slice['records'] as $row) {
|
||||
$stored = DB::table('demographic_observations as o')->join('geo_locations as g', 'g.id', '=', 'o.geo_location_id')
|
||||
->where('o.import_id', $batch->id)->where('o.sheet', $row['sheet'])->where('o.cell', $row['cell'])->first(['o.*', 'g.name']);
|
||||
throw_unless($stored && $stored->name === $row['territory'] && $stored->numeric_value === $row['numeric_value'] && $stored->original_value === $row['original_value'], RuntimeException::class, 'Observation mismatch');
|
||||
$checked++;
|
||||
}
|
||||
}
|
||||
echo json_encode(['database' => $identity->name, 'port' => $identity->port, 'exact_observations_checked' => $checked, 'mismatches' => 0, 'writes' => false, 'traceability_preserved' => true], JSON_PRETTY_PRINT).PHP_EOL;
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
// QA fixture: exact read-only INE slices, synthetic territorial identities and no opportunities.
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
throw_unless($identity->name === 'continuity_20261120_test' && (int) $identity->port === 55441, RuntimeException::class, 'Isolated QA only');
|
||||
$slices = json_decode(file_get_contents(dirname(__DIR__).'/outputs/demography-d01-d06-20261120/source-slices.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$result = DB::transaction(function () use ($slices) {
|
||||
$actor = DB::table('users')->first();
|
||||
throw_unless($actor, RuntimeException::class, 'Existing synthetic investor required');
|
||||
foreach (['comercio-e-servicos' => 'Comércio e serviços', 'turismo' => 'Turismo'] as $slug => $name) {
|
||||
DB::table('sectors')->insertOrIgnore(['slug' => $slug, 'name' => $name, 'is_active' => true, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
$country = DB::table('geo_locations')->where('location_type', 'country')->value('id');
|
||||
$result = [];
|
||||
foreach ($slices as $slice) {
|
||||
$provinceName = $slice['records'][0]['province'];
|
||||
$territoryName = $slice['records'][0]['territory'];
|
||||
foreach ([['province', $provinceName], ['district', $territoryName]] as [$level, $name]) {
|
||||
$id = (string) Str::uuid();
|
||||
$external = '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:D01-D06:'.$name;
|
||||
DB::table('geo_locations')->insertOrIgnore(['id' => $id, 'parent_id' => $level === 'province' ? $country : $province, 'name' => $name, 'code' => 'QA-D01-'.$name, 'location_type' => $level, 'source_system' => 'cartografia-workbook', 'external_id' => $external, 'data_classification' => 'public']);
|
||||
$id = DB::table('geo_locations')->where('external_id', $external)->value('id');
|
||||
if ($level === 'province') {
|
||||
$province = $id;
|
||||
}
|
||||
}
|
||||
$batch = DB::table('demographic_imports')->where('sha256', $slice['sha256'])->value('id');
|
||||
if (! $batch) {
|
||||
$batch = (string) Str::uuid();
|
||||
DB::table('demographic_imports')->insert(['id' => $batch, 'sha256' => $slice['sha256'], 'file_name' => $slice['file'], 'source' => 'Instituto Nacional de Estatística (INE)', 'publication_version' => 'Exemplar INE fornecido pela Tempo; edição não indicada; SHA256 identifica a versão', 'status' => 'approved', 'report' => json_encode(['issue_counts' => [], 'qa_slice' => true]), 'preview_sha256' => hash('sha256', json_encode($slice)), 'prepared_by' => $actor->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
foreach ($slice['records'] as $row) {
|
||||
unset($row['province'], $row['territory'], $row['level']);
|
||||
DB::table('demographic_observations')->insert(['import_id' => $batch, 'geo_location_id' => $id, 'validation_status' => 'valid', ...$row]);
|
||||
}
|
||||
}
|
||||
$result[$territoryName] = ['id' => $id, 'province' => $province, 'batch' => $batch, 'records' => count($slice['records'])];
|
||||
}
|
||||
|
||||
return $result;
|
||||
});
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Read-only D01-D06 QA slices and cell verification; never modifies INE workbooks."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from demography_workbook import parse
|
||||
|
||||
cli = argparse.ArgumentParser()
|
||||
cli.add_argument('directory', type=Path)
|
||||
cli.add_argument('--output', type=Path, required=True)
|
||||
args = cli.parse_args()
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
slices, references = [], []
|
||||
for name, territory, cell in [('Gaza.xlsx', 'Bilene', None),
|
||||
('Inhambane.xlsx', 'Funhalouro', 'B54'),
|
||||
('Maputo Provincia.xlsx', 'Moamba', 'B179')]:
|
||||
original = args.directory / name
|
||||
before = hashlib.sha256(original.read_bytes()).hexdigest()
|
||||
parsed = parse(original)
|
||||
rows = [r for r in parsed['records'] if r['territory'] == territory
|
||||
and 2026 <= r['year'] <= 2028 and r['sex'] == 'all']
|
||||
unchanged = before == hashlib.sha256(original.read_bytes()).hexdigest()
|
||||
if not unchanged:
|
||||
raise RuntimeError('Source changed during verification')
|
||||
slices.append({'file': name, 'sha256': before, 'source_unchanged': unchanged, 'records': rows})
|
||||
if cell:
|
||||
matched = [r for r in rows if r['sheet'] == '2026' and r['cell'] == cell]
|
||||
if len(matched) != 1:
|
||||
raise RuntimeError('Reference not uniquely verified')
|
||||
references.append({'file': name, 'sha256': before, 'source_unchanged': unchanged,
|
||||
'state': 'verified_from_original_labels', 'observation': matched[0]})
|
||||
initial = args.directory.parent / 'Inhambane.xlsx'
|
||||
if initial.is_file():
|
||||
before = hashlib.sha256(initial.read_bytes()).hexdigest()
|
||||
matched = [r for r in parse(initial)['records'] if r['sheet'] == '2026' and r['cell'] == 'B54']
|
||||
if len(matched) != 1 or before != hashlib.sha256(initial.read_bytes()).hexdigest():
|
||||
raise RuntimeError('Initial Inhambane exemplar not verified')
|
||||
references.append({'file': '../Inhambane.xlsx (exemplar inicial distinto)', 'sha256': before,
|
||||
'source_unchanged': True, 'state': 'verified_from_original_labels', 'observation': matched[0]})
|
||||
(args.output / 'source-slices.json').write_text(json.dumps(slices, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
(args.output / 'source-references.json').write_text(json.dumps(references, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps({'files': len(slices), 'verified_cells': len(references), 'originals_unchanged': True}))
|
||||
@@ -0,0 +1,163 @@
|
||||
import fs from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** Printed Portuguese monetary values, not JavaScript floating-point inputs. */
|
||||
export function printedCents(value) {
|
||||
const text = value.trim();
|
||||
if (!/^(?:-?\d+(?:\.\d{3})*(?:,\d{1,2})?|\(\d+(?:\.\d{3})*(?:,\d{1,2})?\))$/.test(text))
|
||||
throw new Error(`Montante impresso não reconhecido: ${text}`);
|
||||
const negative = text.startsWith('(') || text.startsWith('-');
|
||||
const [whole, fraction = ''] = text.replace(/[().-]/g, '').split(',');
|
||||
const amount = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
|
||||
return negative ? -amount : amount;
|
||||
}
|
||||
const decimal = value => `${value < 0n ? '-' : ''}${(value < 0n ? -value : value) / 100n}.${String((value < 0n ? -value : value) % 100n).padStart(2, '0')}`;
|
||||
const sum = values => values.reduce((total, value) => total + value, 0n);
|
||||
|
||||
export function financialTable(text, title, occurrence, width) {
|
||||
const lines = text.normalize('NFC').split(/\r?\n/);
|
||||
const starts = lines.flatMap((line, index) => line.trim() === title ? [index] : []);
|
||||
const start = occurrence === 'last' ? starts.at(-1) : starts[occurrence];
|
||||
if (start === undefined) throw new Error(`Tabela em falta: ${title}`);
|
||||
let end = lines.findIndex((line, index) => index > start && (line.trim().startsWith('Tabela:') || /^\d+\.\d+\s/.test(line.trim())));
|
||||
if (end < 0) end = lines.length;
|
||||
const rows = [];
|
||||
for (let index = start + 1; index < end; index++) {
|
||||
const cells = lines[index].split('\t').map(cell => cell.trim());
|
||||
const numbers = cells.slice(1).filter(cell => /^\(?-?\d[\d.,]*\)?$/.test(cell));
|
||||
if (numbers.length >= width) rows.push({ label: cells[0], line: index + 1, values: numbers.slice(-width).map(printedCents), printed: numbers.slice(-width), rates: cells.slice(1).filter(cell => cell.endsWith('%')) });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
function row(table, label, occurrence = 0) {
|
||||
const record = table.filter(entry => entry.label === label)[occurrence];
|
||||
if (!record) throw new Error(`Rubrica em falta: ${label}`);
|
||||
return record;
|
||||
}
|
||||
function check(id, reported, calculated, references) {
|
||||
return { id, reported: decimal(reported), calculated: decimal(calculated), difference: decimal(calculated - reported), matches: calculated === reported, references };
|
||||
}
|
||||
|
||||
export function financialReferenceTables(text) {
|
||||
return [
|
||||
{ key: 'annualSales', title: 'Tabela: Previsão de Vendas', occurrence: 0, width: 3 },
|
||||
{ key: 'monthlySales', title: 'Tabela: Previsão de Vendas', occurrence: 'last', width: 12 },
|
||||
{ key: 'annualProfit', title: 'Tabela: Lucros e Perdas', occurrence: 0, width: 3 },
|
||||
{ key: 'monthlyProfit', title: 'Tabela: Lucros e Perdas', occurrence: 'last', width: 12 },
|
||||
{ key: 'annualCash', title: 'Tabela: Fluxo de Caixa', occurrence: 0, width: 3 },
|
||||
{ key: 'monthlyCash', title: 'Tabela: Fluxo de Caixa', occurrence: 'last', width: 12 },
|
||||
{ key: 'annualBalance', title: 'Tabela: Balanço', occurrence: 0, width: 3 },
|
||||
{ key: 'monthlyBalance', title: 'Tabela: Balanço', occurrence: 'last', width: 13 },
|
||||
].map(specification => ({ ...specification, rows: financialTable(text, specification.title, specification.occurrence, specification.width) }));
|
||||
}
|
||||
|
||||
export function reconcileFinancialReference(text) {
|
||||
const { annualSales, monthlySales, annualProfit, monthlyProfit, annualCash, monthlyCash, annualBalance, monthlyBalance } = Object.fromEntries(financialReferenceTables(text).map(table => [table.key, table.rows]));
|
||||
const checks = [];
|
||||
const compare = (id, annualTable, annualLabel, monthlyTable, monthlyLabel, occurrence = 0) => {
|
||||
const annual = row(annualTable, annualLabel), monthly = row(monthlyTable, monthlyLabel, occurrence);
|
||||
checks.push(check(id, annual.values[0], sum(monthly.values), [annual.line, monthly.line]));
|
||||
};
|
||||
compare('sales.months_to_2025', annualProfit, 'Vendas', monthlyProfit, 'Vendas');
|
||||
compare('direct_costs.months_to_2025', annualProfit, 'Custo Direto das Vendas', monthlyProfit, 'Custo Direto das Vendas');
|
||||
compare('gross_margin.months_to_2025', annualProfit, 'Margem bruta', monthlyProfit, 'Margem bruta');
|
||||
compare('payroll.months_to_2025', annualProfit, 'Folha de pagamento', monthlyProfit, 'Folha de pagamento');
|
||||
compare('payroll_charges.printed_months_to_2025', annualProfit, 'Impostos sobre Folhas de Pagamento', monthlyProfit, 'Impostos sobre Folhas de Pagamento');
|
||||
compare('operating_expenses.printed_months_to_2025', annualProfit, 'Despesas Operacionais Totais', monthlyProfit, 'Despesas Operacionais Totais');
|
||||
compare('net_profit.printed_months_to_2025', annualProfit, 'Lucro Líquido', monthlyProfit, 'Lucro Líquido');
|
||||
for (const [annualLabel, monthlyLabel] of [
|
||||
['Vendas em Dinheiro', 'Vendas em Dinheiro'],
|
||||
['Caixa proveniente de contas a receber', 'Caixa proveniente de contas a receber'],
|
||||
['Subtotal de Caixa Proveniente das Operações', 'Subtotal de Caixa Proveniente das Operações'],
|
||||
['Imposto sobre vendas, IVA, HST/GST recebidos', 'Imposto sobre vendas, IVA, HST/GST recebidos'],
|
||||
['Pagamentos de Contas', 'Pagamentos de Contas'],
|
||||
['Subtotal gasto em operações', 'Subtotal gasto em operações'],
|
||||
['Imposto sobre vendas, IVA, HST/GST pagos', 'Imposto sobre vendas, IVA, HST/GST pagos'],
|
||||
['Subtotal de Dinheiro Gasto', 'Subtotal de Dinheiro Gasto'],
|
||||
['Fluxo de Caixa Líquido', 'Fluxo de Caixa Líquido'],
|
||||
]) compare(`cash.${annualLabel}`, annualCash, annualLabel, monthlyCash, monthlyLabel);
|
||||
const labels = ['Publicidade', 'Intermediação Comercial', 'Comercialização de Commodities', 'Formação'];
|
||||
const totals = row(annualSales, 'Vendas Totais');
|
||||
const directTotals = row(annualSales, 'Subtotal Direct Cost of Sales');
|
||||
for (let year = 0; year < 3; year++) {
|
||||
checks.push(check(`sales.listed_lines.${2025 + year}`, totals.values[year], sum(labels.map(label => row(annualSales, label).values[year])), [totals.line, ...labels.map(label => row(annualSales, label).line)]));
|
||||
const costRows = labels.map(label => row(annualSales, label, 1)).concat(row(annualSales, 'Marketing'));
|
||||
checks.push(check(`costs.listed_lines.${2025 + year}`, directTotals.values[year], sum(costRows.map(entry => entry.values[year])), [directTotals.line, ...costRows.map(entry => entry.line)]));
|
||||
}
|
||||
for (const label of labels) {
|
||||
compare(`sales.line.${label}`, annualSales, label, monthlySales, label);
|
||||
const annual = row(annualSales, label, 1), monthly = row(monthlySales, label, 1);
|
||||
checks.push(check(`costs.line.${label}`, annual.values[0], sum(monthly.values), [annual.line, monthly.line]));
|
||||
}
|
||||
const cashReceived = row(annualCash, 'Subtotal de Dinheiro Recebido');
|
||||
const cashSpent = row(annualCash, 'Subtotal de Dinheiro Gasto');
|
||||
const operatingPaid = row(annualCash, 'Subtotal gasto em operações');
|
||||
const vatPaid = row(annualCash, 'Imposto sobre vendas, IVA, HST/GST pagos');
|
||||
const initialCash = row(monthlyBalance, 'Dinheiro').values[0];
|
||||
const nonCashAssets = row(annualBalance, 'Contas a receber').values[0] + row(annualBalance, 'Outros ativos correntes').values[0] + row(annualBalance, 'Total de Activos a Longo Prazo').values[0];
|
||||
const capital = row(annualBalance, 'Total Capital').values[0];
|
||||
const liabilities = row(annualBalance, 'Total de Passivos').values[0];
|
||||
const assets = row(annualBalance, 'Total de Activos').values[0];
|
||||
const componentCashSpent = operatingPaid.values[0] + vatPaid.values[0];
|
||||
checks.push(check('cash.2025_spending_components', cashSpent.values[0], componentCashSpent, [cashSpent.line, operatingPaid.line, vatPaid.line]));
|
||||
checks.push(check('balance.2025_assets_vs_liabilities_capital', liabilities + capital, assets, [row(annualBalance, 'Total de Activos').line, row(annualBalance, 'Total de Passivos').line, row(annualBalance, 'Total Capital').line]));
|
||||
const balanceMonths = [];
|
||||
const cashRow = row(monthlyBalance, 'Dinheiro'), arRow = row(monthlyBalance, 'Contas a receber'), otherRow = row(monthlyBalance, 'Outros Activos correntes'), fixedRow = row(monthlyBalance, 'Total de Activos a Longo Prazo'), liabilityRow = row(monthlyBalance, 'Total de Passivos'), capitalRow = row(monthlyBalance, 'Total Capital'), assetRow = row(monthlyBalance, 'Total de Activos');
|
||||
for (let month = 1; month <= 12; month++) {
|
||||
const computedAssets = cashRow.values[month] + arRow.values[month] + otherRow.values[month] + fixedRow.values[month];
|
||||
const computedFunds = liabilityRow.values[month] + capitalRow.values[month];
|
||||
balanceMonths.push({ month, printedAssets: decimal(assetRow.values[month]), componentAssets: decimal(computedAssets), componentLiabilitiesCapital: decimal(computedFunds), componentDifference: decimal(computedAssets - computedFunds) });
|
||||
}
|
||||
const payroll = row(monthlyProfit, 'Folha de pagamento'), charges = row(monthlyProfit, 'Impostos sobre Folhas de Pagamento');
|
||||
if (charges.rates.length !== 1) throw new Error('Taxa de referência da folha não identificada univocamente');
|
||||
const basisPoints = printedCents(charges.rates[0].slice(0, -1));
|
||||
const exactCharges = payroll.values.map(value => {
|
||||
const product = value * basisPoints;
|
||||
if (product % 10000n !== 0n) throw new Error('Precisão adicional necessária para os encargos da folha');
|
||||
return product / 10000n;
|
||||
});
|
||||
const otherExpenses = ['Marketing/Promoção', 'Depreciação', 'Aluguer', 'Serviços públicos', 'Seguros', 'Outros'].map(label => row(monthlyProfit, label));
|
||||
const interest = row(monthlyProfit, 'Despesa com juros'), taxes = row(monthlyProfit, 'Impostos Incorridos');
|
||||
const exactOperating = payroll.values.map((value, index) => value + exactCharges[index] + sum(otherExpenses.map(entry => entry.values[index])));
|
||||
const gross = row(monthlyProfit, 'Margem bruta').values;
|
||||
const exactNetProfit = gross.map((value, index) => value - exactOperating[index] - interest.values[index] - taxes.values[index]);
|
||||
const payrollRecomposition = {
|
||||
scope: 'reference_arithmetic_only_not_a_fiscal_rule', rate: charges.rates[0],
|
||||
monthlyCharges: exactCharges.map(decimal), monthlyOperating: exactOperating.map(decimal), monthlyNetProfit: exactNetProfit.map(decimal),
|
||||
chargesAnnualCheck: check('payroll_charges.cent_recomposition', row(annualProfit, 'Impostos sobre Folhas de Pagamento').values[0], sum(exactCharges), [charges.line, payroll.line]),
|
||||
operatingAnnualCheck: check('operating_expenses.cent_recomposition', row(annualProfit, 'Despesas Operacionais Totais').values[0], sum(exactOperating), [charges.line, payroll.line]),
|
||||
profitAnnualCheck: check('net_profit.cent_recomposition', row(annualProfit, 'Lucro Líquido').values[0], sum(exactNetProfit), [charges.line, payroll.line, row(monthlyProfit, 'Margem bruta').line]),
|
||||
};
|
||||
return {
|
||||
status: 'BLOCKED_SOURCE_PRECISION_OR_COMPLETENESS', annualTotalsChanged: false, applicationFormulasChanged: false,
|
||||
checks, balanceMonths, payrollRecomposition,
|
||||
oneUnitTrace: {
|
||||
approvedCashSpent: decimal(cashSpent.values[0]), componentCashSpent: decimal(componentCashSpent),
|
||||
approvedClosingCash: decimal(initialCash + cashReceived.values[0] - cashSpent.values[0]),
|
||||
componentOnlyClosingCash: decimal(initialCash + cashReceived.values[0] - componentCashSpent),
|
||||
approvedAssets: decimal(assets), componentOnlyAssets: decimal(initialCash + cashReceived.values[0] - componentCashSpent + nonCashAssets),
|
||||
liabilitiesAndCapital: decimal(liabilities + capital), componentOnlyIsDiagnosticNotCorrection: true,
|
||||
},
|
||||
ambiguousCashLabel: monthlyCash.filter(entry => entry.label === 'Novo Investimento Recebido').map(entry => ({ line: entry.line, sum: decimal(sum(entry.values)), printed: entry.printed })),
|
||||
missing: ['Valores monetários de origem sem arredondamento por mês e por rubrica', 'Regras do programa de origem: arredondamento de apresentação versus cálculo e momento do arredondamento', 'Linhas de vendas e custos omitidas ou uma versão completa que explique os subtotais', 'Identificação correcta da segunda linha Novo Investimento Recebido no fluxo mensal'],
|
||||
};
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
if (!process.argv[2]) throw new Error('Indique o caminho do texto financeiro fornecido.');
|
||||
const source = fs.readFileSync(process.argv[2]);
|
||||
const report = { sourceSha256: createHash('sha256').update(source).digest('hex'), ...reconcileFinancialReference(source.toString('utf8')) };
|
||||
const output = JSON.stringify(report, null, 2) + '\n';
|
||||
if (process.argv[3]) {
|
||||
if (resolve(process.argv[3]) === resolve(process.argv[2])) throw new Error('O diagnóstico não pode sobrescrever a fonte.');
|
||||
fs.writeFileSync(process.argv[3], output);
|
||||
} else process.stdout.write(output);
|
||||
process.exitCode = 2;
|
||||
} catch (error) {
|
||||
process.stderr.write(`${error.message}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
// Read-only QA audit: compare source values, allowing JSONB object key ordering.
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$app = require 'bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
if (DB::connection()->getDatabaseName() !== 'continuity_20261120_test') {
|
||||
throw new Exception('QA only');
|
||||
}
|
||||
$f = json_decode(file_get_contents('outputs/funding-b03-b06-20261120/fixture.json'), true);
|
||||
$refs = json_decode(file_get_contents('database/data/funding-institutions-nov2026.json'), true)['references'];
|
||||
foreach ($f['records'] as $key => $r) {
|
||||
$row = DB::table('funding_programmes')->where('id', $r['id'])->first();
|
||||
if (json_decode($row->draft, true) != $refs[$key]['draft']) {
|
||||
throw new Exception('Original draft mismatch');
|
||||
}
|
||||
}
|
||||
echo json_encode(['source_unchanged' => hash_file('sha256', 'database/data/funding-institutions-nov2026.json') === $f['source_sha256'], 'original_drafts_unchanged' => count($f['records']), 'invented_institutions' => 0, 'originals_modified' => false, 'operational_writes' => false], JSON_PRETTY_PRINT);
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
// Only QA fixtures from supplied real institutions; no operational publication.
|
||||
require __DIR__.'/continuity-qa-bootstrap.php';
|
||||
$app = require 'bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
use App\Services\FundingInstitutionDetails;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
$i = DB::selectOne('select current_database() as name,inet_server_port() as port');
|
||||
if ($i->name !== 'continuity_20261120_test' || $i->port != 55441) {
|
||||
throw new Exception('QA only');
|
||||
}
|
||||
$outputDirectory = base_path('outputs/funding-b03-b06-20261120');
|
||||
if (! is_dir($outputDirectory)) {
|
||||
mkdir($outputDirectory, 0700, true);
|
||||
}
|
||||
$package = json_decode(file_get_contents('database/data/funding-institutions-nov2026.json'), true);
|
||||
$snapshotPath = $argv[1] ?? throw new RuntimeException('Supply the existing read-only public geography snapshot');
|
||||
$snapshot = json_decode(file_get_contents($snapshotPath), true);
|
||||
if (! $snapshot['read_only']) {
|
||||
throw new Exception('Original snapshot required');
|
||||
}
|
||||
$result = DB::transaction(function () use ($snapshot, $package) {
|
||||
foreach ($snapshot['records'] as $g) {
|
||||
DB::table('geo_locations')->insertOrIgnore($g);
|
||||
}
|
||||
$provinceIds = collect($snapshot['records'])->where('location_type', 'province')->keyBy('name');
|
||||
$actor = DB::table('users')->first()->id;
|
||||
$out = [];
|
||||
foreach (['moza', 'bci', 'standard-bank', 'ac-microbanco'] as $key) {
|
||||
$ref = $package['references'][$key];
|
||||
$p = $ref['draft'];
|
||||
foreach ($ref['location_territory_names'] ?? [] as $index => $name) {
|
||||
$matches = $provinceIds->filter(fn ($g) => Str::lower(Str::ascii($g['name'])) === Str::lower(Str::ascii($name)));
|
||||
if ($matches->count() === 1) {
|
||||
$p['locations'][$index]['territory_id'] = $matches->first()['id'];
|
||||
}
|
||||
}
|
||||
$p = [...$p, ...app(FundingInstitutionDetails::class)->normalize($p, true)];
|
||||
$code = 'qa-b03-b06-'.$key;
|
||||
$id = DB::table('funding_programmes')->where('code', $code)->value('id');
|
||||
if (! $id) {
|
||||
$id = (string) Str::uuid();
|
||||
$v = (string) Str::uuid();
|
||||
DB::table('funding_programmes')->insert(['id' => $id, 'code' => $code, 'version' => 1, 'draft' => json_encode($ref['draft']), 'created_by' => $actor, 'created_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('funding_programme_versions')->insert(['id' => $v, 'programme_id' => $id, 'version' => 1, 'payload' => json_encode($p), 'reason' => 'QA-only fixture from unchanged supplied source, no editorial or operational publication', 'actor_id' => $actor, 'published_at' => now()]);
|
||||
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $v]);
|
||||
}
|
||||
$out[$key] = ['id' => $id, 'title' => $p['title'], 'products' => array_column($p['products'], 'availability')];
|
||||
}
|
||||
|
||||
return ['source_sha256' => hash_file('sha256', 'database/data/funding-institutions-nov2026.json'), 'records' => $out, 'provinces' => $provinceIds->map(fn ($g) => $g['id'])->all()];
|
||||
});
|
||||
$bytes = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
file_put_contents(base_path('outputs/funding-b03-b06-20261120/fixture.json'), $bytes);
|
||||
echo $bytes;
|
||||
Reference in New Issue
Block a user