Implementa revisao de adjudicacoes e navegacao partilhada do SGC

This commit is contained in:
2026-10-28 17:46:59 +02:00
parent 5ff8d78803
commit ff403ea927
28 changed files with 1767 additions and 131 deletions
+109
View File
@@ -2,7 +2,9 @@
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\AwardCancellation;
use App\Models\Budget;
use App\Models\BudgetEntry;
use App\Models\CostCenter;
use App\Models\CriticalityLevel;
use App\Models\Department;
@@ -10,7 +12,9 @@ use App\Models\Equipment;
use App\Models\EquipmentSparePart;
use App\Models\InvestmentPolicy;
use App\Models\PurchaseAward;
use App\Models\PurchaseControlPolicy;
use App\Models\PurchaseOrder;
use App\Models\PurchaseRevision;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\SparePart;
@@ -23,6 +27,8 @@ use App\Models\Warehouse;
use App\Services\BudgetWorkflow;
use App\Services\ConflictGuard;
use App\Services\EquipmentWorkflow;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow;
use App\Services\RequisitionWorkflow;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
@@ -504,3 +510,106 @@ test('final approval rechecks a department head who moved departments', function
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
expect($award->approvals()->where('decision', 'approved')->count())->toBe(0);
});
function enablePurchaseCancellation(object $test): PurchaseControlPolicy
{
$admins = [$test->admin, User::factory()->create(['tenant_id' => $test->tenant->id, 'purchasing_role' => PurchasingRole::Admin]), User::factory()->create(['tenant_id' => $test->tenant->id, 'purchasing_role' => PurchasingRole::Admin])];
$test->actingAs($admins[0]);
$workflow = app(PurchaseControlPolicyWorkflow::class);
$policy = $workflow->propose($admins[0], ['previous_id' => 0, 'mode' => 'unissued_award', 'enabled' => true, 'valid_from' => today()->format('Y-m-d'), 'valid_until' => today()->addMonth()->format('Y-m-d'), 'reason' => 'Regra fictícia para teste isolado']);
foreach ([$admins[1], $admins[2]] as $admin) {
$test->actingAs($admin);
$workflow->review($admin, $policy, 'approved', 'Validação independente fictícia');
}
return $policy->refresh();
}
test('cancellation requires an explicitly published company policy', function () {
$award = selectPurchaseAward($this);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasErrors('cancellation');
expect(AwardCancellation::query()->count())->toBe(0);
});
test('pending cancellation freezes final approval and rejection resumes the original process', function () {
enablePurchaseCancellation($this);
$award = selectPurchaseAward($this);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
$this->actingAs($this->head)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasErrors('cancellation');
$cancel = AwardCancellation::query()->firstOrFail();
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'rejected', 'reason' => 'Manter o processo original fictício'])->assertSessionHasNoErrors();
issuePurchaseOrder($this, $award);
expect(PurchaseOrder::query()->count())->toBe(1);
});
test('approved cancellation preserves history and creates exactly one fresh requester draft', function () {
enablePurchaseCancellation($this);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$steps = $award->approvals()->count();
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('cancellation');
$cancel = AwardCancellation::query()->firstOrFail();
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'approved', 'reason' => 'Cancelamento independente fictício'])->assertSessionHasNoErrors();
expect($award->refresh()->status)->toBe('cancelled')->and($this->r->refresh()->status)->toBe('cancelled')->and($award->approvals()->count())->toBe($steps)->and(Quotation::query()->count())->toBe(3);
$this->actingAs($this->owner);
$data = ['needed_by' => today()->addWeek()->format('Y-m-d'), 'justification' => 'Nova necessidade fictícia actualizada'];
$this->post('/cancelamentos/'.$cancel->id.'/revisao', $data)->assertSessionHasNoErrors();
$this->post('/cancelamentos/'.$cancel->id.'/revisao', $data)->assertSessionHasNoErrors();
$link = PurchaseRevision::query()->sole();
$draft = Requisition::query()->findOrFail($link->requisition_id);
expect($draft->status)->toBe('draft')->and($draft->steps()->count())->toBe(0)->and($draft->items()->count())->toBe(1)->and($draft->total_minor)->toBe($this->r->total_minor)->and(PurchaseOrder::query()->count())->toBe(0);
});
test('issued orders cannot enter the cancellation circuit', function () {
enablePurchaseCancellation($this);
$award = selectPurchaseAward($this);
issuePurchaseOrder($this, $award);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Tentativa fictícia após emissão'])->assertSessionHasErrors('cancellation');
expect(AwardCancellation::query()->count())->toBe(0)->and(PurchaseOrder::query()->count())->toBe(1);
});
test('cancellation cannot be self reviewed after a role change', function () {
enablePurchaseCancellation($this);
$award = selectPurchaseAward($this);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
$cancel = AwardCancellation::query()->firstOrFail();
DB::table('users')->where('id', $this->buyer->id)->update(['purchasing_role' => 'finance']);
$this->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'approved', 'reason' => 'Tentativa de auto aprovação fictícia'])->assertForbidden();
expect($cancel->refresh()->status)->toBe('pending');
});
test('cancellation releases the unused budget reservation exactly once', function () {
prepareEquipmentInvestment($this);
enablePurchaseCancellation($this);
$award = selectPurchaseAward($this);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
$cancel = AwardCancellation::query()->firstOrFail();
$data = ['decision' => 'approved', 'reason' => 'Libertação independente fictícia'];
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', $data)->assertSessionHasNoErrors();
$this->post('/cancelamentos/'.$cancel->id.'/decidir', $data)->assertSessionHasNoErrors();
expect(BudgetEntry::query()->where('requisition_id', $this->r->id)->sum('reserved_minor'))->toBe(0)
->and(BudgetEntry::query()->where('requisition_id', $this->r->id)->where('kind', 'release')->count())->toBe(1);
});
test('cancellation and reservation release roll back together if audit fails', function () {
prepareEquipmentInvestment($this);
enablePurchaseCancellation($this);
$award = selectPurchaseAward($this);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
$cancel = AwardCancellation::query()->firstOrFail();
$this->actingAs($this->finance);
AuditLog::creating(function (AuditLog $entry) {
if ($entry->action === 'cancellation.approved') {
throw new RuntimeException('Falha fictícia de auditoria');
}
});
try {
expect(fn () => app(PurchaseRevisionWorkflow::class)->review($this->finance, $cancel, 'approved', 'Teste de atomicidade fictício'))->toThrow(RuntimeException::class);
} finally {
AuditLog::flushEventListeners();
}
expect($cancel->refresh()->status)->toBe('pending')->and($award->refresh()->status)->toBe('pending')
->and(BudgetEntry::query()->where('kind', 'release')->count())->toBe(0)
->and((int) BudgetEntry::query()->sum('reserved_minor'))->toBeGreaterThan(0);
});
@@ -0,0 +1,111 @@
<?php
// Explicit operational entry point: backup, restore verification, then only migration 000015.
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_000015_create_purchase_controls';
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/purchase-controls-000015-'.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, 'purchase_control_policies_count' => (int) $pdo->query('SELECT count(*) FROM purchase_control_policies')->fetchColumn(), 'purchase_control_reviews_count' => (int) $pdo->query('SELECT count(*) FROM purchase_control_reviews')->fetchColumn(), 'operational_validation' => false];
file_put_contents(base_path('docs/revisao-migracao-000015.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));
}
}