Implementa qualificacao documental com requisitos e analises por versao
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
use App\Models\QualificationSet;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
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_qualification_'.$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 {
|
||||
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||
if ($payload['action'] === 'define') {
|
||||
$workflow->define($actor, Requisition::query()->findOrFail($argv[3]), $payload['data']);
|
||||
} else {
|
||||
$workflow->assess($actor, QualificationSet::query()->findOrFail($argv[3]), $payload['data']);
|
||||
}
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
} catch (HttpExceptionInterface $exception) {
|
||||
$status = $exception->getStatusCode();
|
||||
}
|
||||
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\QualificationAssessment;
|
||||
use App\Models\QualificationSet;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
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/QualificationFixture.php';
|
||||
$original = DB::connection();
|
||||
if ($original->getDriverName() !== 'pgsql') {
|
||||
throw new LogicException('Exige PostgreSQL.');
|
||||
}
|
||||
$config = $original->getConfig();
|
||||
$admin = $original->getPdo();
|
||||
$database = 'compras_receipts_test_'.bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
$processes = [];
|
||||
$report = ['tested_at_utc' => gmdate('c'), 'separate_database' => true, 'transport' => 'Independent PHP service transactions and PostgreSQL connections', 'scenarios' => []];
|
||||
try {
|
||||
$admin->exec('CREATE DATABASE "'.$database.'"');
|
||||
$created = true;
|
||||
config(['database.connections.pgsql' => [...$config, 'database' => $database, 'url' => null]]);
|
||||
DB::purge('pgsql');
|
||||
DB::setDefaultConnection('pgsql');
|
||||
Schema::clearResolvedInstance('db.schema');
|
||||
app()->forgetInstance('db.schema');
|
||||
if (DB::connection()->getDatabaseName() !== $database || Schema::getConnection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Migração fora do isolamento recusada.');
|
||||
}
|
||||
Artisan::call('migrate', ['--database' => 'pgsql', '--force' => true]);
|
||||
$workerEnv = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_DATABASE' => $database, 'DB_HOST' => $config['host'], 'DB_PORT' => (string) $config['port'], 'DB_USERNAME' => $config['username'], 'DB_PASSWORD' => $config['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array'];
|
||||
foreach (['competing_requirements', 'same_analyst', 'distinct_analysts', 'changed_basis', 'revoked_role', 'requirements_versus_assessment'] as $scenario) {
|
||||
$f = qualificationFixture();
|
||||
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||
$set = null;
|
||||
if ($scenario !== 'competing_requirements') {
|
||||
$set = $workflow->define($f['issuer'], $f['r'], $f['definition']);
|
||||
}
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $f['tenant']->id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach (['A', 'B'] as $index => $suffix) {
|
||||
$define = $scenario === 'competing_requirements' || ($scenario === 'requirements_versus_assessment' && $index === 0);
|
||||
$actor = $define ? $f['issuer'] : ($scenario === 'distinct_analysts' && $index === 1 ? $f['other_analyst'] : $f['analyst']);
|
||||
$target = $define ? $f['r']->id : $set->id;
|
||||
$data = $define ? [...$f['definition'], 'previous_id' => $set->id ?? 0] : $f['assessment'];
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/qualification-worker.php', $database, (string) $actor->id, (string) $target, $suffix], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode(['action' => $define ? 'define' : 'assess', 'data' => $data], 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_qualification_A','sgc_qualification_B') AND wait_event_type = 'Lock'");
|
||||
$deadline = microtime(true) + 20;
|
||||
do {
|
||||
$statement->execute([$database]);
|
||||
$waits = (int) $statement->fetchColumn();
|
||||
if ($waits === 2) {
|
||||
break;
|
||||
}
|
||||
foreach ($processes as $process) {
|
||||
if (! $process->isRunning()) {
|
||||
throw new RuntimeException('Worker terminou antes do bloqueio: '.$process->getErrorOutput());
|
||||
}
|
||||
}
|
||||
usleep(20000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($scenario === 'revoked_role') {
|
||||
$connection->table('users')->where('id', $f['analyst']->id)->update(['purchasing_role' => 'requester']);
|
||||
}
|
||||
if ($scenario === 'changed_basis') {
|
||||
$connection->table('quotations')->where('id', $f['quote']->id)->update(['reference' => 'Proposta alterada durante a espera']);
|
||||
}
|
||||
$connection->commit();
|
||||
if ($waits !== 2) {
|
||||
throw new RuntimeException('Sem sobreposição de bloqueios.');
|
||||
}
|
||||
$results = [];
|
||||
foreach ($processes as $process) {
|
||||
$process->wait();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Falha do worker: '.$process->getErrorOutput());
|
||||
}
|
||||
$results[] = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$statuses = array_column($results, 'status');
|
||||
sort($statuses);
|
||||
$expected = match ($scenario) {
|
||||
'distinct_analysts' => [200, 200], 'changed_basis' => [422, 422], 'revoked_role' => [403, 403], default => [200, 422]
|
||||
};
|
||||
$sets = QualificationSet::query()->count();
|
||||
$assessments = QualificationAssessment::query()->count();
|
||||
if ($scenario === 'requirements_versus_assessment') {
|
||||
if (! in_array($statuses, [[200, 200], [200, 422]], true) || $sets !== 2 || $assessments !== ($statuses === [200, 200] ? 1 : 0) || QualificationAssessment::query()->where('qualification_set_id', QualificationSet::query()->max('id'))->exists()) {
|
||||
throw new RuntimeException('Análise misturada com requisitos novos.');
|
||||
}
|
||||
} elseif ($statuses !== $expected || $sets !== 1 || $assessments !== match ($scenario) {
|
||||
'same_analyst' => 1, 'distinct_analysts' => 2, default => 0
|
||||
}) {
|
||||
throw new RuntimeException('Resultado concorrente inesperado.');
|
||||
}
|
||||
if (count(array_unique(array_column($results, 'backend_pid'))) !== 2 || AuditLog::query()->where('action', 'qualification.defined')->count() !== $sets || AuditLog::query()->where('action', 'qualification.assessed')->count() !== $assessments) {
|
||||
throw new RuntimeException('Auditoria ou ligações inconsistentes.');
|
||||
}
|
||||
if ($scenario === 'distinct_analysts' && QualificationAssessment::query()->distinct()->count('analyst_id') !== 2) {
|
||||
throw new RuntimeException('Registos de analistas substituídos.');
|
||||
}
|
||||
if (QualificationAssessment::query()->where('revision', '!=', 1)->exists()) {
|
||||
throw new RuntimeException('Versões inesperadas.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'requirement_versions' => $sets, 'analyst_records' => $assessments];
|
||||
}
|
||||
$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/qualificacao-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,159 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\Department;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\QualificationAssessment;
|
||||
use App\Models\QualificationSet;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/QualificationFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = qualificationFixture();
|
||||
$this->url = '/requisicoes/'.$this->f['r']->id.'/qualificacao';
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
function defineDocumentaryQualification(object $test, array $changes = []): QualificationSet
|
||||
{
|
||||
$test->actingAs($test->f['issuer'])->post($test->url, [...$test->f['definition'], ...$changes])->assertSessionHasNoErrors();
|
||||
|
||||
return QualificationSet::query()->latest('revision')->firstOrFail();
|
||||
}
|
||||
|
||||
function recordDocumentaryAssessment(object $test, QualificationSet $set, array $changes = [], ?User $actor = null): QualificationAssessment
|
||||
{
|
||||
$test->actingAs($actor ?? $test->f['analyst'])->post('/qualificacoes/'.$set->id.'/analises', [...$test->f['assessment'], ...$changes])->assertSessionHasNoErrors();
|
||||
|
||||
return QualificationAssessment::query()->latest('id')->firstOrFail();
|
||||
}
|
||||
|
||||
test('documentary qualification freezes process criteria without financial decisions', function () {
|
||||
$before = app(ProposalComparison::class)->inspect($this->f['r']);
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$answers = $this->f['assessment']['answers'];
|
||||
$answers[0]['result'] = 'not_met';
|
||||
recordDocumentaryAssessment($this, $set, ['answers' => $answers]);
|
||||
expect($set->criteria[0]['id'])->toBe(1)->and($set->snapshot['proposals'][0]['id'])->toBe($this->f['quote']->id)
|
||||
->and(BudgetEntry::query()->count())->toBe(0)->and(PurchaseAward::query()->count())->toBe(0)
|
||||
->and(app(ProposalComparison::class)->inspect($this->f['r']))->toBe($before);
|
||||
$this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||
->assertInertia(fn (Assert $page) => $page->component('purchases/qualification')->where('isCurrent', true)->has('records', 1));
|
||||
$this->get('/requisicoes/'.$this->f['r']->id.'/processo')->assertInertia(fn (Assert $page) => $page->where('documents', fn ($documents) => collect($documents)->contains('kind', 'Qualificação documental')));
|
||||
});
|
||||
|
||||
test('documentary criteria versions and analyst corrections never overwrite earlier records', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$first = recordDocumentaryAssessment($this, $set);
|
||||
$second = recordDocumentaryAssessment($this, $set, ['previous_id' => $first->id, 'reason' => 'Correcção fictícia identificada']);
|
||||
expect($second->revision)->toBe(2)->and($first->refresh()->reason)->toBe('Análise exclusivamente fictícia');
|
||||
$new = defineDocumentaryQualification($this, ['previous_id' => $set->id, 'reason' => 'Nova versão sem apagar requisitos']);
|
||||
expect($new->revision)->toBe(2)->and(QualificationAssessment::query()->where('qualification_set_id', $new->id)->count())->toBe(0);
|
||||
$this->actingAs($this->f['analyst'])->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'previous_id' => $second->id])->assertSessionHasErrors('qualification');
|
||||
$this->get($this->url.'?version='.$set->id)->assertInertia(fn (Assert $page) => $page->where('isCurrent', false)->where('canAssess', false)->where('records.0.id', $second->id)->has('history.data', 2));
|
||||
});
|
||||
|
||||
test('different documentary analysts retain independent records and cannot replace another analyst', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$first = recordDocumentaryAssessment($this, $set);
|
||||
$this->actingAs($this->f['other_analyst'])->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'previous_id' => $first->id])->assertSessionHasErrors('previous_id');
|
||||
$other = recordDocumentaryAssessment($this, $set, [], $this->f['other_analyst']);
|
||||
expect($other->revision)->toBe(1)->and($other->analyst_id)->not->toBe($first->analyst_id);
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->has('records', 2)->has('history.data', 2));
|
||||
});
|
||||
|
||||
test('documentary results require exact criteria and appropriate evidence and reasons', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$data = $this->f['assessment'];
|
||||
$data['answers'][0]['evidence'] = '';
|
||||
$this->actingAs($this->f['analyst'])->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasErrors('answers');
|
||||
$data['answers'][0]['result'] = 'not_applicable';
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasNoErrors();
|
||||
$data['previous_id'] = QualificationAssessment::query()->sole()->id;
|
||||
$data['answers'][0]['reason'] = '';
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasErrors('answers');
|
||||
$data['answers'][0]['criterion_id'] = 99;
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasErrors('answers');
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'analyst_id' => $this->f['other_analyst']->id])->assertSessionHasErrors('analyst_id');
|
||||
});
|
||||
|
||||
test('documentary requirements reject duplicates forged snapshots and stale versions', function () {
|
||||
$data = $this->f['definition'];
|
||||
$data['criteria'][1]['label'] = mb_strtoupper($data['criteria'][0]['label']);
|
||||
$this->post($this->url, $data)->assertSessionHasErrors('criteria');
|
||||
$this->post($this->url, [...$this->f['definition'], 'snapshot' => ['approved' => true]])->assertSessionHasErrors('snapshot');
|
||||
defineDocumentaryQualification($this);
|
||||
$this->post($this->url, $this->f['definition'])->assertSessionHasErrors('previous_id');
|
||||
expect(QualificationSet::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('changed documentary proposal bases block new analysis and require fresh requirements', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
recordDocumentaryAssessment($this, $set);
|
||||
$this->f['quote']->update(['reference' => 'Referência posterior fictícia']);
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertSessionHasErrors('qualification');
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('isCurrent', false)->where('canAssess', false));
|
||||
$this->actingAs($this->f['issuer'])->post($this->url, [...$this->f['definition'], 'previous_id' => $set->id])->assertSessionHasErrors('basis_hash');
|
||||
$opening = app(ProposalOpeningWorkflow::class);
|
||||
$fresh = defineDocumentaryQualification($this, ['previous_id' => $set->id, 'basis_hash' => $opening->basis($opening->proposals($this->f['r']))]);
|
||||
expect($fresh->snapshot['proposals'][0]['reference'])->toBe('Referência posterior fictícia')->and($set->refresh()->snapshot['proposals'][0]['reference'])->toBe('PROP-TEST');
|
||||
});
|
||||
|
||||
test('documentary requester and revoked analysts cannot write while admin only reads', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertForbidden();
|
||||
$this->actingAs($this->f['analyst']);
|
||||
DB::table('users')->where('id', $this->f['analyst']->id)->update(['purchasing_role' => 'requester']);
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertForbidden();
|
||||
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($admin)->get($this->url)->assertInertia(fn (Assert $page) => $page->where('canDefine', false)->where('canAssess', false));
|
||||
$this->post($this->url, [...$this->f['definition'], 'previous_id' => $set->id])->assertForbidden();
|
||||
});
|
||||
|
||||
test('documentary qualification enforces company department and guest access', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$this->actingAs($this->f['receiver'])->get($this->url)->assertForbidden();
|
||||
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outro departamento']);
|
||||
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($head)->get($this->url)->assertNotFound();
|
||||
$other = Tenant::query()->create(['name' => 'Outra empresa fictícia']);
|
||||
$this->actingAs(User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Finance]))->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertNotFound();
|
||||
auth()->logout();
|
||||
$this->get($this->url)->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('documentary qualification stops new records after award without removing history', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
recordDocumentaryAssessment($this, $set);
|
||||
PurchaseAward::query()->create($this->f['award_attributes']);
|
||||
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertSessionHasErrors('qualification');
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('canDefine', false)->where('canAssess', false)->has('records', 1));
|
||||
});
|
||||
|
||||
test('documentary qualification versions are immutable and audit failure rolls back an assessment', function () {
|
||||
$set = defineDocumentaryQualification($this);
|
||||
$this->actingAs($this->f['analyst']);
|
||||
AuditLog::creating(function (AuditLog $event) {
|
||||
if ($event->action === 'qualification.assessed') {
|
||||
throw new RuntimeException('Falha fictícia de auditoria');
|
||||
}
|
||||
});
|
||||
try {
|
||||
expect(fn () => app(DocumentaryQualificationWorkflow::class)->assess($this->f['analyst'], $set, $this->f['assessment']))->toThrow(RuntimeException::class);
|
||||
} finally {
|
||||
AuditLog::flushEventListeners();
|
||||
}
|
||||
expect(QualificationAssessment::query()->count())->toBe(0);
|
||||
$assessment = recordDocumentaryAssessment($this, $set);
|
||||
expect(fn () => $assessment->update(['reason' => 'Alterar passado']))->toThrow(LogicException::class);
|
||||
expect(fn () => $set->delete())->toThrow(LogicException::class);
|
||||
});
|
||||
@@ -15,6 +15,7 @@ use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseControlPolicy;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\PurchaseRevision;
|
||||
use App\Models\QualificationSet;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SparePart;
|
||||
@@ -27,6 +28,8 @@ use App\Models\Warehouse;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use App\Services\PurchaseControlPolicyWorkflow;
|
||||
use App\Services\PurchaseRevisionWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
@@ -613,3 +616,14 @@ test('cancellation and reservation release roll back together if audit fails', f
|
||||
->and(BudgetEntry::query()->where('kind', 'release')->count())->toBe(0)
|
||||
->and((int) BudgetEntry::query()->sum('reserved_minor'))->toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('documentary noncompliance does not silently exclude an otherwise eligible award', function () {
|
||||
$opening = app(ProposalOpeningWorkflow::class);
|
||||
$comparison = app(ProposalComparison::class)->inspect($this->r);
|
||||
$this->actingAs($this->buyer)->post('/requisicoes/'.$this->r->id.'/qualificacao', ['previous_id' => 0, 'basis_hash' => $opening->basis($opening->proposals($this->r)), 'reason' => 'Requisito documental fictício do processo', 'criteria' => [['label' => 'Requisito documental para conferência', 'category' => 'administrative', 'required' => true]]])->assertSessionHasNoErrors();
|
||||
$set = QualificationSet::query()->sole();
|
||||
$this->actingAs($this->finance)->post('/qualificacoes/'.$set->id.'/analises', ['previous_id' => 0, 'quotation_id' => $this->quotes[0]->id, 'reason' => 'Registo documental sem decisão formal', 'answers' => [['criterion_id' => 1, 'result' => 'not_met', 'evidence' => 'Referência de teste fictícia', 'reason' => 'Não conformidade registada para apreciação']]])->assertSessionHasNoErrors();
|
||||
expect(app(ProposalComparison::class)->inspect($this->r))->toBe($comparison);
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
expect($order->total_minor)->toBe(10000)->and(PurchaseOrder::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
|
||||
require_once __DIR__.'/ProposalOpeningFixture.php';
|
||||
|
||||
/** The underlying fixture refuses non-isolated databases. */
|
||||
function qualificationFixture(): array
|
||||
{
|
||||
$f = proposalOpeningFixture();
|
||||
$analyst = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$otherAnalyst = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$definition = ['previous_id' => 0, 'basis_hash' => $f['data']['basis_hash'], 'reason' => 'Requisitos exclusivamente fictícios', 'criteria' => [['label' => 'Documento definido no processo', 'category' => 'administrative', 'required' => true], ['label' => 'Conformidade com a especificação', 'category' => 'technical', 'required' => false]]];
|
||||
$assessment = ['previous_id' => 0, 'quotation_id' => $f['quote']->id, 'reason' => 'Análise exclusivamente fictícia', 'answers' => [['criterion_id' => 1, 'result' => 'met', 'evidence' => 'Referência fictícia 1', 'reason' => 'Documento conferido no teste isolado'], ['criterion_id' => 2, 'result' => 'pending', 'evidence' => '', 'reason' => '']]];
|
||||
|
||||
return [...$f, 'analyst' => $analyst, 'other_analyst' => $otherAnalyst, 'definition' => $definition, 'assessment' => $assessment];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000018.
|
||||
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_000018_create_documentary_qualification';
|
||||
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/documentary-qualification-000018-'.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, 'qualification_sets_count' => (int) $pdo->query('SELECT count(*) FROM qualification_sets')->fetchColumn(), 'qualification_assessments_count' => (int) $pdo->query('SELECT count(*) FROM qualification_assessments')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/qualificacao-migracao-000018.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