commit melhorias compras3
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
@@ -0,0 +1,64 @@
<?php
use App\Http\Controllers\AgreementFollowupController;
use App\Services\AgreementFollowup;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Worker de relatório fora de QA.');
}
require __DIR__.'/../Support/ReceiptFixture.php';
require __DIR__.'/../Support/SupplyFixture.php';
$f = receiptFixture();
supplyGrant($f['issuer'], ['supply_prepare']);
supplyGrant($f['receiver'], ['supply_read', 'supply_review']);
auth()->guard()->setUser($f['issuer']);
$planning = app(SupplyPlanning::class);
$draft = $planning->save($f['issuer'], 'agreement', supplyInput(['stock_item_id' => $f['stock']->id, 'warehouse_id' => $f['warehouse']->id,
'supplier_id' => $f['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addDay()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => '=PG-FOLLOWUP-PROOF']));
auth()->guard()->setUser($f['receiver']);
$planning->save($f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
config(['agreement_order_limits.qa_enabled' => true]);
auth()->guard()->setUser($f['issuer']);
$header = $planning->save($f['issuer'], 'contract', supplyInput(['supplier_id' => $f['order']->supplier_id, 'reference' => '=PG-CONTRACT-PROOF',
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addDay()->toDateString(), 'order_limit_amount' => '0']));
auth()->guard()->setUser($f['receiver']);
$planning->save($f['receiver'], 'contract', supplyInput([], 'approve', $header));
$before = DB::table('audit_logs')->count();
$checked = false;
DB::listen(function (QueryExecuted $event) use (&$checked): void {
if (! $checked && str_contains($event->sql, 'supply_records')) {
$checked = true;
$state = $event->connection->selectOne("select current_setting('transaction_isolation') as isolation,current_setting('transaction_read_only') as readonly");
if ($state->isolation !== 'repeatable read' || $state->readonly !== 'on') {
throw new RuntimeException('CSV sem leitura consistente/somente leitura.');
}
}
});
$request = Request::create('/compras/acordos/vigencia.csv', 'GET');
$request->setUserResolver(fn () => $f['receiver']);
$response = app(AgreementFollowupController::class)->csv($request, app(AgreementFollowup::class));
if (! $checked || ! str_contains($response->getContent(), "'=PG-FOLLOWUP-PROOF") || ! str_contains($response->getContent(), 'Vigente')
|| $before !== DB::table('audit_logs')->count() || DB::transactionLevel() !== 0) {
throw new RuntimeException('CSV ou ausência de efeitos não demonstrados.');
}
echo json_encode(['agreement_csv_read_only_snapshot' => true, 'formula_cell_protected' => true, 'no_audit_writes' => true, 'transaction_closed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
$checked = false;
$request = Request::create('/compras/acordos/vigencia.csv?kind=contract', 'GET');
$request->setUserResolver(fn () => $f['receiver']);
$response = app(AgreementFollowupController::class)->csv($request, app(AgreementFollowup::class));
if (! $checked || ! str_contains($response->getContent(), "'=PG-CONTRACT-PROOF") || ! str_contains($response->getContent(), 'Limite global por ordem')
|| $before !== DB::table('audit_logs')->count() || DB::transactionLevel() !== 0) {
throw new RuntimeException('CSV global sem prova de leitura consistente ou sem efeitos.');
}
echo json_encode(['contract_csv_read_only_snapshot' => true, 'formula_cell_protected' => true, 'no_audit_writes' => true, 'transaction_closed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,112 @@
<?php
use App\Models\Supplier;
use App\Models\SupplierBankDetail;
use App\Services\SupplierBankWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || DB::connection()->getConfig('host') !== '127.0.0.1') {
throw new LogicException('Ensaio de actualização permitido apenas em PostgreSQL sintético isolado.');
}
$targets = ['2026_11_21_000001_create_quotation_exchange_rates.php', '2026_11_21_000002_add_supplier_bank_account_keys.php'];
$baseline = array_values(array_filter(glob(database_path('migrations/*.php')), fn ($path) => ! in_array(basename($path), $targets, true)));
if (Artisan::call('migrate', ['--path' => $baseline, '--realpath' => true, '--force' => true]) !== 0) {
throw new RuntimeException('Preparação do schema anterior falhou.');
}
require __DIR__.'/../Support/ReceiptFixture.php';
$f = receiptFixture();
auth()->guard()->setUser($f['issuer']);
$detail = app(SupplierBankWorkflow::class)->propose($f['issuer'], Supplier::query()->findOrFail($f['order']->supplier_id), ['previous_id' => 0, 'bank_name' => 'Banco sintético de transição',
'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Beneficiário sintético', 'account_identifier' => 'QA-LEGACY-ONLY',
'evidence_reference' => 'Evidência exclusivamente sintética', 'reason' => 'Ensaio da preservação do histórico anterior.']);
$tables = array_column(DB::select("select tablename from pg_tables where schemaname='public' and tablename <> 'migrations' order by tablename"), 'tablename');
$columns = [];
foreach ($tables as $table) {
$columns[$table] = Schema::getColumnListing($table);
}
$fingerprint = static function ($connection) use ($columns): array {
$hashes = [];
foreach ($columns as $table => $names) {
$quoted = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.$table.'") t order by row_to_json(t)::text');
$hashes[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $hashes;
};
$before = $fingerprint(DB::connection());
$migrationCount = DB::table('migrations')->count();
$config = DB::connection()->getConfig();
unset($config['name']);
$directory = storage_path('framework/testing/commercial-upgrade-'.$database);
if (! mkdir($directory, 0700, true) && ! is_dir($directory)) {
throw new RuntimeException('Não foi possível preparar a salvaguarda sintética.');
}
$pg = static function (string $binary, array $args) use ($config): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $config['host'],
'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password']], timeout: 90);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Salvaguarda/restauro sintéticos não aprovados.');
}
};
$preDump = $directory.'/before.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
$paths = array_map(fn ($name) => database_path('migrations/'.$name), $targets);
if (Artisan::call('migrate', ['--path' => $paths, '--realpath' => true, '--force' => true]) !== 0
|| $fingerprint(DB::connection()) !== $before || DB::table('migrations')->count() !== $migrationCount + 2
|| DB::table('quotation_exchange_rates')->exists() || DB::table('quotations')->whereNotNull('exchange_basis')->exists()
|| DB::table('supplier_bank_details')->whereNotNull('account_key')->exists() || SupplierBankDetail::query()->findOrFail($detail->id)->account_key !== null) {
throw new RuntimeException('Actualização não preservou o schema/dados anteriores ou criou valores novos.');
}
if (Artisan::call('migrate', ['--path' => $paths, '--realpath' => true, '--force' => true]) !== 0
|| DB::table('migrations')->count() !== $migrationCount + 2 || $fingerprint(DB::connection()) !== $before) {
throw new RuntimeException('Reexecução da migração não é inócua.');
}
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
config(['database.connections.upgrade_admin' => [...$config, 'database' => 'postgres', 'url' => null]]);
$admin = DB::connection('upgrade_admin');
$dump = $directory.'/after.dump';
$created = false;
try {
$pg('pg_dump', ['--format=custom', '--file='.$dump, '--dbname='.$database]);
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump]);
config(['database.connections.upgrade_restore' => [...$config, 'database' => $restore, 'url' => null]]);
$restored = DB::connection('upgrade_restore');
if ($fingerprint($restored) !== $before || $restored->table('migrations')->count() !== $migrationCount + 2
|| $restored->table('quotation_exchange_rates')->exists() || $restored->table('supplier_bank_details')->whereNotNull('account_key')->exists()) {
throw new RuntimeException('Restauro não conserva a actualização e os dados anteriores.');
}
DB::purge('upgrade_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
$created = false;
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('upgrade_restore');
if ($fingerprint($restored) !== $before || $restored->table('migrations')->count() !== $migrationCount
|| $restored->getSchemaBuilder()->hasTable('quotation_exchange_rates') || $restored->getSchemaBuilder()->hasColumn('supplier_bank_details', 'account_key')
|| $restored->getSchemaBuilder()->hasColumn('quotations', 'exchange_basis')) {
throw new RuntimeException('Restauro anterior não recupera exactamente a base sintética anterior à actualização.');
}
echo json_encode(['synthetic_upgrade_preserved_tables' => count($before), 'migration_delta' => 2, 'new_values_empty' => true,
'replay_no_changes' => true, 'synthetic_backup_restore_verified' => true, 'pre_upgrade_restore_verified' => true,
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $dump)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
DB::purge('upgrade_restore');
if ($created) {
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
}