Implementa regras de investimento por empresa com dupla aprovacao
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use App\Models\InvestmentPolicy;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
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_investment_'.$argv[4]]);
|
||||
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
|
||||
$user = User::query()->findOrFail($argv[2]);
|
||||
auth()->guard()->setUser($user);
|
||||
$payload = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
if ($payload['action'] === 'propose') {
|
||||
app(InvestmentWorkflow::class)->propose($user, $payload['data']);
|
||||
} else {
|
||||
app(InvestmentWorkflow::class)->review($user, InvestmentPolicy::query()->findOrFail($argv[3]), 'approved', 'Conferência administrativa de teste');
|
||||
}
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
}
|
||||
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\InvestmentPolicy;
|
||||
use App\Models\InvestmentPolicyReview;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentWorkflow;
|
||||
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/ReceiptFixture.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 (['distinct_approvals', 'same_approval', 'competing_versions'] as $scenario) {
|
||||
$f = receiptFixture();
|
||||
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$first = User::factory()->create(['tenant_id' => $author->tenant_id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$second = User::factory()->create(['tenant_id' => $author->tenant_id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
auth()->guard()->setUser($author);
|
||||
$data = ['previous_id' => 0, 'mode' => 'ceiling', 'scope' => 'process_total', 'currency' => 'MZN', 'ceiling' => '100.00', 'includes_tax' => true, 'valid_from' => today()->format('Y-m-d'), 'valid_until' => today()->addMonth()->format('Y-m-d'), 'reason' => 'Apenas teste isolado'];
|
||||
$policy = app(InvestmentWorkflow::class)->propose($author, $data);
|
||||
$payload = ['action' => 'review'];
|
||||
$target = $policy->id;
|
||||
if ($scenario === 'same_approval') {
|
||||
$second = $first;
|
||||
} elseif ($scenario === 'competing_versions') {
|
||||
$first = $second = $author;
|
||||
$payload = ['action' => 'propose', 'data' => [...$data, 'previous_id' => $policy->id]];
|
||||
}
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $author->tenant_id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach ([$first, $second] as $index => $user) {
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/investment-worker.php', $database, (string) $user->id, (string) $target, $index === 0 ? 'A' : 'B'], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
$process->setTimeout(40);
|
||||
$process->start();
|
||||
$processes[] = $process;
|
||||
}
|
||||
$statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name IN ('sgc_investment_A','sgc_investment_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);
|
||||
$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);
|
||||
$state = InvestmentPolicy::query()->latest('revision')->firstOrFail()->status;
|
||||
$count = InvestmentPolicyReview::query()->count();
|
||||
if ($statuses !== ($scenario === 'competing_versions' ? [200, 422] : [200, 200]) || $state !== ($scenario === 'distinct_approvals' ? 'approved' : 'pending') || $count !== match ($scenario) {
|
||||
'distinct_approvals' => 2, 'same_approval' => 1, default => 0
|
||||
} || InvestmentPolicy::query()->count() !== ($scenario === 'competing_versions' ? 2 : 1) || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
|
||||
throw new RuntimeException('Resultado concorrente de regras inesperado.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'state' => $state, 'review_count' => $count];
|
||||
}
|
||||
$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/investimento-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,130 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\InvestmentPolicy;
|
||||
use App\Models\InvestmentPolicyReview;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/InvestmentFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->admins = [];
|
||||
for ($index = 0; $index < 3; $index++) {
|
||||
$this->admins[] = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
}
|
||||
$this->actingAs($this->admins[0]);
|
||||
$this->data = ['previous_id' => 0, 'mode' => 'ceiling', 'scope' => 'process_total', 'currency' => 'MZN', 'ceiling' => '100.00', 'includes_tax' => true, 'valid_from' => today()->format('Y-m-d'), 'valid_until' => today()->addMonth()->format('Y-m-d'), 'reason' => 'Decisão explícita fictícia'];
|
||||
});
|
||||
|
||||
function proposeInvestmentTest(object $test): InvestmentPolicy
|
||||
{
|
||||
$test->actingAs($test->admins[0]);
|
||||
|
||||
return app(InvestmentWorkflow::class)->propose($test->admins[0], $test->data);
|
||||
}
|
||||
|
||||
function reviewInvestmentTest(object $test, InvestmentPolicy $policy, int $actor, string $decision = 'approved'): void
|
||||
{
|
||||
$test->actingAs($test->admins[$actor]);
|
||||
app(InvestmentWorkflow::class)->review($test->admins[$actor], $policy, $decision, 'Conferência administrativa de teste');
|
||||
}
|
||||
|
||||
test('investment policy requires two independent administrators without counting repeats', function () {
|
||||
$policy = proposeInvestmentTest($this);
|
||||
reviewInvestmentTest($this, $policy, 1);
|
||||
reviewInvestmentTest($this, $policy, 1);
|
||||
expect($policy->refresh()->status)->toBe('pending')->and(InvestmentPolicyReview::query()->count())->toBe(1);
|
||||
reviewInvestmentTest($this, $policy, 2);
|
||||
expect($policy->refresh()->status)->toBe('approved')->and(app(InvestmentWorkflow::class)->requireCurrent()->id)->toBe($policy->id);
|
||||
});
|
||||
|
||||
test('policy author cannot approve own proposal', function () {
|
||||
$policy = proposeInvestmentTest($this);
|
||||
$this->post('/regras-investimento/'.$policy->id.'/decidir', ['decision' => 'approved', 'reason' => 'Teste'])->assertForbidden();
|
||||
});
|
||||
|
||||
test('policy parameters and decisions cannot be rewritten', function () {
|
||||
$policy = proposeInvestmentTest($this);
|
||||
expect(fn () => $policy->update(['ceiling_minor' => 1]))->toThrow(LogicException::class);
|
||||
reviewInvestmentTest($this, $policy, 1, 'rejected');
|
||||
expect(fn () => reviewInvestmentTest($this, $policy, 2))->toThrow(ValidationException::class);
|
||||
expect(fn () => InvestmentPolicyReview::query()->firstOrFail()->delete())->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('an unapproved draft does not replace an approved company rule', function () {
|
||||
$approved = publishInvestmentFixture($this->f['tenant']->id);
|
||||
$this->data['previous_id'] = $approved->id;
|
||||
$draft = proposeInvestmentTest($this);
|
||||
expect($draft->status)->toBe('pending')->and(app(InvestmentWorkflow::class)->requireCurrent()->id)->toBe($approved->id);
|
||||
});
|
||||
|
||||
test('new rule starts on its explicit date and expiry cannot restore an older more permissive rule', function () {
|
||||
$old = publishInvestmentFixture($this->f['tenant']->id, '500.00');
|
||||
$this->data['previous_id'] = $old->id;
|
||||
$this->data['valid_from'] = today()->addDay()->format('Y-m-d');
|
||||
$this->data['valid_until'] = today()->addDays(2)->format('Y-m-d');
|
||||
$new = proposeInvestmentTest($this);
|
||||
reviewInvestmentTest($this, $new, 1);
|
||||
reviewInvestmentTest($this, $new, 2);
|
||||
expect(app(InvestmentWorkflow::class)->requireCurrent()->id)->toBe($old->id);
|
||||
$this->travel(1)->days();
|
||||
expect(app(InvestmentWorkflow::class)->requireCurrent()->id)->toBe($new->id);
|
||||
$this->travel(3)->days();
|
||||
expect(fn () => app(InvestmentWorkflow::class)->requireCurrent())->toThrow(ValidationException::class);
|
||||
$this->travelBack();
|
||||
});
|
||||
|
||||
test('stale proposals and decisions on superseded drafts are refused', function () {
|
||||
$first = proposeInvestmentTest($this);
|
||||
expect(fn () => proposeInvestmentTest($this))->toThrow(ValidationException::class);
|
||||
$this->data['previous_id'] = $first->id;
|
||||
proposeInvestmentTest($this);
|
||||
expect(fn () => reviewInvestmentTest($this, $first, 1))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('unsupported limit semantics cannot be configured by the browser', function (string $field, string $value) {
|
||||
$this->post('/regras-investimento', [...$this->data, $field => $value])->assertSessionHasErrors($field);
|
||||
expect(InvestmentPolicy::query()->count())->toBe(0);
|
||||
})->with([['mode', 'additional_approval'], ['scope', 'project'], ['currency', 'USD']]);
|
||||
|
||||
test('finance and procurement may read company rules but cannot change them', function (PurchasingRole $role) {
|
||||
$user = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => $role]);
|
||||
$this->actingAs($user)->get('/regras-investimento')->assertOk();
|
||||
$this->post('/regras-investimento', $this->data)->assertForbidden();
|
||||
})->with([PurchasingRole::Finance, PurchasingRole::Procurement]);
|
||||
|
||||
test('foreign administrators cannot read or approve another company policy', function () {
|
||||
$policy = proposeInvestmentTest($this);
|
||||
$other = receiptFixture();
|
||||
$user = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($user)->post('/regras-investimento/'.$policy->id.'/decidir', ['decision' => 'approved', 'reason' => 'Teste'])->assertNotFound();
|
||||
$this->get('/regras-investimento')->assertOk()->assertInertia(fn ($page) => $page->has('policies', 0));
|
||||
});
|
||||
|
||||
test('audit failure rolls back policy proposal and publication decision', function () {
|
||||
$policy = proposeInvestmentTest($this);
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
|
||||
expect(fn () => reviewInvestmentTest($this, $policy, 1))->toThrow(RuntimeException::class);
|
||||
expect(InvestmentPolicyReview::query()->count())->toBe(0);
|
||||
$this->data['previous_id'] = $policy->id;
|
||||
expect(fn () => proposeInvestmentTest($this))->toThrow(RuntimeException::class);
|
||||
expect(InvestmentPolicy::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('an administrator losing eligibility before publication blocks the second signature', function () {
|
||||
$policy = proposeInvestmentTest($this);
|
||||
reviewInvestmentTest($this, $policy, 1);
|
||||
$this->admins[1]->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
expect(fn () => reviewInvestmentTest($this, $policy, 2))->toThrow(ValidationException::class);
|
||||
expect($policy->refresh()->status)->toBe('pending');
|
||||
});
|
||||
|
||||
test('public investment example contains no company policies', function () {
|
||||
auth()->forgetGuards();
|
||||
$this->get('/consulta/investimento')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'investment')->where('auth.user', null)->missing('policies')->missing('reviews'));
|
||||
});
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Budget;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\CriticalityLevel;
|
||||
use App\Models\Department;
|
||||
use App\Models\Equipment;
|
||||
use App\Models\EquipmentSparePart;
|
||||
use App\Models\InvestmentPolicy;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Quotation;
|
||||
@@ -18,6 +20,9 @@ use App\Models\Supplier;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -60,6 +65,27 @@ function issuePurchaseOrder(object $test, PurchaseAward $award): PurchaseOrder
|
||||
return PurchaseOrder::query()->firstOrFail();
|
||||
}
|
||||
|
||||
function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy
|
||||
{
|
||||
require_once __DIR__.'/../Support/InvestmentFixture.php';
|
||||
$test->item->update(['purchase_type' => 'equipment', 'production_area' => 'Linha fictícia de investimento']);
|
||||
$test->r->update(['status' => 'draft']);
|
||||
$test->r->refresh();
|
||||
$test->actingAs($test->head);
|
||||
$technical = app(EquipmentWorkflow::class);
|
||||
$technical->review($test->head, $test->r, $technical->basis($test->r), 'approved', 'Validação técnica fictícia independente.');
|
||||
$test->r->update(['status' => 'approved']);
|
||||
$test->r->steps()->create(['tenant_id' => $test->tenant->id, 'position' => 2, 'role' => 'finance', 'decision' => 'approved', 'approver_id' => $test->finance->id, 'decided_at' => now()]);
|
||||
$test->actingAs($test->owner);
|
||||
Budget::query()->create(['tenant_id' => $test->tenant->id, 'cost_center_id' => $test->r->cost_center_id, 'year' => now()->year, 'kind' => 'investment', 'amount_minor' => 100000, 'includes_tax' => true, 'created_by' => $test->admin->id, 'approved_by' => $test->finance->id, 'reason' => 'Dotação fictícia de investimento']);
|
||||
DB::transaction(function () use ($test) {
|
||||
app(ConflictGuard::class)->lockCompany($test->owner);
|
||||
app(BudgetWorkflow::class)->record($test->owner, $test->r, 'reserve', $test->r->total_minor, $test->r->subtotal_minor);
|
||||
});
|
||||
|
||||
return publishInvestmentFixture($test->tenant->id, $ceiling, $includesTax);
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
$this->tenant = Tenant::query()->create(['name' => 'Empresa das ordens']);
|
||||
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Produção']);
|
||||
@@ -402,3 +428,61 @@ test('spare purchase flows through award order receipt and issue with equipment
|
||||
$this->postJson('/stock/operacoes', ['kind' => 'issue', 'reference' => 'SAI-FLOW', 'idempotency_key' => (string) Str::uuid(), 'warehouse_id' => $warehouse->id, 'stock_item_id' => $stock->id, 'responsible_id' => $receiver->id, 'destination' => 'Produção', 'reason' => 'Montagem no equipamento', 'quantity' => '0.500', 'equipment_id' => $asset->id])->assertCreated();
|
||||
expect((int) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(500)->and(StockMovement::query()->where('equipment_id', $asset->id)->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('equipment within the explicit inclusive investment ceiling requires finance and flows through receipt', function () {
|
||||
$policy = prepareEquipmentInvestment($this);
|
||||
$award = selectPurchaseAward($this);
|
||||
expect($award->approvals()->pluck('role')->all())->toBe(['department_head', 'finance']);
|
||||
$order = issuePurchaseOrder($this, $award);
|
||||
expect($order->snapshot['investment_rules']['id'])->toBe($policy->id)
|
||||
->and($order->snapshot['investment_rules']['ceiling_minor'])->toBe(10000)
|
||||
->and($order->snapshot['equipment_requests'][0]['production_area'])->toBe('Linha fictícia de investimento');
|
||||
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
||||
$this->actingAs($receiver);
|
||||
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'INV', 'name' => 'Armazém fictício']);
|
||||
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'EQ-INV', 'name' => 'Equipamento recebido fictício', 'unit' => 'un']);
|
||||
$this->postJson('/ordens/'.$order->id.'/recepcoes', ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-INV', 'received_on' => today()->format('Y-m-d'), 'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->firstOrFail()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]])->assertCreated();
|
||||
expect((int) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
|
||||
publishInvestmentFixture($this->tenant->id, '200.00');
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
||||
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->refresh()->snapshot['investment_rules']['ceiling_minor'])->toBe(10000);
|
||||
});
|
||||
|
||||
test('equipment above the company investment ceiling cannot be awarded', function () {
|
||||
prepareEquipmentInvestment($this, '99.99');
|
||||
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors('investment');
|
||||
expect(PurchaseAward::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('investment tax basis is explicit and independent of ordinary approval tiers', function (bool $includesTax) {
|
||||
awardPrices($this, 10000, 16);
|
||||
prepareEquipmentInvestment($this, '100.00', $includesTax);
|
||||
if ($includesTax) {
|
||||
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors('investment');
|
||||
} else {
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
expect($order->total_minor)->toBe(11600)->and($order->snapshot['investment_rules']['includes_tax'])->toBeFalse();
|
||||
}
|
||||
})->with([true, false]);
|
||||
|
||||
test('a newly published investment policy cannot reuse an existing final approval cycle', function () {
|
||||
prepareEquipmentInvestment($this);
|
||||
$award = selectPurchaseAward($this);
|
||||
approvePurchaseAward($this, $award);
|
||||
publishInvestmentFixture($this->tenant->id, '200.00');
|
||||
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('investment');
|
||||
expect(PurchaseOrder::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('equipment cannot bypass technical finance or investment budget requirements', function (string $missing) {
|
||||
prepareEquipmentInvestment($this);
|
||||
if ($missing === 'technical') {
|
||||
DB::table('technical_reviews')->where('requisition_id', $this->r->id)->delete();
|
||||
} elseif ($missing === 'finance') {
|
||||
$this->r->steps()->where('role', 'finance')->delete();
|
||||
} else {
|
||||
DB::table('budgets')->where('tenant_id', $this->tenant->id)->update(['kind' => 'operating']);
|
||||
}
|
||||
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors($missing === 'technical' ? 'technical' : ($missing === 'finance' ? 'approvals' : 'investment'));
|
||||
expect(PurchaseAward::query()->count())->toBe(0);
|
||||
})->with(['technical', 'finance', 'budget']);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\InvestmentPolicy;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
function publishInvestmentFixture(int $tenantId, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy
|
||||
{
|
||||
$connection = DB::connection();
|
||||
$isolated = ($connection->getDriverName() === 'sqlite' && $connection->getDatabaseName() === ':memory:') || ($connection->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/', $connection->getDatabaseName()));
|
||||
if (! app()->environment('testing') || ! $isolated) {
|
||||
throw new LogicException('Regras fictícias proibidas na base de negócio.');
|
||||
}
|
||||
$admins = [];
|
||||
for ($index = 0; $index < 3; $index++) {
|
||||
$admins[] = User::factory()->create(['tenant_id' => $tenantId, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
}
|
||||
auth()->guard()->setUser($admins[0]);
|
||||
$previous = InvestmentPolicy::query()->latest('revision')->first();
|
||||
$policy = app(InvestmentWorkflow::class)->propose($admins[0], ['previous_id' => $previous->id ?? 0, 'mode' => 'ceiling', 'scope' => 'process_total', 'currency' => 'MZN', 'ceiling' => $ceiling, 'includes_tax' => $includesTax, 'valid_from' => today()->format('Y-m-d'), 'valid_until' => today()->addMonth()->format('Y-m-d'), 'reason' => 'Política fictícia para teste isolado']);
|
||||
foreach ([$admins[1], $admins[2]] as $admin) {
|
||||
auth()->guard()->setUser($admin);
|
||||
app(InvestmentWorkflow::class)->review($admin, $policy, 'approved', 'Decisão independente de teste');
|
||||
}
|
||||
|
||||
return $policy->refresh();
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000014.
|
||||
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_000014_create_investment_policies';
|
||||
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/investment-000014-'.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, 'investment_policies_count' => (int) $pdo->query('SELECT count(*) FROM investment_policies')->fetchColumn(), 'investment_policy_reviews_count' => (int) $pdo->query('SELECT count(*) FROM investment_policy_reviews')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/investimento-migracao-000014.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