@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\User;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
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_bank_'.$argv[4]]);
|
||||
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
|
||||
$user = User::query()->findOrFail($argv[2]);
|
||||
auth()->guard()->setUser($user);
|
||||
$payload = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
if ($payload['action'] === 'propose') {
|
||||
app(SupplierBankWorkflow::class)->propose($user, Supplier::query()->findOrFail($argv[3]), $payload['data']);
|
||||
} else {
|
||||
app(SupplierBankWorkflow::class)->review($user, SupplierBankDetail::query()->findOrFail($argv[3]), 'approved', 'Conferência isolada de teste');
|
||||
}
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
}
|
||||
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
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';
|
||||
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/ReceiptFixture.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 (['distinct_approvals', 'same_approval', 'competing_revisions'] as $scenario) {
|
||||
$f = receiptFixture();
|
||||
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id);
|
||||
$author = $f['issuer'];
|
||||
auth()->guard()->setUser($author);
|
||||
$first = User::factory()->create(['tenant_id' => $author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$second = User::factory()->create(['tenant_id' => $author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$data = ['previous_id' => 0, 'bank_name' => 'Banco fictício', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Titular fictício', 'account_identifier' => 'TEST-PG-0001', 'evidence_reference' => 'Apenas teste', 'reason' => 'Apenas teste'];
|
||||
$detail = app(SupplierBankWorkflow::class)->propose($author, $supplier, $data);
|
||||
$payload = ['action' => 'review'];
|
||||
$target = $detail->id;
|
||||
if ($scenario === 'same_approval') {
|
||||
$second = $first;
|
||||
} elseif ($scenario === 'competing_revisions') {
|
||||
$first = $second = $author;
|
||||
$target = $supplier->id;
|
||||
$payload = ['action' => 'propose', 'data' => [...$data, 'previous_id' => $detail->id]];
|
||||
}
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $author->tenant_id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach ([$first, $second] as $index => $user) {
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/bank-worker.php', $database, (string) $user->id, (string) $target, $index === 0 ? 'A' : 'B'], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
$process->setTimeout(40);
|
||||
$process->start();
|
||||
$processes[] = $process;
|
||||
}
|
||||
$statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name IN ('sgc_bank_A','sgc_bank_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);
|
||||
$state = app(SupplierBankWorkflow::class)->state($supplier);
|
||||
$count = SupplierBankReview::query()->count();
|
||||
if ($statuses !== ($scenario === 'competing_revisions' ? [200, 422] : [200, 200]) || $state !== ($scenario === 'distinct_approvals' ? 'approved' : 'pending') || $count !== match ($scenario) {
|
||||
'distinct_approvals' => 2, 'same_approval' => 1, default => 0
|
||||
} || SupplierBankDetail::query()->count() !== ($scenario === 'competing_revisions' ? 2 : 1) || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
|
||||
throw new RuntimeException('Resultado concorrente inesperado.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'state' => $state, 'review_count' => $count];
|
||||
}
|
||||
$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/bancos-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;
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->supplier = Supplier::query()->findOrFail($this->f['order']->supplier_id);
|
||||
$this->buyer = $this->f['issuer'];
|
||||
$this->first = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->second = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($this->buyer);
|
||||
$this->data = ['previous_id' => 0, 'bank_name' => 'Banco fictício', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Beneficiário fictício de teste', 'account_identifier' => 'TEST-ACCOUNT-0001', 'evidence_reference' => 'Referência fictícia de conferência', 'reason' => 'Cadastro fictício'];
|
||||
$this->url = '/fornecedores/'.$this->supplier->id.'/dados-bancarios';
|
||||
});
|
||||
|
||||
function bankProposal(object $test): SupplierBankDetail
|
||||
{
|
||||
$test->actingAs($test->buyer);
|
||||
|
||||
return app(SupplierBankWorkflow::class)->propose($test->buyer, $test->supplier, $test->data);
|
||||
}
|
||||
|
||||
function bankApprove(object $test, User $user, SupplierBankDetail $detail, string $decision = 'approved'): void
|
||||
{
|
||||
$test->actingAs($user);
|
||||
app(SupplierBankWorkflow::class)->review($user, $detail, $decision, 'Conferência independente de teste');
|
||||
}
|
||||
|
||||
test('bank data needs two distinct independent finance reviewers', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail);
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('pending');
|
||||
bankApprove($this, $this->first, $detail);
|
||||
expect(SupplierBankReview::query()->count())->toBe(1);
|
||||
bankApprove($this, $this->second, $detail);
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('approved');
|
||||
});
|
||||
|
||||
test('bank identifiers are encrypted hidden and absent from audit payloads', function () {
|
||||
$detail = bankProposal($this);
|
||||
expect(DB::table('supplier_bank_details')->where('id', $detail->id)->value('account_identifier'))->not->toBe($this->data['account_identifier']);
|
||||
expect($detail->refresh()->account_identifier)->toBe($this->data['account_identifier']);
|
||||
expect($detail->toArray())->not->toHaveKey('account_identifier')->not->toHaveKey('beneficiary');
|
||||
expect(json_encode(AuditLog::query()->get()->toArray()))->not->toContain($this->data['account_identifier'])->not->toContain($this->data['beneficiary']);
|
||||
});
|
||||
|
||||
test('new bank revision invalidates prior availability and refuses stale proposals and reviews', function () {
|
||||
$old = bankProposal($this);
|
||||
bankApprove($this, $this->first, $old);
|
||||
bankApprove($this, $this->second, $old);
|
||||
$this->data['previous_id'] = $old->id;
|
||||
$this->data['account_identifier'] = 'TEST-ACCOUNT-0002';
|
||||
$new = bankProposal($this);
|
||||
expect($new->revision)->toBe(2)->and(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('pending');
|
||||
expect(fn () => bankProposal($this))->toThrow(ValidationException::class);
|
||||
expect(fn () => bankApprove($this, $this->first, $old))->toThrow(ValidationException::class);
|
||||
expect(SupplierBankDetail::query()->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('author cannot validate after changing to finance role', function () {
|
||||
$detail = bankProposal($this);
|
||||
$this->buyer->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->post($this->url.'/'.$detail->id.'/validar', ['decision' => 'approved', 'reason' => 'Teste', 'independently_verified' => true])->assertForbidden();
|
||||
});
|
||||
|
||||
test('rejection blocks bank readiness and cannot be erased', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail, 'rejected');
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('rejected');
|
||||
expect(fn () => bankApprove($this, $this->second, $detail))->toThrow(ValidationException::class);
|
||||
expect(fn () => $detail->update(['bank_name' => 'Alterado']))->toThrow(LogicException::class);
|
||||
expect(fn () => SupplierBankReview::query()->firstOrFail()->delete())->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('bank eligibility changes with reviewer role or supplier suspension', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail);
|
||||
bankApprove($this, $this->second, $detail);
|
||||
$this->first->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
$this->first->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->supplier->update(['status' => 'suspended']);
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
});
|
||||
|
||||
test('foreign users cannot propose read or validate bank information', function () {
|
||||
$detail = bankProposal($this);
|
||||
$other = receiptFixture();
|
||||
$user = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($user)->get($this->url)->assertNotFound();
|
||||
$this->post($this->url.'/'.$detail->id.'/validar', ['decision' => 'approved', 'reason' => 'Teste', 'independently_verified' => true])->assertNotFound();
|
||||
});
|
||||
|
||||
test('warehouse and department heads cannot read bank details', function (PurchasingRole $role) {
|
||||
bankProposal($this);
|
||||
$user = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => $role]);
|
||||
$this->actingAs($user)->get($this->url)->assertForbidden();
|
||||
})->with([PurchasingRole::Warehouse, PurchasingRole::DepartmentHead, PurchasingRole::Requester]);
|
||||
|
||||
test('administration gets metadata only and finance accesses are audited without account numbers', function () {
|
||||
$detail = bankProposal($this);
|
||||
$admin = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($admin)->get($this->url)->assertOk()->assertInertia(fn ($page) => $page->where('current', null));
|
||||
$this->actingAs($this->first)->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn ($page) => $page->where('current.account_identifier', $this->data['account_identifier']));
|
||||
expect(AuditLog::query()->where('action', 'supplier.bank_viewed')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('bank audit failure rolls back proposal and review', function () {
|
||||
$detail = bankProposal($this);
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
|
||||
expect(fn () => bankApprove($this, $this->first, $detail))->toThrow(RuntimeException::class);
|
||||
expect(SupplierBankReview::query()->count())->toBe(0);
|
||||
$this->data['previous_id'] = $detail->id;
|
||||
expect(fn () => bankProposal($this))->toThrow(RuntimeException::class);
|
||||
expect(SupplierBankDetail::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('invalid bank submission does not flash sensitive input to the session', function () {
|
||||
$this->post($this->url, [...$this->data, 'country' => 'INVALID'])->assertSessionHasErrors('country');
|
||||
expect(session()->getOldInput('account_identifier'))->toBeNull()
|
||||
->and(session()->getOldInput('beneficiary'))->toBeNull()
|
||||
->and(session()->getOldInput('reason'))->toBeNull();
|
||||
});
|
||||
|
||||
test('bank review requires the independent verification declaration', function () {
|
||||
$detail = bankProposal($this);
|
||||
$this->actingAs($this->first)->post($this->url.'/'.$detail->id.'/validar', ['decision' => 'approved', 'reason' => 'Conferência'])->assertSessionHasErrors('independently_verified');
|
||||
expect(SupplierBankReview::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('supplier conflict blocks a previously approved banking revision', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail);
|
||||
bankApprove($this, $this->second, $detail);
|
||||
$this->actingAs($this->first)->post('/conflitos', ['scope' => 'supplier', 'supplier_id' => $this->supplier->id, 'has_conflict' => true, 'known_since' => today()->format('Y-m-d'), 'reason' => 'Conflito fictício declarado depois da conferência.'])->assertSessionHasNoErrors();
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
});
|
||||
|
||||
test('public bank example exposes no company banking details', function () {
|
||||
auth()->forgetGuards();
|
||||
$this->get('/consulta/dados-bancarios')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'bank')->where('auth.user', null)->missing('current')->missing('history'));
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000011.
|
||||
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_000011_create_supplier_bank_details';
|
||||
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/bank-000011-'.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, 'bank_details_count' => (int) $pdo->query('SELECT count(*) FROM supplier_bank_details')->fetchColumn(), 'bank_reviews_count' => (int) $pdo->query('SELECT count(*) FROM supplier_bank_reviews')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/bancos-migracao-000011.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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user