Regista abertura de propostas e actas imutaveis por versao
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
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_opening_'.$argv[4]]);
|
||||
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
|
||||
$actor = User::query()->findOrFail($argv[2]);
|
||||
auth()->guard()->setUser($actor);
|
||||
$data = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
app(ProposalOpeningWorkflow::class)->record($actor, Requisition::query()->findOrFail($argv[3]), $data);
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
} catch (HttpExceptionInterface $exception) {
|
||||
$status = $exception->getStatusCode();
|
||||
}
|
||||
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\ProposalOpening;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
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/ProposalOpeningFixture.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 (['competing_initial_versions', 'competing_corrections', 'revoked_role', 'changed_basis'] as $scenario) {
|
||||
$f = proposalOpeningFixture();
|
||||
$actor = $f['issuer'];
|
||||
$data = $f['service_data'];
|
||||
if ($scenario === 'competing_corrections') {
|
||||
$initial = app(ProposalOpeningWorkflow::class)->record($actor, $f['r'], $data);
|
||||
$data['previous_id'] = $initial->id;
|
||||
}
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $actor->tenant_id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach (['A', 'B'] as $suffix) {
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/opening-worker.php', $database, (string) $actor->id, (string) $f['r']->id, $suffix], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode([...$data, 'notes' => 'Versão concorrente fictícia '.$suffix], 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_opening_A','sgc_opening_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);
|
||||
if ($scenario === 'revoked_role') {
|
||||
$connection->table('users')->where('id', $actor->id)->update(['purchasing_role' => 'finance']);
|
||||
}
|
||||
if ($scenario === 'changed_basis') {
|
||||
$connection->table('quotations')->where('id', $f['quote']->id)->update(['reference' => 'Referência alterada durante a espera']);
|
||||
}
|
||||
$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);
|
||||
$expected = match ($scenario) {
|
||||
'revoked_role' => [403, 403], 'changed_basis' => [422, 422], default => [200, 422]
|
||||
};
|
||||
$count = ProposalOpening::query()->count();
|
||||
$expectedCount = match ($scenario) {
|
||||
'competing_initial_versions' => 1, 'competing_corrections' => 2, default => 0
|
||||
};
|
||||
if ($statuses !== $expected || count(array_unique(array_column($results, 'backend_pid'))) !== 2 || $count !== $expectedCount || AuditLog::query()->where('action', 'opening.recorded')->count() !== $expectedCount) {
|
||||
throw new RuntimeException('Versão concorrente inesperada.');
|
||||
}
|
||||
if ($count && (int) ProposalOpening::query()->max('revision') !== $expectedCount) {
|
||||
throw new RuntimeException('Numeração inconsistente.');
|
||||
}
|
||||
if ($scenario === 'competing_corrections' && $initial->refresh()->notes !== $f['data']['notes']) {
|
||||
throw new RuntimeException('Versão anterior alterada.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'immutable_versions' => $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/abertura-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,133 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\Department;
|
||||
use App\Models\ProposalOpening;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ProposalOpeningFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = proposalOpeningFixture();
|
||||
$this->url = '/requisicoes/'.$this->f['r']->id.'/abertura';
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
function recordOpening(object $test, array $changes = []): ProposalOpening
|
||||
{
|
||||
$test->post($test->url, [...$test->f['data'], ...$changes])->assertSessionHasNoErrors();
|
||||
|
||||
return ProposalOpening::query()->latest('revision')->firstOrFail();
|
||||
}
|
||||
|
||||
test('opening is an optional documentary snapshot without approval or financial effects', function () {
|
||||
$opening = recordOpening($this);
|
||||
expect($opening->revision)->toBe(1)->and($opening->snapshot['proposals'][0]['total_minor'])->toBe(10000)
|
||||
->and($opening->snapshot['proposals'][0])->not->toHaveKey('evaluations')->and(BudgetEntry::query()->count())->toBe(0)
|
||||
->and($this->f['r']->refresh()->status)->toBe('approved')->and(PurchaseAward::query()->count())->toBe(0);
|
||||
$this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page->component('purchases/opening')->where('sourceChanged', false)->where('latestId', $opening->id));
|
||||
$this->get('/requisicoes/'.$this->f['r']->id.'/processo')->assertInertia(fn (Assert $page) => $page->where('documents', fn ($documents) => collect($documents)->contains('kind', 'Abertura')));
|
||||
});
|
||||
|
||||
test('opening corrections append a new version and refuse stale predecessor ids', function () {
|
||||
$first = recordOpening($this);
|
||||
$second = recordOpening($this, ['previous_id' => $first->id, 'notes' => 'Nova observação sem apagar o passado']);
|
||||
expect($second->revision)->toBe(2)->and($first->refresh()->notes)->toBe('Observações fictícias');
|
||||
$this->post($this->url, [...$this->f['data'], 'previous_id' => $first->id])->assertSessionHasErrors('previous_id');
|
||||
expect(ProposalOpening::query()->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('opening refuses a proposal basis changed after the form was loaded', function () {
|
||||
$this->f['quote']->update(['reference' => 'Referência actualizada']);
|
||||
$this->post($this->url, $this->f['data'])->assertSessionHasErrors('basis_hash');
|
||||
expect(ProposalOpening::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('printed acta preserves supplier and price snapshots after source changes', function () {
|
||||
$opening = recordOpening($this);
|
||||
$name = $opening->snapshot['proposals'][0]['supplier']['name'];
|
||||
Supplier::query()->whereKey($this->f['quote']->supplier_id)->update(['name' => 'Nome posterior fictício']);
|
||||
$this->f['quote']->update(['total_minor' => 20000]);
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('sourceChanged', true));
|
||||
$this->get('/actas/'.$opening->id.'/imprimir')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertSee($name)->assertDontSee('Nome posterior fictício')->assertSee('100,00')->assertSee('não valida assinaturas');
|
||||
});
|
||||
|
||||
test('opening stores local session time as UTC and prints the declared timezone', function () {
|
||||
$opening = recordOpening($this);
|
||||
expect($opening->opened_at)->toBe($this->f['service_data']['opened_at'])->and($opening->timezone)->toBe('Africa/Johannesburg');
|
||||
$this->get('/actas/'.$opening->id.'/imprimir')->assertSee('Africa/Johannesburg');
|
||||
$this->post($this->url, [...$this->f['data'], 'previous_id' => $opening->id, 'opened_at' => now()->addHour()->timezone('Africa/Johannesburg')->format('Y-m-d\TH:i')])->assertSessionHasErrors('opened_at');
|
||||
});
|
||||
|
||||
test('opening validates deadline confirmation and declared participants', function () {
|
||||
$this->post($this->url, [...$this->f['data'], 'confirmed' => false])->assertSessionHasErrors('confirmed');
|
||||
$this->post($this->url, [...$this->f['data'], 'submission_deadline' => now()->addDay()->timezone('Africa/Johannesburg')->format('Y-m-d\TH:i')])->assertSessionHasErrors('submission_deadline');
|
||||
$this->post($this->url, [...$this->f['data'], 'participants' => []])->assertSessionHasErrors('participants');
|
||||
$this->post($this->url, [...$this->f['data'], 'snapshot' => ['signed' => true]])->assertSessionHasErrors('snapshot');
|
||||
});
|
||||
|
||||
test('opening cannot rewrite a process after an award or record a draft request', function () {
|
||||
$this->f['r']->update(['status' => 'draft']);
|
||||
$this->post($this->url, $this->f['data'])->assertSessionHasErrors('opening');
|
||||
$this->f['r']->update(['status' => 'approved']);
|
||||
PurchaseAward::query()->create($this->f['award_attributes']);
|
||||
$this->post($this->url, $this->f['data'])->assertSessionHasErrors('opening');
|
||||
expect(ProposalOpening::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('opening is restricted by role department company and authentication including print', function () {
|
||||
$opening = recordOpening($this);
|
||||
$print = '/actas/'.$opening->id.'/imprimir';
|
||||
$this->actingAs($this->f['receiver'])->get($this->url)->assertForbidden();
|
||||
$this->get($print)->assertForbidden();
|
||||
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($finance)->get($this->url)->assertOk();
|
||||
$this->get($print)->assertOk();
|
||||
$this->post($this->url, [...$this->f['data'], 'previous_id' => $opening->id])->assertForbidden();
|
||||
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outro departamento']);
|
||||
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($head)->get($print)->assertNotFound();
|
||||
$other = Tenant::query()->create(['name' => 'Outra empresa fictícia']);
|
||||
$this->actingAs(User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Admin]))->get($print)->assertNotFound();
|
||||
auth()->logout();
|
||||
$this->get($print)->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('opening rejects revoked procurement roles and never accepts foreign proposals', function () {
|
||||
$original = $this->f;
|
||||
$foreign = proposalOpeningFixture();
|
||||
$this->actingAs($original['issuer']);
|
||||
$this->post($this->url, [...$original['data'], 'quotation_ids' => [$foreign['quote']->id]])->assertSessionHasErrors('quotation_ids');
|
||||
DB::table('users')->where('id', $original['issuer']->id)->update(['purchasing_role' => 'finance']);
|
||||
$this->post($this->url, $original['data'])->assertForbidden();
|
||||
expect(ProposalOpening::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('opening audit failure rolls back the entire immutable document', function () {
|
||||
AuditLog::creating(function (AuditLog $event) {
|
||||
if ($event->action === 'opening.recorded') {
|
||||
throw new RuntimeException('Falha fictícia de auditoria');
|
||||
}
|
||||
});
|
||||
try {
|
||||
expect(fn () => app(ProposalOpeningWorkflow::class)->record($this->f['issuer'], $this->f['r'], $this->f['service_data']))->toThrow(RuntimeException::class);
|
||||
} finally {
|
||||
AuditLog::flushEventListeners();
|
||||
}
|
||||
expect(ProposalOpening::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('opening documents are immutable and user text is escaped for printing', function () {
|
||||
$opening = recordOpening($this, ['notes' => '<script>alert("ficticio")</script>']);
|
||||
$this->get('/actas/'.$opening->id.'/imprimir')->assertDontSee('<script>', false)->assertSee('<script>', false);
|
||||
expect(fn () => $opening->update(['notes' => 'Alteração proibida']))->toThrow(LogicException::class);
|
||||
expect(fn () => $opening->delete())->toThrow(LogicException::class);
|
||||
});
|
||||
@@ -21,7 +21,7 @@ test('process overview links records without declaring partial execution complet
|
||||
->where('stages.7.state', 'recorded')
|
||||
->where('stages.7.detail', '1 registadas; 0 validadas. O registo não equivale a validação.')
|
||||
->where('stages.8.state', 'not_started')
|
||||
->has('future', 3)
|
||||
->has('future', 2)
|
||||
->where('documents', fn ($documents) => collect($documents)->contains('label', $f['invoice']->number)));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\Quotation;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require_once __DIR__.'/ReceiptFixture.php';
|
||||
|
||||
/** receiptFixture refuses execution outside the isolated test database. */
|
||||
function proposalOpeningFixture(): array
|
||||
{
|
||||
$f = receiptFixture();
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$award = PurchaseAward::query()->findOrFail($f['order']->purchase_award_id);
|
||||
$awardAttributes = $award->getAttributes();
|
||||
unset($awardAttributes['id']);
|
||||
DB::table('purchase_order_items')->where('purchase_order_id', $f['order']->id)->delete();
|
||||
DB::table('purchase_orders')->where('id', $f['order']->id)->delete();
|
||||
DB::table('purchase_awards')->where('id', $award->id)->delete();
|
||||
$quote = Quotation::query()->where('requisition_id', $f['r']->id)->firstOrFail();
|
||||
$workflow = app(ProposalOpeningWorkflow::class);
|
||||
$data = ['previous_id' => 0, 'basis_hash' => $workflow->basis($workflow->proposals($f['r'])), 'opened_at' => now()->subMinute()->timezone('Africa/Johannesburg')->format('Y-m-d\TH:i'), 'timezone' => 'Africa/Johannesburg', 'submission_deadline' => null, 'reference' => 'ABERTURA-FICTICIA', 'location' => 'Sala exclusivamente fictícia', 'reason' => 'Registo exclusivamente fictício de teste', 'notes' => 'Observações fictícias', 'quotation_ids' => [$quote->id], 'participants' => [['name' => 'Participante fictício', 'capacity' => 'Secretariado de teste', 'group' => 'participant']], 'annexes' => ['Lista fictícia de presenças'], 'confirmed' => true];
|
||||
$serviceData = [...$data, 'opened_at' => CarbonImmutable::createFromFormat('!Y-m-d\TH:i', $data['opened_at'], $data['timezone'])->utc()->format('Y-m-d H:i:s')];
|
||||
|
||||
return [...$f, 'quote' => $quote, 'data' => $data, 'service_data' => $serviceData, 'award_attributes' => $awardAttributes];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000017.
|
||||
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_000017_create_proposal_openings';
|
||||
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/proposal-openings-000017-'.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).'"';
|
||||
$columns = [];
|
||||
$fingerprints = function (PDO $db, array $tables) use ($quote, &$columns): array {
|
||||
$result = [];
|
||||
foreach ($tables as $table) {
|
||||
$rows = $db->query('SELECT md5(row_to_json(t)::text) FROM (SELECT '.implode(', ', array_map($quote, $columns[$table])).' 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);
|
||||
foreach ($tables as $table) {
|
||||
$statement = $pdo->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ? ORDER BY ordinal_position");
|
||||
$statement->execute([$table]);
|
||||
$columns[$table] = $statement->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, 'columns' => $columns, '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, 'proposal_openings_count' => (int) $pdo->query('SELECT count(*) FROM proposal_openings')->fetchColumn(), 'purchase_plan_milestones_count' => (int) $pdo->query('SELECT count(*) FROM purchase_plan_milestones')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/abertura-migracao-000017.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