Implementa admissão formal por política e adopção do processo
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use App\Models\AdmissionDecision;
|
||||
use App\Models\User;
|
||||
use App\Services\FormalAdmission;
|
||||
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_admission_'.$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 {
|
||||
app(FormalAdmission::class)->review($actor, AdmissionDecision::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,136 @@
|
||||
<?php
|
||||
|
||||
use App\Models\AdmissionDecision;
|
||||
use App\Models\AdmissionReview;
|
||||
use App\Models\AuditLog;
|
||||
use App\Services\FormalAdmission;
|
||||
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/AdmissionFixture.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'] as $scenario) {
|
||||
$f = admissionFixture(2);
|
||||
$workflow = app(FormalAdmission::class);
|
||||
$decision = $workflow->propose($f['buyer'], $f['r'], $f['proposal']);
|
||||
$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_analyst'] : $f['analyst'];
|
||||
$verdict = $scenario === 'opposing_reviews' && $index === 1 ? 'returned' : 'approved';
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/admission-worker.php', $database, (string) $actor->id, (string) $decision->id, $suffix], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode(['verdict' => $verdict], 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_admission_A','sgc_admission_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['analyst']->id)->update(['purchasing_role' => 'requester']);
|
||||
}
|
||||
if ($scenario === 'changed_basis') {
|
||||
$connection->table('quotations')->where('id', $f['quote']->id)->update(['reference' => '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' => [200, 422], default => [200, 200]
|
||||
};
|
||||
auth()->guard()->setUser($f['buyer']);
|
||||
$reviews = AdmissionReview::query()->count();
|
||||
$expectedReviews = match ($scenario) {
|
||||
'distinct_people' => 2, 'same_person', 'opposing_reviews' => 1, default => 0
|
||||
};
|
||||
if ($statuses !== $expected || $reviews !== $expectedReviews || AuditLog::query()->where('action', 'admission.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']);
|
||||
if (($scenario === 'distinct_people' && $state !== 'confirmed') || ($scenario === 'same_person' && $state !== 'pending') || AdmissionDecision::query()->count() !== 1) {
|
||||
throw new RuntimeException('Quórum ou tentativa alterados indevidamente.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'reviews' => $reviews, 'state' => $state];
|
||||
}
|
||||
$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/admissao-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,168 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AdmissionDecision;
|
||||
use App\Models\AdmissionPolicy;
|
||||
use App\Models\AdmissionReview;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\ConflictDeclaration;
|
||||
use App\Models\Department;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\FormalAdmission;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/AdmissionFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = admissionFixture();
|
||||
$this->url = '/requisicoes/'.$this->f['r']->id.'/admissao';
|
||||
$this->actingAs($this->f['buyer']);
|
||||
});
|
||||
|
||||
function admissionAttempt(object $test, array $changes = []): AdmissionDecision
|
||||
{
|
||||
$test->actingAs($test->f['buyer'])->post($test->url.'/decisoes', [...$test->f['proposal'], ...$changes])->assertSessionHasNoErrors();
|
||||
|
||||
return AdmissionDecision::query()->latest('id')->firstOrFail();
|
||||
}
|
||||
|
||||
function admissionConfer(object $test, AdmissionDecision $decision, ?User $actor = null, string $verdict = 'approved'): void
|
||||
{
|
||||
$test->actingAs($actor ?? $test->f['analyst'])->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => $verdict, 'reason' => 'Conferência exclusivamente fictícia'])->assertSessionHasNoErrors();
|
||||
}
|
||||
|
||||
test('formal admission requires independent company quorum and preserves snapshots without financial writes', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
$workflow = app(FormalAdmission::class);
|
||||
expect($workflow->status($decision, $this->f['adoption']))->toBe('pending')->and($workflow->admitted($this->f['r'], $decision->quotation_id))->toBeFalse();
|
||||
admissionConfer($this, $decision);
|
||||
expect($workflow->status($decision, $this->f['adoption']))->toBe('pending');
|
||||
admissionConfer($this, $decision, $this->f['other_analyst']);
|
||||
$snapshot = $workflow->selection($this->f['r'], $decision->quotation_id);
|
||||
expect($snapshot['review_ids'])->toHaveCount(2)->and($snapshot['decision_id'])->toBe($decision->id)->and(BudgetEntry::query()->count())->toBe(0);
|
||||
$this->f['analyst']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
expect($workflow->selection($this->f['r'], $decision->quotation_id))->toBe($snapshot);
|
||||
$this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $p) => $p->component('purchases/admission')->where('history.data.0.status', 'confirmed')->has('history.data.0.reviews', 2));
|
||||
});
|
||||
|
||||
test('identical conference retries count once and changed retries cannot overwrite', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
admissionConfer($this, $decision);
|
||||
admissionConfer($this, $decision);
|
||||
expect(AdmissionReview::query()->count())->toBe(1)->and(AuditLog::query()->where('action', 'admission.reviewed')->count())->toBe(1);
|
||||
$this->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'returned', 'reason' => 'Outro fundamento fictício'])->assertSessionHasErrors('admission');
|
||||
expect(AdmissionReview::query()->sole()->verdict)->toBe('approved');
|
||||
});
|
||||
|
||||
test('return ends attempt without excluding and a new attempt starts with no reviews', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
admissionConfer($this, $decision, null, 'returned');
|
||||
expect(app(FormalAdmission::class)->status($decision, $this->f['adoption']))->toBe('returned')->and($decision->refresh()->outcome)->toBe('admit');
|
||||
$this->actingAs($this->f['other_analyst'])->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Outra conferência fictícia'])->assertSessionHasErrors('admission');
|
||||
$next = admissionAttempt($this, ['previous_id' => $decision->id]);
|
||||
expect($next->revision)->toBe(2)->and(AdmissionReview::query()->where('admission_decision_id', $next->id)->count())->toBe(0);
|
||||
$this->post($this->url.'/decisoes', $this->f['proposal'])->assertSessionHasErrors('admission');
|
||||
});
|
||||
|
||||
test('pending divergent and unmet mandatory qualification cannot be admitted', function (string $result) {
|
||||
$answers = $this->f['assessment']['answers'];
|
||||
$answers[0]['result'] = $result;
|
||||
$this->actingAs($this->f['analyst']);
|
||||
app(DocumentaryQualificationWorkflow::class)->assess($this->f['analyst'], $this->f['set'], [...$this->f['assessment'], 'previous_id' => $this->f['record']->id, 'answers' => $answers]);
|
||||
$basis = app(FormalAdmission::class)->basis($this->f['r'], $this->f['quote']->id);
|
||||
$this->actingAs($this->f['buyer'])->post($this->url.'/decisoes', [...$this->f['proposal'], 'basis_hash' => $basis['hash']])->assertSessionHasErrors('admission');
|
||||
$decision = admissionAttempt($this, ['basis_hash' => $basis['hash'], 'outcome' => 'clarify']);
|
||||
admissionConfer($this, $decision);
|
||||
admissionConfer($this, $decision, $this->f['other_analyst']);
|
||||
expect(app(FormalAdmission::class)->admitted($this->f['r'], $decision->quotation_id))->toBeFalse();
|
||||
})->with(['pending', 'not_met', 'not_applicable']);
|
||||
|
||||
test('optional uniform non compliance is permitted but analyst divergence is not', function () {
|
||||
$answers = $this->f['assessment']['answers'];
|
||||
$answers[1]['result'] = 'not_met';
|
||||
$this->actingAs($this->f['analyst']);
|
||||
app(DocumentaryQualificationWorkflow::class)->assess($this->f['analyst'], $this->f['set'], [...$this->f['assessment'], 'previous_id' => $this->f['record']->id, 'answers' => $answers]);
|
||||
expect(app(FormalAdmission::class)->basis($this->f['r'], $this->f['quote']->id)['clear'])->toBeTrue();
|
||||
$this->actingAs($this->f['other_analyst']);
|
||||
app(DocumentaryQualificationWorkflow::class)->assess($this->f['other_analyst'], $this->f['set'], $this->f['assessment']);
|
||||
expect(app(FormalAdmission::class)->basis($this->f['r'], $this->f['quote']->id)['clear'])->toBeFalse();
|
||||
});
|
||||
|
||||
test('qualification changes invalidate pending reviews and confirmed selection', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
admissionConfer($this, $decision);
|
||||
$this->f['quote']->update(['reference' => 'Base modificada no teste']);
|
||||
$this->actingAs($this->f['other_analyst'])->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência sobre base antiga'])->assertSessionHasErrors('admission');
|
||||
expect(app(FormalAdmission::class)->admitted($this->f['r'], $decision->quotation_id))->toBeFalse()->and(AdmissionReview::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('new company policy never rewrites a pinned process and new adoption resets decisions', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
admissionConfer($this, $decision);
|
||||
$this->actingAs($this->f['admin']);
|
||||
$workflow = app(FormalAdmission::class);
|
||||
$new = $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', ['policy_id' => $new->id, 'previous_id' => $this->f['adoption']->id, 'reason' => 'Tentativa fictícia desactivada'])->assertSessionHasErrors('admission');
|
||||
admissionConfer($this, $decision, $this->f['other_analyst']);
|
||||
expect($workflow->admitted($this->f['r'], $decision->quotation_id))->toBeTrue()->and($this->f['adoption']->refresh()->snapshot['required_count'])->toBe(2);
|
||||
$this->actingAs($this->f['admin']);
|
||||
$enabled = $workflow->policy($this->f['admin'], [...$this->f['policy_data'], 'previous_id' => $new->id, 'required_count' => 1]);
|
||||
$this->actingAs($this->f['buyer']);
|
||||
$next = $workflow->adopt($this->f['buyer'], $this->f['r'], $enabled->id, $this->f['adoption']->id, 'Nova versão expressamente adoptada');
|
||||
expect($next->snapshot['required_count'])->toBe(1)->and($workflow->admitted($this->f['r'], $decision->quotation_id))->toBeFalse()->and(AdmissionDecision::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('self confirmation and stale reviewer roles are rejected and prior approvals revalidated', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
$this->f['buyer']->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->actingAs($this->f['buyer']->fresh())->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Tentativa fictícia de auto aprovação'])->assertForbidden();
|
||||
admissionConfer($this, $decision);
|
||||
$this->f['analyst']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
$this->actingAs($this->f['other_analyst'])->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência com primeiro revogado'])->assertSessionHasErrors('admission');
|
||||
$this->f['other_analyst']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
||||
$this->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'returned', 'reason' => 'Conferente entretanto revogado'])->assertForbidden();
|
||||
expect(AdmissionReview::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('company policy requires explicit values and admin role and optimistic version', function () {
|
||||
$this->post('/politica-admissao', $this->f['policy_data'])->assertForbidden();
|
||||
$this->actingAs($this->f['admin'])->post('/politica-admissao', ['previous_id' => $this->f['policy']->id, 'enabled' => true, 'roles' => [], 'reason' => 'Configuração sem quórum definido'])->assertSessionHasErrors(['roles', 'required_count']);
|
||||
$this->post('/politica-admissao', $this->f['policy_data'])->assertSessionHasErrors('admission');
|
||||
$this->get('/politica-admissao')->assertOk()->assertInertia(fn (Assert $p) => $p->component('purchases/admission-policy')->has('policies.data', 1));
|
||||
expect(AdmissionPolicy::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('head department scope requester segregation cross tenant and audit rollback are enforced', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
$this->actingAs($this->f['issuer'])->post($this->url.'/decisoes', $this->f['proposal'])->assertForbidden();
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa distinta fictícia']);
|
||||
$outsider = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($outsider)->get($this->url)->assertNotFound();
|
||||
$this->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência de outra empresa'])->assertNotFound();
|
||||
$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();
|
||||
$this->actingAs($this->f['buyer']);
|
||||
$before = AdmissionDecision::query()->count();
|
||||
DB::statement("CREATE TRIGGER fail_admission_audit BEFORE INSERT ON audit_logs WHEN NEW.action = 'admission.proposed' BEGIN SELECT RAISE(ABORT, 'test audit failure'); END");
|
||||
try {
|
||||
app(FormalAdmission::class)->propose($this->f['buyer'], $this->f['r'], [...$this->f['proposal'], 'previous_id' => $decision->id]);
|
||||
$this->fail('Missing rollback');
|
||||
} catch (QueryException) {
|
||||
expect(AdmissionDecision::query()->count())->toBe($before);
|
||||
} finally {
|
||||
DB::statement('DROP TRIGGER fail_admission_audit');
|
||||
}
|
||||
});
|
||||
|
||||
test('active process conflict prevents conference without creating approval', function () {
|
||||
$decision = admissionAttempt($this);
|
||||
ConflictDeclaration::query()->create(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['analyst']->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['analyst'])->post('/admissoes/'.$decision->id.'/conferir', ['verdict' => 'approved', 'reason' => 'Conferência bloqueada por conflito'])->assertSessionHasErrors('conflict');
|
||||
expect(AdmissionReview::query()->count())->toBe(0);
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AdmissionAdoption;
|
||||
use App\Models\AdmissionDecision;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\AwardCancellation;
|
||||
use App\Models\Budget;
|
||||
@@ -27,7 +29,9 @@ use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\FormalAdmission;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
@@ -57,6 +61,29 @@ function selectPurchaseAward(object $test): PurchaseAward
|
||||
return PurchaseAward::query()->firstOrFail();
|
||||
}
|
||||
|
||||
function prepareFormalAwardAdmission(object $test): void
|
||||
{
|
||||
$workflow = app(FormalAdmission::class);
|
||||
$test->actingAs($test->admin);
|
||||
$policy = $workflow->policy($test->admin, ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance', 'department_head'], 'required_count' => 2, 'reason' => 'Política fictícia para adjudicação']);
|
||||
$test->actingAs($test->buyer);
|
||||
$workflow->adopt($test->buyer, $test->r, $policy->id, 0, 'Adopção fictícia antes da adjudicação');
|
||||
$opening = app(ProposalOpeningWorkflow::class);
|
||||
$documentary = app(DocumentaryQualificationWorkflow::class);
|
||||
$set = $documentary->define($test->buyer, $test->r, ['previous_id' => 0, 'basis_hash' => $opening->basis($opening->proposals($test->r)), 'reason' => 'Requisito exclusivamente fictício', 'criteria' => [['label' => 'Conformidade documentada', 'category' => 'technical', 'required' => true]]]);
|
||||
foreach ($test->quotes as $quote) {
|
||||
$test->actingAs($test->finance);
|
||||
$documentary->assess($test->finance, $set, ['previous_id' => 0, 'quotation_id' => $quote->id, 'reason' => 'Análise exclusivamente fictícia', 'answers' => [['criterion_id' => 1, 'result' => 'met', 'evidence' => 'Documento fictício', 'reason' => 'Conformidade confirmada no teste']]]);
|
||||
$test->actingAs($test->buyer);
|
||||
$decision = $workflow->propose($test->buyer, $test->r, ['quotation_id' => $quote->id, 'previous_id' => 0, 'basis_hash' => $workflow->basis($test->r, $quote->id)['hash'], 'outcome' => 'admit', 'reason' => 'Proposta fundamentada no teste']);
|
||||
foreach ([$test->finance, $test->head] as $reviewer) {
|
||||
$test->actingAs($reviewer);
|
||||
$workflow->review($reviewer, $decision, 'approved', 'Conferência independente fictícia');
|
||||
}
|
||||
}
|
||||
$test->actingAs($test->buyer);
|
||||
}
|
||||
|
||||
function approvePurchaseAward(object $test, PurchaseAward $award): void
|
||||
{
|
||||
foreach ($award->approvals()->get() as $step) {
|
||||
@@ -644,3 +671,52 @@ test('review report reflects tied source scores and existing frozen orders witho
|
||||
$report = app(ProcurementReviewReport::class)->build($this->buyer, $this->r->id);
|
||||
expect($report['order']['number'])->toBe($order->number)->and($report['order']['total_minor'])->toBe(10000);
|
||||
});
|
||||
|
||||
test('adopted formal admission preserves scoring and binds award and issued order', function () {
|
||||
$before = app(ProposalComparison::class)->inspect($this->r);
|
||||
prepareFormalAwardAdmission($this);
|
||||
$after = app(ProposalComparison::class)->inspect($this->r);
|
||||
expect($after['ready'])->toBeTrue()->and(array_column($after['rows'], 'score_minor'))->toBe(array_column($before['rows'], 'score_minor'));
|
||||
$award = selectPurchaseAward($this);
|
||||
expect($award->admission_snapshot['review_ids'])->toHaveCount(2)->and($award->admission_snapshot['adoption_id'])->toBeGreaterThan(0);
|
||||
$order = issuePurchaseOrder($this, $award);
|
||||
expect($order->snapshot['admission'])->toBe($award->admission_snapshot);
|
||||
$this->suppliers[0]->update(['name' => 'Alteração posterior à emissão']);
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
||||
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->refresh()->snapshot['supplier']['name'])->toBe('Fornecedor 0');
|
||||
$this->post('/requisicoes/'.$this->r->id.'/admissao/adoptar', ['policy_id' => 1, 'previous_id' => 1, 'reason' => 'Tentativa após a emissão'])->assertSessionHasErrors('admission');
|
||||
});
|
||||
|
||||
test('formal exclusions cannot enter selection and minimum three eligible suppliers remains', function () {
|
||||
prepareFormalAwardAdmission($this);
|
||||
$workflow = app(FormalAdmission::class);
|
||||
$adoption = $workflow->adoption($this->r);
|
||||
$previous = AdmissionDecision::query()->where('quotation_id', $this->quotes[0]->id)->latest('id')->firstOrFail();
|
||||
$decision = $workflow->propose($this->buyer, $this->r, ['quotation_id' => $this->quotes[0]->id, 'previous_id' => $previous->id, 'basis_hash' => $previous->basis_hash, 'outcome' => 'exclude', 'reason' => 'Exclusão fictícia fundamentada']);
|
||||
foreach ([$this->finance, $this->head] as $reviewer) {
|
||||
$this->actingAs($reviewer);
|
||||
$workflow->review($reviewer, $decision, 'approved', 'Conferência de exclusão fictícia');
|
||||
}
|
||||
expect($workflow->status($decision, $adoption))->toBe('confirmed')->and(app(ProposalComparison::class)->inspect($this->r)['ready'])->toBeFalse();
|
||||
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors();
|
||||
expect(PurchaseAward::query()->count())->toBe(0)->and(BudgetEntry::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('admission basis changes block emission and existing legacy award cannot adopt retroactively', function () {
|
||||
prepareFormalAwardAdmission($this);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
$this->suppliers[0]->update(['name' => 'Nome alterado antes de emitir']);
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors();
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('legacy award keeps null admission basis and refuses later adoption', function () {
|
||||
$award = selectPurchaseAward($this);
|
||||
expect($award->admission_snapshot)->toBeNull();
|
||||
$this->actingAs($this->admin);
|
||||
$policy = app(FormalAdmission::class)->policy($this->admin, ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance'], 'required_count' => 1, 'reason' => 'Política fictícia posterior']);
|
||||
$this->actingAs($this->buyer)->post('/requisicoes/'.$this->r->id.'/admissao/adoptar', ['policy_id' => $policy->id, 'previous_id' => 0, 'reason' => 'Adopção retroactiva impedida'])->assertSessionHasErrors('admission');
|
||||
expect(AdmissionAdoption::query()->count())->toBe(0);
|
||||
issuePurchaseOrder($this, $award);
|
||||
});
|
||||
|
||||
@@ -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', 2)
|
||||
->has('future', 1)
|
||||
->where('documents', fn ($documents) => collect($documents)->contains('label', $f['invoice']->number)));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\FormalAdmission;
|
||||
|
||||
require_once __DIR__.'/QualificationFixture.php';
|
||||
|
||||
/** Synthetic data only; the underlying fixture enforces an isolated database. */
|
||||
function admissionFixture(int $quorum = 2): array
|
||||
{
|
||||
$f = qualificationFixture();
|
||||
$admin = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$buyer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$set = app(DocumentaryQualificationWorkflow::class)->define($f['issuer'], $f['r'], $f['definition']);
|
||||
$assessment = $f['assessment'];
|
||||
$assessment['answers'][1] = ['criterion_id' => 2, 'result' => 'met', 'evidence' => 'Referência fictícia 2', 'reason' => 'Conformidade conferida em teste isolado'];
|
||||
auth()->guard()->setUser($f['analyst']);
|
||||
$record = app(DocumentaryQualificationWorkflow::class)->assess($f['analyst'], $set, $assessment);
|
||||
$workflow = app(FormalAdmission::class);
|
||||
$policyData = ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance'], 'required_count' => $quorum, 'reason' => 'Configuraçã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 exclusivamente fictícia');
|
||||
$proposal = ['quotation_id' => $f['quote']->id, 'previous_id' => 0, 'basis_hash' => $workflow->basis($f['r'], $f['quote']->id)['hash'], 'outcome' => 'admit', 'reason' => 'Proposta exclusivamente fictícia'];
|
||||
|
||||
return [...$f, 'admin' => $admin, 'buyer' => $buyer, 'set' => $set, 'record' => $record, 'assessment' => $assessment, 'policy' => $policy, 'policy_data' => $policyData, 'adoption' => $adoption, 'proposal' => $proposal];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000019.
|
||||
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_000019_create_formal_admission';
|
||||
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-admission-000019-'.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, 'admission_policies_count' => (int) $pdo->query('SELECT count(*) FROM admission_policies')->fetchColumn(), 'admission_adoptions_count' => (int) $pdo->query('SELECT count(*) FROM admission_adoptions')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/admissao-migracao-000019.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