Implementa reforcos orcamentais com aprovacao independente
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
use App\Models\BudgetReinforcement;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\BudgetReinforcementWorkflow;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ConflictGuard;
|
||||
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_reinforcement_'.$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'] === 'reserve') {
|
||||
DB::transaction(function () use ($user, $argv) {
|
||||
app(ConflictGuard::class)->lockCompany($user);
|
||||
$request = Requisition::query()->lockForUpdate()->findOrFail($argv[3]);
|
||||
app(BudgetWorkflow::class)->record($user, $request, 'reserve', 10000, 10000);
|
||||
});
|
||||
} else {
|
||||
app(BudgetReinforcementWorkflow::class)->review($user, BudgetReinforcement::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,132 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Budget;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\BudgetReinforcement;
|
||||
use App\Models\User;
|
||||
use App\Services\BudgetReinforcementWorkflow;
|
||||
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 (['same_approval', 'distinct_reinforcements', 'approval_vs_reservation'] as $scenario) {
|
||||
$f = receiptFixture();
|
||||
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
auth()->guard()->setUser($author);
|
||||
$budget = Budget::query()->create(['tenant_id' => $author->tenant_id, 'cost_center_id' => $f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 5000, 'includes_tax' => true, 'created_by' => $author->id, 'approved_by' => $reviewer->id, 'reason' => 'Fixture isolada']);
|
||||
$data = ['reference' => 'REF-PG-1', 'amount' => '70.00', 'reason' => 'Fixture isolada'];
|
||||
$first = app(BudgetReinforcementWorkflow::class)->propose($author, $budget, $data);
|
||||
$second = $first;
|
||||
if ($scenario === 'distinct_reinforcements') {
|
||||
$second = app(BudgetReinforcementWorkflow::class)->propose($author, $budget, [...$data, 'reference' => 'REF-PG-2']);
|
||||
}
|
||||
$jobs = [
|
||||
['user' => $reviewer, 'target' => $first->id, 'payload' => ['action' => 'approve']],
|
||||
['user' => $reviewer, 'target' => $second->id, 'payload' => ['action' => 'approve']],
|
||||
];
|
||||
if ($scenario === 'approval_vs_reservation') {
|
||||
$jobs[1] = ['user' => $author, 'target' => $f['r']->id, 'payload' => ['action' => 'reserve']];
|
||||
}
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $author->tenant_id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach ($jobs as $index => $job) {
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/reinforcement-worker.php', $database, (string) $job['user']->id, (string) $job['target'], $index === 0 ? 'A' : 'B'], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode($job['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_reinforcement_A','sgc_reinforcement_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);
|
||||
$total = $budget->approvedTotalMinor();
|
||||
$reserved = (int) BudgetEntry::query()->sum('reserved_minor');
|
||||
$expectedTotal = $scenario === 'distinct_reinforcements' ? 19000 : 12000;
|
||||
$expectedReserved = $scenario === 'approval_vs_reservation' && $results[1]['status'] === 200 ? 10000 : 0;
|
||||
$validStatuses = $scenario === 'approval_vs_reservation' ? in_array($statuses, [[200, 200], [200, 422]], true) : $statuses === [200, 200];
|
||||
if (! $validStatuses || $results[0]['status'] !== 200 || $total !== $expectedTotal || $reserved !== $expectedReserved || $reserved > $total || BudgetReinforcement::query()->where('status', 'approved')->count() !== ($scenario === 'distinct_reinforcements' ? 2 : 1) || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
|
||||
throw new RuntimeException('Resultado concorrente de refor?os inesperado.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'approved_total_minor' => $total, 'reserved_minor' => $reserved, 'original_allocation_unchanged' => $budget->refresh()->amount_minor === 5000];
|
||||
}
|
||||
$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/reforcos-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,167 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Budget;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\BudgetReinforcement;
|
||||
use App\Models\User;
|
||||
use App\Services\BudgetReinforcementWorkflow;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->author = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($this->author);
|
||||
$this->budget = Budget::query()->create(['tenant_id' => $this->author->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 5000, 'includes_tax' => false, 'created_by' => $this->author->id, 'approved_by' => $this->reviewer->id, 'reason' => 'Dotação inicial de teste']);
|
||||
$this->data = ['reference' => 'REF TEST 01', 'amount' => '70.25', 'reason' => 'Reforço fictício definido pela empresa de teste'];
|
||||
});
|
||||
|
||||
function proposeTestReinforcement(object $test): BudgetReinforcement
|
||||
{
|
||||
$test->actingAs($test->author);
|
||||
|
||||
return app(BudgetReinforcementWorkflow::class)->propose($test->author, $test->budget, $test->data);
|
||||
}
|
||||
|
||||
function approveTestReinforcement(object $test, BudgetReinforcement $reinforcement, string $decision = 'approved'): void
|
||||
{
|
||||
$test->actingAs($test->reviewer);
|
||||
app(BudgetReinforcementWorkflow::class)->review($test->reviewer, $reinforcement, $decision, 'Decisão independente de teste');
|
||||
}
|
||||
|
||||
test('only approved reinforcement increases available budget without rewriting the original', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
expect($this->budget->approvedTotalMinor())->toBe(5000);
|
||||
approveTestReinforcement($this, $reinforcement);
|
||||
expect($this->budget->refresh()->amount_minor)->toBe(5000)
|
||||
->and($this->budget->includes_tax)->toBeFalse()
|
||||
->and($this->budget->approvedTotalMinor())->toBe(12025);
|
||||
$this->get('/orcamentos')->assertOk()->assertInertia(fn ($page) => $page->where('budgets.0.available_minor', 12025)->where('budgets.0.reinforced_minor', 7025));
|
||||
});
|
||||
|
||||
test('approved reinforcement enables a previously unaffordable procurement reservation', function () {
|
||||
expect(fn () => DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->author, $this->f['r'], 'reserve', 10000, 10000)))->toThrow(ValidationException::class);
|
||||
approveTestReinforcement($this, proposeTestReinforcement($this));
|
||||
$this->actingAs($this->author);
|
||||
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->author, $this->f['r'], 'reserve', 10000, 10000));
|
||||
expect((int) BudgetEntry::query()->sum('reserved_minor'))->toBe(10000);
|
||||
});
|
||||
|
||||
test('reinforcement proposals and approvals are idempotent', function () {
|
||||
$first = proposeTestReinforcement($this);
|
||||
$this->data['reference'] = ' ref test 01 ';
|
||||
expect(proposeTestReinforcement($this)->id)->toBe($first->id);
|
||||
approveTestReinforcement($this, $first);
|
||||
approveTestReinforcement($this, $first);
|
||||
expect(BudgetReinforcement::query()->count())->toBe(1)->and($this->budget->approvedTotalMinor())->toBe(12025);
|
||||
});
|
||||
|
||||
test('duplicate reference with changed values cannot create a second reinforcement', function () {
|
||||
proposeTestReinforcement($this);
|
||||
$this->data['amount'] = '71.00';
|
||||
expect(fn () => proposeTestReinforcement($this))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('proposer cannot approve own reinforcement', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
$this->post('/reforcos/'.$reinforcement->id.'/decidir', ['decision' => 'approved', 'reason' => 'Teste'])->assertForbidden();
|
||||
});
|
||||
|
||||
test('rejection leaves balance unchanged and is final', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
approveTestReinforcement($this, $reinforcement, 'rejected');
|
||||
expect($this->budget->approvedTotalMinor())->toBe(5000);
|
||||
expect(fn () => approveTestReinforcement($this, $reinforcement))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('reinforcement amount must be positive and technically representable', function (string $amount) {
|
||||
$this->data['amount'] = $amount;
|
||||
expect(fn () => proposeTestReinforcement($this))->toThrow(ValidationException::class);
|
||||
expect(BudgetReinforcement::query()->count())->toBe(0);
|
||||
})->with(['0.00', '-1.00', '1000000000000.00']);
|
||||
|
||||
test('foreign finance cannot inspect or approve another company reinforcement', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
$other = receiptFixture();
|
||||
$user = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($user)->post('/reforcos/'.$reinforcement->id.'/decidir', ['decision' => 'approved', 'reason' => 'Teste'])->assertNotFound();
|
||||
$this->get('/orcamentos')->assertOk()->assertInertia(fn ($page) => $page->has('reinforcements.data', 0));
|
||||
});
|
||||
|
||||
test('warehouse procurement and requesters cannot propose reinforcements', function (PurchasingRole $role) {
|
||||
$user = User::factory()->create(['tenant_id' => $this->author->tenant_id, 'purchasing_role' => $role]);
|
||||
$this->actingAs($user)->post('/orcamentos/'.$this->budget->id.'/reforcos', $this->data)->assertForbidden();
|
||||
})->with([PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Requester, PurchasingRole::DepartmentHead]);
|
||||
|
||||
test('reinforcement proposal and decision roll back on audit failure', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
|
||||
expect(fn () => approveTestReinforcement($this, $reinforcement))->toThrow(RuntimeException::class);
|
||||
expect($reinforcement->refresh()->status)->toBe('pending')->and($this->budget->approvedTotalMinor())->toBe(5000);
|
||||
$this->data['reference'] = 'REF TEST 02';
|
||||
expect(fn () => proposeTestReinforcement($this))->toThrow(RuntimeException::class);
|
||||
expect(BudgetReinforcement::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('reinforcement history cannot be rewritten or deleted', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
expect(fn () => $reinforcement->update(['amount_minor' => 999]))->toThrow(LogicException::class);
|
||||
expect(fn () => $reinforcement->refresh()->delete())->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('review rechecks current author eligibility', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
$this->author->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
|
||||
expect(fn () => approveTestReinforcement($this, $reinforcement))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('closed exercise prevents new reinforcement approval', function () {
|
||||
$reinforcement = proposeTestReinforcement($this);
|
||||
$this->travel(1)->years();
|
||||
expect(fn () => approveTestReinforcement($this, $reinforcement))->toThrow(ValidationException::class);
|
||||
$this->travelBack();
|
||||
});
|
||||
|
||||
test('unapproved initial allocation cannot receive reinforcement', function () {
|
||||
DB::table('budgets')->where('id', $this->budget->id)->update(['approved_by' => null]);
|
||||
$this->budget->refresh();
|
||||
expect(fn () => proposeTestReinforcement($this))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('current operator role is rechecked instead of trusting a stale session profile', function () {
|
||||
DB::table('users')->where('id', $this->author->id)->update(['purchasing_role' => 'warehouse']);
|
||||
$this->post('/orcamentos/'.$this->budget->id.'/reforcos', $this->data)->assertForbidden();
|
||||
});
|
||||
|
||||
test('browser cannot approve reinforcement or alter the parent allocation base', function () {
|
||||
$this->post('/orcamentos/'.$this->budget->id.'/reforcos', [...$this->data, 'status' => 'approved', 'includes_tax' => true, 'tenant_id' => PHP_INT_MAX, 'budget_id' => PHP_INT_MAX])->assertRedirect();
|
||||
expect(BudgetReinforcement::query()->firstOrFail()->status)->toBe('pending')
|
||||
->and($this->budget->refresh()->includes_tax)->toBeFalse()
|
||||
->and($this->budget->approvedTotalMinor())->toBe(5000);
|
||||
});
|
||||
|
||||
test('different companies may use their own identical reinforcement references and different amounts', function () {
|
||||
proposeTestReinforcement($this);
|
||||
$other = receiptFixture();
|
||||
$author = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($author);
|
||||
$budget = Budget::query()->create(['tenant_id' => $author->tenant_id, 'cost_center_id' => $other['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 2000, 'includes_tax' => true, 'created_by' => $author->id, 'approved_by' => $reviewer->id, 'reason' => 'Outra decisão fictícia']);
|
||||
$reinforcement = app(BudgetReinforcementWorkflow::class)->propose($author, $budget, [...$this->data, 'amount' => '10.01']);
|
||||
$this->actingAs($reviewer);
|
||||
app(BudgetReinforcementWorkflow::class)->review($reviewer, $reinforcement, 'approved', 'Outra decisão independente');
|
||||
expect($budget->approvedTotalMinor())->toBe(3001);
|
||||
$this->actingAs($this->author);
|
||||
expect($this->budget->approvedTotalMinor())->toBe(5000);
|
||||
});
|
||||
|
||||
test('public reinforcement example contains no company allocations', function () {
|
||||
auth()->forgetGuards();
|
||||
$this->get('/consulta/reforcos')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'reinforcements')->where('auth.user', null)->missing('budgets')->missing('reinforcements'));
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000013.
|
||||
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_000013_create_budget_reinforcements';
|
||||
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/reinforcement-000013-'.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, 'budget_reinforcements_count' => (int) $pdo->query('SELECT count(*) FROM budget_reinforcements')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/reforcos-migracao-000013.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