Implementa recomendação formal com adopção e conferência independente
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
use App\Models\RecommendationAttempt;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\FormalRecommendation;
|
||||
use App\Services\PurchaseWorkflow;
|
||||
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_recommendation_'.$argv[4]]);
|
||||
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
|
||||
$actor = User::query()->findOrFail($argv[2]);
|
||||
auth()->guard()->setUser($actor);
|
||||
$payload = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
if (($payload['action'] ?? 'review') === 'propose') {
|
||||
app(FormalRecommendation::class)->propose($actor, Requisition::query()->findOrFail($payload['requisition_id']), $payload['data']);
|
||||
} elseif ($payload['action'] === 'award') {
|
||||
app(PurchaseWorkflow::class)->select($actor, Requisition::query()->findOrFail($payload['requisition_id']), $payload['data']);
|
||||
} else {
|
||||
app(FormalRecommendation::class)->review($actor, RecommendationAttempt::query()->findOrFail($argv[3]), $payload['verdict'], 'Conferência exclusivamente fictícia');
|
||||
}
|
||||
$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,161 @@
|
||||
<?php
|
||||
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\RecommendationAttempt;
|
||||
use App\Models\RecommendationReview;
|
||||
use App\Services\FormalRecommendation;
|
||||
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/RecommendationFixture.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_person', 'distinct_people', 'opposing_reviews', 'revoked_role', 'changed_basis', 'new_adoption', 'competing_attempts', 'recommendation_versus_award'] as $scenario) {
|
||||
$f = recommendationFixture(2);
|
||||
$workflow = app(FormalRecommendation::class);
|
||||
$decision = $workflow->propose($f['buyer'], $f['r'], $f['proposal']);
|
||||
if ($scenario === 'recommendation_versus_award') {
|
||||
foreach ([$f['reviewer'], $f['other_reviewer']] as $reviewer) {
|
||||
auth()->guard()->setUser($reviewer);
|
||||
$workflow->review($reviewer, $decision, 'approved', 'Confirmação fictícia antes da corrida');
|
||||
}
|
||||
auth()->guard()->setUser($f['buyer']);
|
||||
}
|
||||
$beforeReviews = RecommendationReview::query()->count();
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $f['tenant']->id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach (['A', 'B'] as $index => $suffix) {
|
||||
$actor = $scenario === 'distinct_people' && $index === 1 ? $f['other_reviewer'] : $f['reviewer'];
|
||||
$verdict = $scenario === 'opposing_reviews' && $index === 1 ? 'returned' : 'approved';
|
||||
$payload = ['action' => 'review', 'verdict' => $verdict];
|
||||
if (in_array($scenario, ['competing_attempts', 'recommendation_versus_award'], true)) {
|
||||
$actor = $f['buyer'];
|
||||
$award = $scenario === 'recommendation_versus_award' && $index === 1;
|
||||
$payload = ['action' => $award ? 'award' : 'propose', 'requisition_id' => $f['r']->id, 'data' => $award ? $f['selection'] : [...$f['proposal'], 'previous_id' => $decision->id]];
|
||||
}
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/recommendation-worker.php', $database, (string) $actor->id, (string) $decision->id, $suffix], 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_recommendation_A','sgc_recommendation_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 ($waits !== 2) {
|
||||
throw new RuntimeException('Sem sobreposição dos dois bloqueios.');
|
||||
}
|
||||
if ($scenario === 'revoked_role') {
|
||||
$connection->table('users')->where('id', $f['reviewer']->id)->update(['purchasing_role' => 'requester']);
|
||||
}
|
||||
if ($scenario === 'changed_basis') {
|
||||
$connection->table('proposal_evaluations')->where('quotation_id', $f['quote']->id)->update(['comment' => 'Alteração fictícia durante a espera']);
|
||||
}
|
||||
if ($scenario === 'new_adoption') {
|
||||
auth()->guard()->setUser($f['admin']);
|
||||
$policy = $workflow->policy($f['admin'], [...$f['policy_data'], 'previous_id' => $f['policy']->id]);
|
||||
auth()->guard()->setUser($f['buyer']);
|
||||
$workflow->adopt($f['buyer'], $f['r'], $policy->id, $f['adoption']->id, 'Nova adopção enquanto os conferentes aguardam');
|
||||
}
|
||||
$connection->commit();
|
||||
$results = [];
|
||||
foreach ($processes as $process) {
|
||||
$process->wait();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Worker falhou: '.$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', 'new_adoption' => [422, 422], 'opposing_reviews', 'competing_attempts', 'recommendation_versus_award' => [200, 422], default => [200, 200]
|
||||
};
|
||||
auth()->guard()->setUser($f['buyer']);
|
||||
$reviews = RecommendationReview::query()->count();
|
||||
$expectedReviews = match ($scenario) {
|
||||
'distinct_people' => 2, 'same_person', 'opposing_reviews' => 1, default => 0
|
||||
};
|
||||
$expectedReviews += $beforeReviews;
|
||||
if ($statuses !== $expected || $reviews !== $expectedReviews || AuditLog::query()->where('action', 'recommendation.reviewed')->count() !== $reviews || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
|
||||
throw new RuntimeException('Resultado concorrente inconsistente: '.json_encode([$scenario, $statuses, $reviews], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
$state = $workflow->status($decision, $f['adoption']);
|
||||
$attempts = RecommendationAttempt::query()->count();
|
||||
$awards = PurchaseAward::query()->count();
|
||||
$newAttempt = $scenario === 'competing_attempts' || ($scenario === 'recommendation_versus_award' && $results[0]['status'] === 200);
|
||||
if (($scenario === 'distinct_people' && $state !== 'confirmed') || ($scenario === 'same_person' && $state !== 'pending') || $attempts !== ($newAttempt ? 2 : 1) || $awards !== ($scenario === 'recommendation_versus_award' && ! $newAttempt ? 1 : 0)) {
|
||||
throw new RuntimeException('Quórum ou tentativa alterados indevidamente.');
|
||||
}
|
||||
if ($awards && PurchaseAward::query()->sole()->recommendation_snapshot['attempt_id'] !== $decision->id) {
|
||||
throw new RuntimeException('Adjudicação ligada à tentativa errada.');
|
||||
}
|
||||
if (AuditLog::query()->where('action', 'recommendation.proposed')->count() !== $attempts || AuditLog::query()->where('action', 'award.created')->count() !== $awards) {
|
||||
throw new RuntimeException('Auditoria de tentativa/adjudicação inconsistente.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'reviews' => $reviews, 'state' => $state, 'attempts' => $attempts, 'awards' => $awards];
|
||||
}
|
||||
$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/recomendacao-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,275 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AdmissionDecision;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\ConflictDeclaration;
|
||||
use App\Models\Department;
|
||||
use App\Models\ProposalEvaluation;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\RecommendationAdoption;
|
||||
use App\Models\RecommendationAttempt;
|
||||
use App\Models\RecommendationPolicy;
|
||||
use App\Models\RecommendationReview;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\FormalAdmission;
|
||||
use App\Services\FormalRecommendation;
|
||||
use App\Services\ProposalComparison;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/RecommendationFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = recommendationFixture();
|
||||
$this->url = '/requisicoes/'.$this->f['r']->id.'/recomendacao';
|
||||
$this->awardUrl = '/requisicoes/'.$this->f['r']->id.'/adjudicacao';
|
||||
$this->actingAs($this->f['buyer']);
|
||||
});
|
||||
|
||||
function recommendationAttempt(object $test, array $changes = []): RecommendationAttempt
|
||||
{
|
||||
$test->actingAs($test->f['buyer'])->post($test->url.'/tentativas', [...$test->f['proposal'], ...$changes])->assertSessionHasNoErrors();
|
||||
|
||||
return RecommendationAttempt::query()->latest('id')->firstOrFail();
|
||||
}
|
||||
|
||||
function recommendationConfer(object $test, RecommendationAttempt $attempt, ?User $actor = null, string $verdict = 'approved'): void
|
||||
{
|
||||
$test->actingAs($actor ?? $test->f['reviewer'])->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => $verdict, 'reason' => 'Conferência de recomendação fictícia'])->assertSessionHasNoErrors();
|
||||
}
|
||||
|
||||
test('company recommendation requires quorum and binds genuine award and issued order', function () {
|
||||
$before = app(ProposalComparison::class)->inspect($this->f['r']);
|
||||
$attempt = recommendationAttempt($this);
|
||||
$this->get($this->awardUrl)->assertInertia(fn (Assert $p) => $p->where('canSelect', false));
|
||||
$this->post($this->awardUrl, $this->f['selection'])->assertSessionHasErrors('recommendation');
|
||||
recommendationConfer($this, $attempt);
|
||||
expect(app(FormalRecommendation::class)->status($attempt, $this->f['adoption']))->toBe('pending')->and(BudgetEntry::query()->count())->toBe(0);
|
||||
recommendationConfer($this, $attempt, $this->f['head']);
|
||||
expect(app(ProposalComparison::class)->inspect($this->f['r']))->toBe($before);
|
||||
$this->actingAs($this->f['buyer'])->post($this->awardUrl, $this->f['selection'])->assertSessionHasNoErrors();
|
||||
$award = PurchaseAward::query()->sole();
|
||||
expect($award->recommendation_snapshot['attempt_id'])->toBe($attempt->id)->and($award->recommendation_snapshot['review_ids'])->toHaveCount(2);
|
||||
$this->actingAs($this->f['head'])->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
||||
$this->actingAs($this->f['buyer'])->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
expect($order->snapshot['recommendation'])->toBe($award->recommendation_snapshot);
|
||||
$this->f['quotes'][0]->update(['reference' => 'Alteração posterior à emissão']);
|
||||
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
||||
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->refresh()->snapshot['quotation']['reference'])->toBe('PROP-TEST');
|
||||
$this->post($this->url.'/tentativas', [...$this->f['proposal'], 'previous_id' => $attempt->id])->assertSessionHasErrors('recommendation');
|
||||
});
|
||||
|
||||
test('recommendation retries count one person once and returned attempt cannot authorize award', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
recommendationConfer($this, $attempt);
|
||||
expect(RecommendationReview::query()->count())->toBe(1)->and(AuditLog::query()->where('action', 'recommendation.reviewed')->count())->toBe(1);
|
||||
$this->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'returned', 'reason' => 'Outra resposta para a mesma pessoa'])->assertSessionHasErrors('recommendation');
|
||||
recommendationConfer($this, $attempt, $this->f['other_reviewer'], 'returned');
|
||||
expect(app(FormalRecommendation::class)->status($attempt, $this->f['adoption']))->toBe('returned')->and(AdmissionDecision::query()->where('outcome', 'admit')->count())->toBe(3);
|
||||
$next = recommendationAttempt($this, ['previous_id' => $attempt->id]);
|
||||
expect($next->revision)->toBe(2)->and(RecommendationReview::query()->where('recommendation_attempt_id', $next->id)->count())->toBe(0);
|
||||
$this->post($this->url.'/tentativas', $this->f['proposal'])->assertSessionHasErrors('recommendation');
|
||||
$this->actingAs($this->f['head'])->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência de tentativa anterior'])->assertSessionHasErrors('recommendation');
|
||||
$this->actingAs($this->f['buyer'])->post($this->awardUrl, $this->f['selection'])->assertSessionHasErrors('recommendation');
|
||||
});
|
||||
|
||||
test('recommendation rejects lower score incomplete matrix and stale admission', function (string $case) {
|
||||
if ($case === 'incomplete') {
|
||||
ProposalEvaluation::query()->where('quotation_id', $this->f['quotes'][0]->id)->where('evaluator_id', $this->f['analyst']->id)->delete();
|
||||
} elseif ($case === 'admission') {
|
||||
$old = AdmissionDecision::query()->where('quotation_id', $this->f['quotes'][0]->id)->latest('id')->firstOrFail();
|
||||
app(FormalAdmission::class)->propose($this->f['buyer'], $this->f['r'], ['quotation_id' => $old->quotation_id, 'previous_id' => $old->id, 'basis_hash' => $old->basis_hash, 'outcome' => 'admit', 'reason' => 'Nova tentativa de admissão sem confirmação']);
|
||||
}
|
||||
$data = [...$this->f['proposal'], 'basis_hash' => app(FormalRecommendation::class)->basis($this->f['r'])['hash']];
|
||||
if ($case === 'lower') {
|
||||
$data['quotation_id'] = $this->f['quotes'][2]->id;
|
||||
}
|
||||
$this->post($this->url.'/tentativas', $data)->assertSessionHasErrors('recommendation');
|
||||
expect(RecommendationAttempt::query()->count())->toBe(0);
|
||||
})->with(['lower', 'incomplete', 'admission']);
|
||||
|
||||
test('tie permits reasoned recommendation and award only of the chosen tied proposal', function () {
|
||||
// Only evaluations change, preserving documentary admission basis.
|
||||
ProposalEvaluation::query()->where('quotation_id', $this->f['quotes'][0]->id)->update(['quality' => '0', 'history' => '0', 'payment' => '0']);
|
||||
ProposalEvaluation::query()->where('quotation_id', $this->f['quotes'][1]->id)->update(['quality' => '5', 'history' => '5', 'payment' => '2.5']);
|
||||
// Existing weights yield 5.50 for each of the first two proposals, without changing received prices.
|
||||
$this->f['quotes'][2]->evaluations()->update(['quality' => '0', 'history' => '0', 'payment' => '0']);
|
||||
$basis = app(FormalRecommendation::class)->basis($this->f['r']);
|
||||
expect($basis['ready'])->toBeTrue()->and($basis['top_ids'])->toHaveCount(2)->toContain($this->f['quotes'][0]->id, $this->f['quotes'][1]->id);
|
||||
$attempt = recommendationAttempt($this, ['basis_hash' => $basis['hash'], 'quotation_id' => $this->f['quotes'][1]->id, 'reason' => 'Escolha fundamentada da segunda proposta empatada']);
|
||||
recommendationConfer($this, $attempt);
|
||||
recommendationConfer($this, $attempt, $this->f['other_reviewer']);
|
||||
$this->actingAs($this->f['buyer'])->post($this->awardUrl, $this->f['selection'])->assertSessionHasErrors('recommendation');
|
||||
$this->post($this->awardUrl, [...$this->f['selection'], 'quotation_id' => $this->f['quotes'][1]->id])->assertSessionHasNoErrors();
|
||||
expect(PurchaseAward::query()->sole()->quotation_id)->toBe($this->f['quotes'][1]->id);
|
||||
});
|
||||
|
||||
test('changed matrix invalidates pending reviews and blocks emission after award', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
recommendationConfer($this, $attempt, $this->f['head']);
|
||||
$this->actingAs($this->f['buyer'])->post($this->awardUrl, $this->f['selection'])->assertSessionHasNoErrors();
|
||||
$award = PurchaseAward::query()->sole();
|
||||
$this->actingAs($this->f['head'])->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
||||
ProposalEvaluation::query()->where('quotation_id', $this->f['quotes'][2]->id)->update(['comment' => 'Análise alterada antes da emissão']);
|
||||
$this->actingAs($this->f['buyer'])->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('recommendation');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('changed evaluation requires a new recommendation with no inherited approvals', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
ProposalEvaluation::query()->where('quotation_id', $this->f['quotes'][1]->id)->update(['comment' => 'Nova fundamentação da avaliação']);
|
||||
$this->actingAs($this->f['other_reviewer'])->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência sobre uma base anterior'])->assertSessionHasErrors('recommendation');
|
||||
$next = recommendationAttempt($this, ['previous_id' => $attempt->id, 'basis_hash' => app(FormalRecommendation::class)->basis($this->f['r'])['hash']]);
|
||||
expect($next->revision)->toBe(2)->and(RecommendationReview::query()->where('recommendation_attempt_id', $next->id)->count())->toBe(0)->and(RecommendationReview::query()->where('recommendation_attempt_id', $attempt->id)->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('new confirmed admission invalidates recommendation even with identical scores and prices', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
recommendationConfer($this, $attempt, $this->f['other_reviewer']);
|
||||
$before = app(ProposalComparison::class)->inspect($this->f['r']);
|
||||
$this->actingAs($this->f['buyer']);
|
||||
$admission = app(FormalAdmission::class);
|
||||
$old = AdmissionDecision::query()->where('quotation_id', $this->f['quotes'][1]->id)->latest('id')->firstOrFail();
|
||||
$new = $admission->propose($this->f['buyer'], $this->f['r'], ['quotation_id' => $old->quotation_id, 'previous_id' => $old->id, 'basis_hash' => $old->basis_hash, 'outcome' => 'admit', 'reason' => 'Reapreciação de admissão fundamentada']);
|
||||
$this->actingAs($this->f['analyst']);
|
||||
$admission->review($this->f['analyst'], $new, 'approved', 'Nova conferência de admissão fictícia');
|
||||
expect(app(ProposalComparison::class)->inspect($this->f['r']))->toBe($before);
|
||||
$this->actingAs($this->f['buyer'])->post($this->awardUrl, $this->f['selection'])->assertSessionHasErrors('recommendation');
|
||||
expect(PurchaseAward::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('one identity cannot count again after role change and review audit failure rolls back', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
$this->f['reviewer']->forceFill(['purchasing_role' => PurchasingRole::DepartmentHead, 'department_id' => $this->f['r']->department_id])->save();
|
||||
recommendationConfer($this, $attempt, $this->f['reviewer']->fresh());
|
||||
expect(RecommendationReview::query()->count())->toBe(1)->and(RecommendationReview::query()->sole()->snapshot['purchasing_role'])->toBe('finance');
|
||||
$this->actingAs($this->f['head']);
|
||||
DB::statement("CREATE TRIGGER fail_recommendation_review BEFORE INSERT ON audit_logs WHEN NEW.action = 'recommendation.reviewed' BEGIN SELECT RAISE(ABORT, 'test audit failure'); END");
|
||||
try {
|
||||
app(FormalRecommendation::class)->review($this->f['head'], $attempt, 'approved', 'Confirmação que deve ser revertida');
|
||||
$this->fail('Missing conference rollback');
|
||||
} catch (QueryException) {
|
||||
expect(RecommendationReview::query()->count())->toBe(1)->and(app(FormalRecommendation::class)->status($attempt, $this->f['adoption']))->toBe('pending');
|
||||
} finally {
|
||||
DB::statement('DROP TRIGGER fail_recommendation_review');
|
||||
}
|
||||
$other = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra chefia']);
|
||||
$this->f['reviewer']->forceFill(['department_id' => $other->id])->save();
|
||||
$this->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferente anterior mudou de departamento'])->assertSessionHasErrors('recommendation');
|
||||
});
|
||||
|
||||
test('current and earlier reviewer eligibility is revalidated while completed history remains', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
$this->f['reviewer']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
$this->actingAs($this->f['other_reviewer'])->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Primeiro conferente perdeu o perfil'])->assertSessionHasErrors('recommendation');
|
||||
$this->f['other_reviewer']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
$this->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'returned', 'reason' => 'Perfil revogado durante a sessão'])->assertForbidden();
|
||||
$this->f['reviewer']->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
recommendationConfer($this, $attempt, $this->f['head']);
|
||||
$this->f['reviewer']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
expect(app(FormalRecommendation::class)->selection($this->f['r'], $attempt->quotation_id)['review_ids'])->toHaveCount(2);
|
||||
});
|
||||
|
||||
test('proponent requester and wrong department cannot confirm recommendations', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
$this->f['buyer']->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->actingAs($this->f['buyer']->fresh())->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Auto confirmação indevida'])->assertForbidden();
|
||||
$this->f['issuer']->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->actingAs($this->f['issuer'])->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Solicitante não pode conferir'])->assertForbidden();
|
||||
$other = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Departamento distinto']);
|
||||
$this->f['head']->forceFill(['department_id' => $other->id])->save();
|
||||
$this->actingAs($this->f['head'])->get($this->url)->assertNotFound();
|
||||
$this->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Chefia de outro departamento'])->assertNotFound();
|
||||
expect(RecommendationReview::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('policy changes preserve adoption until explicit new version and reset recommendations', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
recommendationConfer($this, $attempt);
|
||||
$workflow = app(FormalRecommendation::class);
|
||||
$this->actingAs($this->f['admin']);
|
||||
$disabled = $workflow->policy($this->f['admin'], [...$this->f['policy_data'], 'previous_id' => $this->f['policy']->id, 'required_count' => 1, 'enabled' => false]);
|
||||
$this->actingAs($this->f['buyer'])->post($this->url.'/adoptar', ['previous_id' => $this->f['adoption']->id, 'policy_id' => $disabled->id, 'reason' => 'Adopção com política desactivada'])->assertSessionHasErrors('recommendation');
|
||||
recommendationConfer($this, $attempt, $this->f['other_reviewer']);
|
||||
expect($workflow->status($attempt, $this->f['adoption']))->toBe('confirmed')->and($this->f['adoption']->refresh()->snapshot['required_count'])->toBe(2);
|
||||
$this->actingAs($this->f['admin']);
|
||||
$new = $workflow->policy($this->f['admin'], [...$this->f['policy_data'], 'previous_id' => $disabled->id, 'required_count' => 1]);
|
||||
$this->actingAs($this->f['buyer']);
|
||||
$workflow->adopt($this->f['buyer'], $this->f['r'], $new->id, $this->f['adoption']->id, 'Outra versão expressamente adoptada');
|
||||
$this->post($this->awardUrl, $this->f['selection'])->assertSessionHasErrors('recommendation');
|
||||
expect(RecommendationAttempt::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('policy is admin only explicit and independent from admission and absent adoption keeps legacy circuit', function () {
|
||||
$this->post('/politica-recomendacao', $this->f['policy_data'])->assertForbidden();
|
||||
$this->actingAs($this->f['admin'])->post('/politica-recomendacao', ['previous_id' => $this->f['policy']->id, 'enabled' => true, 'roles' => [], 'reason' => 'Sem valores definidos pela empresa'])->assertSessionHasErrors(['roles', 'required_count']);
|
||||
$this->post('/politica-recomendacao', $this->f['policy_data'])->assertSessionHasErrors('recommendation');
|
||||
$this->get('/politica-recomendacao')->assertInertia(fn (Assert $p) => $p->component('purchases/recommendation-policy')->has('policies.data', 1));
|
||||
// Remove only synthetic adoption from the isolated test DB to exercise the legacy path.
|
||||
DB::table('recommendation_adoptions')->delete();
|
||||
$this->actingAs($this->f['buyer'])->post($this->awardUrl, $this->f['selection'])->assertSessionHasNoErrors();
|
||||
$award = PurchaseAward::query()->sole();
|
||||
expect($award->recommendation_snapshot)->toBeNull();
|
||||
$this->post($this->url.'/adoptar', ['policy_id' => $this->f['policy']->id, 'previous_id' => 0, 'reason' => 'Adopção retroactiva impedida'])->assertSessionHasErrors('recommendation');
|
||||
});
|
||||
|
||||
test('recommendation requires prior formal admission adoption and no implicit policy', function () {
|
||||
// All fixture rows belong only to this in-memory database.
|
||||
DB::table('recommendation_adoptions')->delete();
|
||||
DB::table('admission_reviews')->delete();
|
||||
DB::table('admission_decisions')->delete();
|
||||
DB::table('admission_adoptions')->delete();
|
||||
$this->post($this->url.'/adoptar', ['policy_id' => $this->f['policy']->id, 'previous_id' => 0, 'reason' => 'Sem adopção formal de admissão'])->assertSessionHasErrors('recommendation');
|
||||
expect(RecommendationAdoption::query()->count())->toBe(0)->and(RecommendationPolicy::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('report and history are restricted read only preserve old basis and escape user text', function () {
|
||||
$attempt = recommendationAttempt($this, ['reason' => '<script>alert("ficticio")</script>Fundamento fictício']);
|
||||
recommendationConfer($this, $attempt, null, 'returned');
|
||||
$next = recommendationAttempt($this, ['previous_id' => $attempt->id]);
|
||||
$before = AuditLog::query()->count();
|
||||
$this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $p) => $p->component('purchases/recommendation')->where('history.data.0.id', $next->id)->where('history.data.1.status', 'returned')->where('basis.ready', true));
|
||||
$this->get('/recomendacoes/'.$next->id.'/imprimir')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertSee('Sistema de Gestão de Compras (SGC)')->assertSee('Histórico desta adopção')->assertSee('<script>', false)->assertDontSee('<script>alert', false);
|
||||
$this->f['quotes'][0]->update(['reference' => 'Referência actual diferente']);
|
||||
$this->get('/recomendacoes/'.$attempt->id.'/imprimir')->assertOk()->assertSee('Histórica ou base desactualizada')->assertSee('PROP-TEST')->assertDontSee('Referência actual diferente');
|
||||
expect(AuditLog::query()->count())->toBe($before);
|
||||
$this->f['issuer']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
foreach ([$this->f['issuer'], $this->f['receiver']] as $reader) {
|
||||
$this->actingAs($reader)->get($this->url)->assertForbidden();
|
||||
$this->get('/recomendacoes/'.$attempt->id.'/imprimir')->assertForbidden();
|
||||
}
|
||||
});
|
||||
|
||||
test('other tenant conflict and audit rollback cannot introduce recommendation decisions', function () {
|
||||
$attempt = recommendationAttempt($this);
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa fictícia distinta']);
|
||||
$other = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($other)->get($this->url)->assertNotFound();
|
||||
$this->get('/recomendacoes/'.$attempt->id.'/imprimir')->assertNotFound();
|
||||
$this->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência de empresa distinta'])->assertNotFound();
|
||||
$this->actingAs($this->f['buyer']);
|
||||
DB::statement("CREATE TRIGGER fail_recommendation_audit BEFORE INSERT ON audit_logs WHEN NEW.action = 'recommendation.proposed' BEGIN SELECT RAISE(ABORT, 'test audit failure'); END");
|
||||
try {
|
||||
app(FormalRecommendation::class)->propose($this->f['buyer'], $this->f['r'], [...$this->f['proposal'], 'previous_id' => $attempt->id]);
|
||||
$this->fail('Missing audit rollback');
|
||||
} catch (QueryException) {
|
||||
expect(RecommendationAttempt::query()->count())->toBe(1);
|
||||
} finally {
|
||||
DB::statement('DROP TRIGGER fail_recommendation_audit');
|
||||
}
|
||||
ConflictDeclaration::query()->create(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['reviewer']->id, 'requisition_id' => $this->f['r']->id, 'has_conflict' => true, 'known_since' => now()->toDateString(), 'declared_at' => now(), 'reason' => 'Conflito fictício documentado']);
|
||||
$this->actingAs($this->f['reviewer'])->post('/recomendacoes/'.$attempt->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência bloqueada por conflito'])->assertSessionHasErrors('conflict');
|
||||
expect(RecommendationReview::query()->count())->toBe(0);
|
||||
});
|
||||
@@ -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', 1)
|
||||
->has('future', 0)
|
||||
->where('documents', fn ($documents) => collect($documents)->contains('label', $f['invoice']->number)));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\ProposalEvaluation;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\FormalAdmission;
|
||||
use App\Services\FormalRecommendation;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
|
||||
require_once __DIR__.'/QualificationFixture.php';
|
||||
|
||||
/** Genuine three-quotation basis; underlying fixture refuses non-isolated databases. */
|
||||
function recommendationFixture(int $quorum = 2): array
|
||||
{
|
||||
$f = qualificationFixture();
|
||||
$tenantId = $f['tenant']->id;
|
||||
$departmentId = $f['r']->department_id;
|
||||
$admin = User::factory()->create(['tenant_id' => $tenantId, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$buyer = User::factory()->create(['tenant_id' => $tenantId, 'department_id' => $departmentId, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||
$head = User::factory()->create(['tenant_id' => $tenantId, 'department_id' => $departmentId, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $tenantId, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$otherReviewer = User::factory()->create(['tenant_id' => $tenantId, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
auth()->guard()->setUser($buyer);
|
||||
$f['r']->update(['approval_snapshot' => ['first_limit_minor' => 2500000, 'second_limit_minor' => 15000000, 'approval_includes_tax' => true, 'rules_provisional' => true]]);
|
||||
$f['r']->steps()->create(['tenant_id' => $tenantId, 'position' => 1, 'role' => 'department_head', 'decision' => 'approved', 'approver_id' => $head->id, 'decided_at' => now()]);
|
||||
$supplier = Supplier::query()->findOrFail($f['quote']->supplier_id);
|
||||
$quotes = [$f['quote']];
|
||||
for ($i = 1; $i <= 2; $i++) {
|
||||
$otherSupplier = $supplier->replicate();
|
||||
$otherSupplier->fill(['nuit' => '12345678'.$i, 'name' => 'Fornecedor fictício '.$i])->save();
|
||||
$quote = $f['quote']->replicate();
|
||||
$quote->fill(['supplier_id' => $otherSupplier->id, 'reference' => 'PROP-FICTICIA-'.$i])->save();
|
||||
$quotes[] = $quote;
|
||||
}
|
||||
$item = $f['r']->items()->firstOrFail();
|
||||
foreach ($quotes as $index => $quote) {
|
||||
$amount = 10000 * ($index + 1);
|
||||
$quote->update(['created_by' => $buyer->id, 'subtotal_minor' => $amount, 'total_minor' => $amount]);
|
||||
$quote->items()->create(['tenant_id' => $tenantId, 'requisition_item_id' => $item->id, 'description' => $item->description, 'quantity' => '1.000', 'unit_price_minor' => $amount, 'tax_rate' => '0', 'subtotal_minor' => $amount, 'tax_minor' => 0, 'total_minor' => $amount]);
|
||||
foreach ([$buyer, $f['analyst']] as $evaluator) {
|
||||
ProposalEvaluation::query()->create(['tenant_id' => $tenantId, 'quotation_id' => $quote->id, 'evaluator_id' => $evaluator->id, 'quality' => '8', 'history' => '5', 'payment' => '8', 'no_conflict' => true, 'comment' => 'Avaliação exclusivamente fictícia']);
|
||||
}
|
||||
}
|
||||
$opening = app(ProposalOpeningWorkflow::class);
|
||||
$documentary = app(DocumentaryQualificationWorkflow::class);
|
||||
$set = $documentary->define($buyer, $f['r'], [...$f['definition'], 'basis_hash' => $opening->basis($opening->proposals($f['r']))]);
|
||||
$answers = $f['assessment']['answers'];
|
||||
$answers[1] = ['criterion_id' => 2, 'result' => 'met', 'evidence' => 'Documento fictício', 'reason' => 'Conformidade exclusivamente fictícia'];
|
||||
foreach ($quotes as $quote) {
|
||||
auth()->guard()->setUser($f['analyst']);
|
||||
$documentary->assess($f['analyst'], $set, [...$f['assessment'], 'quotation_id' => $quote->id, 'answers' => $answers]);
|
||||
}
|
||||
$admission = app(FormalAdmission::class);
|
||||
auth()->guard()->setUser($admin);
|
||||
$admissionPolicy = $admission->policy($admin, ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance'], 'required_count' => 1, 'reason' => 'Política de admissão exclusivamente fictícia']);
|
||||
auth()->guard()->setUser($buyer);
|
||||
$admissionAdoption = $admission->adopt($buyer, $f['r'], $admissionPolicy->id, 0, 'Adopção de admissão exclusivamente fictícia');
|
||||
foreach ($quotes as $quote) {
|
||||
auth()->guard()->setUser($buyer);
|
||||
$decision = $admission->propose($buyer, $f['r'], ['quotation_id' => $quote->id, 'previous_id' => 0, 'basis_hash' => $admission->basis($f['r'], $quote->id)['hash'], 'outcome' => 'admit', 'reason' => 'Proposta de admissão exclusivamente fictícia']);
|
||||
auth()->guard()->setUser($f['analyst']);
|
||||
$admission->review($f['analyst'], $decision, 'approved', 'Conferência de admissão exclusivamente fictícia');
|
||||
}
|
||||
$workflow = app(FormalRecommendation::class);
|
||||
$policyData = ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance', 'department_head'], 'required_count' => $quorum, 'reason' => 'Política de recomendação exclusivamente fictícia'];
|
||||
auth()->guard()->setUser($admin);
|
||||
$policy = $workflow->policy($admin, $policyData);
|
||||
auth()->guard()->setUser($buyer);
|
||||
$adoption = $workflow->adopt($buyer, $f['r'], $policy->id, 0, 'Adopção de recomendação exclusivamente fictícia');
|
||||
$proposal = ['previous_id' => 0, 'quotation_id' => $quotes[0]->id, 'basis_hash' => $workflow->basis($f['r'])['hash'], 'reason' => 'Recomendação exclusivamente fictícia'];
|
||||
$selection = ['quotation_id' => $quotes[0]->id, 'justification' => 'Proposta de maior pontuação com recomendação.', 'delivery_date' => today()->addWeek()->format('Y-m-d'), 'delivery_location' => 'Armazém fictício'];
|
||||
|
||||
return [...$f, 'quotes' => $quotes, 'set' => $set, 'admin' => $admin, 'buyer' => $buyer, 'head' => $head, 'reviewer' => $reviewer, 'other_reviewer' => $otherReviewer, 'admission_policy' => $admissionPolicy, 'admission_adoption' => $admissionAdoption, 'policy' => $policy, 'policy_data' => $policyData, 'adoption' => $adoption, 'proposal' => $proposal, 'selection' => $selection];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000020.
|
||||
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_000020_create_formal_recommendations';
|
||||
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/formal-recommendation-000020-'.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, 'recommendation_policies_count' => (int) $pdo->query('SELECT count(*) FROM recommendation_policies')->fetchColumn(), 'recommendation_adoptions_count' => (int) $pdo->query('SELECT count(*) FROM recommendation_adoptions')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/recomendacao-migracao-000020.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