commit melhorias compras4
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 16:28:03 +02:00
parent efd97e265b
commit 36dcfdf00c
118 changed files with 6042 additions and 92 deletions
@@ -0,0 +1,135 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
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();
$database = $argv[1] ?? '';
$db = DB::connection();
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $db->getConfig('host') !== '127.0.0.1') {
throw new LogicException('Recovery is restricted to disposable local PostgreSQL QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$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]);
auth()->guard()->setUser($author);
$budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Synthetic pre-extension budget.']);
auth()->guard()->setUser($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
auth()->guard()->setUser($author);
app(CommonBudget::class)->for($author)->record($f['r']->id, $f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
$balanceBefore = app(CommonBudget::class)->for($author)->balance($budget);
$columns = [];
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
$columns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
}
$fingerprint = static function (Connection $connection, array $definition): array {
$result = [];
foreach ($definition as $table => $names) {
$quoted = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.$table.'") t order by row_to_json(t)::text');
$result[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $result;
};
$before = $fingerprint($db, $columns);
$config = $db->getConfig();
unset($config['name']);
$directory = storage_path('framework/testing/distribution-recovery-'.$database);
if (! mkdir($directory, 0700, true) && ! is_dir($directory)) {
throw new RuntimeException('Unable to create the synthetic recovery directory.');
}
$pg = static function (string $binary, array $arguments) use ($config): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
['PGHOST' => $config['host'], 'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password']], timeout: 60);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Synthetic backup/restore failed.');
}
};
$preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
budgetDistributionFixtureSchema();
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->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']);
$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);
}
$after = $fingerprint($db, $afterColumns);
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $restore) || $restore === $database) {
throw new LogicException('Invalid isolated restore database.');
}
config(['database.connections.distribution_restore_admin' => [...$config, 'database' => 'postgres', 'url' => null],
'database.connections.distribution_restore' => [...$config, 'database' => $restore, 'url' => null]]);
$admin = DB::connection('distribution_restore_admin');
$created = false;
$default = DB::getDefaultConnection();
try {
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $postDump]);
$restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Restored distribution history or source data differs.');
}
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']);
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Recovered command was not replayed without new effects.');
}
DB::setDefaultConnection($default);
DB::purge('distribution_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
$created = false;
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $columns) !== $before || $restored->getSchemaBuilder()->hasTable('budget_distributions')
|| $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
throw new RuntimeException('Pre-extension recovery did not restore the original schema/data.');
}
DB::setDefaultConnection('distribution_restore');
auth()->guard()->setUser(User::query()->findOrFail($author->id));
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,
'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 {
DB::setDefaultConnection($default);
DB::purge('distribution_restore');
if ($created) {
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
}
@@ -0,0 +1,113 @@
<?php
use App\Enums\PurchasingRole;
use App\Http\Controllers\QuotationController;
use App\Models\CostCenter;
use App\Models\Quotation;
use App\Models\Supplier;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Visual fixture is restricted to disposable PostgreSQL QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$f = receiptFixture();
budgetDistributionFixtureSchema();
config(['budget-distributions.qa_enabled' => true]);
$users = [];
foreach (['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin] as $name => $role) {
$users[$name] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'name' => 'QA sintética · '.$role->label(), 'email' => 'qa-'.$name.'@sgc.example.invalid', 'purchasing_role' => $role]);
}
$centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'code' => 'QA-2', 'name' => 'Segundo centro sintético']);
foreach ([$f['r']->cost_center_id, $centre->id] as $id) {
auth()->guard()->setUser($users['finance']);
$budget = app(CommonBudget::class)->for($users['finance'])->create(['cost_center_id' => $id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação exclusivamente sintética da revisão visual.']);
auth()->guard()->setUser($users['admin']);
app(CommonBudget::class)->for($users['admin'])->approve($budget);
}
$workflow = app(RequisitionWorkflow::class);
$requests = [];
foreach (['draft', 'award', 'foreign'] as $purpose) {
auth()->guard()->setUser($users['owner']);
$r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id,
'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade exclusivamente sintética para revisão visual '.$purpose,
'items' => [['description' => 'Material sintético '.$purpose, 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$rows = array_map(fn ($id) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $r->items()->firstOrFail()->id,
'centre_id' => $id, 'subtotal' => '50.00', 'total' => '50.00'], [$f['r']->cost_center_id, $centre->id]);
$r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'process_version' => $r->getAttribute('process_version'),
'budget_distribution_preparation' => $rows, 'reason' => 'Parcelas explícitas sintéticas para revisão visual.'], $r);
$requests[$purpose] = $r;
if ($purpose === 'draft') {
continue;
}
$workflow->submit($users['owner'], $r, (string) Str::uuid(), $r->getAttribute('process_version'));
while (($r = $r->fresh())->status === 'pending') {
$step = $r->steps()->where('decision', 'pending')->orderBy('position')->firstOrFail();
$actor = match ($step->role) {
'department_head' => $users['head'], 'procurement' => $users['buyer'], 'finance' => $users['finance']
};
auth()->guard()->setUser($actor);
$workflow->decide($actor, $r, 'approved', null, (string) Str::uuid(), $r->getAttribute('process_version'));
}
if ($purpose === 'foreign') {
auth()->guard()->setUser($users['finance']);
app(QuotationExchange::class)->record($users['finance'], $r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD',
'rate' => '1.0000000000', 'quoted_on' => today()->toDateString(), 'source' => 'Referência exclusivamente sintética, sem cotação de mercado.']);
}
$quotes = [];
for ($index = 0; $index < 3; $index++) {
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id)->replicate();
$supplier->name = 'Fornecedor sintético '.$purpose.' '.$index;
$supplier->nuit = (string) (200000000 + count($requests) * 100 + $index);
$supplier->created_by = $users['buyer']->id;
$supplier->save();
$actor = $users['buyer'];
auth()->guard()->setUser($actor);
$input = Request::create('/', 'POST', ['supplier_id' => $supplier->id, 'currency' => $purpose === 'foreign' ? 'USD' : 'MZN',
'reference' => 'QA-'.$purpose.'-'.$index, 'delivery_days' => 5, 'valid_until' => today()->addMonth()->toDateString(), 'payment_terms' => '30 dias',
'no_conflict' => true, 'items' => [['requisition_item_id' => $r->items()->firstOrFail()->id, 'unit_price' => '100.00']]]);
$input->setUserResolver(fn () => $actor);
app(QuotationController::class)->store($input, $r, $workflow);
$quote = Quotation::query()->where('requisition_id', $r->id)->latest('id')->firstOrFail();
$quotes[] = $quote;
foreach ([$users['buyer'], $users['finance']] as $actor) {
auth()->guard()->setUser($actor);
$input = Request::create('/', 'POST', ['quality' => '8', 'history' => '5', 'payment' => '8', 'comment' => 'Avaliação exclusivamente sintética.', 'no_conflict' => true]);
$input->setUserResolver(fn () => $actor);
app(QuotationController::class)->evaluate($input, $quote, $workflow);
}
}
if ($purpose === 'foreign') {
auth()->guard()->setUser($users['buyer']);
$award = app(PurchaseWorkflow::class)->select($users['buyer'], $r, ['quotation_id' => $quotes[0]->id,
'justification' => 'Proposta exclusivamente sintética para revisão visual.', 'delivery_date' => today()->addWeek()->toDateString(),
'delivery_location' => 'Armazém sintético', 'budget_distribution_preparation' => $rows, 'reason' => 'Imputação explícita sintética da proposta em MZN.']);
foreach ($award->approvals()->orderBy('position')->get() as $step) {
$actor = match ($step->role) {
'department_head' => $users['head'], 'finance' => $users['finance'], 'procurement' => $users['admin']
};
auth()->guard()->setUser($actor);
app(PurchaseWorkflow::class)->decide($actor, $award, 'approved', null);
}
auth()->guard()->setUser($users['buyer']);
$order = app(PurchaseWorkflow::class)->issue($users['buyer'], $award);
}
}
echo json_encode(['synthetic_only' => true, 'draft' => $requests['draft']->id, 'award' => $requests['award']->id,
'foreign_order' => $order->id, 'users' => array_map(fn ($user) => $user->email, $users)], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,129 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CostCenter;
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
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || ! method_exists(BudgetControl::class, 'amendDistribution')) {
throw new LogicException('Distribution concurrency requires the authorised common source and disposable QA database.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
if (($argv[2] ?? '') === 'prepare') {
$f = receiptFixture();
$actor = 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]);
$centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'code' => 'QA-RACE', 'name' => 'Synthetic race centre']);
foreach ([$f['r']->cost_center_id, $centre->id] as $id) {
auth()->guard()->setUser($actor);
$budget = app(CommonBudget::class)->for($actor)->create(['cost_center_id' => $id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Synthetic concurrency budget only.']);
auth()->guard()->setUser($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
}
auth()->guard()->setUser($actor);
$plan = array_map(fn ($id) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $f['line']->requisition_item_id,
'centre_id' => $id, 'subtotal_minor' => 5000, 'total_minor' => 5000], [$f['r']->cost_center_id, $centre->id]);
$lines = [$f['line']->requisition_item_id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$engine = app(CommonBudget::class)->for($actor);
$engine->recordDistribution($f['r']->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
$commit = $engine->recordDistribution($f['r']->id, 'commit', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
$plan[0]['subtotal_minor'] = $plan[0]['total_minor'] = 6000;
$plan[1]['subtotal_minor'] = $plan[1]['total_minor'] = 4000;
echo json_encode(['tenant' => $actor->tenant_id, 'actor' => $actor->id, 'origin' => $f['r']->id, 'source' => $commit['distribution_id'],
'hash' => $commit['plan_hash'], 'plan' => $plan, 'operation' => (string) Str::uuid()], 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_distribution_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$result = app(CommonBudget::class)->for($actor)->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic Finance amendment under real contention.', $input['operation']);
echo json_encode(['status' => 200, 'version' => $result['amendment_version'], '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 distribution worker mode.');
}
budgetDistributionFixtureSchema();
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['plan'][0]['subtotal_minor'] = $input['plan'][0]['total_minor'] = 5999;
$input['plan'][1]['subtotal_minor'] = $input['plan'][1]['total_minor'] = 4001;
}
$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_distribution_write_%' and wait_event_type='Lock'", [$database])->n;
if ($blocked >= 2) {
break;
}
usleep(50000);
} while (microtime(true) < $deadline);
if ($blocked < 2) {
throw new RuntimeException('Real contention was not demonstrated.');
}
$db->commit();
$statuses = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException($worker->getErrorOutput());
}
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
}
sort($statuses);
$snapshot = json_decode($db->table('budget_distributions')->where('id', $input['source'])->value('snapshot'), true, 32, JSON_THROW_ON_ERROR);
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $snapshot['amendment_version'] !== 1
|| $db->table('budget_distribution_events')->where('distribution_id', $input['source'])->count() !== 3
|| $db->table('budget_distribution_entries')->where('distribution_id', $input['source'])->count() !== 6
|| $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.distribution_amended')->count() !== 1) {
throw new RuntimeException('Version, effects, replay and unique audit were not demonstrated.');
}
echo json_encode(['distribution_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses,
'one_amendment_version_and_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
@@ -0,0 +1,434 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CostCenter;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\CommonBudget;
use App\Services\InvoiceWorkflow;
use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
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';
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Unpublished common source requires explicit COMMON_BUDGET_PATH QA selection.');
}
$this->f = receiptFixture();
budgetDistributionFixtureSchema();
config(['budget-distributions.qa_enabled' => true]);
$this->author = 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->centre2 = CostCenter::query()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'code' => 'DISTR-2', 'name' => 'Centro sintético adicional']);
$this->actingAs($this->author);
$this->budgetIds = [];
foreach ([$this->f['r']->cost_center_id, $this->centre2->id] as $centre) {
$budget = app(CommonBudget::class)->for($this->author)->create(['cost_center_id' => $centre, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => $centre !== $this->centre2->id, 'amount_minor' => 20000, 'reason' => 'Dotação sintética para contrato comum']);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer)->approve($budget);
$this->budgetIds[] = $budget;
$this->actingAs($this->author);
}
// Explicit synthetic host source contract; not a claim of an invoice workflow execution.
$this->lines = [12 => ['subtotal_minor' => 10000, 'total_minor' => 11600, 'required_kind' => 'operating']];
$this->plan = [
['allocation_key' => 'a', 'line_id' => 12, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 5000, 'total_minor' => 5800],
['allocation_key' => 'b', 'line_id' => 12, 'centre_id' => $this->centre2->id, 'subtotal_minor' => 5000, 'total_minor' => 5800],
];
});
function distributedRecord(object $test, string $phase, ?string $key = null, ?array $plan = null): array
{
return app(CommonBudget::class)->for($test->author)->recordDistribution($test->f['r']->id, $phase, $plan ?? $test->plan,
$test->lines, str_repeat('a', 64), $key ?? (string) Str::uuid());
}
test('explicit optional contract composition loads the selected standalone source without sibling fallback', function () {
$selected = getenv('COMMON_BUDGET_PATH');
expect($selected)->toBeString()->not->toBe('')
->and(realpath((new ReflectionClass(BudgetControl::class))->getFileName()))->toBe(realpath($selected.'/src/BudgetControl.php'));
});
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,
'supplier_id' => $test->f['order']->supplier_id, 'created_by' => $test->author->id, 'number' => $number, 'issued_on' => today(),
'status' => 'pending', 'subtotal_minor' => $net, 'tax_minor' => $gross - $net, 'total_minor' => $gross, 'snapshot' => ['synthetic_contract_fixture' => true]]);
}
function preparedDistributedRequisition(object $test): array
{
$workflow = app(RequisitionWorkflow::class);
$data = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $test->f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Pedido sintético com distribuição explícita.',
'items' => [['description' => 'Material sintético distribuído', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']]];
$request = $workflow->save($test->author, $data);
$line = $request->items()->firstOrFail();
$preparation = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->getAttribute('process_version'),
'reason' => 'Distribuição explícita pelos centros autorizados.', 'budget_distribution_preparation' => [
['allocation_key' => (string) Str::uuid(), 'line_id' => $line->id, 'centre_id' => $test->f['r']->cost_center_id, 'subtotal' => '50.00', 'total' => '58.00'],
['allocation_key' => (string) Str::uuid(), 'line_id' => $line->id, 'centre_id' => $test->centre2->id, 'subtotal' => '50.00', 'total' => '58.00'],
]];
$prepared = $workflow->save($test->author, $preparation, $request);
return [$prepared, $data, $preparation];
}
test('native requisition save and submit reuse the common distributed writer without parallel reservations', function () {
[$request, , $preparation] = preparedDistributedRequisition($this);
$version = $request->getAttribute('process_version');
$again = app(RequisitionWorkflow::class)->save($this->author, $preparation, $request);
expect($again->getAttribute('process_version'))->toBe($version)->and($request->budget_distribution_preparation['prepared_by'])->toBe($this->author->id);
app(RequisitionWorkflow::class)->submit($this->author, $request, (string) Str::uuid(), $version);
expect($request->fresh()->status)->toBe('pending')->and(DB::table('budget_distributions')->where('requisition_id', $request->id)->value('phase'))->toBe('reserve')
->and(DB::table('budget_distribution_entries')->count())->toBe(2)->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0);
});
test('distribution preparation has an encrypted HTTP form and uses native versioned save', function () {
$this->withoutVite();
[$request, , $preparation] = preparedDistributedRequisition($this);
$this->get('/requisicoes/'.$request->id.'/distribuicoes')->assertOk()
->assertViewHas('page', fn (array $page) => $page['component'] === 'requisitions/distributions' && $page['encryptHistory'] === true);
$preparation['operation_key'] = (string) Str::uuid();
$preparation['process_version'] = $request->getAttribute('process_version');
$this->postJson('/requisicoes/'.$request->id.'/distribuicoes', $preparation)->assertRedirect('/requisicoes/'.$request->id);
expect($request->fresh()->getAttribute('process_version'))->toBe($preparation['process_version'] + 1)
->and(DB::table('budget_distribution_entries')->count())->toBe(0);
$this->actingAs($this->reviewer);
$this->get('/requisicoes/'.$request->id.'/distribuicoes')->assertForbidden();
$this->postJson('/requisicoes/'.$request->id.'/distribuicoes', [...$preparation, 'operation_key' => (string) Str::uuid()])->assertForbidden();
config(['budget-distributions.qa_enabled' => false]);
$this->actingAs($this->author);
$this->get('/requisicoes/'.$request->id.'/distribuicoes')->assertServiceUnavailable();
});
test('explicit amendment action requires current Finance function even when the common command is called directly', function () {
distributedRecord($this, 'reserve');
$commit = distributedRecord($this, 'commit');
$this->actingAs($this->reviewer);
$changed = [[...$this->plan[0], 'subtotal_minor' => 4999, 'total_minor' => 5799], [...$this->plan[1], 'subtotal_minor' => 5001, 'total_minor' => 5801]];
try {
app(CommonBudget::class)->for($this->reviewer)->amendDistribution($this->f['r']->id, $changed, $commit['plan_hash'], 'Administrador sem função financeira explícita.', (string) Str::uuid());
$this->fail('Finance authority is mandatory.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(403);
}
expect(DB::table('budget_distribution_events')->count())->toBe(2);
});
test('quotation allocation uses actual changed MZN line amounts and freezes the source before commitment', function () {
[$request, , $preparation] = preparedDistributedRequisition($this);
app(RequisitionWorkflow::class)->submit($this->author, $request, (string) Str::uuid(), $request->getAttribute('process_version'));
$quote = Quotation::query()->create(['tenant_id' => $this->author->tenant_id, 'requisition_id' => $request->id,
'supplier_id' => $this->f['order']->supplier_id, 'created_by' => $this->f['issuer']->id, 'reference' => 'QA-DISTR-QUOTE',
'delivery_days' => 5, 'valid_until' => today()->addWeek(), 'payment_terms' => '30 dias', 'currency' => 'MZN',
'subtotal_minor' => 12000, 'tax_minor' => 1920, 'total_minor' => 13920, 'weights' => []]);
$line = $quote->items()->create(['tenant_id' => $this->author->tenant_id, 'requisition_item_id' => $request->items()->firstOrFail()->id,
'description' => 'Proposta sintética com valor alterado', 'quantity' => '2.000', 'unit_price_minor' => 6000, 'tax_rate' => '16.00',
'subtotal_minor' => 12000, 'tax_minor' => 1920, 'total_minor' => 13920]);
$this->actingAs($this->f['issuer']);
$budget = app(BudgetWorkflow::class);
expect(fn () => $budget->record($this->f['issuer'], $request, 'award', 13920, 12000, $quote))->toThrow(ValidationException::class);
$input = $preparation;
$input['budget_distribution_preparation'] = array_map(fn ($row) => [...$row, 'subtotal' => '60.00', 'total' => '69.60'], $input['budget_distribution_preparation']);
DB::transaction(function () use ($request, $quote, $input, $budget) {
app(RequisitionBudgetDistributions::class)->prepareQuote($this->f['issuer'], $request, $quote, $input);
$budget->record($this->f['issuer'], $request, 'award', 13920, 12000, $quote);
});
expect($request->fresh()->budget_distribution_preparation['allocations'][0]['total_minor'])->toBe(5800)
->and($request->fresh()->budget_distribution_preparation['quotation']['allocations'][0]['total_minor'])->toBe(6960);
expect(array_key_exists('budget_distribution_preparation', $request->fresh()->toArray()))->toBeFalse();
$this->actingAs($this->author);
$this->get('/requisicoes/'.$request->id)->assertOk()->assertViewHas('page', fn (array $page) => ! array_key_exists('budget_distribution_preparation', json_decode(json_encode($page['props']['requisition'], JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)));
$this->actingAs($this->f['issuer']);
$line->update(['description' => 'Mesmo valor, descrição posteriormente editada']);
// Descriptive edits do not replace monetary source values; actual monetary changes do.
$line->update(['subtotal_minor' => 12001]);
expect(fn () => $budget->record($this->f['issuer'], $request->fresh(), 'commit', 13920, 12000, $quote))->toThrow(ValidationException::class);
expect(DB::table('budget_distributions')->where('requisition_id', $request->id)->value('phase'))->toBe('award');
$line->update(['subtotal_minor' => 12000]);
$budget->record($this->f['issuer'], $request->fresh(), 'commit', 13920, 12000, $quote);
expect(DB::table('budget_distributions')->where('requisition_id', $request->id)->value('phase'))->toBe('commit');
});
test('changed draft basis requires reconfirmation and disabled distribution never falls back to the old writer', function () {
[$request, $data] = preparedDistributedRequisition($this);
$changed = app(RequisitionWorkflow::class)->save($this->author, [...$data, 'operation_key' => (string) Str::uuid(), 'process_version' => $request->getAttribute('process_version')], $request);
expect(fn () => app(RequisitionWorkflow::class)->submit($this->author, $changed, (string) Str::uuid(), $changed->getAttribute('process_version')))->toThrow(ValidationException::class);
expect($changed->fresh()->status)->toBe('draft')->and(DB::table('budget_distribution_entries')->count())->toBe(0);
[$another] = preparedDistributedRequisition($this);
config(['budget-distributions.qa_enabled' => false]);
try {
app(RequisitionWorkflow::class)->submit($this->author, $another, (string) Str::uuid(), $another->getAttribute('process_version'));
$this->fail('Distribution must not fall back to the legacy writer.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(503);
}
expect($another->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->where('requisition_id', $another->id)->count())->toBe(0);
});
test('distributed reservation commitment and partial consumption share native balances and replay exactly once', function () {
$key = (string) Str::uuid();
distributedRecord($this, 'reserve', $key);
expect(distributedRecord($this, 'reserve', $key)['replayed'])->toBeTrue()
->and(DB::table('budget_distribution_entries')->count())->toBe(2);
$engine = app(CommonBudget::class)->for($this->author);
expect($engine->balance($this->budgetIds[0])['reserved_minor'])->toBe(5800)
->and($engine->balance($this->budgetIds[1])['reserved_minor'])->toBe(5000);
distributedRecord($this, 'award');
distributedRecord($this, 'commit');
$invoice = distributionInvoice($this, 'DISTR-PARTIAL', 1000, 1160);
$partial = array_map(fn ($row) => [...$row, 'subtotal_minor' => 500, 'total_minor' => 580], $this->plan);
$lines = [12 => ['subtotal_minor' => 1000, 'total_minor' => 1160, 'required_kind' => 'operating']];
$operation = (string) Str::uuid();
$consume = fn () => $engine->consumeDistribution($this->f['r']->id, $invoice->id, $partial, $lines, str_repeat('b', 64), $operation);
expect($consume()['replayed'])->toBeFalse()->and($consume()['replayed'])->toBeTrue();
expect($engine->balance($this->budgetIds[0]))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 5220, 'consumed_minor' => 580, 'available_minor' => 14200]);
expect($engine->balance($this->budgetIds[1]))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 4500, 'consumed_minor' => 500, 'available_minor' => 15000]);
expect(DB::table('budget_distribution_consumptions')->count())->toBe(2)
->and(DB::table('budget_distribution_events')->count())->toBe(4)
->and(fn () => $engine->record($this->f['r']->id, $this->f['r']->cost_center_id, 'operating', 'reserve', 11600, 10000))->toThrow(BudgetFailure::class)
->and(fn () => distributedRecord($this, 'cancel'))->toThrow(BudgetFailure::class);
});
test('explicit commitment amendment preserves native totals and history with versioned replay', function () {
distributedRecord($this, 'reserve');
$commit = distributedRecord($this, 'commit');
$engine = app(CommonBudget::class)->for($this->author);
$changed = [[...$this->plan[0], 'subtotal_minor' => 4999, 'total_minor' => 5799], [...$this->plan[1], 'subtotal_minor' => 5001, 'total_minor' => 5801]];
$operation = (string) Str::uuid();
$amend = fn () => $engine->amendDistribution($this->f['r']->id, $changed, $commit['plan_hash'], 'Reafectação explícita sintética por Finanças.', $operation);
$result = $amend();
expect($result['amendment_version'])->toBe(1)->and($amend()['replayed'])->toBeTrue()
->and($engine->balance($this->budgetIds[0])['committed_minor'])->toBe(5799)
->and($engine->balance($this->budgetIds[1])['committed_minor'])->toBe(5001);
expect(fn () => $engine->amendDistribution($this->f['r']->id, $this->plan, $commit['plan_hash'], 'Versão desactualizada não pode alterar.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
$restored = $engine->amendDistribution($this->f['r']->id, $this->plan, $result['plan_hash'], 'Nova reafectação explícita preservando histórico.', (string) Str::uuid());
expect($restored['amendment_version'])->toBe(2)->and($restored['plan_hash'])->not->toBe($commit['plan_hash'])
->and(DB::table('budget_distribution_events')->count())->toBe(4);
$original = json_decode(DB::table('budget_distribution_events')->where('kind', 'commit')->value('snapshot'), true);
expect($original['allocations'][0]['total_minor'])->toBe(5800);
});
test('amendment cannot erase consumed amounts or exceed an approved destination budget', function () {
distributedRecord($this, 'reserve');
$commit = distributedRecord($this, 'commit');
$engine = app(CommonBudget::class)->for($this->author);
$invoice = distributionInvoice($this, 'AMEND-USED', 5000, 5800);
$engine->consumeDistribution($this->f['r']->id, $invoice->id, [$this->plan[0]], [12 => ['subtotal_minor' => 5000, 'total_minor' => 5800, 'required_kind' => 'operating']], str_repeat('d', 64), (string) Str::uuid());
$changed = [[...$this->plan[0], 'subtotal_minor' => 4999, 'total_minor' => 5799], [...$this->plan[1], 'subtotal_minor' => 5001, 'total_minor' => 5801]];
expect(fn () => $engine->amendDistribution($this->f['r']->id, $changed, $commit['plan_hash'], 'Não reduzir o consumo documental anterior.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
$before = DB::table('budget_distribution_entries')->get()->toJson();
$increase = [[...$this->plan[0], 'subtotal_minor' => 5000, 'total_minor' => 5801], [...$this->plan[1], 'subtotal_minor' => 5000, 'total_minor' => 5799]];
// Increase the tax-inclusive first allocation; consumed amounts remain respected.
$other = $this->f['r']->replicate(['number']);
$other->number = 'QA-AMEND-BALANCE';
$other->save();
$engine->record($other->id, $this->f['r']->cost_center_id, 'operating', 'reserve', 14200, 14200);
expect(fn () => $engine->amendDistribution($this->f['r']->id, $increase, $commit['plan_hash'], 'Reafectação sem saldo deve ser integralmente recusada.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_distribution_entries')->get()->toJson())->toBe($before)
->and(DB::table('budget_distribution_events')->count())->toBe(3);
});
test('explicit reference line reallocation preserves native header totals without automatic cents', function () {
// Synthetic reference imputations: one MZN cent shared across two documentary lines.
$this->lines = [12 => ['subtotal_minor' => 1, 'total_minor' => 1, 'required_kind' => 'operating'],
13 => ['subtotal_minor' => 0, 'total_minor' => 0, 'required_kind' => 'operating']];
$this->plan = [[...$this->plan[0], 'subtotal_minor' => 1, 'total_minor' => 1],
[...$this->plan[1], 'line_id' => 13, 'subtotal_minor' => 0, 'total_minor' => 0]];
distributedRecord($this, 'reserve');
$commit = distributedRecord($this, 'commit');
$next = [[...$this->plan[0], 'subtotal_minor' => 0, 'total_minor' => 0], [...$this->plan[1], 'subtotal_minor' => 1, 'total_minor' => 1]];
$lines = [12 => ['subtotal_minor' => 0, 'total_minor' => 0, 'required_kind' => 'operating'],
13 => ['subtotal_minor' => 1, 'total_minor' => 1, 'required_kind' => 'operating']];
$engine = app(CommonBudget::class)->for($this->author);
$invalid = $lines;
$invalid[13]['subtotal_minor'] = 2;
$invalid[13]['total_minor'] = 2;
$wrongPlan = $next;
$wrongPlan[1]['subtotal_minor'] = 2;
$wrongPlan[1]['total_minor'] = 2;
expect(fn () => $engine->amendDistribution($this->f['r']->id, $wrongPlan, $commit['plan_hash'], 'Não alterar os totais nativos congelados.', (string) Str::uuid(), $invalid))->toThrow(BudgetFailure::class);
$operation = (string) Str::uuid();
$amend = fn () => $engine->amendDistribution($this->f['r']->id, $next, $commit['plan_hash'], 'Imputação explícita sintética do centavo por Finanças.', $operation, $lines);
expect($amend()['replayed'])->toBeFalse()->and($amend()['replayed'])->toBeTrue()
->and($engine->balance($this->budgetIds[0])['committed_minor'])->toBe(0)
->and($engine->balance($this->budgetIds[1])['committed_minor'])->toBe(1);
$invoice = distributionInvoice($this, 'EXPLICIT-CENT', 1, 1);
$engine->consumeDistribution($this->f['r']->id, $invoice->id, [$next[1]], [13 => $lines[13]], str_repeat('e', 64), (string) Str::uuid());
expect($engine->balance($this->budgetIds[1])['consumed_minor'])->toBe(1);
});
test('native partial invoice registration and independent validation use distributed consumption exactly once', function () {
$id = $this->f['line']->requisition_item_id;
$this->lines = [$id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$this->plan = array_map(fn ($row) => [...$row, 'allocation_key' => (string) Str::uuid(), 'line_id' => $id, 'subtotal_minor' => 5000, 'total_minor' => 5000], $this->plan);
distributedRecord($this, 'reserve');
distributedRecord($this, 'commit');
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->actingAs($this->author);
$data = ['number' => 'DISTR-NATIVE-PARTIAL', 'issued_on' => today()->toDateString(), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00',
'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '0.600']], 'reason' => 'Imputação explícita da factura parcial sintética.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => '30.00', 'total' => '30.00'], $this->plan)];
$invalid = $data;
$invalid['budget_distribution_preparation'][0]['allocation_key'] = (string) Str::uuid();
expect(fn () => app(InvoiceWorkflow::class)->register($this->author, $this->f['order'], $invalid))->toThrow(ValidationException::class)
->and(Invoice::query()->count())->toBe(0)->and(DB::table('budget_distribution_consumptions')->count())->toBe(0);
$invoice = app(InvoiceWorkflow::class)->register($this->author, $this->f['order'], $data);
expect($invoice->snapshot['budget_distribution']['reference']['total_minor'])->toBe(6000)
->and(DB::table('budget_distribution_consumptions')->count())->toBe(0);
try {
app(InvoiceWorkflow::class)->validate($this->author, $invoice);
$this->fail('The invoice author cannot validate their own preparation.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(403);
}
$validator = User::factory()->create(['tenant_id' => $this->author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($validator);
app(InvoiceWorkflow::class)->validate($validator, $invoice);
app(InvoiceWorkflow::class)->validate($validator, $invoice);
expect($invoice->fresh()->status)->toBe('validated')->and(DB::table('budget_distribution_consumptions')->count())->toBe(2)
->and(DB::table('budget_consumptions')->count())->toBe(0)
->and(app(CommonBudget::class)->for($validator)->balance($this->budgetIds[0]))->toMatchArray(['committed_minor' => 2000, 'consumed_minor' => 3000]);
$this->get('/requisicoes/'.$this->f['r']->id.'/processo')->assertOk()->assertInertia(fn ($page) => $page->where('stages', fn ($stages) => collect($stages)->firstWhere('label', 'Controlo orçamental')['state'] === 'recorded'));
});
test('Finance explicitly versions a foreign order allocation through HTTP without altering its frozen document', function () {
$this->withoutVite();
// Synthetic issued-order fixture; no claim of a full adjudication journey.
$request = $this->f['r']->replicate(['number']);
$request->number = 'QA-FX-DISTR-'.Str::random(8);
$request->save();
$requested = $this->f['r']->items()->firstOrFail()->replicate();
$requested->requisition_id = $request->id;
$requested->save();
app(QuotationExchange::class)->record($this->author, $request, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD',
'rate' => '1.0000000000', 'quoted_on' => today()->toDateString(), 'source' => 'Taxa exclusivamente sintética para teste, sem cotação de mercado.']);
$basis = app(QuotationExchange::class)->basis($request, 'USD');
$quote = Quotation::query()->where('requisition_id', $this->f['r']->id)->firstOrFail()->replicate();
$quote->requisition_id = $request->id;
$quote->currency = 'USD';
$quote->exchange_basis = $basis;
$quote->save();
$award = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id)->replicate();
$award->requisition_id = $request->id;
$award->quotation_id = $quote->id;
$award->save();
$order = $this->f['order']->replicate(['number']);
$order->number = 'QA-OC-FX-'.Str::random(8);
$order->requisition_id = $request->id;
$order->purchase_award_id = $award->id;
$order->currency = 'USD';
$order->snapshot = [...$order->snapshot, 'exchange_basis' => $basis, 'reference_amounts' => ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]];
$order->save();
$line = $this->f['line']->replicate();
$line->purchase_order_id = $order->id;
$line->requisition_item_id = $requested->id;
$line->save();
$plan = array_map(fn ($row) => [...$row, 'allocation_key' => (string) Str::uuid(), 'line_id' => $requested->id, 'subtotal_minor' => 5000, 'total_minor' => 5000], $this->plan);
$lines = [$requested->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$engine = app(CommonBudget::class)->for($this->author);
$engine->recordDistribution($request->id, 'reserve', $plan, $lines, str_repeat('f', 64), (string) Str::uuid());
$commit = $engine->recordDistribution($request->id, 'commit', $plan, $lines, str_repeat('f', 64), (string) Str::uuid());
$document = $order->fresh()->getRawOriginal();
$this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
$input = ['operation_key' => (string) Str::uuid(), 'expected_plan_hash' => $commit['plan_hash'], 'reason' => 'Reafectação explícita sintética para conferência da factura parcial.',
'budget_distribution_preparation' => array_map(fn ($row, $amount) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => $amount, 'total' => $amount], $plan, ['60.01', '39.99'])];
$this->postJson('/ordens/'.$order->id.'/reafectacao', $input)->assertRedirect('/ordens/'.$order->id);
$this->postJson('/ordens/'.$order->id.'/reafectacao', $input)->assertRedirect('/ordens/'.$order->id);
expect($order->fresh()->getRawOriginal())->toBe($document)
->and(DB::table('budget_distribution_events')->where('distribution_id', $commit['distribution_id'])->count())->toBe(3);
$this->actingAs($this->f['issuer']);
$this->postJson('/ordens/'.$order->id.'/reafectacao', [...$input, 'operation_key' => (string) Str::uuid()])->assertForbidden();
$this->actingAs($this->f['receiver']);
$fixture = [...$this->f, 'r' => $request, 'order' => $order, 'line' => $line];
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $order, receiptPayload($fixture, '1.000'));
$this->actingAs($this->author);
$data = ['number' => 'QA-FX-PARTIAL', 'issued_on' => today()->toDateString(), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00',
'items' => [['purchase_order_item_id' => $line->id, 'quantity' => '0.600']], 'reason' => 'Imputação explícita em MZN da factura parcial.',
'budget_distribution_preparation' => array_map(fn ($row) => [...$row, 'subtotal' => '30.00', 'total' => '30.00'], $input['budget_distribution_preparation'])];
$invoice = app(InvoiceWorkflow::class)->register($this->author, $order, $data);
$validator = User::factory()->create(['tenant_id' => $this->author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($validator);
app(InvoiceWorkflow::class)->validate($validator, $invoice);
expect($invoice->fresh()->status)->toBe('validated')->and($invoice->snapshot['exchange_basis'])->toBe($basis)
->and($invoice->snapshot['budget_distribution']['reference']['total_minor'])->toBe(6000);
});
test('failure of any destination rolls back the entire distribution and its origin', function () {
$centre = CostCenter::query()->create(['tenant_id' => $this->author->tenant_id, 'department_id' => $this->f['department']->id, 'code' => 'DISTR-SMALL', 'name' => 'Dotação insuficiente sintética']);
$budget = app(CommonBudget::class)->for($this->author)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100, 'reason' => 'Limite sintético do cenário de falha']);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer)->approve($budget);
$this->actingAs($this->author);
$plan = $this->plan;
$plan[1]['centre_id'] = $centre->id;
expect(fn () => distributedRecord($this, 'reserve', null, $plan))->toThrow(BudgetFailure::class);
foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries'] as $table) {
expect(DB::table($table)->count())->toBe(0);
}
expect(app(CommonBudget::class)->for($this->author)->balance($this->budgetIds[0])['available_minor'])->toBe(20000);
});
test('a same-budget redistribution checks its combined delta instead of rejecting a temporary line ordering', function () {
$centre = CostCenter::query()->create(['tenant_id' => $this->author->tenant_id, 'department_id' => $this->f['department']->id, 'code' => 'DISTR-EXACT', 'name' => 'Dotação exacta sintética']);
$budget = app(CommonBudget::class)->for($this->author)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 11600, 'reason' => 'Dotação exacta para a distribuição']);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer)->approve($budget);
$this->actingAs($this->author);
$plan = array_map(fn ($row) => [...$row, 'centre_id' => $centre->id], $this->plan);
distributedRecord($this, 'reserve', null, $plan);
$changed = [[...$plan[0], 'subtotal_minor' => 9000, 'total_minor' => 10440], [...$plan[1], 'subtotal_minor' => 1000, 'total_minor' => 1160]];
distributedRecord($this, 'award', null, $changed);
expect(app(CommonBudget::class)->for($this->author)->balance($budget))->toMatchArray(['reserved_minor' => 11600, 'available_minor' => 0]);
});
test('cancellation releases each unused commitment once and cannot restart the distributed process', function () {
distributedRecord($this, 'reserve');
distributedRecord($this, 'commit');
$operation = (string) Str::uuid();
expect(distributedRecord($this, 'cancel', $operation)['replayed'])->toBeFalse()
->and(distributedRecord($this, 'cancel', $operation)['replayed'])->toBeTrue();
foreach ($this->budgetIds as $budget) {
expect(app(CommonBudget::class)->for($this->author)->balance($budget))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'available_minor' => 20000]);
}
expect(fn () => distributedRecord($this, 'award'))->toThrow(BudgetFailure::class)
->and(DB::table('budget_distribution_events')->count())->toBe(3);
});
test('changed replay and cumulative allocation overspending cannot alter distributed effects', function () {
$key = (string) Str::uuid();
distributedRecord($this, 'reserve', $key);
$changed = [[...$this->plan[0], 'subtotal_minor' => 6000, 'total_minor' => 6960], [...$this->plan[1], 'subtotal_minor' => 4000, 'total_minor' => 4640]];
expect(fn () => distributedRecord($this, 'reserve', $key, $changed))->toThrow(BudgetFailure::class);
distributedRecord($this, 'commit');
$engine = app(CommonBudget::class)->for($this->author);
$invoice = distributionInvoice($this, 'DISTR-ONE', 1000, 1160);
$partial = array_map(fn ($row) => [...$row, 'subtotal_minor' => 500, 'total_minor' => 580], $this->plan);
$engine->consumeDistribution($this->f['r']->id, $invoice->id, $partial, [12 => ['subtotal_minor' => 1000, 'total_minor' => 1160, 'required_kind' => 'operating']], str_repeat('b', 64), (string) Str::uuid());
$invoice2 = distributionInvoice($this, 'DISTR-TOO-MUCH', 5000, 5800);
$before = DB::table('budget_distribution_entries')->get()->toJson();
expect(fn () => $engine->consumeDistribution($this->f['r']->id, $invoice2->id, [$this->plan[0]], [12 => ['subtotal_minor' => 5000, 'total_minor' => 5800, 'required_kind' => 'operating']], str_repeat('c', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_distribution_entries')->get()->toJson())->toBe($before);
});
test('partial distribution schema fails closed instead of hiding existing financial positions', function () {
DB::connection()->getSchemaBuilder()->drop('budget_distribution_events');
expect(app(RequisitionBudgetDistributions::class)->ready())->toBeFalse();
expect(fn () => app(CommonBudget::class)->for($this->author)->balance($this->budgetIds[0]))->toThrow(BudgetFailure::class);
});
@@ -0,0 +1,48 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('old pinned runtime refuses partial optional schema even when its source table is absent', function () {
if (method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Recovery boundary requires the unchanged installed artifact.');
}
$f = receiptFixture();
budgetDistributionFixtureSchema();
DB::connection()->getSchemaBuilder()->drop('budget_distributions');
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($actor);
try {
app(CommonBudget::class)->for($actor);
$this->fail('Partial optional schema cannot silently become a legacy balance.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(503);
}
expect(DB::table('budget_entries')->count())->toBe(0);
});
test('old pinned runtime refuses to ignore a distributed origin instead of presenting a false available balance', function () {
if (method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('This recovery boundary exercises the unchanged installed artifact.');
}
$f = receiptFixture();
budgetDistributionFixtureSchema();
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($actor);
DB::table('budget_distributions')->insert(['tenant_id' => $actor->tenant_id, 'requisition_id' => $f['r']->id,
'phase' => 'reserve', 'snapshot' => '{}', 'created_by' => $actor->id, 'created_at' => now(), 'updated_at' => now()]);
try {
app(CommonBudget::class)->for($actor);
$this->fail('An incompatible runtime must fail closed.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(503);
}
expect(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
@@ -0,0 +1,49 @@
<?php
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('optional QA migration installs once explicitly and preserves previous records', function () {
$f = receiptFixture();
$columns = Schema::getColumnListing('requisitions');
$before = DB::table('requisitions')->select($columns)->get()->toJson();
$count = DB::table('migrations')->count();
$path = database_path('qa-migrations/2026_11_22_000004_create_budget_distributions.php');
foreach ([1, 2] as $attempt) {
expect(Artisan::call('migrate', ['--path' => [$path], '--realpath' => true, '--force' => true]))->toBe(0);
expect(DB::table('migrations')->count())->toBe($count + 1)
->and(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);
}
$migration = require $path;
expect(fn () => $migration->down())->toThrow(LogicException::class)
->and(Schema::hasTable('budget_distribution_events'))->toBeTrue()
->and(DB::table('requisitions')->where('id', $f['r']->id)->exists())->toBeTrue();
});
test('optional schema failure is atomic and cannot leave a new preparation column', function () {
receiptFixture();
Schema::create('budget_distribution_entries', fn ($table) => $table->id());
$migration = require database_path('qa-migrations/2026_11_22_000004_create_budget_distributions.php');
expect(fn () => $migration->up())->toThrow(QueryException::class)
->and(Schema::hasColumn('requisitions', 'budget_distribution_preparation'))->toBeFalse()
->and(Schema::hasTable('budget_distributions'))->toBeFalse()
->and(Schema::hasTable('budget_distribution_events'))->toBeFalse();
});
test('QA migration refuses an operational environment before writing schema', function () {
receiptFixture();
$migration = require database_path('qa-migrations/2026_11_22_000004_create_budget_distributions.php');
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');
}
});
@@ -18,6 +18,15 @@ beforeEach(function () {
]];
});
test('new and existing requisition form history is encrypted without creating a process on read', function () {
$count = Requisition::query()->count();
$this->get('/requisicoes/criar')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect(Requisition::query()->count())->toBe($count);
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$this->get('/requisicoes/'.$r->id.'/editar')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
});
test('incomplete draft persists unknown values without invented amounts and cannot reserve or submit', function () {
$entries = DB::table('budget_entries')->count();
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
@@ -112,6 +112,17 @@ test('autonomous adapter executes shared lifecycle with one request one reserve
$this->get('/requisicoes/'.$r->id)->assertOk();
});
test('one eligible approver completes the level even when another approver is eligible for the same level', function () {
$alternative = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'department_id' => $this->actor->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->postJson('/requisicoes', $this->data)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$this->postJson('/requisicoes/'.$r->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect();
expect($r->fresh()->canDecide($this->head))->toBeTrue()->and($r->fresh()->canDecide($alternative))->toBeTrue();
$this->actingAs($alternative)->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => 2, 'decision' => 'approved'])->assertRedirect();
expect($r->fresh()->status)->toBe('approved')->and($r->steps()->sole()->approver_id)->toBe($alternative->id)
->and($r->fresh()->canDecide($this->head))->toBeFalse()->and($r->steps()->count())->toBe(1);
});
test('source adapter refuses changed replay stale version revoked role and another tenant', function () {
$this->postJson('/requisicoes', $this->data)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
@@ -39,7 +39,25 @@ beforeEach(function () {
$this->actingAs($this->admin);
});
afterEach(function () {
if ($this->committedReportFixture ?? 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('Report fixture cleanup requires the disposable PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
test('intelligence settings are independently configurable audited and scoped without rewriting processes', function () {
if (DB::getDriverName() === 'pgsql') {
// The real report opens its own read-only snapshot, outside the test wrapper.
if (! app()->environment('testing') || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Report fixtures require the disposable PostgreSQL test transaction.');
}
DB::commit();
$this->committedReportFixture = true;
}
$before = $this->f['r']->fresh()->toArray();
$body = ['version' => 1, 'procurement_brief' => false, 'people_brief' => true, 'reason' => 'Apresentar sínteses apenas no percurso de Pessoas.'];
$this->postJson($this->base.'/intelligence', $body)->assertRedirect();
@@ -0,0 +1,115 @@
<?php
use App\Models\Requisition;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPayableInsights;
use App\Services\SupplierPayables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
$this->f = paymentFixture();
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'insights-fixture-instance']);
foreach ([$this->f['author'], $this->f['validator']] as $user) {
foreach (['view', 'prepare', 'validate'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $user->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $user->id, 'person' => 'insights-person-'.$user->id, 'action' => $action]);
}
}
$this->actingAs($this->f['author']);
$prepared = app(SupplierPayables::class)->engine($this->f['author'])->command('prepare', $this->f['invoice']->id, 'Preparação sintética para consulta', (string) Str::uuid());
$this->actingAs($this->f['validator']);
app(SupplierPayables::class)->engine($this->f['validator'])->command('validate', $prepared['proposal_id'], 'Conferência sintética independente', (string) Str::uuid());
});
afterEach(function () {
if ($this->committedInsightsFixture ?? 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('Read report fixture cleanup requires the disposable database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
test('financial insights use native positions across authorised filtered requests without modifying sources', function () {
$copy = $this->f['invoice']->replicate();
$copy->number = 'UNRECOGNISED-INSIGHTS';
$copy->save();
receiptFixture(); // Another company is never included.
$this->actingAs($this->f['validator']);
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 disposable report test fixture.');
}
DB::commit();
$this->committedInsightsFixture = true;
}
$tables = ['pa_obligations', 'pa_sources', 'pa_proposals', 'pa_events', 'pa_commands', 'invoices', 'external_payments', 'audit_logs'];
$before = [];
foreach ($tables as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('payableInsights.coverage', ['invoices' => 2, 'recognised' => 1, 'unrecognised' => 1, 'indeterminate' => 0])
->where('payableInsights.currencies.0.currency', 'MZN')->where('payableInsights.currencies.0.principal_minor', '6000')
->where('payableInsights.currencies.0.balance_minor', '6000')->where('payableInsights.currencies.0.confirmed_payments_minor', '0')
->where('payableInsights.currencies.0.allocated_payments_minor', '0')->missing('payableInsights.bank_snapshot'));
$this->get('/relatorios?search=NO-MATCH-INSIGHTS')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('payableInsights.coverage.invoices', 0)->where('payableInsights.currencies', []));
$csv = $this->get('/relatorios/obrigacoes.csv')->assertOk()->assertDownload();
expect($csv->streamedContent())->toContain('MZN;1;6000;0;0;6000')->toContain('2;1;1;0')->not->toContain('bank_snapshot');
$this->actingAs($this->f['issuer'])->get('/relatorios/obrigacoes.csv')->assertForbidden();
foreach ($tables as $table) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($before[$table]);
}
});
test('a divergent native position is counted as indeterminate and never replaced by zero', function () {
DB::table('invoices')->where('id', $this->f['invoice']->id)->update(['total_minor' => 6001]);
$result = app(ProcurementPayableInsights::class)->build($this->f['validator'], Requisition::query()->visibleTo($this->f['validator']));
expect($result['coverage']['indeterminate'])->toBe(1)->and($result['coverage']['recognised'])->toBe(0)->and($result['currencies'])->toBe([]);
});
test('native imported history is counted once and pending payments do not reduce the reported balance', function () {
$f = paymentFixture();
config(['common-payables.history_enabled' => true]);
foreach ([$f['author'], $f['validator']] as $user) {
foreach (['view', 'prepare', 'validate'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $user->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $user->id,
'person' => 'history-insights-'.$user->id, 'action' => $action]);
}
}
$this->actingAs($f['author']);
$payments = app(ExternalPaymentWorkflow::class);
$payment = $payments->register($f['author'], $f['invoice'], [...$f['payment_data'], 'amount' => '30.00']);
$this->actingAs($f['validator']);
$payments->review($f['validator'], $payment, 'confirmed', 'Conferência histórica sintética');
$this->actingAs($f['author']);
$payments->register($f['author'], $f['invoice'], [...$f['payment_data'], 'amount' => '10.00', 'external_reference' => 'INSIGHTS-PENDING']);
$adapter = app(SupplierPayables::class);
$proposal = $adapter->engine($f['author'])->command('prepare_history', $f['invoice']->id, 'Importação histórica sintética', (string) Str::uuid());
$this->actingAs($f['validator']);
$adapter->engine($f['validator'])->command('validate_history', $proposal['proposal_id'], 'Conferência independente do histórico', (string) Str::uuid());
$result = app(ProcurementPayableInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']));
expect($result['coverage']['recognised'])->toBe(1)->and($result['currencies'][0]['principal_minor'])->toBe('6000')
->and($result['currencies'][0]['confirmed_payments_minor'])->toBe('3000')->and($result['currencies'][0]['allocated_payments_minor'])->toBe('0')
->and($result['currencies'][0]['balance_minor'])->toBe('3000');
});
test('read composition rejects commands and revalidates withdrawn native financial access', function () {
$actor = $this->f['validator'];
$engine = app(SupplierPayables::class)->readEngine($actor);
$commands = DB::table('pa_commands')->count();
expect(fn () => $engine->command('prepare', $this->f['invoice']->id, 'Proibido na composição de leitura', (string) Str::uuid()))->toThrow(LogicException::class);
expect(DB::table('pa_commands')->count())->toBe($commands);
DB::table('pa_access')->where('user_id', $actor->id)->where('action', 'view')->delete();
expect(fn () => $engine->positionForSource($this->f['invoice']->id))->toThrow(HttpException::class);
expect(app(ProcurementPayableInsights::class)->build($actor, Requisition::query()->visibleTo($actor)))->toBeNull();
$this->actingAs($this->f['issuer']);
expect(app(ProcurementPayableInsights::class)->build($this->f['issuer'], Requisition::query()->visibleTo($this->f['issuer'])))->toBeNull();
});
+3 -3
View File
@@ -105,10 +105,10 @@ test('optional finance search uses native invoice scope and returns references w
$create(receiptFixture());
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 8)
->where('groups.7.key', 'invoices')->where('groups.7.records.total', 1)->where('groups.7.records.data.0.href', '/facturas?invoice_id='.$ownInvoice->id)
->where('invoiceSearchAvailable', true)->where('groups.7.key', 'invoices')->where('groups.7.records.total', 1)->where('groups.7.records.data.0.href', '/facturas?invoice_id='.$ownInvoice->id)
->missing('groups.7.records.data.0.snapshot')->missing('groups.7.records.data.0.total_minor'));
$this->get('/facturas?invoice_id='.$ownInvoice->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('focusInvoiceId', $ownInvoice->id));
$this->actingAs($f['issuer'])->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 7));
$this->actingAs($f['issuer'])->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->where('invoiceSearchAvailable', false)->has('groups', 7));
config(['procurement_search.finance_metadata_enabled' => false]);
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->has('groups', 7));
$this->actingAs($finance)->get('/compras/pesquisa?q=QA-SEARCH-INVOICE')->assertInertia(fn (Assert $page) => $page->where('invoiceSearchAvailable', false)->has('groups', 7));
});
+41
View File
@@ -29,6 +29,7 @@ use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\BudgetWorkflow;
use App\Services\CommonBudget;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
use App\Services\DocumentaryQualificationWorkflow;
@@ -43,6 +44,7 @@ use App\Services\ProposalOpeningWorkflow;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow;
use App\Services\QuotationExchange;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
@@ -53,9 +55,48 @@ use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Unpublished common source requires explicit QA selection.');
}
budgetDistributionFixtureSchema();
config(['budget-distributions.qa_enabled' => true]);
$this->withoutVite();
$second = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'QA-SPLIT', 'name' => 'Segundo centro sintético']);
$adapter = app(CommonBudget::class);
foreach ([$this->r->cost_center_id, $second->id] as $centre) {
$this->actingAs($this->finance);
$id = $adapter->for($this->finance)->create(['cost_center_id' => $centre, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true,
'amount_minor' => 20000, 'reason' => 'Dotação sintética do percurso distribuído.']);
$this->actingAs($this->admin);
$adapter->for($this->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = array_map(fn ($centre) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $this->item->id, 'centre_id' => $centre,
'subtotal_minor' => 5000, 'total_minor' => 5000], [$this->r->cost_center_id, $second->id]);
// The approved source is the existing fixture; preparation/submission have their separate native tests.
$this->r->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($this->r, $host->requestLines($this->r)), 'prepared_by' => $this->owner->id, 'reason' => 'Distribuição da fonte sintética aprovada.']])->save();
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$this->selection['reason'] = 'Confirmação explícita das parcelas da proposta seleccionada.';
$this->selection['budget_distribution_preparation'] = array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => '50.00', 'total' => '50.00'], $allocations);
$this->actingAs($this->buyer)->get($this->awardUrl)->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['budget_control']['phase'])->toBe('commit')
->and(DB::table('budget_distribution_entries')->where('kind', 'commit')->count())->toBe(2)
->and(DB::table('budget_entries')->where('requisition_id', $this->r->id)->count())->toBe(0);
$before = DB::table('budget_distribution_entries')->count();
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
expect(DB::table('budget_distribution_entries')->count())->toBe($before)->and(PurchaseOrder::query()->count())->toBe(1);
});
function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $quantity = '1.000', ?string $stockUnit = null): array
{
@@ -0,0 +1,17 @@
<?php
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('older synthetic order remains readable and printable without rewriting its incomplete snapshot', function () {
$f = receiptFixture();
$order = $f['order'];
$before = $order->fresh()->toArray();
$this->actingAs($f['issuer']);
$this->get('/ordens')->assertOk()->assertInertia(fn (Assert $page) => $page->where('orders.data.0.id', $order->id));
$this->get('/ordens/'.$order->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('snapshotComplete', false)->where('order.snapshot', $order->snapshot));
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Documento original incompleto.')->assertSee($order->number)->assertSee('100,00 MZN')->assertDontSee('Matriz de avaliação congelada');
expect($order->fresh()->toArray())->toBe($before);
$this->actingAs(receiptFixture()['issuer'])->get('/ordens/'.$order->id.'/imprimir')->assertNotFound();
});
@@ -0,0 +1,243 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Department;
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionApprovalLevels;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowNotices;
use App\Services\WorkflowTaskInbox;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('approval schema rollback preserves configured plans and frozen routing', function () {
$migration = require database_path('migrations/2026_11_22_000003_add_configured_requisition_levels.php');
$this->f['tenant']->forceFill(['requisition_approval_policy' => ['enabled' => false, 'levels' => []]])->save();
expect(fn () => $migration->down())->toThrow(LogicException::class);
expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBe(['enabled' => false, 'levels' => []]);
$this->f['tenant']->forceFill(['requisition_approval_policy' => null])->save();
$step = $this->f['r']->steps()->create(['tenant_id' => $this->f['tenant']->id, 'position' => 1, 'role' => 'configured_1', 'decision' => 'pending', 'routing' => ['name' => 'QA preserved route']]);
expect(fn () => $migration->down())->toThrow(LogicException::class);
expect($step->fresh()->routing)->toBe(['name' => 'QA preserved route']);
});
test('installed capability is explicitly enabled independently from the isolated QA flag', function () {
config(['requisition_approval.qa_enabled' => false, 'requisition_approval.enabled' => false]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
config(['requisition_approval.enabled' => true]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeTrue();
$this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect();
expect($this->f['tenant']->fresh()->requisition_approval_policy['quorum'])->toBe('one_eligible');
config(['requisition_approval.enabled' => false]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
});
test('approval schema upgrade adds empty fields without rewriting existing company or approval data', function () {
$migration = require database_path('migrations/2026_11_22_000003_add_configured_requisition_levels.php');
$columns = fn ($table) => array_values(array_diff(DB::connection()->getSchemaBuilder()->getColumnListing($table), ['requisition_approval_policy', 'routing']));
$tenantColumns = $columns('tenants');
$stepColumns = $columns('approval_steps');
$beforeTenants = DB::table('tenants')->orderBy('id')->get($tenantColumns)->toJson();
$beforeSteps = DB::table('approval_steps')->orderBy('id')->get($stepColumns)->toJson();
$migration->down();
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
$migration->up();
expect(DB::table('tenants')->orderBy('id')->get($tenantColumns)->toJson())->toBe($beforeTenants)
->and(DB::table('approval_steps')->orderBy('id')->get($stepColumns)->toJson())->toBe($beforeSteps)
->and(DB::table('tenants')->whereNotNull('requisition_approval_policy')->exists())->toBeFalse()
->and(DB::table('approval_steps')->whereNotNull('routing')->exists())->toBeFalse()
->and(app(RequisitionApprovalLevels::class)->ready())->toBeTrue();
});
function approvalLevelProfile(int $tenant, string $name, array $permissions): int
{
return DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => $name, 'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
}
function approvalLevelMember(User $actor, int $profile): void
{
DB::table('organization_memberships')->insert(['tenant_id' => $actor->tenant_id, 'user_id' => $actor->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
}
beforeEach(function () {
$this->withoutVite();
config(['requisition_approval.qa_enabled' => true]);
$this->f = receiptFixture();
$tenant = $this->f['tenant']->id;
$this->admin = $this->f['issuer'];
$this->f['tenant']->update(['first_limit_minor' => 0, 'second_limit_minor' => 0, 'approval_includes_tax' => true, 'rules_provisional' => false]);
$this->head = User::factory()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id, 'purchasing_role' => PurchasingRole::Configured]);
$this->buyer = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]);
$this->financier = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]);
$secondAdmin = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]);
$adminProfile = approvalLevelProfile($tenant, 'Administração QA', ['admin', 'requester']);
approvalLevelMember($this->admin, $adminProfile);
approvalLevelMember($secondAdmin, $adminProfile);
approvalLevelMember($this->head, approvalLevelProfile($tenant, 'Chefia QA', ['department_head']));
approvalLevelMember($this->buyer, approvalLevelProfile($tenant, 'Compras QA', ['procurement']));
approvalLevelMember($this->financier, approvalLevelProfile($tenant, 'Finanças QA', ['finance']));
$this->pool = approvalLevelProfile($tenant, 'Aprovadores adicionais QA', ['requisition_approve']);
$this->approvers = [];
foreach (range(1, 6) as $index) {
$actor = User::factory()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id, 'purchasing_role' => PurchasingRole::Configured]);
approvalLevelMember($actor, $this->pool);
$this->approvers[] = $actor;
}
DB::table('organization_access')->insert(['tenant_id' => $tenant, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
Budget::query()->create(['tenant_id' => $tenant, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 1000000, 'includes_tax' => true, 'reason' => 'Dotação exclusivamente sintética.', 'created_by' => $this->admin->id, 'approved_by' => $this->financier->id]);
$this->plan = ['version' => 1, 'enabled' => true, 'reason' => 'Plano de níveis adicionais para ensaio isolado.', 'levels' => array_map(fn ($number) => ['name' => 'Nível adicional '.$number, 'profile_ids' => [(string) $this->pool], 'scope' => 'company', 'min_amount' => null, 'categories' => [], 'cost_center_ids' => []], range(1, 5))];
$this->body = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade sintética com oito níveis.',
'items' => [['description' => 'Material QA', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']]];
$this->actingAs($this->admin);
});
function submitConfiguredRequest($test): Requisition
{
$test->actingAs($test->admin)->postJson('/administracao/parametrizacao/approval_levels', $test->plan)->assertRedirect();
$test->postJson('/requisicoes', $test->body)->assertRedirect();
$record = Requisition::query()->latest('id')->firstOrFail();
$test->postJson('/requisicoes/'.$record->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect();
return $record->fresh();
}
function configuredDecision($test, User $actor, Requisition $record, string $decision = 'approved'): void
{
$test->actingAs($actor)->postJson('/requisicoes/'.$record->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $record->fresh()->process_version, 'decision' => $decision, 'comment' => 'Fundamento sintético da decisão.'])->assertRedirect();
}
test('native three controls and five configured levels progress sequentially with one eligible person per level', function () {
$r = submitConfiguredRequest($this);
expect($r->steps()->count())->toBe(8)->and($r->approval_snapshot['routing_quorum'])->toBe('one_eligible');
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
$first = $this->approvers[0];
$this->actingAs($first)->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canDecide', true)->where('approvalRouting.label', 'Nível adicional 1'));
expect(collect(app(WorkflowNotices::class)->visible($first))->contains('role_label', 'Nível adicional 1'))->toBeTrue();
$this->get('/facturas')->assertForbidden();
expect(collect(app(WorkflowTaskInbox::class)->build($first, 'procurement'))->contains('reference', $r->number))->toBeTrue();
expect($r->fresh()->canDecide($this->approvers[1]))->toBeTrue();
foreach (array_slice($this->approvers, 0, 5) as $actor) {
configuredDecision($this, $actor, $r);
}
expect($r->fresh()->status)->toBe('approved')->and($r->steps()->where('decision', 'approved')->count())->toBe(8)
->and($r->steps()->where('position', 4)->sole()->approver_id)->toBe($first->id);
expect($r->fresh()->canDecide($this->approvers[5]))->toBeFalse();
});
test('conditions use exact amount category and cost centre and current rules do not rewrite a submitted route', function () {
$this->plan['levels'][0]['min_amount'] = '116.01';
$this->plan['levels'][1]['categories'] = ['Outra categoria'];
$this->plan['levels'][2]['categories'] = ['MATERIAL'];
$this->plan['levels'][2]['cost_center_ids'] = [(string) $this->f['r']->cost_center_id];
$this->plan['levels'][4]['min_amount'] = '116.00';
$r = submitConfiguredRequest($this);
expect($r->steps()->count())->toBe(6)->and($r->steps()->where('role', 'configured_3')->sole()->routing['profile_ids'])->toBe([$this->pool]);
$snapshot = $r->approval_snapshot;
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2, 'enabled' => false])->assertRedirect();
expect($r->fresh()->approval_snapshot)->toBe($snapshot);
foreach ([$this->head, $this->buyer, $this->financier, ...array_slice($this->approvers, 0, 3)] as $actor) {
configuredDecision($this, $actor, $r);
}
expect($r->fresh()->status)->toBe('approved');
});
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) {
configuredDecision($this, $actor, $r);
}
configuredDecision($this, $this->approvers[0], $r);
$this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
DB::table('organization_memberships')->where('user_id', $this->approvers[1]->id)->update(['expires_at' => now()->subMinute()]);
$this->actingAs($this->approvers[1])->get('/requisicoes/'.$r->id)->assertForbidden();
$this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
expect($r->fresh()->status)->toBe('pending');
approvalLevelMember($this->approvers[2], approvalLevelProfile($r->tenant_id, 'Solicitação sem poderes de aprovação', ['requester']));
DB::table('organization_memberships')->where('user_id', $this->approvers[2]->id)->where('profile_id', $this->pool)->update(['maintenance' => true]);
$this->actingAs($this->approvers[2])->get('/requisicoes/'.$r->id)->assertNotFound();
});
test('QA capability is opt in and a configured plan never silently falls back when capability is unavailable', function () {
$r = submitConfiguredRequest($this);
config(['requisition_approval.qa_enabled' => false]);
expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse();
$this->body['operation_key'] = (string) Str::uuid();
$this->postJson('/requisicoes', $this->body)->assertRedirect();
$new = Requisition::query()->latest('id')->firstOrFail();
$before = DB::table('budget_entries')->count();
$this->postJson('/requisicoes/'.$new->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertStatus(503);
expect(DB::table('budget_entries')->count())->toBe($before)->and($new->fresh()->status)->toBe('draft')->and($r->steps()->count())->toBe(8);
});
test('parallel candidates are bound to the version they reviewed and cannot advance another level with an old decision', function () {
$r = submitConfiguredRequest($this);
$this->actingAs($this->head)->postJson('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertUnprocessable();
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
$version = $r->fresh()->process_version;
$this->actingAs($this->approvers[0])->postJson('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertUnprocessable();
configuredDecision($this, $this->approvers[0], $r);
$this->actingAs($this->approvers[1])->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $version, 'decision' => 'approved'])->assertStatus(409);
expect($r->steps()->where('role', 'like', 'configured_%')->where('decision', 'approved')->count())->toBe(1);
});
test('invalid foreign pools and too many levels do not change the plan or its organisation version', function () {
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'levels' => array_fill(0, 6, $this->plan['levels'][0])])->assertUnprocessable();
$this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'levels' => ['invalid_key' => $this->plan['levels'][0]]])->assertUnprocessable();
$bad = $this->plan;
$bad['levels'][0]['min_amount'] = '-1';
$this->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable();
$bad = $this->plan;
$bad['levels'][0]['profile_ids'] = [approvalLevelProfile($this->admin->tenant_id, 'Consulta sem aprovação', ['requester'])];
$this->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable();
$other = receiptFixture();
$bad['levels'][0]['profile_ids'] = [approvalLevelProfile($other['tenant']->id, 'Perfil de outra empresa', ['requisition_approve'])];
$this->actingAs($this->admin)->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable();
expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBeNull()
->and(DB::table('organization_access')->where('tenant_id', $this->admin->tenant_id)->value('version'))->toBe(1);
});
test('department levels revalidate the department and the request owner never approves an assigned level', function () {
foreach ($this->plan['levels'] as &$level) {
$level['scope'] = 'department';
}
unset($level);
$r = submitConfiguredRequest($this);
foreach ([$this->head, $this->buyer, $this->financier] as $actor) {
configuredDecision($this, $actor, $r);
}
approvalLevelMember($this->admin, $this->pool);
$this->actingAs($this->admin)->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
$other = Department::query()->create(['tenant_id' => $r->tenant_id, 'name' => 'Outro departamento QA']);
DB::table('users')->where('id', $this->approvers[0]->id)->update(['department_id' => $other->id]);
$this->actingAs($this->approvers[0])->get('/requisicoes/'.$r->id)->assertNotFound();
$this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden();
expect($r->fresh()->status)->toBe('pending');
});
test('a plan update and its version roll back when audit cannot be recorded', function () {
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->once()->andThrow(new RuntimeException('Injected audit failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->postJson('/administracao/parametrizacao/approval_levels', $this->plan))->toThrow(RuntimeException::class);
expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBeNull()
->and(DB::table('organization_access')->where('tenant_id', $this->admin->tenant_id)->value('version'))->toBe(1);
});
test('an invalid stored plan cannot leave a reservation or partial approval queue behind', function () {
$plan = app(RequisitionApprovalLevels::class)->prepare($this->admin, $this->plan);
$plan['levels'][] = $plan['levels'][0];
$this->f['tenant']->update(['requisition_approval_policy' => $plan]);
$this->postJson('/requisicoes', $this->body)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$before = DB::table('budget_entries')->count();
$this->postJson('/requisicoes/'.$r->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertUnprocessable();
expect($r->fresh()->status)->toBe('draft')->and($r->steps()->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe($before);
});
+12
View File
@@ -12,6 +12,7 @@ use App\Services\WarehouseFulfilment;
use App\Services\WarehouseRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Integration\WarehouseFeed;
use Tempo\Integration\WarehouseInbox;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -50,6 +51,17 @@ function exchangeDeliver($test, string $quantity = '1.500'): WarehouseRequestEve
return exchangeCommand($test, $test->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => $quantity]]]);
}
test('production consumption remains compatible with the unchanged v1 feed while preserving local production details', function () {
$this->r = app(WarehouseRequests::class)->draft($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
'destination' => 'Linha de produção QA', 'reason' => 'Consumo sintético de insumos de produção.', 'priority' => 'normal',
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '4.000', 'use' => 'production', 'equipment_id' => null, 'production_reference' => 'OP-QA-001']]]);
$event = exchangeDeliver($this);
$page = $this->getJson('/stock/integracao/entregas')->assertOk()->assertJsonPath('items.0.lines.0.use', 'internal')->json();
WarehouseFeed::validate($page, $this->f['tenant']->id);
expect($this->r->fresh()->snapshot['lines'][0]['use'])->toBe('production')
->and($event->data['lines'][0]['production']['reference'])->toBe('OP-QA-001');
});
test('warehouse exchange publishes only physical facts with original identifiers and stable replay content', function () {
$url = '/stock/integracao/entregas';
$this->getJson($url)->assertOk()->assertJsonCount(0, 'items');
@@ -0,0 +1,8 @@
<?php
/** One versioned optional host schema, used only by guarded disposable QA fixtures. */
function budgetDistributionFixtureSchema(): void
{
$migration = require __DIR__.'/../../database/qa-migrations/2026_11_22_000004_create_budget_distributions.php';
$migration->up();
}
@@ -0,0 +1,36 @@
<?php
use Illuminate\Http\Request;
// Private loopback QA composition; no authentication bypass or public-path change in the product.
$settingsFile = getenv('SGC_DISTRIBUTION_QA_SETTINGS_FILE');
if (! is_string($settingsFile) || ! is_file($settingsFile)) {
http_response_code(503);
exit;
}
$settings = json_decode(file_get_contents($settingsFile), true, 32, JSON_THROW_ON_ERROR);
if (($settings['APP_ENV'] ?? '') !== 'testing' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $settings['DB_DATABASE'] ?? '')
|| ($settings['DB_HOST'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != 8006) {
http_response_code(503);
exit;
}
foreach ($settings as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$public = realpath($settings['SGC_DISTRIBUTION_QA_PUBLIC']);
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = realpath($public.'/'.ltrim(rawurldecode($path), '/'));
if ($file && str_starts_with(str_replace('\\', '/', $file), str_replace('\\', '/', $public).'/') && is_file($file)) {
$mime = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (isset($mime[$extension])) {
header('Content-Type: '.$mime[$extension]);
readfile($file);
exit;
}
}
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->usePublicPath($public);
$app->handleRequest(Request::capture());
+50
View File
@@ -0,0 +1,50 @@
<?php
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetDistributionPlan;
use Tempo\Finance\Budget\BudgetFailure;
// Approved common-source extension, exercised without modifying installed artifacts or a database.
if (! class_exists(BudgetControl::class)) {
require_once (getenv('COMMON_BUDGET_PATH') ?: __DIR__.'/../../packages/budget-control').'/bootstrap.php';
}
require_once 'C:/laragon/www/sgf-tempo/packages/budget-control/src/BudgetDistributionPlan.php';
function distributionPlanFixture(): array
{
return [
[12 => ['subtotal_minor' => 10000, 'total_minor' => 11600, 'required_kind' => 'operating'],
13 => ['subtotal_minor' => 2000, 'total_minor' => 2000, 'required_kind' => 'operating']],
[
['allocation_key' => 'line-12-centre-1', 'line_id' => 12, 'centre_id' => 1, 'subtotal_minor' => 3333, 'total_minor' => 3866],
['allocation_key' => 'line-12-centre-2', 'line_id' => 12, 'centre_id' => 2, 'subtotal_minor' => 6667, 'total_minor' => 7734],
['allocation_key' => 'line-13-centre-1', 'line_id' => 13, 'centre_id' => 1, 'subtotal_minor' => 2000, 'total_minor' => 2000],
],
];
}
test('explicit allocations reconcile every native line without invented rounding or percentages', function () {
[$lines, $input] = distributionPlanFixture();
$plan = BudgetDistributionPlan::normalise($input, $lines);
expect(array_sum(array_column($plan, 'subtotal_minor')))->toBe(12000)
->and(array_sum(array_column($plan, 'total_minor')))->toBe(13600)
->and($plan[0]['subtotal_minor'])->toBe(3333)->and($plan[0]['total_minor'])->toBe(3866)
->and($plan[1]['required_kind'])->toBe('operating');
$hash = BudgetDistributionPlan::fingerprint($plan, str_repeat('a', 64));
expect(BudgetDistributionPlan::fingerprint(BudgetDistributionPlan::normalise(array_reverse($input), $lines), str_repeat('a', 64)))->toBe($hash)
->and(BudgetDistributionPlan::fingerprint($plan, str_repeat('b', 64)))->not->toBe($hash);
});
test('missing excessive repeated foreign and ambiguous allocations are rejected before any financial effect', function () {
[$lines, $input] = distributionPlanFixture();
$cases = [[], [$input[0], $input[1]], [...$input, $input[0]]];
foreach ([['subtotal_minor' => -1], ['total_minor' => 3867], ['line_id' => 99], ['centre_id' => 0], ['allocation_key' => '../other'],
['subtotal_minor' => '3333'], ['subtotal_minor' => 3333.0], ['total_minor' => 1], ['override' => true]] as $change) {
$cases[] = [[...$input[0], ...$change], ...array_slice($input, 1)];
}
foreach ($cases as $case) {
expect(fn () => BudgetDistributionPlan::normalise($case, $lines))->toThrow(BudgetFailure::class);
}
expect(fn () => BudgetDistributionPlan::normalise($input, []))->toThrow(BudgetFailure::class)
->and(fn () => BudgetDistributionPlan::fingerprint(BudgetDistributionPlan::normalise($input, $lines), 'unknown'))->toThrow(BudgetFailure::class);
});
@@ -0,0 +1,119 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Award from '@/pages/purchases/award';
import { money } from '@/types/procurement';
afterEach(() => vi.restoreAllMocks());
const option = {
allocation_key: 'qa-a',
line_id: 12,
centre_id: 4,
subtotal: '50.00',
total: '50.00',
line_label: 'Artigo sintético',
centre_label: 'Centro sintético',
};
function render(
currency = 'MZN',
reference: object | null = null,
actorId = 7,
) {
return renderToStaticMarkup(
<App
initialComponent={Award}
initialPage={{
component: 'purchases/award',
url: '/requisicoes/2/adjudicacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actorId, tenant_id: 3 } },
requisition: { id: 2, number: 'QA-2', process_version: 4 },
award: null,
canSelect: true,
canDecide: false,
canIssue: false,
order: null,
recommendation: { adopted: false, quotation_id: null },
budgetDistributionOptions: [option],
comparison: {
ready: true,
top_ids: [1],
policy: {
revision: 0,
configured: false,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: {
price: 40,
quality: 20,
delivery: 15,
history: 15,
payment: 10,
},
},
rows: [
{
id: 1,
reference: 'QA-QUOTE',
supplier: { name: 'Fornecedor sintético' },
total_minor: 10000,
subtotal_minor: 10000,
tax_minor: 0,
currency,
reference_amounts: reference,
evaluation_count: 2,
eligible: true,
ineligibility_reasons: [],
score: 8,
},
],
},
},
}}
/>,
);
}
function rememberSelection() {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'award-selection:3:7:2:4:data'
? {
quotation_id: '1',
justification: '',
delivery_date: '',
delivery_location: '',
reason: '',
budget_distribution_preparation: [option],
}
: undefined,
);
}
test('quote is chosen before explicit allocations and a different actor cannot inherit the selection', () => {
expect(render()).not.toContain('<legend>Distribuição explícita');
rememberSelection();
const html = render();
expect(html.indexOf('id="award-quote"')).toBeLessThan(
html.indexOf('<legend>Distribuição explícita'),
);
expect(html).toContain('Referência da proposta em MZN');
expect(render('MZN', null, 8)).not.toContain(
'<legend>Distribuição explícita',
);
});
test('foreign values never replace an unavailable MZN reference and a frozen reference is shown exactly', () => {
rememberSelection();
const missing = render('USD');
expect(missing).toContain('Referência em MZN indisponível');
expect(missing).toMatch(/disabled=""[^>]*>Registar adjudicação/);
const converted = render('USD', {
subtotal_minor: 600000,
tax_minor: 0,
total_minor: 600000,
});
expect(converted).toContain(money(600000, 'MZN'));
expect(converted).not.toContain(`sem IVA ${money(10000, 'MZN')}`);
expect(converted).not.toContain('Referência em MZN indisponível');
});
@@ -0,0 +1,65 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import BudgetDistributionFields from '@/components/budget-distribution-fields';
test('explicit MZN input preserves decimal strings and identifies each article and centre accessibly', () => {
const row = {
allocation_key: 'qa-a',
line_id: 12,
centre_id: 4,
subtotal: '999999999999.99',
total: '999999999999.99',
};
const html = renderToStaticMarkup(
<BudgetDistributionFields
options={[
{
...row,
line_label: 'Artigo sintético',
centre_label: 'Produção sintética',
},
]}
rows={[row]}
onChange={() => {}}
reason=""
onReason={() => {}}
/>,
);
expect(html).toContain('Artigo sintético');
expect(html).toContain('Produção sintética');
expect(html.match(/value="999999999999.99"/g)).toHaveLength(2);
expect(html).toContain('Sem IVA (MZN)');
expect(html).toContain('Total (MZN)');
expect(html).toContain('minLength="10"');
expect(html).toContain(
'Nenhuma diferença será distribuída automaticamente',
);
});
test('unknown partial allocations stay blank until explicitly entered', () => {
const row = {
allocation_key: 'qa-b',
line_id: 13,
centre_id: 5,
subtotal: '',
total: '',
};
const html = renderToStaticMarkup(
<BudgetDistributionFields
options={[
{
...row,
line_label: 'Outro artigo',
centre_label: 'Outro centro',
},
]}
rows={[row]}
onChange={() => {}}
reason=""
onReason={() => {}}
/>,
);
expect(html.match(/value=""/g)).toHaveLength(2);
expect(html).not.toContain('value="0"');
expect(html).toContain('inputMode="decimal"');
});
@@ -0,0 +1,101 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Invoices from '@/pages/invoices/index';
afterEach(() => vi.restoreAllMocks());
function render(actorId = 7) {
return renderToStaticMarkup(
<App
initialComponent={Invoices}
initialPage={{
component: 'invoices/index',
url: '/facturas?purchase_order_id=2',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actorId, tenant_id: 3 } },
focusOrderId: 2,
canManage: true,
invoices: {
data: [],
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
total: 0,
},
orders: [
{
id: 2,
number: 'QA-OC',
currency: 'USD',
supplier: 'Fornecedor sintético',
items: [
{
id: 5,
requisition_item_id: 12,
description: 'Material sintético',
unit: 'cx',
unit_price_minor: 10000,
tax_rate: '0',
},
],
budgetDistributionOptions: [
{
allocation_key: 'qa-a',
line_id: 12,
centre_id: 4,
subtotal: '50.00',
total: '50.00',
line_label: 'Material sintético',
centre_label: 'Centro sintético',
},
],
},
],
},
}}
/>,
);
}
test('returning from explicit commitment amendment restores invoice fields and MZN parcels within the same actor context', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'invoice-preparation:3:7:2:data'
? {
number: 'QA-UNSAVED',
issued_on: '2026-11-22',
subtotal: '60.00',
tax: '0.00',
total: '60.00',
reason: 'Imputação sintética ainda em preparação.',
items: [
{
purchase_order_item_id: 5,
quantity: '0.600',
unit: 'cx',
unit_price: '100.00',
tax_rate: '0',
},
],
budget_distribution_preparation: [
{
allocation_key: 'qa-a',
line_id: 12,
centre_id: 4,
subtotal: '30.00',
total: '30.00',
},
],
}
: undefined,
);
const html = render();
expect(html).toContain('value="QA-UNSAVED"');
expect(html).toContain('value="0.600"');
expect(html).toContain('value="30.00"');
expect(html).toContain('/ordens/2/reafectacao');
expect(render(8)).not.toContain('value="QA-UNSAVED"');
});
@@ -0,0 +1,50 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
ProcurementPayableInsights,
exactMinorAmount,
} from '@/components/procurement-payable-insights';
test('financial display preserves cent values beyond floating point precision', () => {
expect(exactMinorAmount('9007199254740993', 'MZN')).toBe(
'90.071.992.547.409,93 MZN',
);
expect(exactMinorAmount('1', 'USD')).toBe('0,01 USD');
expect(exactMinorAmount('-100', 'MZN')).toBe('-1,00 MZN');
expect(exactMinorAmount('unknown', 'MZN')).toBe('Indeterminado');
});
test('report explains its native coverage current balance and separate currencies without treating unknowns as zero', () => {
const html = renderToStaticMarkup(
<ProcurementPayableInsights
exportHref="/relatorios/obrigacoes.csv?status=approved&search=QA"
data={{
method: 'native_payable_positions_v1',
coverage: {
invoices: 4,
recognised: 2,
unrecognised: 1,
indeterminate: 1,
},
currencies: ['MZN', 'USD'].map((currency) => ({
currency,
count: 1,
principal_minor: '10000',
balance_minor: '6000',
confirmed_payments_minor: '1000',
allocated_payments_minor: '3000',
})),
}}
/>,
);
expect(html).toContain('100,00 MZN');
expect(html).toContain('60,00 USD');
expect(html).toContain('não é tratada como saldo zero');
expect(html).toContain('sem conversão adicional');
expect(html).toContain('criação do pedido');
expect(html).toContain('/obrigacoes-fornecedores');
expect(html).toContain(
'/relatorios/obrigacoes.csv?status=approved&amp;search=QA',
);
expect(html).toContain('Exportar posição actual (CSV)');
});
+48 -1
View File
@@ -46,7 +46,54 @@ test('process search separates result groups escapes text and retains page links
expect(html).toContain('Rascunho');
expect(html).toContain('q=QA&amp;requests_page=2');
expect(html).toContain('/requisicoes/7');
expect(html).toContain('ainda não pesquisa Pessoas, facturas');
expect(html).toContain('A pesquisa não inclui Pessoas');
expect(html).not.toContain('acesso financeiro');
});
test('financial search explains references and states only when available', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=FT',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'FT',
invoiceSearchAvailable: true,
groups: [
{
key: 'invoices',
title: 'Facturas de fornecedor',
records: {
total: 1,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
data: [
{
id: 9,
title: 'FT <QA>',
detail: 'confirmed',
href: '/facturas?invoice_id=9',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('pelo número, dentro do seu acesso financeiro');
expect(html).toContain('mostram a referência e o estado');
expect(html).toContain('FT &lt;QA&gt;');
expect(html).toContain('Confirmada');
expect(html).toContain('/facturas?invoice_id=9');
});
test('empty search explains the minimum input rather than implying that the database is empty', () => {
@@ -0,0 +1,66 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Orders from '@/pages/purchases/index';
import Show from '@/pages/purchases/show';
const order = {
id: 1,
number: 'OC-QA',
requisition_id: 2,
issued_at: '2026-11-22T08:00:00Z',
currency: 'MZN',
total_minor: 10000,
snapshot: {
supplier: { name: 'Fornecedor <QA>' },
company: { name: 'Empresa QA' },
},
items: [
{
id: 1,
description: 'Artigo preservado',
quantity: '1.000',
unit: 'cx',
total_minor: 10000,
},
],
};
function render(
component: typeof Orders | typeof Show,
props: Record<string, unknown>,
) {
return renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'purchases/index',
url: '/ordens',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
}
test('an older incomplete order cannot blank the order list', () => {
const html = render(Orders, {
orders: { data: [order], prev_page_url: null, next_page_url: null },
awards: { data: [], prev_page_url: null, next_page_url: null },
});
expect(html).toContain('OC-QA');
expect(html).toContain('Fornecedor &lt;QA&gt;');
expect(html).toContain('Referência não preservada no original');
expect(html).toContain('/ordens/1');
});
test('incomplete detail identifies the missing original and preserves documented values and items', () => {
const html = render(Show, { order, history: [], snapshotComplete: false });
expect(html).toContain('Documento original incompleto');
expect(html).toContain('Artigo preservado');
expect(html).toContain('100,00');
expect(html).toContain('/ordens/1/imprimir');
expect(html).not.toContain('Aprovações do valor final');
});
@@ -0,0 +1,82 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { RequisitionApprovalSettings } from '@/components/requisition-approval-settings';
import { procurementNavigation } from '@/lib/procurement-navigation';
function render(ready: boolean) {
return renderToStaticMarkup(
<App
initialComponent={RequisitionApprovalSettings}
initialPage={{
component: 'company/parameters',
url: '/administracao/parametrizacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
ready,
version: 4,
profiles: [
{
id: 7,
name: 'Direcção QA',
permissions: ['requisition_approve'],
},
{
id: 8,
name: 'Consulta revogada QA',
permissions: ['requester'],
},
],
costCenters: [{ id: 1, code: 'QA', name: 'Centro QA' }],
plan: {
revision: 2,
enabled: true,
quorum: 'one_eligible',
levels: [
{
name: 'Conferência <QA>',
profile_ids: [7, 8],
scope: 'company',
min_minor: 11601,
categories: ['Material'],
cost_center_ids: [1],
},
],
},
},
}}
/>,
);
}
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');
expect(html).toContain('Conferência &lt;QA&gt;');
expect(html).toContain('Direcção QA');
expect(html).toContain('Consulta revogada QA');
expect(html).toContain('Sem competência de aprovação actualmente');
expect(html).toContain('basta um aprovador');
expect(html).toContain('apenas a novas submissões');
});
test('unavailable capability explains the existing circuit without offering a nonfunctional plan form', () => {
const html = render(false);
expect(html).toContain('O circuito actual permanece em vigor');
expect(html).not.toContain('<form');
});
test('a configured approver gets approval navigation without supplier or finance access links', () => {
const entries = procurementNavigation(
['requisition_approve'],
false,
).flatMap((group) => group.entries);
expect(
entries.some((entry) => entry.path === '/requisicoes?view=approvals'),
).toBe(true);
expect(entries.some((entry) => entry.path === '/facturas')).toBe(false);
expect(entries.some((entry) => entry.path === '/fornecedores')).toBe(false);
});
+124
View File
@@ -0,0 +1,124 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import RequisitionForm from '@/pages/requisitions/form';
import { hasPreparationChanges } from '@/lib/requisition-history';
afterEach(() => vi.restoreAllMocks());
test('restored technical identities do not mark a cleared preparation as changed', () => {
const original = {
operation_key: 'initial-operation',
justification: '',
items: [
{
key: 'initial-row',
description: '',
quantity: '1.000',
unit_price: '',
},
],
};
const recovered = {
items: [
{
unit_price: '',
quantity: '1.000',
description: '',
key: 'recovered-row',
},
],
justification: '',
operation_key: 'recovered-operation',
};
expect(hasPreparationChanges(original, recovered)).toBe(false);
expect(
hasPreparationChanges(original, {
...recovered,
justification: 'Still unsaved',
}),
).toBe(true);
expect(
hasPreparationChanges(original, {
...recovered,
items: [{ ...recovered.items[0], quantity: '2.000' }],
}),
).toBe(true);
expect(
hasPreparationChanges(original, {
...recovered,
items: [...recovered.items, recovered.items[0]],
}),
).toBe(true);
});
const restored = {
operation_key: 'kept-operation',
process_version: null,
cost_center_id: '',
priority: 'normal',
needed_by: '',
justification: 'Preparação ao regressar',
items: [
{
key: 'kept-line',
source_line_id: '',
catalogue_entry_id: '',
catalogue_version: '',
catalogue_code: '',
description: 'Artigo ainda por gravar',
category: 'Material',
purchase_type: 'consumable',
quantity: '2.000',
unit: 'UN',
unit_price: '',
tax_rate: '16.00',
equipment_id: '',
spare_part_id: '',
production_area: '',
downtime_started_at: '',
},
],
};
function render(userId = 7, tenantId = 3) {
return renderToStaticMarkup(
<App
initialComponent={RequisitionForm}
initialPage={{
component: 'requisitions/form',
url: '/requisicoes/criar',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: userId, tenant_id: tenantId } },
internalRequisitionReady: true,
incompleteDraftsAvailable: true,
costCenters: [],
requisition: null,
},
}}
/>,
);
}
test('native remembered history restores unfinished fields and line values without saving a process', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'requisition:3:7:new:0:data' ? restored : undefined,
);
const html = render();
expect(html).toContain('Preparação ao regressar');
expect(html).toContain('Artigo ainda por gravar');
expect(html).toContain('value="2.000"');
expect(html).not.toContain('value="0.00"');
});
test('remembered preparation is separated by user and company', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'requisition:3:7:new:0:data' ? restored : undefined,
);
expect(render(8, 3)).not.toContain('Artigo ainda por gravar');
expect(render(7, 4)).not.toContain('Artigo ainda por gravar');
});