commit melhorias compras5
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-22 19:39:09 +02:00
parent 36dcfdf00c
commit db1615fac1
79 changed files with 4082 additions and 120 deletions
@@ -0,0 +1,15 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Tempo\Finance\Budget\BudgetControl;
// No database access or business commands: exercise the host's actual pre-load verification.
require dirname(__DIR__, 2).'/vendor/autoload.php';
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
try {
$app->make(Kernel::class)->bootstrap();
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage().PHP_EOL);
exit(1);
}
echo json_encode(['runtime' => realpath((new ReflectionClass(BudgetControl::class))->getFileName())], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -19,6 +19,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderParts = ($argv[2] ?? '') === 'order-parts';
$f = receiptFixture();
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
@@ -63,17 +64,23 @@ $preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
budgetDistributionFixtureSchema();
if ($orderParts) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
}
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
}
$prepare = new Process([PHP_BINARY, __DIR__.'/budget-distribution-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __DIR__.($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php'), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
$engine = app(CommonBudget::class)->for($actor);
$engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
$apply = static fn ($engine) => $orderParts
? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
$apply($engine);
$afterColumns = [];
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
$afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
@@ -100,8 +107,7 @@ try {
DB::setDefaultConnection('distribution_restore');
$restoredActor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($restoredActor);
$again = app(CommonBudget::class)->for($restoredActor)->amendDistribution($input['origin'], $input['plan'], $input['hash'],
'Explicit synthetic amendment preserved in backup.', $input['operation']);
$again = $apply(app(CommonBudget::class)->for($restoredActor));
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Recovered command was not replayed without new effects.');
}
@@ -122,7 +128,7 @@ try {
if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) {
throw new RuntimeException('Pre-extension recovery changed the native balance.');
}
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => 4, 'existing_balances_preserved' => true,
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $orderParts ? 8 : 4, 'existing_balances_preserved' => true,
'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true,
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
@@ -0,0 +1,154 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|| (($argv[2] ?? '') !== 'legacy' && ! method_exists(BudgetControl::class, 'commitOrderParts'))) {
throw new LogicException('Order-part contention requires the explicit common source and disposable local QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
if (($argv[2] ?? '') === 'legacy') {
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
auth()->guard()->setUser($actor);
try {
app(CommonBudget::class)->for($actor);
throw new RuntimeException('The old runtime must refuse balances with partial-order effects.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 503 || method_exists(BudgetControl::class, 'commitOrderParts')) {
throw $error;
}
echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503], JSON_THROW_ON_ERROR).PHP_EOL;
}
exit;
}
if (($argv[2] ?? '') === 'prepare') {
$f = receiptFixture();
$source = unissuedOrderPartsSource($f, 10000);
$line = $source->items()->sole();
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
auth()->guard()->setUser($finance);
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 10000, 'reason' => 'Synthetic partial-order contention only.']);
auth()->guard()->setUser($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
auth()->guard()->setUser($f['issuer']);
$engine = app(CommonBudget::class)->for($f['issuer']);
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$plan = [['allocation_key' => 'synthetic', 'line_id' => $line->id, 'centre_id' => $f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
$engine->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
$award = $engine->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
'order' => (string) Str::uuid(), 'operation' => (string) Str::uuid(), 'sources' => [['origin' => $source->id, 'version' => 0,
'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]], JSON_THROW_ON_ERROR);
exit;
}
if (($argv[2] ?? '') === 'write') {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_order_parts_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$result = app(CommonBudget::class)->for($actor)->commitOrderParts($input['order'], $input['sources'], $input['operation']);
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (BudgetFailure $error) {
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
}
exit;
}
if (($argv[2] ?? '') !== 'race') {
throw new InvalidArgumentException('Invalid order-part worker mode.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
foreach (['same_operation', 'conflicting_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
$db = DB::connection();
$db->beginTransaction();
try {
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
for ($index = 0; $index < 2; $index++) {
if ($index === 1 && $scenario === 'conflicting_version') {
$input['operation'] = (string) Str::uuid();
$input['order'] = (string) Str::uuid();
$input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
$input['sources'][0]['allocations'][0]['total_minor'] = 6000;
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
$deadline = microtime(true) + 10;
do {
$db->select('select pg_stat_clear_snapshot()');
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_order_parts_write_%' and wait_event_type='Lock'", [$database])->n;
if ($blocked >= 2) {
break;
}
usleep(50000);
} while (microtime(true) < $deadline);
if ($blocked < 2) {
throw new RuntimeException('Both contenders must demonstrably wait on the company lock.');
}
$db->commit();
$results = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException($worker->getErrorOutput());
}
$results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
}
$statuses = array_column($results, 'status');
sort($statuses);
$entries = $db->table('budget_distribution_entries')->where('distribution_id', $input['source']);
$reserved = (int) (clone $entries)->sum('reserved_minor');
$committed = (int) (clone $entries)->sum('committed_minor');
$commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.orders_committed')->count();
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1
|| $reserved + $committed !== 10000 || ! in_array($committed, [4000, 6000], true)
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention did not preserve one command, one audit and the exact original budget.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved, 'committed_minor' => $committed], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
$legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy', (string) $input['actor']], dirname(__DIR__, 2),
['COMMON_BUDGET_PATH' => base_path($proof['path'])], timeout: 30);
$legacy->mustRun();
echo $legacy->getOutput();
}
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
@@ -0,0 +1,72 @@
<?php
use App\Services\BudgetDistributionArtifact;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
beforeEach(function () {
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
$this->artifactDirectory = storage_path('framework/testing/distribution-integrity-'.Str::uuid());
mkdir($this->artifactDirectory.'/src', 0700, true);
foreach ($proof['files'] as $file => $hash) {
copy(base_path($proof['path'].'/'.$file), $this->artifactDirectory.'/'.$file);
}
$this->artifactManifest = $this->artifactDirectory.'/manifest.json';
$this->artifactData = ['files' => $proof['files']];
file_put_contents($this->artifactManifest, json_encode($this->artifactData, JSON_THROW_ON_ERROR));
$this->artifactPin = hash_file('sha256', $this->artifactManifest);
});
afterEach(function () {
foreach (glob($this->artifactDirectory.'/src/*') as $file) {
unlink($file);
}
rmdir($this->artifactDirectory.'/src');
foreach (glob($this->artifactDirectory.'/*') as $file) {
unlink($file);
}
rmdir($this->artifactDirectory);
});
test('frozen standalone budget release verifies all seven files without executing its PHP', function () {
BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, $this->artifactPin);
expect(config('budget-distributions.enabled'))->toBeFalse();
});
test('budget release rejects changed executable files before loading them', function (string $file) {
file_put_contents($this->artifactDirectory.'/'.$file, "\n// changed", FILE_APPEND);
expect(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, $this->artifactPin))
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_FILE_MISMATCH');
})->with(['bootstrap.php', 'src/BudgetControl.php', 'src/BudgetDistributions.php', 'src/BudgetDistributionPlan.php']);
test('budget release rejects a changed manifest even when its replacement lists current hashes', function () {
$this->artifactData['files']['src/BudgetControl.php'] = str_repeat('0', 64);
file_put_contents($this->artifactManifest, json_encode($this->artifactData, JSON_THROW_ON_ERROR));
expect(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, $this->artifactPin))
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_MANIFEST_MISMATCH');
});
test('budget release rejects incomplete inventories and missing trust anchors', function () {
unset($this->artifactData['files']['src/BudgetDistributions.php']);
file_put_contents($this->artifactManifest, json_encode($this->artifactData, JSON_THROW_ON_ERROR));
expect(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, hash_file('sha256', $this->artifactManifest)))
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_INVENTORY_MISMATCH')
->and(fn () => BudgetDistributionArtifact::verify($this->artifactDirectory, $this->artifactManifest, null))
->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_ARTIFACT_CONFIGURATION');
});
test('host boots the independently pinned release and rejects changed bootstrap before it can execute', function () {
$environment = ['APP_ENV' => 'testing', 'COMMON_BUDGET_PATH' => $this->artifactDirectory,
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => $this->artifactManifest,
'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => $this->artifactPin];
$process = new Process([PHP_BINARY, base_path('tests/Concurrency/budget-distribution-artifact-boot.php')], base_path(), $environment, timeout: 30);
$process->run();
expect($process->isSuccessful())->toBeTrue();
$result = json_decode(trim($process->getOutput()), true, 32, JSON_THROW_ON_ERROR);
expect($result['runtime'])->toBe(realpath($this->artifactDirectory.'/src/BudgetControl.php'));
file_put_contents($this->artifactDirectory.'/bootstrap.php', '<?php file_put_contents(__DIR__."/executed", "yes");');
$process->run();
expect($process->isSuccessful())->toBeFalse()
->and($process->getOutput().$process->getErrorOutput())->toContain('BUDGET_DISTRIBUTION_FILE_MISMATCH')
->and(file_exists($this->artifactDirectory.'/executed'))->toBeFalse();
});
@@ -63,6 +63,26 @@ test('explicit optional contract composition loads the selected standalone sourc
->and(realpath((new ReflectionClass(BudgetControl::class))->getFileName()))->toBe(realpath($selected.'/src/BudgetControl.php'));
});
test('prepared deployment capability verifies the selected standalone artifact outside QA and remains disabled by default', function () {
$proofPath = base_path('docs/proofs/rq01-distribution-artifact.json');
$proof = json_decode(file_get_contents($proofPath), true, 32, JSON_THROW_ON_ERROR);
// Only the process which already loaded the frozen artifact can enable this composition.
$selected = realpath((new ReflectionClass(BudgetControl::class))->getFileName());
$artifact = base_path($proof['path']);
config(['budget-distributions.qa_enabled' => false, 'budget-distributions.enabled' => false]);
app()->instance('env', 'local');
try {
expect(app(RequisitionBudgetDistributions::class)->ready())->toBeFalse();
config(['budget-distributions.enabled' => true, 'budget-distributions.artifact_manifest' => $proofPath,
'budget-distributions.artifact_manifest_sha256' => hash_file('sha256', $proofPath), 'common-budget.path' => $artifact]);
expect(app(RequisitionBudgetDistributions::class)->ready())->toBe($selected === realpath($artifact.'/src/BudgetControl.php'));
config(['budget-distributions.artifact_manifest_sha256' => str_repeat('0', 64)]);
expect(fn () => app(RequisitionBudgetDistributions::class)->ready())->toThrow(LogicException::class, 'BUDGET_DISTRIBUTION_MANIFEST_MISMATCH');
} finally {
app()->instance('env', 'testing');
}
});
function distributionInvoice(object $test, string $number, int $net, int $gross): Invoice
{
return Invoice::query()->create(['tenant_id' => $test->author->tenant_id, 'purchase_order_id' => $test->f['order']->id,
@@ -0,0 +1,48 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('staged pilot schema refuses missing installer scope without changing requisitions', function () {
receiptFixture();
$migration = require database_path('deployment-migrations/2026_11_22_000004_create_budget_distributions.php');
expect(fn () => $migration->up())->toThrow(LogicException::class)
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse();
});
test('local preparation uses the same schema definition and preserves previous records under its exact scope', function () {
if (DB::getDriverName() !== 'pgsql') {
$this->markTestSkipped('Exact native identity is checked on isolated PostgreSQL.');
}
receiptFixture();
$columns = Schema::getColumnListing('requisitions');
$before = DB::table('requisitions')->select($columns)->get()->toJson();
config(['budget-distributions.schema_installation' => ['database' => DB::connection()->getDatabaseName(), 'username' => DB::connection()->getConfig('username')]]);
$migration = require database_path('deployment-migrations/2026_11_22_000004_create_budget_distributions.php');
app()->instance('env', 'local');
try {
$migration->up();
} finally {
app()->instance('env', 'testing');
}
expect(DB::table('requisitions')->select($columns)->get()->toJson())->toBe($before)
->and(DB::table('budget_distributions')->count())->toBe(0)
->and(DB::table('requisitions')->whereNotNull('budget_distribution_preparation')->count())->toBe(0)
->and(fn () => $migration->down())->toThrow(LogicException::class);
});
test('staged pilot schema refuses an incorrect target and operational production environment', function () {
receiptFixture();
config(['budget-distributions.schema_installation' => ['database' => 'different_database', 'username' => DB::connection()->getConfig('username')]]);
$migration = require database_path('deployment-migrations/2026_11_22_000004_create_budget_distributions.php');
expect(fn () => $migration->up())->toThrow(LogicException::class);
app()->instance('env', 'production');
try {
expect(fn () => $migration->up())->toThrow(LogicException::class)
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse();
} finally {
app()->instance('env', 'testing');
}
});
@@ -0,0 +1,366 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the explicitly authorized unpublished common source for isolated QA.');
}
$this->f = receiptFixture();
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
$this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($this->finance);
$this->budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->f['r']->cost_center_id,
'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000,
'reason' => 'Dotação exclusivamente sintética para ordens parciais.']);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer)->approve($this->budget);
$this->actingAs($this->f['issuer']);
});
/** Synthetic financial source contract; deliberately not a claim of native purchase issuance. */
function orderPartsSource(object $test, int $amount, string $allocation = 'same-key'): array
{
$source = unissuedOrderPartsSource($test->f, $amount);
$line = $source->items()->sole();
$lines = [$line->id => ['subtotal_minor' => $amount, 'total_minor' => $amount, 'required_kind' => 'operating']];
$plan = [['allocation_key' => $allocation, 'line_id' => $line->id, 'centre_id' => $test->f['r']->cost_center_id, 'subtotal_minor' => $amount, 'total_minor' => $amount]];
$control = app(CommonBudget::class)->for($test->f['issuer']);
$control->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
$award = $control->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
return ['origin' => $source->id, 'version' => 0, 'plan_hash' => $award['plan_hash'],
'allocations' => [['allocation_key' => $allocation, 'subtotal_minor' => $amount, 'total_minor' => $amount]]];
}
function orderPartsAmount(array $source, int $amount, int $version): array
{
$source['version'] = $version;
$source['allocations'][0]['subtotal_minor'] = $amount;
$source['allocations'][0]['total_minor'] = $amount;
return $source;
}
function orderPartsInvoice(object $test, int $amount): Invoice
{
return Invoice::query()->create(['tenant_id' => $test->finance->tenant_id, 'purchase_order_id' => $test->f['order']->id,
'supplier_id' => $test->f['order']->supplier_id, 'created_by' => $test->finance->id, 'number' => 'QA-PARTS-'.Str::random(12),
'issued_on' => today(), 'status' => 'pending', 'subtotal_minor' => $amount, 'tax_minor' => 0, 'total_minor' => $amount,
'snapshot' => ['synthetic_contract_fixture' => true]]);
}
function orderPartsBalance(object $test): array
{
$test->actingAs($test->finance);
$balance = app(CommonBudget::class)->for($test->finance)->balance($test->budget);
$test->actingAs($test->f['issuer']);
return $balance;
}
test('one approved synthetic source commits forty then sixty without committing the unissued portion', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
$operation = (string) Str::uuid();
$input = [orderPartsAmount($source, 4000, 0)];
$control = app(CommonBudget::class)->for($this->f['issuer']);
expect($control->commitOrderParts($order, $input, $operation)['replayed'])->toBeFalse();
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000, 'consumed_minor' => 0, 'available_minor' => 90000]);
expect($control->commitOrderParts($order, $input, $operation)['replayed'])->toBeTrue();
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 1)], (string) Str::uuid());
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 10000, 'consumed_minor' => 0]);
expect(DB::table('budget_order_commands')->count())->toBe(2)->and(DB::table('budget_order_bindings')->count())->toBe(2)
->and(Requisition::query()->findOrFail($source['origin'])->status)->toBe('approved');
});
test('two origins keep identical allocation keys separate and consume one invoice atomically', function () {
$a = orderPartsSource($this, 10000);
$b = orderPartsSource($this, 20000);
$order = (string) Str::uuid();
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$b, $a], (string) Str::uuid());
$this->actingAs($this->finance);
$invoice = orderPartsInvoice($this, 15000);
$input = [orderPartsAmount($a, 5000, 1), orderPartsAmount($b, 10000, 1)];
foreach ($input as &$source) {
$source['allocations'][0]['order_key'] = $order;
}
unset($source);
$operation = (string) Str::uuid();
$control = app(CommonBudget::class)->for($this->finance);
$control->checkOrderPartsConsumption($input);
expect(DB::table('budget_order_consumptions')->count())->toBe(0);
$result = $control->consumeOrderParts($invoice->id, $input, $operation);
expect($result['replayed'])->toBeFalse()->and($control->consumeOrderParts($invoice->id, array_reverse($input), $operation)['replayed'])->toBeTrue();
expect(DB::table('budget_order_consumptions')->count())->toBe(2)->and(Invoice::query()->whereKey($invoice->id)->count())->toBe(1)
->and(DB::table('budget_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(0);
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 15000, 'consumed_minor' => 15000, 'available_minor' => 70000]);
});
test('one bad source rejects the complete order before effects, phase or versions change', function () {
$a = orderPartsSource($this, 10000);
$b = orderPartsSource($this, 20000);
$bad = orderPartsAmount($b, 20001, 0);
$before = DB::table('budget_distribution_entries')->count();
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts((string) Str::uuid(), [$a, $bad], (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(DB::table('budget_order_bindings')->count())->toBe(0)
->and(DB::table('budget_distribution_entries')->count())->toBe($before)
->and(DB::table('budget_distributions')->where('phase', 'award')->count())->toBe(2);
});
test('stale versions and changed replay amounts cannot issue another part', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
$key = (string) Str::uuid();
$control = app(CommonBudget::class)->for($this->f['issuer']);
$control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], $key);
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 0)], (string) Str::uuid()))->toThrow(BudgetFailure::class)
->and(fn () => $control->commitOrderParts($order, [orderPartsAmount($source, 4001, 0)], $key))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_commands')->count())->toBe(1);
});
test('one invoice may consume two parts of the same source with one journal effect per allocation', function () {
$source = orderPartsSource($this, 10000);
$first = (string) Str::uuid();
$second = (string) Str::uuid();
$control = app(CommonBudget::class)->for($this->f['issuer']);
$control->commitOrderParts($first, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid());
$control->commitOrderParts($second, [orderPartsAmount($source, 6000, 1)], (string) Str::uuid());
$input = orderPartsAmount($source, 2000, 2);
$input['allocations'][0]['order_key'] = $first;
$input['allocations'][] = ['allocation_key' => 'same-key', 'order_key' => $second, 'subtotal_minor' => 3000, 'total_minor' => 3000];
$this->actingAs($this->finance);
$invoice = orderPartsInvoice($this, 5000);
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
expect(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(2)
->and(DB::table('budget_distribution_entries')->where('kind', 'like', 'order-invoice-%')->count())->toBe(1);
expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]);
});
test('cancellation releases only its unconsumed issued part and never replenishes issuance capacity', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
$control = app(CommonBudget::class)->for($this->f['issuer']);
$control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid());
$key = (string) Str::uuid();
$input = [orderPartsAmount($source, 4000, 1)];
expect($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse()
->and($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue();
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 0, 'available_minor' => 94000]);
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6001, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 2)], (string) Str::uuid());
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 6000]);
});
test('consumed orders reject cancellation and over-consumption without changing the invoice effect', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
$this->actingAs($this->finance);
$input = orderPartsAmount($source, 5000, 1);
$input['allocations'][0]['order_key'] = $order;
$invoice = orderPartsInvoice($this, 5000);
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
$next = orderPartsAmount($source, 5001, 2);
$next['allocations'][0]['order_key'] = $order;
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts(orderPartsInvoice($this, 5001)->id, [$next], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->actingAs($this->f['issuer']);
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]);
});
test('mutating order commands require the current procurement actor and consuming requires Finance', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
$this->actingAs($this->finance);
expect(fn () => app(CommonBudget::class)->for($this->finance)->commitOrderParts($order, [$source], (string) Str::uuid()))->toThrow(HttpException::class);
$this->actingAs($this->f['issuer']);
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
$input = orderPartsAmount($source, 100, 1);
$input['allocations'][0]['order_key'] = $order;
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->checkOrderPartsConsumption([$input]))->toThrow(HttpException::class);
});
test('invalid shapes, duplicate sources and empty parts fail before a command is recorded', function () {
$source = orderPartsSource($this, 10000);
$control = app(CommonBudget::class)->for($this->f['issuer']);
foreach ([[], [$source, $source], [orderPartsAmount($source, -1, 0)], [[...$source, 'version' => '0']], [[...$source, 'origin' => -1]]] as $input) {
expect(fn () => $control->commitOrderParts((string) Str::uuid(), $input, (string) Str::uuid()))->toThrow(BudgetFailure::class);
}
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(orderPartsBalance($this)['reserved_minor'])->toBe(10000);
});
test('an explicit zero-cent native rounding remainder retains lineage without inventing another cent', function () {
$source = orderPartsSource($this, 1);
$first = (string) Str::uuid();
$remainder = (string) Str::uuid();
$control = app(CommonBudget::class)->for($this->f['issuer']);
$control->commitOrderParts($first, [$source], (string) Str::uuid());
$control->commitOrderParts($remainder, [orderPartsAmount($source, 0, 1)], (string) Str::uuid());
$this->actingAs($this->finance);
$invoice = orderPartsInvoice($this, 0);
$input = orderPartsAmount($source, 0, 2);
$input['allocations'][0]['order_key'] = $remainder;
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
expect(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->value('amount_minor'))->toBe(0)
->and(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 1, 'consumed_minor' => 0, 'available_minor' => 99999]);
});
test('bad invoice allocation rolls back every origin and an unconsumed cancelled order cannot be invoiced', function () {
$a = orderPartsSource($this, 10000);
$b = orderPartsSource($this, 20000);
$order = (string) Str::uuid();
$control = app(CommonBudget::class)->for($this->f['issuer']);
$control->commitOrderParts($order, [$a, $b], (string) Str::uuid());
$this->actingAs($this->finance);
$input = [orderPartsAmount($a, 5000, 1), orderPartsAmount($b, 20001, 1)];
foreach ($input as &$source) {
$source['allocations'][0]['order_key'] = $order;
}
unset($source);
$invoice = orderPartsInvoice($this, 25001);
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, $input, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_consumptions')->count())->toBe(0)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->actingAs($this->f['issuer']);
$control->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid());
$this->actingAs($this->finance);
$cancelled = orderPartsAmount($a, 100, 2);
$cancelled['allocations'][0]['order_key'] = $order;
expect(fn () => app(CommonBudget::class)->for($this->finance)->checkOrderPartsConsumption([$cancelled]))->toThrow(BudgetFailure::class);
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'available_minor' => 100000]);
});
test('operation identifiers cannot cross V1 and partial order contracts', function () {
$source = orderPartsSource($this, 10000);
$control = app(CommonBudget::class)->for($this->f['issuer']);
$oldOperation = DB::table('budget_distribution_events')->value('operation_key');
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [$source], $oldOperation))->toThrow(BudgetFailure::class);
$operation = (string) Str::uuid();
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 4000, 0)], $operation);
$line = Requisition::query()->findOrFail($source['origin'])->items()->sole();
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$plan = [['allocation_key' => 'same-key', 'line_id' => $line->id, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
expect(fn () => $control->recordDistribution($source['origin'], 'commit', $plan, $lines, str_repeat('b', 64), $operation))->toThrow(BudgetFailure::class)
->and(fn () => $control->recordDistribution($source['origin'], 'commit', $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000]);
});
test('a complete order command is invisible and unusable from another company', function () {
$source = orderPartsSource($this, 10000);
$other = receiptFixture();
$this->actingAs($other['issuer']);
expect(fn () => app(CommonBudget::class)->for($other['issuer'])->commitOrderParts((string) Str::uuid(), [$source], (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_commands')->count())->toBe(0);
});
test('legacy consumption cannot consume an invoice already used by an order-part command', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
$this->actingAs($this->finance);
$invoice = orderPartsInvoice($this, 5000);
$input = orderPartsAmount($source, 5000, 1);
$input['allocations'][0]['order_key'] = $order;
$control = app(CommonBudget::class)->for($this->finance);
$control->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
expect(fn () => $control->consume($this->f['r']->id, $invoice->id, 5000, 5000))->toThrow(BudgetFailure::class);
expect(DB::table('budget_consumptions')->count())->toBe(0)->and(DB::table('budget_order_consumptions')->count())->toBe(1);
});
test('explicit adoption preserves all old entries and the exact balance before partial issuance', function () {
$control = app(CommonBudget::class)->for($this->f['issuer']);
$request = unissuedOrderPartsSource($this->f, 10000);
$origin = $request->id;
$centre = $this->f['r']->cost_center_id;
$line = $request->items()->sole();
expect(PurchaseOrder::query()->where('requisition_id', $origin)->exists())->toBeFalse();
$control->record($origin, $centre, 'operating', 'reserve', 10000, 10000);
$control->record($origin, $centre, 'operating', 'award', 10000, 10000);
$original = DB::table('budget_entries')->where('requisition_id', $origin)->orderBy('id')->get()->toArray();
$before = orderPartsBalance($this);
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$plan = [['allocation_key' => 'native-line', 'line_id' => $line->id, 'centre_id' => $centre, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
$key = (string) Str::uuid();
$adopt = $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), $key);
expect($adopt['replayed'])->toBeFalse()
->and($control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), $key)['replayed'])->toBeTrue()
->and(orderPartsBalance($this))->toBe($before)
->and(DB::table('budget_entries')->where('requisition_id', $origin)->orderBy('id')->limit(2)->get()->toArray())->toEqual($original)
->and(DB::table('budget_entries')->where('kind', 'order-adoption')->count())->toBe(1);
$input = ['origin' => $origin, 'version' => 0, 'plan_hash' => $adopt['plan_hash'],
'allocations' => [['allocation_key' => 'native-line', 'subtotal_minor' => 4000, 'total_minor' => 4000]]];
$control->commitOrderParts((string) Str::uuid(), [$input], (string) Str::uuid());
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000])
->and(fn () => $control->record($origin, $centre, 'operating', 'commit', 10000, 10000))->toThrow(BudgetFailure::class);
});
test('adoption rejects a changed amount and an already committed source without compensating values', function () {
$control = app(CommonBudget::class)->for($this->f['issuer']);
$request = unissuedOrderPartsSource($this->f, 10000);
$origin = $request->id;
$centre = $this->f['r']->cost_center_id;
$line = $request->items()->sole();
$control->record($origin, $centre, 'operating', 'reserve', 10000, 10000);
$control->record($origin, $centre, 'operating', 'award', 10000, 10000);
$lines = [$line->id => ['subtotal_minor' => 9999, 'total_minor' => 9999, 'required_kind' => 'operating']];
$plan = [['allocation_key' => 'native-line', 'line_id' => $line->id, 'centre_id' => $centre, 'subtotal_minor' => 9999, 'total_minor' => 9999]];
expect(fn () => $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
$control->record($origin, $centre, 'operating', 'commit', 10000, 10000);
$lines[$line->id]['subtotal_minor'] = $lines[$line->id]['total_minor'] = 10000;
$plan[0]['subtotal_minor'] = $plan[0]['total_minor'] = 10000;
expect(fn () => $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(DB::table('budget_distributions')->count())->toBe(0)
->and(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 10000]);
});
test('order-part schema cannot be installed in an operational environment or silently reinstalled', function () {
$migration = require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php';
expect(fn () => $migration->up())->toThrow(LogicException::class);
app()->instance('env', 'production');
try {
expect(fn () => $migration->up())->toThrow(LogicException::class, 'guarded disposable QA')
->and(fn () => $migration->down())->toThrow(LogicException::class);
} finally {
app()->instance('env', 'testing');
}
});
test('PostgreSQL rejects mutation or deletion of each partial-order history table', function () {
if (DB::getDriverName() !== 'pgsql') {
$this->markTestSkipped('PostgreSQL append-only triggers require the disposable PostgreSQL run.');
}
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
$this->actingAs($this->finance);
$invoice = orderPartsInvoice($this, 5000);
$input = orderPartsAmount($source, 5000, 1);
$input['allocations'][0]['order_key'] = $order;
app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid());
foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'] as $table) {
$row = DB::table($table)->orderBy('id')->first();
expect($row)->not->toBeNull();
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $row->id)->update(['tenant_id' => $row->tenant_id])))
->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $row->id)->delete()))
->toThrow(QueryException::class);
expect(DB::table($table)->where('id', $row->id)->first())->toEqual($row);
}
});
+4 -2
View File
@@ -133,7 +133,9 @@ test('equipment integration block separates native purchase requests from actual
test('equipment integration block preserves department and native requisition visibility with tenant isolation', function () {
$this->withoutVite();
$request = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
// An existing equipment association belongs to a spare-part purchase, not a new capital asset.
$request = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f, 'spare_part'));
expect($request->items()->sole()->purchase_type)->toBe('spare_part')->and($request->items()->sole()->equipment_id)->toBe($this->f['asset']->id);
$this->actingAs($this->f['finance'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('purchases.total', 1));
$otherDepartment = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
$request->update(['department_id' => $otherDepartment->id]);
@@ -150,7 +152,7 @@ test('equipment integration block keeps old purchase and movement pages independ
$this->withoutVite();
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
foreach (range(1, 16) as $index) {
app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f, 'spare_part'));
app(StockWorkflow::class)->record($this->f['receiver'], ['kind' => 'issue', 'reference' => 'EQ-PAGE-'.$index, 'idempotency_key' => (string) Str::uuid(),
'responsible_id' => $this->f['receiver']->id, 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'equipment_id' => $this->f['asset']->id,
'quantity' => '0.001', 'reason' => 'Saída física nativa para paginação.']);
@@ -10,6 +10,17 @@ use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
afterEach(function () {
if ($this->committedDraftReportFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Draft report cleanup requires the disposable PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
beforeEach(function () {
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
@@ -38,6 +49,13 @@ test('incomplete draft persists unknown values without invented amounts and cann
$this->get('/requisicoes/'.$r->id.'/editar')->assertInertia(fn (Assert $page) => $page->where('incompleteDraftsAvailable', true)->where('requisition.draft_input.values.justification', 'Ini'));
$this->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('requisition.total_minor', null));
$this->get('/requisicoes/'.$r->id.'/processo')->assertOk();
if (DB::getDriverName() === 'pgsql') {
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Commit only the isolated synthetic draft before the native read-only report transaction.');
}
DB::commit();
$this->committedDraftReportFixture = true;
}
$this->get('/relatorios?search='.$r->number)->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.data.0.total_minor', null));
$this->postJson('/requisicoes/'.$r->id.'/submeter')->assertUnprocessable();
expect($r->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->count())->toBe($entries);
+83
View File
@@ -37,12 +37,14 @@ use App\Services\EquipmentWorkflow;
use App\Services\FormalAdmission;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsPreparation;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
use App\Services\ProposalOpeningWorkflow;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow;
use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
@@ -1349,3 +1351,84 @@ test('quotation tasks hand a ready comparison to adjudication without reopening
$this->actingAs($this->buyer)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
$this->get('/requisicoes/'.$this->r->id.'/cotacoes')->assertInertia(fn (Assert $page) => $page->where('canCreate', false)->where('canEvaluate', false));
});
test('optional partial-order preparation reuses native final approvals and preserves all documents and financial effects', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
config(['order-parts.qa_enabled' => true]);
$award = selectPurchaseAward($this);
$service = app(OrderPartsPreparation::class);
$input = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]]]];
$this->actingAs($this->buyer);
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(HttpException::class);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer);
$before = [PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()];
$result = $service->prepare($this->buyer, $input);
expect($result)->toMatchArray(['currency' => 'MZN', 'subtotal_minor' => 4000, 'tax_minor' => 0, 'total_minor' => 4000, 'issued' => false, 'budget_effects' => false])
->and($result['sources'][0]['items'][0]['quantity_offset_milli'])->toBe(0)
->and($service->prepare($this->buyer, $input)['fingerprint'])->toBe($result['fingerprint'])
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
$this->actingAs($this->finance);
expect(fn () => $service->prepare($this->finance, $input))->toThrow(HttpException::class);
$this->actingAs($this->buyer);
$bad = $input;
$bad['sources'][0]['items'][0]['quantity'] = '1.001';
expect(fn () => $service->prepare($this->buyer, $bad))->toThrow(ValidationException::class);
config(['order-parts.qa_enabled' => false]);
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(HttpException::class);
config(['order-parts.qa_enabled' => true]);
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(ValidationException::class);
});
test('optional partial-order preparation consolidates two independently approved native origins without issuing or averaging data', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
config(['order-parts.qa_enabled' => true]);
$first = selectPurchaseAward($this);
approvePurchaseAward($this, $first);
$this->actingAs($this->buyer);
$secondRequest = $this->r->fresh()->replicate();
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
$secondRequest->save();
$line = $this->item->replicate();
$line->requisition_id = $secondRequest->id;
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
$line->save();
foreach ($this->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->requisition_id = $secondRequest->id;
$copy->save();
}
$quotes = [];
foreach ($this->suppliers as $index => $supplier) {
$this->actingAs($this->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
$quotes[] = $quote;
foreach ([$this->buyer, $this->finance] as $evaluator) {
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
}
}
$this->actingAs($this->buyer);
$second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]);
approvePurchaseAward($this, $second);
$this->actingAs($this->buyer);
$before = [PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()];
$input = ['sources' => [
['award_id' => $second->id, 'items' => [['quotation_item_id' => $quotes[0]->items()->sole()->id, 'quantity' => '0.500']]],
['award_id' => $first->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]],
]];
$result = app(OrderPartsPreparation::class)->prepare($this->buyer, $input);
expect($result)->toMatchArray(['currency' => 'MZN', 'total_minor' => 14000, 'issued' => false, 'budget_effects' => false])
->and($result['sources'])->toHaveCount(2)
->and(array_column($result['sources'], 'requisition_id'))->toBe([$this->r->id, $secondRequest->id])
->and(array_column($result['sources'], 'exchange_basis'))->toBe([null, null])
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
});
@@ -148,6 +148,47 @@ test('conditions use exact amount category and cost centre and current rules do
expect($r->fresh()->status)->toBe('approved');
});
test('explicit RQ01 category conditions combine with native filters and remain frozen through the full approval journey', function () {
$this->plan['levels'] = [$this->plan['levels'][0]];
$this->plan['levels'][0] += ['procurement_categories' => ['office_equipment']];
$this->plan['levels'][0]['categories'] = ['Material'];
$this->plan['levels'][0]['min_amount'] = '116.00';
$this->plan['levels'][0]['cost_center_ids'] = [(string) $this->f['r']->cost_center_id];
$this->body['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo sintético de escritório fora do catálogo.'];
$matched = submitConfiguredRequest($this);
expect($matched->steps()->count())->toBe(4)
->and($matched->approval_snapshot['additional_levels']['configured_1']['procurement_categories'])->toBe(['office_equipment']);
$next = $this->body;
$next['operation_key'] = (string) Str::uuid();
$next['items'][0]['procurement_category'] = 'other';
$this->postJson('/requisicoes', $next)->assertRedirect();
$different = Requisition::query()->latest('id')->firstOrFail();
$this->postJson('/requisicoes/'.$different->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect();
expect($different->steps()->count())->toBe(3);
$snapshot = $matched->approval_snapshot;
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2, 'enabled' => false])->assertRedirect();
expect($matched->fresh()->approval_snapshot)->toBe($snapshot);
foreach ([$this->head, $this->buyer, $this->financier, $this->approvers[0]] as $actor) {
configuredDecision($this, $actor, $matched);
}
expect($matched->fresh()->status)->toBe('approved');
});
test('RQ01 filtered plans refuse an absent classification schema instead of dropping a required approval', function () {
$this->plan['levels'] = [$this->plan['levels'][0] + ['procurement_categories' => ['office_equipment']]];
$this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect();
$this->body['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo sintético de escritório fora do catálogo.'];
$this->postJson('/requisicoes', $this->body)->assertRedirect();
$request = Requisition::query()->latest('id')->firstOrFail();
$policy = $this->f['tenant']->fresh()->requisition_approval_policy;
DB::getSchemaBuilder()->table('requisition_items', fn ($table) => $table->dropColumn('category_context'));
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertServiceUnavailable();
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2])->assertUnprocessable();
expect($request->fresh()->status)->toBe('draft')->and($request->steps()->count())->toBe(0)
->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0)
->and($this->f['tenant']->fresh()->requisition_approval_policy)->toBe($policy);
});
test('revoked membership and expired maintenance do not approve or expose assigned requests and repeated identity cannot decide two stages', function () {
$r = submitConfiguredRequest($this);
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
+109
View File
@@ -0,0 +1,109 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use App\Services\EquipmentWorkflow;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
$this->f = receiptFixture();
$this->author = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($this->author);
$this->payload = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Pedido sintético para classificação explícita.',
'items' => [['description' => 'Material sintético', 'category' => 'Categoria anterior', 'purchase_type' => 'consumable',
'quantity' => '2.000', 'unit' => 'cx', 'unit_price' => '10.00', 'tax_rate' => '16.00']]];
});
test('office classification and its explicit text justification persist through the native HTTP workflow and audit', function () {
$this->payload['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo de escritório ainda sem entrada no catálogo.'];
$this->postJson('/requisicoes', $this->payload)->assertRedirect();
$request = Requisition::query()->where('requester_id', $this->author->id)->sole();
$line = $request->items()->sole();
expect($request->draft_input)->toBeNull()->and($line->category)->toBe('Categoria anterior')
->and($line->category_context)->toBe(['version' => 1, 'category' => 'office_equipment', 'reason' => $this->payload['items'][0]['category_reason']])
->and($request->total_minor)->toBe(2320)
->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0);
$event = DB::table('audit_logs')->where('requisition_id', $request->id)->where('action', 'requisition.created')->sole();
expect($event)->not->toBeNull();
});
test('unfinished category requirements are saved as an incomplete draft and cannot reserve or submit', function () {
$this->payload['items'][0]['procurement_category'] = 'office_equipment';
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
expect($request->draft_input['incomplete'])->toBeTrue()->and($request->items()->count())->toBe(0)
->and($request->draft_input['values']['items'][0]['procurement_category'])->toBe('office_equipment');
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])->assertUnprocessable();
expect($request->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0);
});
test('production inputs use the native published stock catalogue and retain its authoritative descriptors', function () {
$stock = $this->f['stock']->fresh();
$this->actingAs($this->f['receiver']);
app(RequisitionCatalogue::class)->save($this->f['receiver'], $stock->id, ['version' => 0, 'stock_basis' => app(RequisitionCatalogue::class)->basis($stock),
'category' => 'Material catalogado', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Publicação sintética para a classificação.']);
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $stock->id)->sole();
$this->actingAs($this->author);
$this->payload['items'] = [['catalogue_entry_id' => $entry->id, 'catalogue_version' => $entry->version, 'procurement_category' => 'production_input',
'quantity' => '2.000', 'unit_price' => '10.00', 'tax_rate' => '16.00']];
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
expect($request->draft_input)->toBeNull()->and($request->items()->sole()->category_context['category'])->toBe('production_input')
->and($request->items()->sole()->catalogue_snapshot['stock_item_id'])->toBe($stock->id)
->and($request->items()->sole()->category)->toBe('Material catalogado');
});
test('unclassified legacy lines remain unchanged and adding an empty context preserves the accepted technical basis', function () {
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
expect($request->items()->sole()->category_context)->toBeNull();
$withEmptyColumn = app(EquipmentWorkflow::class)->basis($request);
Schema::table('requisition_items', fn ($table) => $table->dropColumn('category_context'));
expect(app(EquipmentWorkflow::class)->basis($request->fresh()))->toBe($withEmptyColumn);
$migration = require database_path('migrations/2026_11_22_000005_add_requisition_category_context.php');
$migration->up();
expect(app(EquipmentWorkflow::class)->basis($request->fresh()))->toBe($withEmptyColumn)
->and(fn () => $migration->down())->toThrow(LogicException::class);
});
test('unknown classification and a missing schema are rejected without silently discarding inputs', function () {
$this->payload['items'][0]['procurement_category'] = 'unknown';
$this->postJson('/requisicoes', $this->payload)->assertUnprocessable();
Schema::table('requisition_items', fn ($table) => $table->dropColumn('category_context'));
$this->payload['items'][0]['procurement_category'] = 'office_equipment';
$this->payload['items'][0]['category_reason'] = 'Razão explícita de texto livre.';
$this->postJson('/requisicoes', $this->payload)->assertUnprocessable();
expect(Requisition::query()->where('requester_id', $this->author->id)->count())->toBe(0);
});
test('capital classification retains the native equipment controls and requires an explicit investment reason', function () {
$this->payload['items'][0] += ['procurement_category' => 'capital_equipment', 'category_reason' => 'Investimento sintético para ampliar a capacidade.', 'production_area' => 'Área sintética'];
$this->payload['items'][0]['purchase_type'] = 'equipment';
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
expect($request->draft_input)->toBeNull()->and($request->items()->sole()->purchase_type)->toBe('equipment')
->and($request->items()->sole()->category_context['category'])->toBe('capital_equipment');
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])->assertUnprocessable();
expect($request->fresh()->status)->toBe('draft');
});
test('an older client preserves the exact classification by native line identity and only an explicit clear removes it', function () {
$this->payload['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Necessidade sintética sem entrada no catálogo.'];
$request = app(RequisitionWorkflow::class)->save($this->author, $this->payload);
$original = $request->items()->sole()->category_context;
$this->payload['items'][0]['source_line_id'] = $request->items()->sole()->id;
unset($this->payload['items'][0]['procurement_category'], $this->payload['items'][0]['category_reason']);
$this->payload['operation_key'] = (string) Str::uuid();
$this->payload['process_version'] = $request->process_version;
$saved = app(RequisitionWorkflow::class)->save($this->author, $this->payload, $request);
expect($saved->items()->sole()->category_context)->toBe($original);
$this->payload['items'][0] += ['procurement_category' => '', 'category_reason' => ''];
$this->payload['operation_key'] = (string) Str::uuid();
$this->payload['process_version'] = $saved->process_version;
$saved = app(RequisitionWorkflow::class)->save($this->author, $this->payload, $saved);
expect($saved->items()->sole()->category_context)->toBeNull();
});
@@ -0,0 +1,125 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->body = ['name' => 'Necessidades da área', 'term' => 'QA-NEED', 'q' => 'QA-NEED'];
});
test('saved criteria are private encrypted metadata and repeated creation preserves a single preference', function () {
foreach ([1, 2] as $attempt) {
$this->postJson('/compras/pesquisas-guardadas', $this->body + ['tenant_id' => 999, 'user_id' => 999])->assertRedirect();
}
$row = DB::table('procurement_saved_searches')->sole();
expect($row->tenant_id)->toBe($this->f['tenant']->id)->and($row->user_id)->toBe($this->f['issuer']->id)->and($row->version)->toBe(1);
$this->get('/compras/pesquisa?q=QA-NEED')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 1)
->where('savedSearches.active.0.name', $this->body['name'])->missing('savedSearches.active.0.user_id')->missing('savedSearches.active.0.results'));
$this->get('/compras/pesquisa')->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
});
test('opening saved criteria reruns the current native query instead of caching results or granting access', function () {
$this->f['r']->update(['number' => 'QA-NEED-ONE']);
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
$href = '/compras/pesquisa?q=QA-NEED';
$this->get($href)->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 1));
$this->f['r']->update(['number' => 'CHANGED-SOURCE']);
$this->get($href)->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0)->has('savedSearches.active', 1));
$other = receiptFixture();
$this->actingAs($other['issuer'])->get($href)->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0)->has('savedSearches.active', 0));
});
test('rename archive and restore preserve explicit versions criteria and all business records', function () {
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
$row = DB::table('procurement_saved_searches')->sole();
$before = [];
foreach (['requisitions', 'audit_logs', 'budget_entries', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$path = '/compras/pesquisas-guardadas/'.$row->id;
$this->putJson($path, ['version' => 1, 'name' => 'Nome revisto', 'term' => 'Texto revisto', 'q' => 'QA'])->assertRedirect();
$this->postJson($path.'/arquivar', ['version' => 1])->assertConflict();
$this->postJson($path.'/arquivar', ['version' => 2, 'q' => 'QA'])->assertRedirect();
$this->get('/compras/pesquisa?q=QA')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 0)
->where('savedSearches.archived.total', 1)->where('savedSearches.archived.data.0.term', 'Texto revisto'));
$this->postJson($path.'/restaurar', ['version' => 3])->assertRedirect();
expect(DB::table('procurement_saved_searches')->sole()->version)->toBe(4)
->and(DB::table('procurement_saved_searches')->sole()->archived_at)->toBeNull();
foreach ($before as $table => $snapshot) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($snapshot);
}
});
test('another user or company cannot read or mutate guessed preference identifiers', function () {
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
$id = DB::table('procurement_saved_searches')->sole()->id;
$colleague = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
$foreign = receiptFixture();
foreach ([$colleague, $foreign['issuer']] as $actor) {
$this->actingAs($actor)->get('/compras/pesquisa')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 0));
$this->putJson('/compras/pesquisas-guardadas/'.$id, $this->body + ['version' => 1])->assertNotFound();
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/arquivar', ['version' => 1])->assertNotFound();
}
expect(DB::table('procurement_saved_searches')->sole()->version)->toBe(1);
});
test('active names are unique per user and restoring a colliding archived name never overwrites either record', function () {
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
$id = DB::table('procurement_saved_searches')->sole()->id;
$this->postJson('/compras/pesquisas-guardadas', [...$this->body, 'term' => 'OTHER'])->assertUnprocessable();
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/arquivar', ['version' => 1])->assertRedirect();
$this->postJson('/compras/pesquisas-guardadas', [...$this->body, 'term' => 'OTHER'])->assertRedirect();
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/restaurar', ['version' => 2])->assertUnprocessable();
expect(DB::table('procurement_saved_searches')->whereNotNull('archived_at')->sole()->term)->toBe('QA-NEED')
->and(DB::table('procurement_saved_searches')->whereNull('archived_at')->sole()->term)->toBe('OTHER');
});
test('query links encode criteria as local text and invalid or unavailable storage never silently discards them', function () {
$term = 'https://example.invalid/?x=%_&q=<script>';
$this->postJson('/compras/pesquisas-guardadas', [...$this->body, 'term' => $term])->assertRedirect();
$response = $this->get('/compras/pesquisa')->assertOk();
$page = $response->viewData('page');
$href = $page['props']['savedSearches']['active'][0]['href'];
expect(str_starts_with($href, '/compras/pesquisa?'))->toBeTrue();
parse_str(parse_url($href, PHP_URL_QUERY), $query);
expect($query['q'])->toBe($term);
$this->postJson('/compras/pesquisas-guardadas', ['name' => ' ', 'term' => ' '])->assertUnprocessable();
Schema::drop('procurement_saved_searches');
$this->get('/compras/pesquisa')->assertInertia(fn (Assert $page) => $page->where('savedSearches', null));
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertServiceUnavailable();
});
test('revoked native access is checked again before preference changes or live search exposure', function () {
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
$id = DB::table('procurement_saved_searches')->sole()->id;
// This security field is deliberately not mass assignable on User.
DB::table('users')->where('tenant_id', $this->f['tenant']->id)->where('id', $this->f['issuer']->id)->update(['purchasing_role' => PurchasingRole::Configured->value]);
expect(User::query()->findOrFail($this->f['issuer']->id)->purchasing_role)->toBe(PurchasingRole::Configured);
$this->get('/compras/pesquisa')->assertForbidden();
$this->postJson('/compras/pesquisas-guardadas/'.$id.'/arquivar', ['version' => 1])->assertForbidden();
expect(DB::table('procurement_saved_searches')->sole()->archived_at)->toBeNull();
});
test('active capacity and archived pagination preserve older criteria instead of deleting or overwriting them', function () {
foreach (range(1, 50) as $number) {
DB::table('procurement_saved_searches')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['issuer']->id,
'name' => 'Sintética '.$number, 'term' => 'QA-'.$number, 'active_name_key' => hash('sha256', 'sintética '.$number),
'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
}
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertUnprocessable();
foreach (DB::table('procurement_saved_searches')->orderBy('id')->limit(11)->get() as $row) {
$this->postJson('/compras/pesquisas-guardadas/'.$row->id.'/arquivar', ['version' => 1])->assertRedirect();
}
$this->postJson('/compras/pesquisas-guardadas', $this->body)->assertRedirect();
$this->get('/compras/pesquisa?archived_page=2')->assertInertia(fn (Assert $page) => $page->has('savedSearches.active', 40)
->where('savedSearches.archived.total', 11)->has('savedSearches.archived.data', 1));
expect(DB::table('procurement_saved_searches')->count())->toBe(51);
});
+30
View File
@@ -0,0 +1,30 @@
<?php
use App\Models\Requisition;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** Financial-contract fixture, without an issued native order. Not a native approval execution. */
function unissuedOrderPartsSource(array $fixture, int $amount): Requisition
{
$db = DB::connection();
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
if (! app()->environment('testing') || ! $isolated || $amount < 0) {
throw new LogicException('Unissued order fixtures require isolated synthetic QA.');
}
$source = $fixture['r']->replicate();
$source->number = 'REQ-PARTS-'.Str::random(12);
$source->subtotal_minor = $source->total_minor = $amount;
$source->tax_minor = 0;
$source->save();
$line = $fixture['r']->items()->firstOrFail()->replicate();
$line->requisition_id = $source->id;
$line->quantity = '1.000';
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = $amount;
$line->tax_rate = '0.00';
$line->tax_minor = 0;
$line->save();
return $source;
}
+22
View File
@@ -0,0 +1,22 @@
<?php
use App\Services\PurchaseLineAmounts;
test('successive native portions preserve the original line price and VAT exactly', function () {
$first = PurchaseLineAmounts::portion(223, '16.00', 0, 400);
$second = PurchaseLineAmounts::portion(223, '16.00', 400, 600);
$third = PurchaseLineAmounts::portion(223, '16.00', 1000, 700);
expect($first)->toBe(['subtotal_minor' => 89, 'tax_minor' => 14, 'total_minor' => 103])
->and($second)->toBe(['subtotal_minor' => 134, 'tax_minor' => 22, 'total_minor' => 156])
->and($third)->toBe(['subtotal_minor' => 156, 'tax_minor' => 25, 'total_minor' => 181])
->and($first['total_minor'] + $second['total_minor'] + $third['total_minor'])->toBe(440);
});
test('a half-cent remainder is not rounded again when the original quantity offset is retained', function () {
expect(PurchaseLineAmounts::portion(1, '0', 0, 500))->toBe(['subtotal_minor' => 1, 'tax_minor' => 0, 'total_minor' => 1])
->and(PurchaseLineAmounts::portion(1, '0', 500, 500))->toBe(['subtotal_minor' => 0, 'tax_minor' => 0, 'total_minor' => 0]);
});
test('invalid cumulative bases are refused without truncation or floating arithmetic', function (int $price, string $tax, int $before, int $quantity) {
expect(fn () => PurchaseLineAmounts::portion($price, $tax, $before, $quantity))->toThrow(InvalidArgumentException::class);
})->with([[-1, '0', 0, 1], [1, '-1', 0, 1], [1, '0', -1, 1], [1, '0', 0, 0], [1, '0', PHP_INT_MAX, 1]]);
@@ -4,7 +4,7 @@ import { expect, test } from 'vitest';
import { RequisitionApprovalSettings } from '@/components/requisition-approval-settings';
import { procurementNavigation } from '@/lib/procurement-navigation';
function render(ready: boolean) {
function render(ready: boolean, categoryOptions: Record<string, string> = {}) {
return renderToStaticMarkup(
<App
initialComponent={RequisitionApprovalSettings}
@@ -17,6 +17,7 @@ function render(ready: boolean) {
props: {
errors: {},
ready,
categoryOptions,
version: 4,
profiles: [
{
@@ -42,6 +43,13 @@ function render(ready: boolean) {
scope: 'company',
min_minor: 11601,
categories: ['Material'],
...(Object.keys(categoryOptions).length
? {
procurement_categories: [
'office_equipment',
],
}
: {}),
cost_center_ids: [1],
},
],
@@ -52,6 +60,24 @@ function render(ready: boolean) {
);
}
test('explicit RQ01 group conditions are separate from original article categories and remain hidden until available', () => {
const html = render(true, {
office_equipment: 'Equipamento de escritório',
capital_equipment: 'Maquinaria',
});
expect(html).toContain('Categoria da necessidade (RQ-01)');
expect(html).toContain('Categorias exactas do artigo');
expect(html).toContain('Equipamento de escritório');
expect(html).toContain('Maquinaria');
expect(html).toContain('não são classificados automaticamente');
const groups = html.slice(
html.indexOf('Categoria da necessidade (RQ-01)'),
html.indexOf('Perfis elegíveis'),
);
expect(groups).toContain('checked=""');
expect(render(true)).not.toContain('Categoria da necessidade (RQ-01)');
});
test('approval settings retain exact threshold and selected revoked profiles so the administrator can reconcile the plan', () => {
const html = render(true);
expect(html).toContain('116.01');
@@ -0,0 +1,48 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
RequisitionCategoryFields,
requisitionCategoryLabels,
} from '@/components/requisition-category-fields';
test('classification fields explain the native controls and preserve the explicit investment reason', () => {
const html = renderToStaticMarkup(
<RequisitionCategoryFields
index={2}
category="capital_equipment"
reason="Investimento deliberado"
options={requisitionCategoryLabels}
onChange={() => {}}
/>,
);
expect(html).toContain('Justificação do investimento');
expect(html).toContain('Investimento deliberado');
expect(html).toContain('orçamento de investimento');
expect(html).toContain('aria-describedby="rq-category-2-help"');
expect(html).toContain('Peças sobressalentes');
});
test('legacy classification stays unselected and production guidance requires the published stock catalogue', () => {
const legacy = renderToStaticMarkup(
<RequisitionCategoryFields
index={0}
category=""
reason=""
options={requisitionCategoryLabels}
onChange={() => {}}
/>,
);
expect(legacy).toContain('Sem classificação adicional');
expect(legacy).toContain('não é inferida');
expect(legacy).not.toContain('<textarea');
const production = renderToStaticMarkup(
<RequisitionCategoryFields
index={1}
category="production_input"
reason=""
options={requisitionCategoryLabels}
onChange={() => {}}
/>,
);
expect(production).toContain('material de stock no catálogo publicado');
});
@@ -6,6 +6,38 @@ import { hasPreparationChanges } from '@/lib/requisition-history';
afterEach(() => vi.restoreAllMocks());
test('new empty classification fields preserve an older recovered preparation while real classification changes remain dirty', () => {
const old = { items: [{ description: 'Artigo anterior' }] };
const current = {
items: [
{
description: 'Artigo anterior',
procurement_category: '',
category_reason: '',
},
],
};
expect(hasPreparationChanges(old, current)).toBe(false);
expect(hasPreparationChanges(current, old)).toBe(false);
expect(
hasPreparationChanges(old, {
items: [
{
...current.items[0],
procurement_category: 'office_equipment',
},
],
}),
).toBe(true);
expect(
hasPreparationChanges(old, {
items: [
{ ...current.items[0], category_reason: 'Razão deliberada' },
],
}),
).toBe(true);
});
test('restored technical identities do not mark a cleared preparation as changed', () => {
const original = {
operation_key: 'initial-operation',
@@ -0,0 +1,96 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import ProcurementSearch from '@/pages/search/procurement';
import type { SavedSearches } from '../../resources/js/components/saved-procurement-searches';
afterEach(() => vi.restoreAllMocks());
const saved: SavedSearches = {
max_active: 50,
active: [
{
id: 3,
name: '<script>Nome privado</script>',
term: 'QA%_',
version: 4,
href: '/compras/pesquisa?q=QA%25_',
},
],
archived: {
data: [
{
id: 6,
name: 'Anterior',
term: 'Outro texto',
version: 2,
href: '/compras/pesquisa?q=Outro%20texto',
},
],
total: 1,
prev_page_url: null,
next_page_url: null,
},
};
function renderSearch(searches: SavedSearches | null, actorId = 7) {
return renderToStaticMarkup(
<App
initialComponent={ProcurementSearch}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=QA',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actorId, tenant_id: 2 } },
term: 'QA',
groups: [],
savedSearches: searches,
},
}}
/>,
);
}
test('private saved criteria reopen a local live search and explain archival recovery without rendering supplied markup', () => {
const html = renderSearch(saved);
expect(html).toContain('As minhas pesquisas guardadas');
expect(html).toContain('pesquisa activa');
expect(html).toContain('href="/compras/pesquisa?q=QA%25_"');
expect(html).toContain('acesso actual');
expect(html).toContain('Arquivar pesquisa');
expect(html).toContain('Restaurar pesquisa Anterior');
expect(html).toContain('&lt;script&gt;Nome privado&lt;/script&gt;');
expect(html).not.toContain('<script>Nome privado');
});
test('uninstalled saved-search storage does not advertise unavailable actions', () => {
const html = renderSearch(null);
expect(html).not.toContain('As minhas pesquisas guardadas');
expect(html).not.toContain('Guardar pesquisa');
expect(html).toContain('Pesquisar processos');
});
test('encrypted preparation keys isolate owner company source version and editing state', () => {
const keys: string[] = [];
vi.spyOn(router, 'restore').mockImplementation((key) => {
if (key) keys.push(key);
return undefined;
});
renderSearch(saved, 7);
expect(keys.some((key) => key.startsWith('saved-search:2:7:QA'))).toBe(
true,
);
expect(
keys.some((key) => key.startsWith('saved-search-edit:2:7:3:4')),
).toBe(true);
keys.length = 0;
renderSearch(saved, 8);
expect(
keys.some((key) => key.startsWith('saved-search-edit:2:8:3:4')),
).toBe(true);
expect(keys.some((key) => key.includes(':2:7:'))).toBe(false);
});