Reune comparacao e qualificacao em relatorio de conferencia imprimivel
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Database\Events\QueryExecuted;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
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_review_report']);
|
||||
$actor = User::query()->findOrFail($argv[2]);
|
||||
auth()->guard()->setUser($actor);
|
||||
$lock = (int) $argv[4];
|
||||
$proof = null;
|
||||
if ($argv[5] === 'consistent_snapshot') {
|
||||
$paused = false;
|
||||
DB::listen(function (QueryExecuted $query) use ($lock, &$proof, &$paused) {
|
||||
if (! $paused && str_contains($query->sql, 'from "qualification_sets"')) {
|
||||
$paused = true;
|
||||
$proof = DB::selectOne("select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only");
|
||||
DB::select('select pg_advisory_xact_lock(?)', [$lock]);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Cache the authenticated actor before the parent revokes role/department.
|
||||
DB::select('select pg_advisory_lock(?)', [$lock]);
|
||||
DB::select('select pg_advisory_unlock(?)', [$lock]);
|
||||
}
|
||||
try {
|
||||
$report = app(ProcurementReviewReport::class)->build($actor, (int) $argv[3]);
|
||||
$status = 200;
|
||||
} catch (HttpExceptionInterface $exception) {
|
||||
$status = $exception->getStatusCode();
|
||||
$report = null;
|
||||
} catch (ModelNotFoundException) {
|
||||
$status = 404;
|
||||
$report = null;
|
||||
}
|
||||
echo json_encode(['status' => $status, 'report' => $report, 'proof' => $proof], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Department;
|
||||
use App\Models\QualificationAssessment;
|
||||
use App\Models\QualificationSet;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
foreach (['APP_ENV' => 'testing', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
require __DIR__.'/../Support/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;
|
||||
$lockHeld = false;
|
||||
$process = null;
|
||||
$report = ['tested_at_utc' => gmdate('c'), 'separate_database' => true, 'transport' => 'Independent report reader and concurrent PostgreSQL business connection', '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 (['consistent_snapshot', 'revoked_role', 'changed_department'] as $scenario) {
|
||||
$f = qualificationFixture();
|
||||
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||
$set = $workflow->define($f['issuer'], $f['r'], $f['definition']);
|
||||
$actor = $f['analyst'];
|
||||
auth()->guard()->setUser($actor);
|
||||
$first = $workflow->assess($actor, $set, $f['assessment']);
|
||||
if ($scenario === 'changed_department') {
|
||||
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
}
|
||||
$lock = random_int(1, 1000000000);
|
||||
DB::select('select pg_advisory_lock(?)', [$lock]);
|
||||
$lockHeld = true;
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/review-report-worker.php', $database, (string) $actor->id, (string) $f['r']->id, (string) $lock, $scenario], base_path(), $workerEnv);
|
||||
$process->setTimeout(40);
|
||||
$process->start();
|
||||
$statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name = 'sgc_review_report' AND wait_event_type = 'Lock' AND wait_event = 'advisory'");
|
||||
$deadline = microtime(true) + 20;
|
||||
do {
|
||||
$statement->execute([$database]);
|
||||
$waits = (int) $statement->fetchColumn();
|
||||
if ($waits === 1) {
|
||||
break;
|
||||
}
|
||||
if (! $process->isRunning()) {
|
||||
throw new RuntimeException('Leitor terminou antes do bloqueio: '.$process->getErrorOutput());
|
||||
}
|
||||
usleep(20000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($waits !== 1) {
|
||||
throw new RuntimeException('Leitura concorrente não demonstrada.');
|
||||
}
|
||||
if ($scenario === 'consistent_snapshot') {
|
||||
$answers = $f['assessment']['answers'];
|
||||
$answers[0]['result'] = 'not_met';
|
||||
$workflow->assess($f['analyst'], $set, [...$f['assessment'], 'previous_id' => $first->id, 'answers' => $answers]);
|
||||
$f['quote']->update(['reference' => 'REFERENCIA-CONCORRENTE']);
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$opening = app(ProposalOpeningWorkflow::class);
|
||||
$workflow->define($f['issuer'], $f['r'], [...$f['definition'], 'previous_id' => $set->id, 'basis_hash' => $opening->basis($opening->proposals($f['r']))]);
|
||||
} elseif ($scenario === 'revoked_role') {
|
||||
DB::table('users')->where('id', $actor->id)->update(['purchasing_role' => 'requester']);
|
||||
} else {
|
||||
$other = Department::query()->create(['tenant_id' => $f['tenant']->id, 'name' => 'Departamento posterior fictício']);
|
||||
DB::table('users')->where('id', $actor->id)->update(['department_id' => $other->id]);
|
||||
}
|
||||
$audits = AuditLog::query()->count();
|
||||
DB::select('select pg_advisory_unlock(?)', [$lock]);
|
||||
$lockHeld = false;
|
||||
$process->wait();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Falha do leitor: '.$process->getErrorOutput());
|
||||
}
|
||||
$result = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (AuditLog::query()->count() !== $audits) {
|
||||
throw new RuntimeException('O relatório criou eventos de negócio.');
|
||||
}
|
||||
if ($scenario === 'consistent_snapshot') {
|
||||
$data = $result['report'];
|
||||
if ($result['status'] !== 200 || $result['proof']['isolation'] !== 'repeatable read' || $result['proof']['read_only'] !== 'on' || $data['comparison']['rows'][0]['reference'] !== 'PROP-TEST' || $data['qualification']['revision'] !== 1 || $data['qualification']['proposals'][0]['analyses'][0]['revision'] !== 1 || $data['qualification']['proposals'][0]['analyses'][0]['answers'][0]['result'] !== 'met' || QualificationSet::query()->count() !== 2 || QualificationAssessment::query()->max('revision') !== 2) {
|
||||
throw new RuntimeException('Relatório misturou momentos de consulta.');
|
||||
}
|
||||
} elseif ($result['status'] !== ($scenario === 'revoked_role' ? 403 : 404) || $result['report'] !== null) {
|
||||
throw new RuntimeException('Acesso revogado expôs o relatório.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'observed_advisory_waits' => $waits, 'business_audit_unchanged' => true];
|
||||
}
|
||||
$report['passed'] = true;
|
||||
} finally {
|
||||
if ($process && $process->isRunning()) {
|
||||
$process->stop();
|
||||
}
|
||||
if ($lockHeld) {
|
||||
DB::select('select pg_advisory_unlock(?)', [$lock]);
|
||||
}
|
||||
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/relatorio-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,93 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Department;
|
||||
use App\Models\QualificationAssessment;
|
||||
use App\Models\QualificationSet;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
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.'/relatorio';
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
function documentaryReportRecords(object $test): QualificationSet
|
||||
{
|
||||
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||
$test->actingAs($test->f['issuer']);
|
||||
$set = $workflow->define($test->f['issuer'], $test->f['r'], $test->f['definition']);
|
||||
$test->actingAs($test->f['analyst']);
|
||||
$workflow->assess($test->f['analyst'], $set, $test->f['assessment']);
|
||||
|
||||
return $set;
|
||||
}
|
||||
|
||||
test('review report returns a private read-only consultation without inventing missing decisions', function () {
|
||||
$before = AuditLog::query()->count();
|
||||
$this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||
->assertInertia(fn (Assert $page) => $page->component('purchases/review-report')
|
||||
->where('report.requisition.number', $this->f['r']->number)
|
||||
->where('report.comparison.ready', false)->where('report.comparison.top_count', 0)
|
||||
->where('report.comparison.rows.0.score_minor', null)->where('report.comparison.rows.0.is_top', false)
|
||||
->where('report.qualification', null)->where('report.award', null)->where('report.order', null)
|
||||
->missing('report.recommended_supplier_id')->missing('report.bank_snapshot'));
|
||||
expect(AuditLog::query()->count())->toBe($before);
|
||||
});
|
||||
|
||||
test('review report separates current comparison from outdated documentary identities and results', function () {
|
||||
$set = documentaryReportRecords($this);
|
||||
$this->f['quote']->update(['reference' => 'REFERENCIA-POSTERIOR']);
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('report.comparison.rows.0.reference', 'REFERENCIA-POSTERIOR')
|
||||
->where('report.qualification.is_current', false)->where('report.qualification.revision', $set->revision)
|
||||
->where('report.qualification.proposals.0.reference', 'PROP-TEST')
|
||||
->where('report.qualification.proposals.0.analyses.0.answers.1.result', 'pending'));
|
||||
});
|
||||
|
||||
test('review report retains the latest record of each analyst without majority or silent replacement', function () {
|
||||
$set = documentaryReportRecords($this);
|
||||
$first = QualificationAssessment::query()->sole();
|
||||
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||
$workflow->assess($this->f['analyst'], $set, [...$this->f['assessment'], 'previous_id' => $first->id, 'reason' => 'Correcção fictícia para conferência']);
|
||||
$this->actingAs($this->f['other_analyst']);
|
||||
$workflow->assess($this->f['other_analyst'], $set, $this->f['assessment']);
|
||||
$before = AuditLog::query()->count();
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('report.qualification.is_current', true)
|
||||
->has('report.qualification.proposals.0.analyses', 2)
|
||||
->where('report.qualification.proposals.0.analyses.0.revision', 2)
|
||||
->where('report.qualification.proposals.0.analyses.1.revision', 1));
|
||||
expect(QualificationAssessment::query()->count())->toBe(3)->and(AuditLog::query()->count())->toBe($before);
|
||||
});
|
||||
|
||||
test('review report enforces financial-reader roles companies departments and guest protection', function () {
|
||||
$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();
|
||||
$head->forceFill(['department_id' => $this->f['r']->department_id])->save();
|
||||
$this->actingAs($head)->get($this->url)->assertOk();
|
||||
$other = Tenant::query()->create(['name' => 'Outra empresa fictícia']);
|
||||
$this->actingAs(User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Admin]))->get($this->url)->assertNotFound();
|
||||
auth()->logout();
|
||||
$this->get($this->url)->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('review report reloads cached actor access before reading business records', function () {
|
||||
$this->actingAs($this->f['analyst']);
|
||||
DB::table('users')->where('id', $this->f['analyst']->id)->update(['purchasing_role' => 'requester']);
|
||||
$this->get($this->url)->assertForbidden();
|
||||
});
|
||||
|
||||
test('review report omits unneeded supplier and evaluator details', function () {
|
||||
$report = app(ProcurementReviewReport::class)->build($this->f['issuer'], $this->f['r']->id);
|
||||
expect($report['comparison']['rows'][0]['supplier'])->toBeString()
|
||||
->and($report['comparison']['rows'][0])->not->toHaveKeys(['evaluations', 'qualified_evaluations', 'items', 'beneficiaries', 'document_references', 'bank_snapshot']);
|
||||
});
|
||||
@@ -28,6 +28,7 @@ use App\Models\Warehouse;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use App\Services\PurchaseControlPolicyWorkflow;
|
||||
@@ -627,3 +628,19 @@ test('documentary noncompliance does not silently exclude an otherwise eligible
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
expect($order->total_minor)->toBe(10000)->and(PurchaseOrder::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('review report reflects tied source scores and existing frozen orders without deciding a winner', function () {
|
||||
foreach ($this->quotes as $quote) {
|
||||
$quote->items()->update(['unit_price_minor' => 10000, 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
||||
$quote->update(['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
||||
}
|
||||
$this->actingAs($this->buyer);
|
||||
$comparison = app(ProposalComparison::class)->inspect($this->r);
|
||||
$report = app(ProcurementReviewReport::class)->build($this->buyer, $this->r->id);
|
||||
expect($report['comparison']['ready'])->toBeTrue()->and($report['comparison']['top_count'])->toBe(3)
|
||||
->and(array_column($report['comparison']['rows'], 'score_minor'))->toBe(array_column($comparison['rows'], 'score_minor'))
|
||||
->and($report)->not->toHaveKey('recommended_supplier_id');
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
$report = app(ProcurementReviewReport::class)->build($this->buyer, $this->r->id);
|
||||
expect($report['order']['number'])->toBe($order->number)->and($report['order']['total_minor'])->toBe(10000);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user