Implementa registo e conferencia de pagamentos externos

This commit is contained in:
2026-10-28 14:51:53 +02:00
parent f0f7b8ce9d
commit c41628d738
25 changed files with 1279 additions and 10 deletions
+30
View File
@@ -0,0 +1,30 @@
<?php
use App\Models\ExternalPayment;
use App\Models\User;
use App\Services\ExternalPaymentWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/', $database)) {
throw new LogicException('Base de teste inválida.');
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('testing') || DB::connection()->getDatabaseName() !== $database) {
throw new LogicException('Worker não isolado.');
}
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_payment_'.$argv[4]]);
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
$user = User::query()->findOrFail($argv[2]);
auth()->guard()->setUser($user);
try {
app(ExternalPaymentWorkflow::class)->review($user, ExternalPayment::query()->findOrFail($argv[3]), 'confirmed', 'Conferência isolada de teste');
$status = 200;
} catch (ValidationException) {
$status = 422;
}
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
+122
View File
@@ -0,0 +1,122 @@
<?php
use App\Models\BudgetConsumption;
use App\Models\BudgetEntry;
use App\Models\ExternalPayment;
use App\Services\ExternalPaymentWorkflow;
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';
foreach (['APP_ENV' => 'testing', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
require __DIR__.'/../Support/PaymentFixture.php';
$original = DB::connection();
if ($original->getDriverName() !== 'pgsql') {
throw new LogicException('Exige PostgreSQL.');
}
$config = $original->getConfig();
$admin = $original->getPdo();
$database = 'compras_receipts_test_'.bin2hex(random_bytes(6));
$created = false;
$processes = [];
$report = ['tested_at_utc' => gmdate('c'), 'separate_database' => true, 'transport' => 'Independent PHP service transactions and PostgreSQL connections', 'scenarios' => []];
try {
$admin->exec('CREATE DATABASE "'.$database.'"');
$created = true;
config(['database.connections.pgsql' => [...$config, 'database' => $database, 'url' => null]]);
DB::purge('pgsql');
DB::setDefaultConnection('pgsql');
Schema::clearResolvedInstance('db.schema');
app()->forgetInstance('db.schema');
if (DB::connection()->getDatabaseName() !== $database || Schema::getConnection()->getDatabaseName() !== $database) {
throw new LogicException('Migração fora do isolamento recusada.');
}
Artisan::call('migrate', ['--database' => 'pgsql', '--force' => true]);
$workerEnv = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_DATABASE' => $database, 'DB_HOST' => $config['host'], 'DB_PORT' => (string) $config['port'], 'DB_USERNAME' => $config['username'], 'DB_PASSWORD' => $config['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array'];
foreach (['over_payment', 'same_confirmation', 'complementary_payments'] as $scenario) {
$f = paymentFixture();
$first = app(ExternalPaymentWorkflow::class)->register($f['author'], $f['invoice'], $f['payment_data']);
$second = $first;
if ($scenario !== 'same_confirmation') {
$data = $f['payment_data'];
$data['external_reference'] = 'TEST-EXT-02';
if ($scenario === 'complementary_payments') {
$data['amount'] = '20.00';
}
$second = app(ExternalPaymentWorkflow::class)->register($f['author'], $f['invoice'], $data);
}
$connection = DB::connection();
$connection->beginTransaction();
$connection->table('tenants')->where('id', $f['tenant']->id)->lockForUpdate()->first();
$processes = [];
foreach ([$first, $second] as $index => $payment) {
$process = new Process([PHP_BINARY, __DIR__.'/payment-worker.php', $database, (string) $f['validator']->id, (string) $payment->id, $index === 0 ? 'A' : 'B'], base_path(), $workerEnv);
$process->setTimeout(40);
$process->start();
$processes[] = $process;
}
$statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name IN ('sgc_payment_A','sgc_payment_B') AND wait_event_type = 'Lock'");
$deadline = microtime(true) + 20;
do {
$statement->execute([$database]);
$waits = (int) $statement->fetchColumn();
if ($waits === 2) {
break;
}
foreach ($processes as $process) {
if (! $process->isRunning()) {
throw new RuntimeException('Worker terminou antes do bloqueio: '.$process->getErrorOutput());
}
}
usleep(20000);
} while (microtime(true) < $deadline);
$connection->commit();
if ($waits !== 2) {
throw new RuntimeException('Sem sobreposição de bloqueios.');
}
$results = [];
foreach ($processes as $process) {
$process->wait();
if (! $process->isSuccessful()) {
throw new RuntimeException('Falha do worker: '.$process->getErrorOutput());
}
$results[] = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
}
$statuses = array_column($results, 'status');
sort($statuses);
$consumed = (int) BudgetConsumption::query()->sum('amount_minor');
$committed = (int) BudgetEntry::query()->sum('committed_minor');
$confirmed = (int) ExternalPayment::query()->where('status', 'confirmed')->sum('amount_minor');
$count = $scenario === 'complementary_payments' ? 2 : 1;
$expected = $scenario === 'complementary_payments' ? 6000 : 4000;
if ($statuses !== ($scenario === 'over_payment' ? [200, 422] : [200, 200]) || $confirmed !== $expected || $consumed !== 6000 || $committed !== 4000 || ExternalPayment::query()->where('status', 'confirmed')->count() !== $count || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
throw new RuntimeException('Resultado concorrente de pagamentos inesperado.');
}
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'confirmed_minor' => $confirmed, 'outstanding_minor' => 6000 - $confirmed, 'budget_consumption_unchanged' => true];
}
$report['passed'] = true;
} finally {
foreach ($processes as $process) {
if ($process->isRunning()) {
$process->stop();
}
}
if (isset($connection) && $connection->transactionLevel() > 0) {
$connection->rollBack();
}
DB::disconnect('pgsql');
if ($created && $database !== $original->getDatabaseName() && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/', $database)) {
$admin->exec('DROP DATABASE "'.$database.'"');
$report['test_database_dropped'] = true;
}
}
file_put_contents(base_path('docs/pagamentos-concorrencia-postgresql.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
+206
View File
@@ -0,0 +1,206 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\BudgetConsumption;
use App\Models\BudgetEntry;
use App\Models\ExternalPayment;
use App\Models\User;
use App\Services\ExternalPaymentWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\SupplierBankWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
$this->f = paymentFixture();
$this->data = $this->f['payment_data'];
$this->actingAs($this->f['author']);
});
function registerTestPayment(object $test): ExternalPayment
{
$test->actingAs($test->f['author']);
return app(ExternalPaymentWorkflow::class)->register($test->f['author'], $test->f['invoice'], $test->data);
}
function confirmTestPayment(object $test, ExternalPayment $payment, string $decision = 'confirmed'): void
{
$test->actingAs($test->f['validator']);
app(ExternalPaymentWorkflow::class)->review($test->f['validator'], $payment, $decision, 'Conferência independente de teste');
}
test('external payment reduces invoice debt only after independent confirmation without consuming budget twice', function () {
$before = (int) BudgetConsumption::query()->sum('amount_minor');
$commitment = (int) BudgetEntry::query()->sum('committed_minor');
$payment = registerTestPayment($this);
expect(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']))->toBe(6000);
confirmTestPayment($this, $payment);
confirmTestPayment($this, $payment);
expect(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']))->toBe(2000)
->and((int) BudgetConsumption::query()->sum('amount_minor'))->toBe($before)
->and((int) BudgetEntry::query()->sum('committed_minor'))->toBe($commitment)
->and(ExternalPayment::query()->where('status', 'confirmed')->count())->toBe(1);
});
test('external reference retries are idempotent but altered data are refused', function () {
$first = registerTestPayment($this);
$this->data['external_reference'] = ' test-ext-01 ';
expect(registerTestPayment($this)->id)->toBe($first->id);
$this->data['amount'] = '30.00';
expect(fn () => registerTestPayment($this))->toThrow(ValidationException::class);
expect(ExternalPayment::query()->count())->toBe(1);
});
test('payment author cannot confirm own record', function () {
$payment = registerTestPayment($this);
$this->post('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'reason' => 'Teste', 'independently_verified' => true])->assertForbidden();
});
test('invalid dates amounts and bank versions cannot register a payment', function (string $case) {
match ($case) {
'over' => $this->data['amount'] = '60.01',
'zero' => $this->data['amount'] = '0.00',
'negative' => $this->data['amount'] = '-1.00',
'future' => $this->data['paid_on'] = today()->addDay()->format('Y-m-d'),
'before_invoice' => $this->data['paid_on'] = today()->subDay()->format('Y-m-d'),
'old_year' => $this->data['paid_on'] = today()->subYear()->format('Y-m-d'),
'bank' => $this->data['supplier_bank_detail_id'] = PHP_INT_MAX,
'reference' => $this->data['external_reference'] = ' ',
'evidence' => $this->data['evidence_reference'] = ' ',
};
expect(fn () => registerTestPayment($this))->toThrow(ValidationException::class);
expect(ExternalPayment::query()->count())->toBe(0);
})->with(['over', 'zero', 'negative', 'future', 'before_invoice', 'old_year', 'bank', 'reference', 'evidence']);
test('competing pending payments cannot overpay an invoice when confirmed', function () {
$first = registerTestPayment($this);
$this->data['external_reference'] = 'TEST-EXT-02';
$second = registerTestPayment($this);
confirmTestPayment($this, $first);
expect(fn () => confirmTestPayment($this, $second))->toThrow(ValidationException::class);
expect($second->refresh()->status)->toBe('pending')
->and(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']))->toBe(2000);
});
test('complementary payments settle invoice exactly', function () {
confirmTestPayment($this, registerTestPayment($this));
$this->data['external_reference'] = 'TEST-EXT-02';
$this->data['amount'] = '20.00';
confirmTestPayment($this, registerTestPayment($this));
expect(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']))->toBe(0);
});
test('bank revision changed after registration blocks confirmation and preserves encrypted snapshot', function () {
$payment = registerTestPayment($this);
$this->actingAs($this->f['issuer']);
app(SupplierBankWorkflow::class)->propose($this->f['issuer'], $this->f['supplier'], [...$this->f['bank_data'], 'previous_id' => $this->f['bank']->id, 'account_identifier' => 'TEST-NEW-ACCOUNT']);
expect(fn () => confirmTestPayment($this, $payment))->toThrow(ValidationException::class);
expect($payment->refresh()->bank_snapshot['account_identifier'])->toBe('TEST-PAY-ACCOUNT');
});
test('loss of reviewer eligibility or supplier eligibility blocks confirmation', function (string $case) {
$payment = registerTestPayment($this);
if ($case === 'reviewer') {
$this->f['author']->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
} else {
$this->f['supplier']->update(['status' => 'suspended']);
}
expect(fn () => confirmTestPayment($this, $payment))->toThrow(ValidationException::class);
})->with(['reviewer', 'supplier']);
test('rejected evidence leaves invoice outstanding and decision cannot be changed', function () {
$payment = registerTestPayment($this);
confirmTestPayment($this, $payment, 'rejected');
expect(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']))->toBe(6000);
expect(fn () => confirmTestPayment($this, $payment))->toThrow(ValidationException::class);
});
test('payment audit failure rolls back registration and confirmation', function () {
$payment = registerTestPayment($this);
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
expect(fn () => confirmTestPayment($this, $payment))->toThrow(RuntimeException::class);
expect($payment->refresh()->status)->toBe('pending');
$this->data['external_reference'] = 'TEST-EXT-02';
expect(fn () => registerTestPayment($this))->toThrow(RuntimeException::class);
expect(ExternalPayment::query()->count())->toBe(1);
});
test('payment references and bank snapshot are encrypted hidden and absent from audit', function () {
$payment = registerTestPayment($this);
expect(DB::table('external_payments')->where('id', $payment->id)->value('external_reference'))->not->toBe($this->data['external_reference']);
expect($payment->toArray())->not->toHaveKey('bank_snapshot')->not->toHaveKey('external_reference');
$audit = json_encode(AuditLog::query()->get()->toArray());
expect($audit)->not->toContain('TEST-PAY-ACCOUNT')->not->toContain('TEST-EXT-01');
expect(fn () => $payment->update(['amount_minor' => 1]))->toThrow(LogicException::class);
expect(fn () => $payment->refresh()->delete())->toThrow(LogicException::class);
});
test('foreign finance cannot inspect or confirm payment', function () {
$payment = registerTestPayment($this);
$other = receiptFixture();
$user = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($user)->post('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'reason' => 'Teste', 'independently_verified' => true])->assertNotFound();
$this->get('/pagamentos')->assertOk()->assertInertia(fn ($page) => $page->has('payments.data', 0));
});
test('non finance roles cannot register payments', function (PurchasingRole $role) {
$user = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => $role]);
$this->actingAs($user)->post('/facturas/'.$this->f['invoice']->id.'/pagamentos', $this->data)->assertForbidden();
})->with([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Requester]);
test('administration sees payment metadata without external evidence or banking snapshots', function () {
registerTestPayment($this);
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($admin)->get('/pagamentos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn ($page) => $page->where('payments.data.0.external_reference', null)->where('payments.data.0.evidence_reference', null)->missing('payments.data.0.bank_snapshot'));
});
test('invalid submission does not flash external references', function () {
$this->post('/facturas/'.$this->f['invoice']->id.'/pagamentos', [...$this->data, 'paid_on' => 'invalid'])->assertSessionHasErrors('paid_on');
expect(session()->getOldInput('external_reference'))->toBeNull()->and(session()->getOldInput('evidence_reference'))->toBeNull();
});
test('payment review requires explicit independent verification', function () {
$payment = registerTestPayment($this);
$this->actingAs($this->f['validator'])->post('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'reason' => 'Teste'])->assertSessionHasErrors('independently_verified');
expect($payment->refresh()->status)->toBe('pending');
});
test('conflict declared after payment registration blocks confirmation', function () {
$payment = registerTestPayment($this);
$this->post('/conflitos', ['scope' => 'supplier', 'supplier_id' => $this->f['supplier']->id, 'has_conflict' => true, 'known_since' => today()->format('Y-m-d'), 'reason' => 'Conflito fictício posterior ao registo externo.'])->assertSessionHasNoErrors();
expect(fn () => confirmTestPayment($this, $payment))->toThrow(ValidationException::class);
expect($payment->refresh()->status)->toBe('pending');
});
test('bank account in another currency does not imply permission to convert money', function () {
$this->actingAs($this->f['issuer']);
$bank = app(SupplierBankWorkflow::class)->propose($this->f['issuer'], $this->f['supplier'], [...$this->f['bank_data'], 'previous_id' => $this->f['bank']->id, 'currency' => 'USD']);
foreach ([$this->f['author'], $this->f['validator']] as $user) {
$this->actingAs($user);
app(SupplierBankWorkflow::class)->review($user, $bank, 'approved', 'Conferência de teste');
}
$this->data['supplier_bank_detail_id'] = $bank->id;
expect(fn () => registerTestPayment($this))->toThrow(ValidationException::class);
});
test('browser cannot forge a confirmed payment or its encrypted banking snapshot', function () {
$this->post('/facturas/'.$this->f['invoice']->id.'/pagamentos', [...$this->data, 'status' => 'confirmed', 'reviewed_by' => $this->f['author']->id, 'tenant_id' => PHP_INT_MAX, 'bank_snapshot' => ['account_identifier' => 'FORGED']])->assertRedirect('/pagamentos');
$payment = ExternalPayment::query()->firstOrFail();
expect($payment->status)->toBe('pending')->and($payment->tenant_id)->toBe($this->f['tenant']->id)
->and($payment->bank_snapshot['account_identifier'])->toBe('TEST-PAY-ACCOUNT');
});
test('public payment example exposes no company payment data', function () {
auth()->forgetGuards();
$this->get('/consulta/pagamentos')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'payments')->where('auth.user', null)->missing('payments')->missing('invoices'));
});
test('financial role is reloaded after the company lock rather than trusting a stale session user', function () {
DB::table('users')->where('id', $this->f['author']->id)->update(['purchasing_role' => 'warehouse']);
$this->post('/facturas/'.$this->f['invoice']->id.'/pagamentos', $this->data)->assertForbidden();
expect(ExternalPayment::query()->count())->toBe(0);
});
+27
View File
@@ -0,0 +1,27 @@
<?php
use App\Models\Supplier;
use App\Services\InvoiceWorkflow;
use App\Services\SupplierBankWorkflow;
require_once __DIR__.'/InvoiceFixture.php';
/** invoiceFixture enforces a synthetic, isolated test database. */
function paymentFixture(): array
{
$f = invoiceFixture();
auth()->guard()->setUser($f['validator']);
app(InvoiceWorkflow::class)->validate($f['validator'], $f['invoice']);
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id);
auth()->guard()->setUser($f['issuer']);
$bankData = ['previous_id' => 0, 'bank_name' => 'Banco fictício', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Titular de teste', 'account_identifier' => 'TEST-PAY-ACCOUNT', 'evidence_reference' => 'Evidência de teste', 'reason' => 'Somente teste isolado'];
$bank = app(SupplierBankWorkflow::class)->propose($f['issuer'], $supplier, $bankData);
foreach ([$f['author'], $f['validator']] as $reviewer) {
auth()->guard()->setUser($reviewer);
app(SupplierBankWorkflow::class)->review($reviewer, $bank, 'approved', 'Conferência de teste');
}
auth()->guard()->setUser($f['author']);
$paymentData = ['supplier_bank_detail_id' => $bank->id, 'amount' => '40.00', 'paid_on' => today()->format('Y-m-d'), 'external_reference' => 'TEST-EXT-01', 'evidence_reference' => 'Evidência externa fictícia'];
return [...$f, 'supplier' => $supplier, 'bank' => $bank, 'bank_data' => $bankData, 'payment_data' => $paymentData];
}
+105
View File
@@ -0,0 +1,105 @@
<?php
// Explicit operational entry point: backup, restore verification, then only migration 000012.
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$connection = DB::connection();
if ($connection->getDriverName() !== 'pgsql' || $connection->getDatabaseName() !== 'compras_dev' || ! $app->environment('local')) {
throw new LogicException('Aplicação recusada fora de compras_dev/local.');
}
$pdo = $connection->getPdo();
$migration = '2026_10_28_000012_create_external_payments';
if ($pdo->query("SELECT count(*) FROM migrations WHERE migration = '$migration'")->fetchColumn() > 0) {
throw new LogicException('Migração já aplicada; não repetir.');
}
$config = $connection->getConfig();
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
foreach (['pg_dump.exe', 'pg_restore.exe'] as $tool) {
if (! is_file($bin.$tool)) {
throw new LogicException('Ferramentas PostgreSQL 17 ausentes.');
}
}
$envHash = hash_file('sha256', base_path('.env'));
$directory = storage_path('app/private/backups/payment-000012-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3)));
if (! mkdir($directory, 0700, true)) {
throw new RuntimeException('Não foi possível criar backup privado.');
}
$env = ['PGHOST' => $config['host'], 'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password'], 'PGSSLMODE' => $config['sslmode'] ?? 'prefer'];
$quote = fn (string $name) => '"'.str_replace('"', '""', $name).'"';
$fingerprints = function (PDO $db, array $tables) use ($quote): array {
$result = [];
foreach ($tables as $table) {
$rows = $db->query('SELECT md5(row_to_json(t)::text) FROM public.'.$quote($table).' t')->fetchAll(PDO::FETCH_COLUMN);
sort($rows, SORT_STRING);
$result[$table] = ['count' => count($rows), 'sha256' => hash('sha256', implode('\n', $rows))];
}
return $result;
};
$tables = $pdo->query("SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN);
$restoreDatabase = 'compras_restore_check_'.bin2hex(random_bytes(6));
$restoreCreated = false;
try {
// pg_dump and the manifest read exactly the same committed snapshot.
$pdo->beginTransaction();
$pdo->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
$snapshot = $pdo->query('SELECT pg_export_snapshot()')->fetchColumn();
$backupState = $fingerprints($pdo, $tables);
$dump = new Process([$bin.'pg_dump.exe', '--format=custom', '--no-owner', '--no-acl', '--snapshot='.$snapshot, '--file='.$directory.'/database.dump', '--dbname='.$config['database']], base_path(), $env);
$dump->setTimeout(120);
$dump->run();
if (! $dump->isSuccessful()) {
throw new RuntimeException('Falha no backup PostgreSQL; migração não executada.');
}
$pdo->commit();
$pdo->exec('CREATE DATABASE '.$quote($restoreDatabase));
$restoreCreated = true;
$restore = new Process([$bin.'pg_restore.exe', '--exit-on-error', '--no-owner', '--no-acl', '--dbname='.$restoreDatabase, $directory.'/database.dump'], base_path(), $env);
$restore->setTimeout(120);
$restore->run();
if (! $restore->isSuccessful()) {
throw new RuntimeException('Restauro de verificação falhou; migração não executada.');
}
config(['database.connections.budget_restore' => [...$config, 'url' => null, 'database' => $restoreDatabase]]);
$restored = DB::connection('budget_restore')->getPdo();
if ($fingerprints($restored, $tables) !== $backupState) {
throw new RuntimeException('Restauro não corresponde ao backup; migração recusada.');
}
file_put_contents($directory.'/manifest.json', json_encode(['tables' => $backupState, 'dump_sha256' => hash_file('sha256', $directory.'/database.dump')], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
file_put_contents($directory.'/RECUPERACAO.txt', "Backup custom PostgreSQL 17 verificado por restauro numa base separada.\nUsar pg_restore --exit-on-error --no-owner --no-acl --dbname=NOVA_BASE database.dump.\nAs credenciais pertencem ao ambiente local e não estão neste manifesto.\nNão restaurar por cima da base existente.\n");
DB::disconnect('budget_restore');
unset($restored);
$pdo->exec('DROP DATABASE '.$quote($restoreDatabase));
$restoreCreated = false;
$businessTables = array_values(array_diff($tables, ['migrations', 'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches']));
$before = $fingerprints($pdo, $businessTables);
$oldMigrations = $pdo->query('SELECT id, migration, batch FROM migrations ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$constraints = $pdo->query("SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE connamespace = 'public'::regnamespace ORDER BY conname, definition")->fetchAll(PDO::FETCH_ASSOC);
$exit = Artisan::call('migrate', ['--path' => 'database/migrations/'.$migration.'.php', '--force' => true]);
if ($exit !== 0) {
throw new RuntimeException('Migração falhou; consultar backup privado.');
}
$after = $fingerprints($pdo, $businessTables);
$newMigrations = $pdo->query('SELECT id, migration, batch FROM migrations ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$newConstraints = $pdo->query("SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE connamespace = 'public'::regnamespace ORDER BY conname, definition")->fetchAll(PDO::FETCH_ASSOC);
if ($before !== $after || array_slice($newMigrations, 0, count($oldMigrations)) !== $oldMigrations || count($newMigrations) !== count($oldMigrations) + 1 || array_diff(array_map('serialize', $constraints), array_map('serialize', $newConstraints)) !== [] || hash_file('sha256', base_path('.env')) !== $envHash) {
throw new RuntimeException('Verificação de preservação falhou; não executar mais escritas.');
}
$report = ['verified_at_utc' => gmdate('c'), 'migration' => $migration, 'batch' => (int) end($newMigrations)['batch'], 'backup_created' => true, 'backup_bytes' => filesize($directory.'/database.dump'), 'restore_verified' => true, 'restored_tables' => count($tables), 'restore_database_dropped' => true, 'business_records_unchanged' => true, 'existing_constraints_preserved' => true, 'env_unchanged' => true, 'external_payments_count' => (int) $pdo->query('SELECT count(*) FROM external_payments')->fetchColumn(), 'operational_validation' => false];
file_put_contents(base_path('docs/pagamentos-migracao-000012.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
DB::disconnect('budget_restore');
if ($restoreCreated && preg_match('/^compras_restore_check_[a-f0-9]{12}$/', $restoreDatabase) && $restoreDatabase !== $connection->getDatabaseName()) {
$pdo->exec('DROP DATABASE '.$quote($restoreDatabase));
}
}