Implementa conferencia de facturas e consumo por empresa

This commit is contained in:
2026-10-28 14:26:18 +02:00
parent f86ecef44d
commit 332cb9f1b7
28 changed files with 1356 additions and 8 deletions
+30
View File
@@ -0,0 +1,30 @@
<?php
use App\Models\Invoice;
use App\Models\User;
use App\Services\InvoiceWorkflow;
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_invoice_'.$argv[4]]);
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
$user = User::query()->findOrFail($argv[2]);
auth()->guard()->setUser($user);
try {
app(InvoiceWorkflow::class)->validate($user, Invoice::query()->findOrFail($argv[3]));
$status = 200;
} catch (ValidationException) {
$status = 422;
}
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
+121
View File
@@ -0,0 +1,121 @@
<?php
use App\Models\BudgetConsumption;
use App\Models\BudgetEntry;
use App\Models\Invoice;
use App\Services\InvoiceWorkflow;
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/InvoiceFixture.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_invoice', 'same_validation', 'complementary_invoices'] as $scenario) {
$f = invoiceFixture();
$second = $f['invoice'];
if ($scenario !== 'same_validation') {
$data = $f['data'];
$data['number'] = 'FT-PG-2';
if ($scenario === 'complementary_invoices') {
$data['items'][0]['quantity'] = '0.400';
$data['subtotal'] = $data['total'] = '40.00';
}
$second = app(InvoiceWorkflow::class)->register($f['author'], $f['order'], $data);
}
$connection = DB::connection();
$connection->beginTransaction();
$connection->table('tenants')->where('id', $f['tenant']->id)->lockForUpdate()->first();
$processes = [];
foreach ([$f['invoice'], $second] as $index => $invoice) {
$process = new Process([PHP_BINARY, __DIR__.'/invoice-worker.php', $database, (string) $f['validator']->id, (string) $invoice->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_invoice_A','sgc_invoice_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');
$expectedConsumption = $scenario === 'complementary_invoices' ? 10000 : 6000;
$count = $scenario === 'complementary_invoices' ? 2 : 1;
if ($statuses !== ($scenario === 'over_invoice' ? [200, 422] : [200, 200]) || $consumed !== $expectedConsumption || $committed !== 10000 - $expectedConsumption || BudgetConsumption::query()->count() !== $count || Invoice::query()->where('status', 'validated')->count() !== $count || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
throw new RuntimeException('Resultado inesperado: '.json_encode([$statuses, $consumed, $committed]));
}
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'consumed_minor' => $consumed, 'committed_minor' => $committed, 'validated_invoices' => $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/facturas-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;
+195
View File
@@ -0,0 +1,195 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\BudgetConsumption;
use App\Models\BudgetEntry;
use App\Models\Invoice;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\ConflictGuard;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptWorkflow;
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->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->validator = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->actingAs($this->finance);
$this->budget = Budget::query()->create(['tenant_id' => $this->finance->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 20000, 'includes_tax' => true, 'created_by' => $this->finance->id, 'approved_by' => $this->validator->id, 'reason' => 'Fixture financeira isolada']);
DB::transaction(function () {
app(ConflictGuard::class)->lockCompany($this->finance);
app(BudgetWorkflow::class)->record($this->finance, $this->f['r'], 'reserve', 10000, 10000);
app(BudgetWorkflow::class)->record($this->finance, $this->f['r'], 'commit', 10000, 10000);
});
$this->data = ['number' => 'FT TEST 01', 'issued_on' => today()->format('Y-m-d'), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00', 'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '0.600', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']]];
});
function registerTestInvoice(object $test): Invoice
{
$test->actingAs($test->finance);
return app(InvoiceWorkflow::class)->register($test->finance, $test->f['order'], $test->data);
}
test('partial invoice converts commitment to consumption exactly once', function () {
$invoice = registerTestInvoice($this);
expect(BudgetConsumption::query()->count())->toBe(0);
$this->actingAs($this->validator);
app(InvoiceWorkflow::class)->validate($this->validator, $invoice);
app(InvoiceWorkflow::class)->validate($this->validator, $invoice);
expect($invoice->refresh()->status)->toBe('validated')
->and((int) BudgetEntry::query()->sum('committed_minor'))->toBe(4000)
->and((int) BudgetConsumption::query()->sum('amount_minor'))->toBe(6000)
->and(BudgetConsumption::query()->count())->toBe(1);
$this->get('/orcamentos')->assertOk()->assertInertia(fn ($page) => $page->where('budgets.0.available_minor', 10000)->where('budgets.0.consumed_minor', 6000));
});
test('author cannot validate own invoice', function () {
$invoice = registerTestInvoice($this);
$this->post('/facturas/'.$invoice->id.'/validar')->assertForbidden();
expect(BudgetConsumption::query()->count())->toBe(0);
});
test('number normalized per supplier prevents duplicates', function () {
registerTestInvoice($this);
$this->data['number'] = ' ft test 01 ';
expect(fn () => registerTestInvoice($this))->toThrow(ValidationException::class);
expect(Invoice::query()->count())->toBe(1);
});
test('differences in invoice values block registration', function (string $field) {
if (in_array($field, ['unit_price', 'tax_rate', 'unit', 'quantity'])) {
$this->data['items'][0][$field] = match ($field) {
'unit_price' => '101.00', 'tax_rate' => '16', 'unit' => 'un', default => '1.001'
};
} else {
$this->data[$field] = '61.00';
}
expect(fn () => registerTestInvoice($this))->toThrow(ValidationException::class);
expect(Invoice::query()->count())->toBe(0);
})->with(['unit_price', 'tax_rate', 'unit', 'quantity', 'subtotal', 'tax', 'total']);
test('pending overlapping invoices are rechecked at independent validation', function () {
$first = registerTestInvoice($this);
$this->data['number'] = 'FT TEST 02';
$second = registerTestInvoice($this);
$this->actingAs($this->validator);
app(InvoiceWorkflow::class)->validate($this->validator, $first);
expect(fn () => app(InvoiceWorkflow::class)->validate($this->validator, $second))->toThrow(ValidationException::class);
expect($second->refresh()->status)->toBe('pending')->and(BudgetConsumption::query()->count())->toBe(1);
});
test('failed audit rolls back invoice validation and consumption', function () {
$invoice = registerTestInvoice($this);
$this->actingAs($this->validator);
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
expect(fn () => app(InvoiceWorkflow::class)->validate($this->validator, $invoice))->toThrow(RuntimeException::class);
expect($invoice->refresh()->status)->toBe('pending')->and(BudgetConsumption::query()->count())->toBe(0)
->and((int) BudgetEntry::query()->sum('committed_minor'))->toBe(10000);
});
test('foreign finance cannot read or validate invoice', function () {
$invoice = registerTestInvoice($this);
$other = receiptFixture();
$user = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($user)->post('/facturas/'.$invoice->id.'/validar')->assertNotFound();
$this->get('/facturas')->assertOk()->assertInertia(fn ($page) => $page->has('invoices.data', 0));
});
test('warehouse cannot access or register invoices', function () {
$this->actingAs($this->f['receiver'])->get('/facturas')->assertForbidden();
$this->post('/ordens/'.$this->f['order']->id.'/facturas', $this->data)->assertForbidden();
});
test('registered documents cannot be rewritten or deleted', function () {
$invoice = registerTestInvoice($this);
expect(fn () => $invoice->update(['total_minor' => 1]))->toThrow(LogicException::class);
expect(fn () => $invoice->items()->firstOrFail()->delete())->toThrow(LogicException::class);
expect(fn () => $invoice->refresh()->delete())->toThrow(LogicException::class);
});
test('complementary invoices consume the exact commitment without increasing available budget', function () {
$first = registerTestInvoice($this);
$this->actingAs($this->validator);
app(InvoiceWorkflow::class)->validate($this->validator, $first);
$this->data['number'] = 'FT TEST 02';
$this->data['items'][0]['quantity'] = '0.400';
$this->data['subtotal'] = $this->data['total'] = '40.00';
$second = registerTestInvoice($this);
$this->actingAs($this->validator);
app(InvoiceWorkflow::class)->validate($this->validator, $second);
expect((int) BudgetEntry::query()->sum('committed_minor'))->toBe(0)
->and((int) BudgetConsumption::query()->sum('amount_minor'))->toBe(10000);
$request = $this->f['r']->replicate();
$request->number = 'REQ-SECOND';
$request->save();
expect(fn () => DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->validator, $request, 'reserve', 10001, 10001)))->toThrow(ValidationException::class);
});
test('invoice without a committed budget remains pending', function () {
$other = receiptFixture();
app(ReceiptWorkflow::class)->confirm($other['receiver'], $other['order'], receiptPayload($other, '1.000'));
$author = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$validator = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($author);
$data = $this->data;
$data['items'][0]['purchase_order_item_id'] = $other['line']->id;
$invoice = app(InvoiceWorkflow::class)->register($author, $other['order'], $data);
$this->actingAs($validator);
expect(fn () => app(InvoiceWorkflow::class)->validate($validator, $invoice))->toThrow(ValidationException::class);
expect($invoice->refresh()->status)->toBe('pending')->and(BudgetConsumption::query()->count())->toBe(0);
});
test('future invoice date and foreign order line are rejected', function (string $case) {
if ($case === 'future') {
$this->data['issued_on'] = today()->addDay()->format('Y-m-d');
} else {
$this->data['items'][0]['purchase_order_item_id'] = PHP_INT_MAX;
}
expect(fn () => registerTestInvoice($this))->toThrow(ValidationException::class);
})->with(['future', 'foreign_line']);
test('reception acceptance is required before invoicing services', function () {
$other = receiptFixture('1.000', 'service');
$author = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($author);
$data = $this->data;
$data['items'][0]['purchase_order_item_id'] = $other['line']->id;
expect(fn () => app(InvoiceWorkflow::class)->register($author, $other['order'], $data))->toThrow(ValidationException::class);
});
test('partial invoices preserve cents and VAT across cumulative rounding', function () {
// Configure only the isolated frozen-order fixture before registering any invoice.
DB::table('purchase_order_items')->where('id', $this->f['line']->id)->update(['unit_price_minor' => 10001, 'tax_rate' => '16.00', 'subtotal_minor' => 10001, 'tax_minor' => 1600, 'total_minor' => 11601]);
DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['subtotal_minor' => 10001, 'tax_minor' => 1600, 'total_minor' => 11601]);
DB::table('budget_entries')->where('requisition_id', $this->f['r']->id)->where('kind', 'commit')->update(['committed_minor' => 11601]);
foreach ([['0.333', '33.30', '5.33', '38.63'], ['0.333', '33.31', '5.33', '38.64'], ['0.334', '33.40', '5.34', '38.74']] as $index => [$quantity, $subtotal, $tax, $total]) {
$this->data['number'] = 'FT-ROUND-'.$index;
$this->data['items'][0]['quantity'] = $quantity;
$this->data['items'][0]['unit_price'] = '100.01';
$this->data['items'][0]['tax_rate'] = '16';
$this->data['subtotal'] = $subtotal;
$this->data['tax'] = $tax;
$this->data['total'] = $total;
$invoice = registerTestInvoice($this);
$this->actingAs($this->validator);
app(InvoiceWorkflow::class)->validate($this->validator, $invoice);
}
expect((int) Invoice::query()->sum('subtotal_minor'))->toBe(10001)
->and((int) Invoice::query()->sum('tax_minor'))->toBe(1600)
->and((int) BudgetConsumption::query()->sum('amount_minor'))->toBe(11601)
->and((int) BudgetEntry::query()->sum('committed_minor'))->toBe(0);
});
test('public invoice example is available without exposing company invoices', function () {
auth()->forgetGuards();
$this->get('/consulta/facturas')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'invoices')->where('auth.user', null)->missing('invoices')->missing('orders'));
});
+32
View File
@@ -0,0 +1,32 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\ConflictGuard;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptWorkflow;
use Illuminate\Support\Facades\DB;
require_once __DIR__.'/ReceiptFixture.php';
/** Synthetic data: receiptFixture enforces an isolated test database. */
function invoiceFixture(): array
{
$f = receiptFixture();
app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f, '1.000'));
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$validator = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
auth()->guard()->setUser($author);
Budget::query()->create(['tenant_id' => $author->tenant_id, 'cost_center_id' => $f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 20000, 'includes_tax' => true, 'created_by' => $author->id, 'approved_by' => $validator->id, 'reason' => 'Somente para teste isolado']);
DB::transaction(function () use ($author, $f) {
app(ConflictGuard::class)->lockCompany($author);
app(BudgetWorkflow::class)->record($author, $f['r'], 'reserve', 10000, 10000);
app(BudgetWorkflow::class)->record($author, $f['r'], 'commit', 10000, 10000);
});
$data = ['number' => 'FT-PG-1', 'issued_on' => today()->format('Y-m-d'), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00', 'items' => [['purchase_order_item_id' => $f['line']->id, 'quantity' => '0.600', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']]];
$invoice = app(InvoiceWorkflow::class)->register($author, $f['order'], $data);
return [...$f, 'author' => $author, 'validator' => $validator, 'invoice' => $invoice, 'data' => $data];
}
+105
View File
@@ -0,0 +1,105 @@
<?php
// Explicit operational entry point: backup, restore verification, then only migration 000010.
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_000010_create_invoices';
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/invoice-000010-'.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, 'invoices_count' => (int) $pdo->query('SELECT count(*) FROM invoices')->fetchColumn(), 'budget_consumptions_count' => (int) $pdo->query('SELECT count(*) FROM budget_consumptions')->fetchColumn(), 'operational_validation' => false];
file_put_contents(base_path('docs/facturas-migracao-000010.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));
}
}