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

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
@@ -0,0 +1,64 @@
<?php
use App\Http\Controllers\AgreementFollowupController;
use App\Services\AgreementFollowup;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
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)) {
throw new LogicException('Worker de relatório fora de QA.');
}
require __DIR__.'/../Support/ReceiptFixture.php';
require __DIR__.'/../Support/SupplyFixture.php';
$f = receiptFixture();
supplyGrant($f['issuer'], ['supply_prepare']);
supplyGrant($f['receiver'], ['supply_read', 'supply_review']);
auth()->guard()->setUser($f['issuer']);
$planning = app(SupplyPlanning::class);
$draft = $planning->save($f['issuer'], 'agreement', supplyInput(['stock_item_id' => $f['stock']->id, 'warehouse_id' => $f['warehouse']->id,
'supplier_id' => $f['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addDay()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => '=PG-FOLLOWUP-PROOF']));
auth()->guard()->setUser($f['receiver']);
$planning->save($f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
config(['agreement_order_limits.qa_enabled' => true]);
auth()->guard()->setUser($f['issuer']);
$header = $planning->save($f['issuer'], 'contract', supplyInput(['supplier_id' => $f['order']->supplier_id, 'reference' => '=PG-CONTRACT-PROOF',
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addDay()->toDateString(), 'order_limit_amount' => '0']));
auth()->guard()->setUser($f['receiver']);
$planning->save($f['receiver'], 'contract', supplyInput([], 'approve', $header));
$before = DB::table('audit_logs')->count();
$checked = false;
DB::listen(function (QueryExecuted $event) use (&$checked): void {
if (! $checked && str_contains($event->sql, 'supply_records')) {
$checked = true;
$state = $event->connection->selectOne("select current_setting('transaction_isolation') as isolation,current_setting('transaction_read_only') as readonly");
if ($state->isolation !== 'repeatable read' || $state->readonly !== 'on') {
throw new RuntimeException('CSV sem leitura consistente/somente leitura.');
}
}
});
$request = Request::create('/compras/acordos/vigencia.csv', 'GET');
$request->setUserResolver(fn () => $f['receiver']);
$response = app(AgreementFollowupController::class)->csv($request, app(AgreementFollowup::class));
if (! $checked || ! str_contains($response->getContent(), "'=PG-FOLLOWUP-PROOF") || ! str_contains($response->getContent(), 'Vigente')
|| $before !== DB::table('audit_logs')->count() || DB::transactionLevel() !== 0) {
throw new RuntimeException('CSV ou ausência de efeitos não demonstrados.');
}
echo json_encode(['agreement_csv_read_only_snapshot' => true, 'formula_cell_protected' => true, 'no_audit_writes' => true, 'transaction_closed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
$checked = false;
$request = Request::create('/compras/acordos/vigencia.csv?kind=contract', 'GET');
$request->setUserResolver(fn () => $f['receiver']);
$response = app(AgreementFollowupController::class)->csv($request, app(AgreementFollowup::class));
if (! $checked || ! str_contains($response->getContent(), "'=PG-CONTRACT-PROOF") || ! str_contains($response->getContent(), 'Limite global por ordem')
|| $before !== DB::table('audit_logs')->count() || DB::transactionLevel() !== 0) {
throw new RuntimeException('CSV global sem prova de leitura consistente ou sem efeitos.');
}
echo json_encode(['contract_csv_read_only_snapshot' => true, 'formula_cell_protected' => true, 'no_audit_writes' => true, 'transaction_closed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,112 @@
<?php
use App\Models\Supplier;
use App\Models\SupplierBankDetail;
use App\Services\SupplierBankWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$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) || DB::connection()->getConfig('host') !== '127.0.0.1') {
throw new LogicException('Ensaio de actualização permitido apenas em PostgreSQL sintético isolado.');
}
$targets = ['2026_11_21_000001_create_quotation_exchange_rates.php', '2026_11_21_000002_add_supplier_bank_account_keys.php'];
$baseline = array_values(array_filter(glob(database_path('migrations/*.php')), fn ($path) => ! in_array(basename($path), $targets, true)));
if (Artisan::call('migrate', ['--path' => $baseline, '--realpath' => true, '--force' => true]) !== 0) {
throw new RuntimeException('Preparação do schema anterior falhou.');
}
require __DIR__.'/../Support/ReceiptFixture.php';
$f = receiptFixture();
auth()->guard()->setUser($f['issuer']);
$detail = app(SupplierBankWorkflow::class)->propose($f['issuer'], Supplier::query()->findOrFail($f['order']->supplier_id), ['previous_id' => 0, 'bank_name' => 'Banco sintético de transição',
'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Beneficiário sintético', 'account_identifier' => 'QA-LEGACY-ONLY',
'evidence_reference' => 'Evidência exclusivamente sintética', 'reason' => 'Ensaio da preservação do histórico anterior.']);
$tables = array_column(DB::select("select tablename from pg_tables where schemaname='public' and tablename <> 'migrations' order by tablename"), 'tablename');
$columns = [];
foreach ($tables as $table) {
$columns[$table] = Schema::getColumnListing($table);
}
$fingerprint = static function ($connection) use ($columns): array {
$hashes = [];
foreach ($columns 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');
$hashes[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $hashes;
};
$before = $fingerprint(DB::connection());
$migrationCount = DB::table('migrations')->count();
$config = DB::connection()->getConfig();
unset($config['name']);
$directory = storage_path('framework/testing/commercial-upgrade-'.$database);
if (! mkdir($directory, 0700, true) && ! is_dir($directory)) {
throw new RuntimeException('Não foi possível preparar a salvaguarda sintética.');
}
$pg = static function (string $binary, array $args) use ($config): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $config['host'],
'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password']], timeout: 90);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Salvaguarda/restauro sintéticos não aprovados.');
}
};
$preDump = $directory.'/before.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
$paths = array_map(fn ($name) => database_path('migrations/'.$name), $targets);
if (Artisan::call('migrate', ['--path' => $paths, '--realpath' => true, '--force' => true]) !== 0
|| $fingerprint(DB::connection()) !== $before || DB::table('migrations')->count() !== $migrationCount + 2
|| DB::table('quotation_exchange_rates')->exists() || DB::table('quotations')->whereNotNull('exchange_basis')->exists()
|| DB::table('supplier_bank_details')->whereNotNull('account_key')->exists() || SupplierBankDetail::query()->findOrFail($detail->id)->account_key !== null) {
throw new RuntimeException('Actualização não preservou o schema/dados anteriores ou criou valores novos.');
}
if (Artisan::call('migrate', ['--path' => $paths, '--realpath' => true, '--force' => true]) !== 0
|| DB::table('migrations')->count() !== $migrationCount + 2 || $fingerprint(DB::connection()) !== $before) {
throw new RuntimeException('Reexecução da migração não é inócua.');
}
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
config(['database.connections.upgrade_admin' => [...$config, 'database' => 'postgres', 'url' => null]]);
$admin = DB::connection('upgrade_admin');
$dump = $directory.'/after.dump';
$created = false;
try {
$pg('pg_dump', ['--format=custom', '--file='.$dump, '--dbname='.$database]);
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump]);
config(['database.connections.upgrade_restore' => [...$config, 'database' => $restore, 'url' => null]]);
$restored = DB::connection('upgrade_restore');
if ($fingerprint($restored) !== $before || $restored->table('migrations')->count() !== $migrationCount + 2
|| $restored->table('quotation_exchange_rates')->exists() || $restored->table('supplier_bank_details')->whereNotNull('account_key')->exists()) {
throw new RuntimeException('Restauro não conserva a actualização e os dados anteriores.');
}
DB::purge('upgrade_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('upgrade_restore');
if ($fingerprint($restored) !== $before || $restored->table('migrations')->count() !== $migrationCount
|| $restored->getSchemaBuilder()->hasTable('quotation_exchange_rates') || $restored->getSchemaBuilder()->hasColumn('supplier_bank_details', 'account_key')
|| $restored->getSchemaBuilder()->hasColumn('quotations', 'exchange_basis')) {
throw new RuntimeException('Restauro anterior não recupera exactamente a base sintética anterior à actualização.');
}
echo json_encode(['synthetic_upgrade_preserved_tables' => count($before), 'migration_delta' => 2, 'new_values_empty' => true,
'replay_no_changes' => true, 'synthetic_backup_restore_verified' => true, 'pre_upgrade_restore_verified' => true,
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $dump)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
DB::purge('upgrade_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;
}
}
@@ -8,6 +8,7 @@ use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\StockMovement;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\ConflictGuard;
use App\Services\InventoryDispositions;
use App\Services\InventoryLots;
@@ -18,6 +19,7 @@ use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\StockWorkflow;
use App\Services\SupplyCoordination;
use App\Services\SupplyPlanning;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -203,6 +205,17 @@ test('confirmed delivery feeds replenishment in base units and supplies the same
expect($coordination->remainingDelivery($record))->toBe(6000)
->and($coordination->events($this->f['stock']->id, $this->f['warehouse']->id, today()->toDateString())['receipts'][0]['quantity'])->toBe(6000)
->and(StockMovement::query()->sole()->quantity_milli)->toBe(18000);
$csv = $this->get('/compras/fornecimento.csv?view=deliveries')->assertOk()->streamedContent();
$stream = fopen('php://temp', 'w+');
fwrite($stream, $csv);
rewind($stream);
$rows = [];
while (($row = fgetcsv($stream, null, ';', '"', '')) !== false) {
$rows[] = $row;
}
fclose($stream);
expect($rows[3][8])->toBe('2')->and($rows[3][9])->toBe('cx')->and($rows[3][11])->toBe('6')
->and($rows[3][16])->toBe('un')->and($rows[3][17])->toBe('12/1')->and($rows[3][18])->toBe($this->conversion['source']);
$bad = $data;
$bad['conversion']['numerator'] = '24';
expect(fn () => $coordination->save($this->f['receiver'], 'delivery', supplyInput($bad, 'save', $record)))->toThrow(ValidationException::class);
@@ -230,3 +243,51 @@ test('receipt reversal negates the physical movement and restores documentary pe
->and(app(ReceiptWorkflow::class)->progress($this->f['order'])['lines'][0]['delivery_pending_milli'])->toBe(2000)
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(0);
});
test('receipt reuses the per order agreement conversion and destination without reentering the frozen basis', function () {
config(['agreement_order_limits.qa_enabled' => true]);
supplyGrant($this->f['issuer'], ['procurement', 'supply_prepare', 'supply_read']);
supplyGrant($this->f['receiver'], ['warehouse', 'supply_review']);
$this->actingAs($this->f['issuer']);
$planning = app(SupplyPlanning::class);
$draft = $planning->save($this->f['issuer'], 'agreement', supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
'supplier_id' => $this->f['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'QA-ORDER-RECEIPT-BRIDGE', 'order_limit_amount' => '200.00', 'order_limit_quantity' => '24.000']));
$this->actingAs($this->f['receiver']);
$agreement = $planning->save($this->f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
// A new synthetic issued source; existing immutable fixture orders are never amended retroactively.
$request = $this->f['r']->replicate();
$request->forceFill(['number' => 'REQ-CONTRACT-BRIDGE'])->save();
$item = $this->f['r']->items()->sole()->replicate();
$item->forceFill(['requisition_id' => $request->id, 'catalogue_snapshot' => ['stock_item_id' => $this->f['stock']->id]])->save();
$oldAward = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id);
$quote = Quotation::query()->findOrFail($oldAward->quotation_id)->replicate();
$quote->forceFill(['requisition_id' => $request->id])->save();
$award = $oldAward->replicate();
$award->forceFill(['requisition_id' => $request->id, 'quotation_id' => $quote->id])->save();
$this->actingAs($this->f['issuer']);
$frozen = DB::transaction(function () use ($request, $quote, $item, $agreement) {
app(ConflictGuard::class)->lockCompany($this->f['issuer']);
return app(AgreementOrderLimits::class)->freeze($this->f['issuer'], $quote, $request,
[[...$this->f['line']->toArray(), 'requisition_item_id' => $item->id]],
[['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id, 'conversion' => $this->conversion]]);
});
$order = $this->f['order']->replicate();
$order->forceFill(['number' => 'OC-CONTRACT-BRIDGE', 'requisition_id' => $request->id, 'purchase_award_id' => $award->id,
'snapshot' => [...$this->f['order']->snapshot, ...$frozen]])->save();
$line = $this->f['line']->replicate();
$line->forceFill(['purchase_order_id' => $order->id, 'requisition_item_id' => $item->id])->save();
$this->actingAs($this->f['receiver']);
$body = $this->body;
$body['items'][0]['purchase_order_item_id'] = $line->id;
$body['items'][0]['stock_item_id'] = null;
unset($body['items'][0]['conversion']);
$bad = $body;
$bad['warehouse_id'] = null;
$this->postJson('/ordens/'.$order->id.'/recepcoes', $bad)->assertUnprocessable();
$id = $this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated()->json('id');
expect(GoodsReceipt::query()->findOrFail($id)->items()->sole()->accepted_milli)->toBe(2000)
->and(StockMovement::query()->sole()->quantity_milli)->toBe(24000)
->and($order->fresh()->snapshot)->toBe($order->snapshot)->and($order->total_minor)->toBe(20000);
});
+174
View File
@@ -0,0 +1,174 @@
<?php
use App\Models\SupplyRecord;
use App\Services\SupplyPlanning;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
// Data/workflow checks use a private build separately; never install a new manifest in the pilot for a test.
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['supply_prepare']);
supplyGrant($this->f['receiver'], ['supply_read', 'supply_review']);
$this->actingAs($this->f['receiver']);
});
function followupAgreement($test, string $from, string $until, string $reference = 'AGREEMENT-QA'): SupplyRecord
{
$test->actingAs($test->f['issuer']);
$service = app(SupplyPlanning::class);
$draft = $service->save($test->f['issuer'], 'agreement', supplyInput(['stock_item_id' => $test->f['stock']->id, 'warehouse_id' => $test->f['warehouse']->id,
'supplier_id' => $test->f['order']->supplier_id, 'habitual' => false, 'valid_from' => $from, 'valid_until' => $until, 'origin' => 'local',
'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => $reference]));
$test->actingAs($test->f['receiver']);
return $service->save($test->f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
}
function followupCounts(): array
{
return collect(['supply_records', 'audit_logs', 'stock_movements', 'purchase_orders', 'invoices', 'requisitions'])
->mapWithKeys(fn ($table) => [$table => DB::table($table)->count()])->all();
}
test('global contract vigency exports all filtered headers with frozen caps and links to approved articles without writes', function () {
config(['agreement_order_limits.qa_enabled' => true]);
$service = app(SupplyPlanning::class);
$contracts = [];
foreach ([null, '0', '100.00', ...array_fill(0, 24, null)] as $i => $cap) {
$this->actingAs($this->f['issuer']);
$draft = $service->save($this->f['issuer'], 'contract', supplyInput(['supplier_id' => $this->f['order']->supplier_id,
'reference' => '=QA-HEADER-'.$i, 'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'periodicity_days' => 30, 'order_limit_amount' => $cap]));
$this->actingAs($this->f['receiver']);
$contracts[] = $service->save($this->f['receiver'], 'contract', supplyInput([], 'approve', $draft));
}
$this->actingAs($this->f['issuer']);
$draft = $service->save($this->f['issuer'], 'agreement', supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
'supplier_id' => $this->f['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'reference' => 'QA-CHILD', 'contract_key' => $contracts[0]->record_key, 'lead_days' => 2]));
$this->actingAs($this->f['receiver']);
$child = $service->save($this->f['receiver'], 'agreement', supplyInput([], 'approve', $draft));
$before = followupCounts();
$this->get('/compras/acordos/vigencia?kind=contract&validity=current')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('kind', 'contract')->has('records.data', 25)->where('records.total', 27)->where('records.data.0.approved_articles', 1)->where('records.data.0.max_order_value_minor', null)
->where('records.data.1.max_order_value_minor', 0)->where('records.data.0.articles_href', '/compras/fornecimento?view=agreements&linked_contract_key='.$contracts[0]->record_key));
$response = $this->get('/compras/acordos/vigencia.csv?kind=contract&validity=current');
$response->assertOk()->assertHeader('Content-Disposition', 'attachment; filename="vigencia-contratos-'.today()->toDateString().'.csv"');
$rows = followupCsv($response->getContent());
expect($rows)->toHaveCount(30)->and($rows[2])->toHaveCount(18)->and($rows[3])->toHaveCount(18)->and($rows[3][2])->toBe("'=QA-HEADER-0")
->and($rows[3][14])->toBe('Não definido')->and($rows[4][14])->toBe('0')->and($rows[5][14])->toBe('10000')->and($rows[3][16])->toBe('1');
expect(followupCounts())->toBe($before);
$service->save($this->f['receiver'], 'agreement', supplyInput([], 'suspend', $child));
$this->get('/compras/acordos/vigencia?kind=contract')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.data.0.approved_articles', 0));
$service->save($this->f['receiver'], 'contract', supplyInput([], 'suspend', $contracts[0]));
$this->get('/compras/acordos/vigencia?kind=contract')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.total', 26));
config(['agreement_order_limits.qa_enabled' => false]);
$this->get('/compras/acordos/vigencia?kind=contract')->assertStatus(503);
$this->get('/compras/acordos/vigencia?kind=other')->assertSessionHasErrors('kind');
});
function followupCsv(string $body): array
{
$file = fopen('php://temp', 'w+');
fwrite($file, $body);
rewind($file);
$rows = [];
while (($row = fgetcsv($file, null, ';', '"', '')) !== false) {
$rows[] = $row;
}
fclose($file);
return $rows;
}
test('agreement vigency uses inclusive boundaries and keeps missing legacy dates indeterminate', function () {
$today = today()->toDateString();
$endToday = followupAgreement($this, today()->subDay()->toDateString(), $today, 'END-TODAY');
$startToday = followupAgreement($this, $today, today()->addDay()->toDateString(), 'START-TODAY');
followupAgreement($this, today()->subDays(3)->toDateString(), today()->subDay()->toDateString(), 'EXPIRED');
followupAgreement($this, today()->addDay()->toDateString(), today()->addDays(2)->toDateString(), 'FUTURE');
// Synthetic legacy source without dates: unknown is not zero, expired or current.
SupplyRecord::query()->create(['tenant_id' => $this->f['tenant']->id, 'kind' => 'agreement', 'record_key' => (string) Str::uuid(), 'version' => 1, 'state' => 'approved',
'stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id, 'supplier_id' => $this->f['order']->supplier_id,
'created_by' => $this->f['issuer']->id, 'data' => ['reference' => 'LEGACY-NO-DATE'], 'snapshot' => [], 'reason' => 'Fonte legada sintética de teste.',
'operation_key' => (string) Str::uuid(), 'input_hash' => str_repeat('0', 64), 'created_at' => now()]);
$counts = followupCounts();
$this->get('/compras/acordos/vigencia?validity=current')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->component('supply/agreement-followup')->where('asOf', $today)->where('records.total', 2)
->where('records.data.0.id', $endToday->id)->where('records.data.1.id', $startToday->id));
foreach (['expired' => 'EXPIRED', 'future' => 'FUTURE', 'unknown' => 'LEGACY-NO-DATE'] as $filter => $reference) {
$this->get('/compras/acordos/vigencia?validity='.$filter)->assertInertia(fn (Assert $page) => $page->where('records.total', 1)->where('records.data.0.reference', $reference));
}
expect(followupCounts())->toBe($counts);
});
test('expiry search and explicit cutoff use the same scope in the page and complete csv across pages', function () {
for ($i = 0; $i < 27; $i++) {
followupAgreement($this, today()->subDay()->toDateString(), today()->addDay()->toDateString(), 'EXPIRY-QA-'.$i);
}
followupAgreement($this, today()->toDateString(), today()->addMonth()->toDateString(), 'LATER-QA');
$cutoff = today()->addDay()->toDateString();
$counts = followupCounts();
$this->get('/compras/acordos/vigencia?search=expiry&expires_by='.$cutoff.'&page=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 27)->has('records.data', 2)
->where('filters.expires_by', $cutoff)->where('filters.search', 'expiry'));
$response = $this->get('/compras/acordos/vigencia.csv?search=expiry&expires_by='.$cutoff.'&page=2')->assertOk()->assertHeader('Content-Type', 'text/csv; charset=UTF-8');
$rows = followupCsv($response->getContent());
expect($rows)->toHaveCount(30)->and(array_unique(array_column(array_slice($rows, 3), 0)))->toHaveCount(27)
->and(array_column(array_slice($rows, 3), 2))->not->toContain('LATER-QA')->and(followupCounts())->toBe($counts);
});
test('a later suspension excludes an old approved version and does not revive it in the report', function () {
$record = followupAgreement($this, today()->toDateString(), today()->addWeek()->toDateString());
app(SupplyPlanning::class)->save($this->f['receiver'], 'agreement', supplyInput([], 'suspend', $record));
$this->get('/compras/acordos/vigencia')->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
expect(followupCsv($this->get('/compras/acordos/vigencia.csv')->assertOk()->getContent()))->toHaveCount(3);
expect($record->fresh()->state)->toBe('approved');
});
test('the report counts approved policy identities and opens only policies linked to the selected agreement', function () {
$record = followupAgreement($this, today()->toDateString(), today()->addWeek()->toDateString());
$other = followupAgreement($this, today()->toDateString(), today()->addWeek()->toDateString(), 'OTHER-AGREEMENT');
$planning = app(SupplyPlanning::class);
$this->actingAs($this->f['issuer']);
$draft = $planning->save($this->f['issuer'], 'policy', supplyInput([...supplyPolicy($this->f), 'agreement_key' => $record->record_key]));
$this->actingAs($this->f['receiver']);
$approved = $planning->save($this->f['receiver'], 'policy', supplyInput([], 'approve', $draft));
$this->get('/compras/acordos/vigencia')->assertInertia(fn (Assert $page) => $page->where('records.data.0.approved_policies', 1)->where('records.data.1.approved_policies', 0)
->where('records.data.0.policies_href', '/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key));
$this->get('/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key)->assertInertia(fn (Assert $page) => $page->has('records', 1)->where('records.0.id', $approved->id)->where('linkedAgreementKey', $record->record_key));
$this->get('/compras/fornecimento?view=calendar&linked_agreement_key='.$other->record_key)->assertInertia(fn (Assert $page) => $page->has('records', 0));
});
test('csv neutralizes formula text and preserves unknown dates without inventing values', function () {
$record = followupAgreement($this, today()->toDateString(), today()->addDay()->toDateString(), '=SYNTHETIC()');
$rows = followupCsv($this->get('/compras/acordos/vigencia.csv')->assertOk()->getContent());
expect($rows[3][2])->toBe("'=SYNTHETIC()")->and($rows[3][9])->toBe('Vigente')->and($rows[3][10])->toBe('0')
->and($rows[3][11])->toContain('record_id='.$record->id);
});
test('scope current permissions and maintenance are revalidated with no grants or cross company leakage', function () {
followupAgreement($this, today()->toDateString(), today()->addDay()->toDateString());
$foreign = receiptFixture();
supplyGrant($foreign['receiver'], ['supply_read']);
$this->actingAs($foreign['receiver'])->get('/compras/acordos/vigencia')->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
$this->actingAs($this->f['otherReceiver'])->get('/compras/acordos/vigencia')->assertForbidden();
$this->actingAs($this->f['receiver']);
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => true]);
$this->get('/compras/acordos/vigencia.csv')->assertForbidden();
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => false, 'expires_at' => now()->subMinute()]);
$this->get('/compras/acordos/vigencia')->assertForbidden();
});
test('malformed filters are refused rather than silently widening the report', function () {
foreach (['validity=wrong', 'expires_by=invalid', 'page=0', 'search='.str_repeat('x', 101)] as $filter) {
$this->getJson('/compras/acordos/vigencia?'.$filter)->assertUnprocessable();
$this->getJson('/compras/acordos/vigencia.csv?'.$filter)->assertUnprocessable();
}
$this->getJson('/compras/fornecimento?view=calendar&linked_agreement_key=invalid')->assertUnprocessable();
});
+17
View File
@@ -322,6 +322,23 @@ test('warehouse shortage carries the original destination and equipment and is n
$this->actingAs($this->f['issuer'])->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('automaticSource.origins.0.destination', 'Oficina central, bancada de montagem'));
});
test('production shortage retains the declared production reference in the native purchase origin', function () {
activateAutomaticRule($this);
supplyGrant($this->f['issuer'], ['warehouse_request_prepare']);
supplyGrant($this->f['receiver'], ['warehouse_request_review']);
$this->actingAs($this->f['issuer']);
$request = 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' => 'Insumos sintéticos para a produção.', 'priority' => 'normal',
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '125.000', 'use' => 'production', 'equipment_id' => null, 'production_reference' => 'OP-QA-001']]]);
app(WarehouseFulfilment::class)->command($this->f['issuer'], $request->id, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'submit', 'reason' => 'Submissão de teste da produção.', 'partial_allowed' => true]);
$this->actingAs($this->f['receiver']);
app(WarehouseFulfilment::class)->command($this->f['receiver'], $request->id, ['operation_key' => (string) Str::uuid(), 'version' => 1, 'action' => 'authorize', 'reason' => 'Autorização de teste da produção.', 'partial_allowed' => true]);
app(AutomaticPurchases::class)->evaluate($this->f['receiver'], $this->f['stock']->id, $this->f['warehouse']->id);
$need = app(SupplyPlanning::class)->latest('auto_need')->sole();
$r = Requisition::query()->findOrFail($need->data['purchases'][0]['id']);
expect(app(AutomaticPurchases::class)->origin($r)['origins'][0]['production'])->toBe(['reference' => 'OP-QA-001', 'verification' => 'user_supplied']);
});
test('revoked requester authority or expired work context cannot be borrowed for automatic purchases', function () {
activateAutomaticRule($this);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['expires_at' => now()->subMinute()]);
@@ -0,0 +1,116 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->partial = ['operation_key' => (string) Str::uuid(), 'priority' => 'normal', 'justification' => 'Ini', 'items' => [
['description' => 'Artigo sintético em preparação', 'purchase_type' => 'consumable', 'quantity' => null, 'unit_price' => null, 'tax_rate' => '16.00', 'unexpected' => 'Do not persist unrelated data'],
]];
});
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();
$r = Requisition::query()->latest('id')->firstOrFail();
expect($r->status)->toBe('draft')->and($r->total_minor)->toBeNull()->and($r->needed_by)->toBeNull()
->and($r->cost_center_id)->toBeNull()->and($r->draft_input['values']['items'][0]['unit_price'])->toBeNull()
->and($r->items()->count())->toBe(0)->and($r->steps()->count())->toBe(0);
expect(array_key_exists('unexpected', $r->draft_input['values']['items'][0]))->toBeFalse();
$this->get('/requisicoes/'.$r->id.'/editar')->assertInertia(fn (Assert $page) => $page->where('incompleteDraftsAvailable', true)->where('requisition.draft_input.values.justification', 'Ini'));
$this->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('requisition.total_minor', null));
$this->get('/requisicoes/'.$r->id.'/processo')->assertOk();
$this->get('/relatorios?search='.$r->number)->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.data.0.total_minor', null));
$this->postJson('/requisicoes/'.$r->id.'/submeter')->assertUnprocessable();
expect($r->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->count())->toBe($entries);
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
expect(Requisition::query()->where('requester_id', $this->f['issuer']->id)->where('status', 'draft')->count())->toBe(1);
});
test('completing the same draft restores exact calculations and clears preparation without duplicating the process', function () {
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$this->putJson('/requisicoes/'.$r->id, ['operation_key' => (string) Str::uuid(), 'process_version' => $r->process_version,
'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Preparação sintética agora completa.',
'items' => [['description' => 'Artigo sintético', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']],
])->assertRedirect();
expect($r->fresh()->draft_input)->toBeNull()->and($r->fresh()->total_minor)->toBe(11600)->and($r->items()->count())->toBe(1)->and($r->fresh()->status)->toBe('draft');
});
test('partial preparation still rejects invalid supplied values and foreign cost centres', function () {
foreach (['quantity' => '-1', 'unit_price' => '-1', 'tax_rate' => '101'] as $key => $value) {
$body = $this->partial;
$body['items'][0][$key] = $value;
$this->postJson('/requisicoes', $body)->assertUnprocessable();
}
$other = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->postJson('/requisicoes', [...$this->partial, 'cost_center_id' => $other['r']->cost_center_id])->assertUnprocessable();
});
test('rollback refuses to discard incomplete input and an empty draft can be saved', function () {
$this->postJson('/requisicoes', ['items' => []])->assertRedirect();
$migration = require database_path('migrations/2026_11_22_000002_allow_incomplete_requisition_drafts.php');
expect(fn () => $migration->down())->toThrow(LogicException::class);
expect(Requisition::query()->latest('id')->firstOrFail()->total_minor)->toBeNull();
});
test('migration preserves existing document values and legacy validation until explicitly installed', function () {
$migration = require database_path('migrations/2026_11_22_000002_allow_incomplete_requisition_drafts.php');
$sqlite = DB::getDriverName() === 'sqlite';
if ($sqlite) {
expect(fn () => $migration->down())->toThrow(LogicException::class);
DB::getSchemaBuilder()->table('requisitions', fn ($table) => $table->dropColumn('draft_input'));
} else {
$migration->down();
}
$columns = DB::getSchemaBuilder()->getColumnListing('requisitions');
$before = DB::table('requisitions')->select($columns)->orderBy('id')->get()->toArray();
try {
$this->postJson('/requisicoes', $this->partial)->assertUnprocessable();
if ($sqlite) {
DB::getSchemaBuilder()->table('requisitions', fn ($table) => $table->json('draft_input')->nullable());
} else {
$migration->up();
}
expect(DB::table('requisitions')->select($columns)->orderBy('id')->get()->toArray())->toEqual($before);
} finally {
if (! DB::getSchemaBuilder()->hasColumn('requisitions', 'draft_input')) {
if ($sqlite) {
DB::getSchemaBuilder()->table('requisitions', fn ($table) => $table->json('draft_input')->nullable());
} else {
$migration->up();
}
}
}
});
test('partial preparation remains author scoped and refuses stale concurrent edits', function () {
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
$body = [...$this->partial, 'operation_key' => (string) Str::uuid(), 'process_version' => $r->process_version, 'justification' => 'Nova preparação parcial'];
$this->putJson('/requisicoes/'.$r->id, $body)->assertRedirect();
$this->putJson('/requisicoes/'.$r->id, [...$body, 'operation_key' => (string) Str::uuid(), 'justification' => 'Edição concorrente'])->assertStatus(409);
$other = User::factory()->create(['tenant_id' => $r->tenant_id, 'department_id' => $r->department_id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($other)->putJson('/requisicoes/'.$r->id, [...$body, 'process_version' => $r->fresh()->process_version])->assertForbidden();
expect($r->fresh()->draft_input['values']['justification'])->toBe('Nova preparação parcial');
});
test('PostgreSQL refuses a direct transition of incomplete preparation into approval', function () {
if (DB::getDriverName() !== 'pgsql') {
$this->markTestSkipped('Database constraint is PostgreSQL-specific; SQLite validates application behavior.');
}
$this->postJson('/requisicoes', $this->partial)->assertRedirect();
$r = Requisition::query()->latest('id')->firstOrFail();
expect(fn () => DB::transaction(fn () => DB::table('requisitions')->where('id', $r->id)->update(['status' => 'pending'])))->toThrow(QueryException::class);
expect($r->fresh()->status)->toBe('draft');
});
@@ -2,13 +2,16 @@
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\Tenant;
use App\Models\User;
use App\Services\CompanyDetails;
use App\Services\OrganizationAccess;
use App\Services\RequisitionWorkflow;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -259,3 +262,73 @@ test('a configured account has no fallback development permissions while activat
DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->update(['active' => true]);
$this->get($this->base)->assertOk();
});
test('company details preserve identifiers and are scoped audited and versioned', function () {
$body = array_fill_keys(array_keys(CompanyDetails::FIELDS), null) + ['version' => 1, 'reason' => 'Cadastro sintético para ensaio isolado.'];
$body['legal_name'] = 'Empresa sintética QA';
$body['nuit'] = '001234567';
$account = array_fill_keys(array_keys(CompanyDetails::BANK_FIELDS), null);
$body['bank_accounts'] = [
[...$account, 'id' => (string) Str::uuid(), 'account_number' => '00001234', 'currency' => 'MZN'],
[...$account, 'id' => (string) Str::uuid(), 'account_number' => '00005678', 'currency' => 'USD'],
];
$location = array_fill_keys(array_keys(CompanyDetails::LOCATION_FIELDS), null);
$body['establishments'] = [
[...$location, 'id' => (string) Str::uuid(), 'kind' => 'headquarters', 'name' => 'Sede QA', 'address' => 'Endereço sintético A'],
[...$location, 'id' => (string) Str::uuid(), 'kind' => 'branch', 'name' => 'Sucursal QA', 'address' => 'Endereço sintético B'],
];
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
$purchase = $this->f['r']->fresh()->toArray();
$this->postJson($this->base.'/company_details', $body)->assertRedirect();
expect($this->f['tenant']->fresh()->company_details['bank_accounts'][0]['account_number'])->toBe('00001234')
->and($this->f['tenant']->fresh()->company_details['bank_accounts'][1]['currency'])->toBe('USD')
->and($this->f['tenant']->fresh()->company_details['establishments'][1]['address'])->toBe('Endereço sintético B')
->and($other->fresh()->company_details)->toBeNull()
->and($this->f['r']->fresh()->toArray())->toBe($purchase)
->and(AuditLog::query()->where('action', 'organization.company_details')->count())->toBe(1);
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('companyDetailsReady', true)->where('companyDetails.nuit', '001234567'));
$this->postJson($this->base.'/company_details', $body)->assertUnprocessable();
$this->postJson($this->base.'/company_details', [...$body, 'version' => 2, 'nuit' => '12', 'email' => 'invalid'])->assertUnprocessable();
$this->postJson($this->base.'/company_details', [...$body, 'version' => 2, 'tenant_id' => $other->id])->assertUnprocessable();
$invalid = $body;
$invalid['version'] = 2;
$invalid['establishments'][1]['kind'] = 'headquarters';
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
$invalid = $body;
$invalid['version'] = 2;
$invalid['bank_accounts'][1]['id'] = $invalid['bank_accounts'][0]['id'];
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
$this->postJson($this->base.'/company_details', [...$body, 'version' => 2])->assertRedirect();
expect($this->f['tenant']->fresh()->company_details['bank_accounts'])->toBe($body['bank_accounts']);
$invalid = $body;
$invalid['version'] = 3;
$invalid['bank_accounts'][1]['currency'] = 'US';
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
$invalid['bank_accounts'][1]['currency'] = 'USD';
$invalid['establishments'][1]['tenant_id'] = $other->id;
$this->postJson($this->base.'/company_details', $invalid)->assertUnprocessable();
$this->actingAs($this->f['receiver'])->postJson($this->base.'/company_details', [...$body, 'version' => 2])->assertForbidden();
});
test('company details remain unavailable before installation without changing the existing company', function () {
$migration = require database_path('migrations/2026_11_22_000001_add_company_details_to_tenants.php');
$migration->down();
try {
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('companyDetailsReady', false)->where('companyDetails', null));
$body = array_fill_keys(array_keys(CompanyDetails::FIELDS), null) + ['bank_accounts' => [], 'establishments' => [], 'version' => 1, 'reason' => 'Ensaio anterior à instalação dos campos.'];
$this->postJson($this->base.'/company_details', $body)->assertStatus(503);
expect(DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->value('version'))->toBe(1)
->and(Tenant::query()->findOrFail($this->f['tenant']->id)->name)->toBe($this->f['tenant']->name);
} finally {
$migration->up();
}
});
test('company details are not saved without their audit record', function () {
$body = array_fill_keys(array_keys(CompanyDetails::FIELDS), null) + ['bank_accounts' => [], 'establishments' => [], 'version' => 1, 'reason' => 'Ensaio de recuperação sem auditoria.'];
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->once()->andThrow(new RuntimeException('Injected audit failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->postJson($this->base.'/company_details', $body))->toThrow(RuntimeException::class);
expect($this->f['tenant']->fresh()->company_details)->toBeNull()
->and(DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->value('version'))->toBe(1);
});
+16
View File
@@ -228,6 +228,22 @@ test('procurement reading distinguishes submission age need dates and incomplete
expect(AuditLog::query()->count())->toBe($audits);
});
test('approval duration uses complete native decisions and filters without inventing missing dates', function () {
$this->travelTo(CarbonImmutable::parse('2026-11-22 12:00:00'));
$before = AuditLog::query()->count();
foreach ([['FAST', '2026-11-21 13:00:00'], ['SLOW', '2026-11-21 15:00:00'], ['FUTURE', '2026-11-23 12:00:00'], ['REVERSED', '2026-11-20 12:00:00']] as [$number, $date]) {
$r = reportCopy($this->f['r'], 'DURATION-'.$number, ['status' => 'approved', 'submitted_at' => '2026-11-21 12:00:00']);
$r->steps()->create(['tenant_id' => $r->tenant_id, 'position' => 1, 'role' => 'department_head', 'decision' => 'approved', 'decided_at' => $date]);
}
reportCopy($this->f['r'], 'DURATION-MISSING', ['status' => 'approved', 'submitted_at' => null]);
$this->get('/relatorios?search=DURATION')->assertInertia(fn (Assert $page) => $page
->where('insights.approval_times.measured', 2)->where('insights.approval_times.unknown', 3)
->where('insights.approval_times.total_seconds', 14400)->where('insights.approval_times.min_seconds', 3600)->where('insights.approval_times.max_seconds', 10800));
$this->get('/relatorios?search=DURATION-MISSING')->assertInertia(fn (Assert $page) => $page
->where('insights.approval_times.measured', 0)->where('insights.approval_times.unknown', 1)->where('insights.approval_times.min_seconds', null));
expect(AuditLog::query()->count())->toBe($before);
});
test('reports reject invalid filters on both the screen and export', function () {
foreach (['status=unknown', 'from=invalid', 'from=2026-02-02&to=2026-01-01', 'department_id=-1'] as $filter) {
$this->getJson('/relatorios?'.$filter)->assertUnprocessable();
@@ -32,6 +32,20 @@ function reviewCsvRows(string $content): array
return $rows;
}
test('review csv exports each frozen per order agreement once and distinguishes undefined caps from zero', function () {
$report = app(ProcurementReviewReport::class)->build($this->f['issuer'], $this->f['r']->id);
$binding = ['agreement_id' => 7, 'record_key' => 'synthetic', 'version' => 2, 'reference' => '=AGREEMENT-QA', 'basis' => 'per_order', 'currency' => 'MZN', 'unit' => 'un', 'includes_tax' => true,
'max_order_value_minor' => null, 'max_order_quantity_milli' => 0, 'checked_order_value_minor' => 12345, 'checked_order_quantity_milli' => '1000'];
$report['agreement_limits'] = [$binding, $binding];
$rows = reviewCsvRows(app(ProcurementReviewCsv::class)->render($report));
expect(array_values(array_filter($rows, fn ($row) => $row === ['Acordo por ordem', '7', 'Referência', "'=AGREEMENT-QA"])))->toHaveCount(1);
expect($rows)->toContain(['Acordo por ordem', '7', 'Limite por ordem (centavos)', 'Não definido'])
->toContain(['Acordo por ordem', '7', 'Limite por ordem (milésimos)', '0'])
->toContain(['Acordo por ordem', '7', 'Total conferido nesta ordem (centavos)', '12345']);
$report['agreement_limits'] = 'invalid';
expect(fn () => app(ProcurementReviewCsv::class)->render($report))->toThrow(UnexpectedValueException::class);
});
test('complete review csv keeps missing scores distinct from zero and makes no business writes', function () {
$before = AuditLog::query()->count();
$response = $this->get($this->url)->assertOk()
+114
View File
@@ -0,0 +1,114 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CriticalityLevel;
use App\Models\Department;
use App\Models\Equipment;
use App\Models\GoodsReceipt;
use App\Models\Invoice;
use App\Models\Supplier;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
// The new page is built privately; HTTP scope tests must not require publishing it to the pilot.
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
});
test('process search combines native modules without exposing financial or contact data or writing records', function () {
$this->f['r']->update(['number' => 'QA-NEED-001', 'justification' => 'Necessidade sintética de ensaio global.']);
$supplier = Supplier::query()->findOrFail($this->f['order']->supplier_id);
$supplier->update(['name' => 'QA Supplier', 'email' => 'private@example.invalid']);
$before = [];
foreach (['audit_logs', 'requisitions', 'purchase_orders', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->count();
}
$response = $this->get('/compras/pesquisa?q=qa')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$response->assertInertia(fn (Assert $page) => $page->component('search/procurement')->where('term', 'qa')->has('groups', 7)
->where('groups.0.records.total', 1)->where('groups.0.records.data.0.title', 'QA-NEED-001')
->where('groups.2.records.total', 1)->missing('groups.2.records.data.0.email')->missing('groups.2.records.data.0.nuit'));
foreach ($before as $table => $count) {
expect(DB::table($table)->count())->toBe($count);
}
$this->get('/compras/pesquisa?q=global')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 1));
$this->get('/compras/pesquisa?q='.urlencode($this->f['order']->number))->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
});
test('search scopes results to the current company department and native role', function () {
$own = $this->f;
$other = receiptFixture();
$other['r']->update(['number' => 'SECRET-OTHER-COMPANY']);
$this->actingAs($own['issuer']);
$department = Department::query()->create(['tenant_id' => $own['tenant']->id, 'name' => 'Outro departamento sintético']);
$copy = $own['r']->replicate();
$copy->forceFill(['number' => 'SECRET-OTHER-DEPARTMENT', 'department_id' => $department->id])->save();
$head = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($head)->get('/compras/pesquisa?q=SECRET')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0));
$requester = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($requester)->get('/compras/pesquisa?q=TEST')->assertInertia(fn (Assert $page) => $page->has('groups', 1)->where('groups.0.records.total', 0));
});
test('search paginates each module and treats wildcards as text without listing the database on empty terms', function () {
foreach (range(1, 17) as $index) {
$copy = $this->f['r']->replicate();
$copy->forceFill(['number' => 'PAGE-SEARCH-'.$index])->save();
}
$this->get('/compras/pesquisa?q=PAGE-SEARCH')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 17)->has('groups.0.records.data', 15));
$this->get('/compras/pesquisa?q=PAGE-SEARCH&requests_page=2')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.current_page', 2)->has('groups.0.records.data', 2));
foreach (['', 'x', ' '] as $term) {
$this->get('/compras/pesquisa?q='.urlencode($term))->assertInertia(fn (Assert $page) => $page->where('groups', []));
}
$this->get('/compras/pesquisa?q=%25_')->assertInertia(fn (Assert $page) => $page->where('groups.0.records.total', 0)->where('groups.2.records.total', 0));
$this->getJson('/compras/pesquisa?q='.str_repeat('x', 101))->assertUnprocessable();
$this->getJson('/compras/pesquisa?q=QA&requests_page=0')->assertUnprocessable();
});
test('search covers stock warehouses equipment and receipt references with native permissions', function () {
$f = $this->f;
$level = CriticalityLevel::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['issuer']->id, 'code' => 'SEARCH', 'name' => 'QA', 'criteria' => 'Synthetic test', 'is_critical' => false, 'created_at' => now()]);
$asset = Equipment::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['issuer']->id, 'department_id' => $f['department']->id, 'criticality_level_id' => $level->id, 'code' => 'FIND-EQ', 'description' => 'Synthetic search equipment', 'area' => 'QA', 'status' => 'active']);
$receipt = GoodsReceipt::query()->create(['tenant_id' => $f['tenant']->id, 'purchase_order_id' => $f['order']->id, 'received_by' => $f['receiver']->id, 'warehouse_id' => $f['warehouse']->id,
'idempotency_key' => (string) Str::uuid(), 'payload_hash' => str_repeat('a', 64), 'delivery_note' => 'FIND-GR', 'received_on' => today(), 'status' => 'confirmed', 'snapshot' => ['synthetic' => true], 'confirmed_at' => now()]);
$f['stock']->update(['name' => 'FIND-STOCK']);
$f['warehouse']->update(['name' => 'FIND-WAREHOUSE']);
$this->get('/compras/pesquisa?q=FIND')->assertInertia(fn (Assert $page) => $page
->where('groups.3.records.total', 1)->where('groups.3.records.data.0.href', '/equipamentos/'.$asset->id)
->where('groups.4.records.total', 1)->where('groups.5.records.total', 1)
->where('groups.6.records.total', 1)->where('groups.6.records.data.0.href', '/recepcoes/'.$receipt->id));
$head = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$otherDepartment = Department::query()->create(['tenant_id' => $f['tenant']->id, 'name' => 'Other QA department']);
$asset->update(['department_id' => $otherDepartment->id]);
$this->actingAs($head)->get('/compras/pesquisa?q=FIND')->assertInertia(fn (Assert $page) => $page->has('groups', 5)->where('groups.3.records.total', 0)->where('groups.4.key', 'receipts')->where('groups.4.records.total', 1));
$this->actingAs($f['receiver'])->get('/compras/pesquisa?q=FIND')->assertInertia(fn (Assert $page) => $page->has('groups', 5)->where('groups.1.key', 'equipment')->where('groups.4.records.total', 1));
});
test('search reloads revoked access instead of trusting the authenticated model and requires login', function () {
DB::table('users')->where('id', $this->f['issuer']->id)->update(['purchasing_role' => PurchasingRole::Configured->value]);
$this->get('/compras/pesquisa?q=TEST')->assertForbidden();
auth()->logout();
$this->get('/compras/pesquisa?q=TEST')->assertRedirect('/login');
});
test('optional finance search uses native invoice scope and returns references without private snapshots or money', function () {
config(['procurement_search.finance_metadata_enabled' => true]);
$f = $this->f;
$create = fn ($fixture) => Invoice::query()->create(['tenant_id' => $fixture['tenant']->id, 'purchase_order_id' => $fixture['order']->id, 'supplier_id' => $fixture['order']->supplier_id,
'created_by' => $fixture['issuer']->id, 'number' => 'QA-SEARCH-INVOICE', 'issued_on' => today(), 'status' => 'pending', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000,
'snapshot' => ['synthetic' => true, 'private_note' => 'Never return in search']]);
$ownInvoice = $create($f);
$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)
->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));
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));
});
+382 -3
View File
@@ -27,12 +27,16 @@ use App\Models\Supplier;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\BudgetWorkflow;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
use App\Services\DocumentaryQualificationWorkflow;
use App\Services\EquipmentWorkflow;
use App\Services\FormalAdmission;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
use App\Services\ProposalOpeningWorkflow;
@@ -41,12 +45,387 @@ use App\Services\PurchaseRevisionWorkflow;
use App\Services\QuotationExchange;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $quantity = '1.000', ?string $stockUnit = null): array
{
config(['agreement_order_limits.qa_enabled' => true]);
expect(app(AgreementOrderLimits::class)->ready())->toBeTrue();
foreach (User::query()->where('tenant_id', $test->tenant->id)->get() as $user) {
$permissions = [$user->purchasing_role->value];
if ($user->id === $test->buyer->id) {
$permissions = [...$permissions, 'supply_prepare', 'supply_read'];
}
if ($user->id === $test->finance->id) {
$permissions = [...$permissions, 'supply_review'];
}
supplyGrant($user, $permissions);
}
$stock = StockItem::query()->create(['tenant_id' => $test->tenant->id, 'created_by' => $test->buyer->id, 'code' => 'QA-ORDER-LIMIT', 'name' => 'Artigo contratual sintético', 'unit' => $stockUnit ?? $test->item->unit]);
$warehouse = Warehouse::query()->create(['tenant_id' => $test->tenant->id, 'created_by' => $test->buyer->id, 'code' => 'QA-LIMIT', 'name' => 'Armazém contratual sintético']);
// Explicit synthetic catalogue identity, prepared before selecting/approving the award. Never match by name.
$test->item->update(['catalogue_snapshot' => ['stock_item_id' => $stock->id]]);
$test->actingAs($test->buyer);
$planning = app(SupplyPlanning::class);
$draft = $planning->save($test->buyer, 'agreement', supplyInput(['stock_item_id' => $stock->id, 'warehouse_id' => $warehouse->id, 'supplier_id' => $test->quotes[0]->supplier_id,
'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'origin' => 'local', 'currency' => 'MZN',
'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'QA-PER-ORDER', 'order_limit_amount' => $amount, 'order_limit_quantity' => $quantity]));
$test->actingAs($test->finance);
$agreement = $planning->save($test->finance, 'agreement', supplyInput([], 'approve', $draft));
$binding = ['requisition_item_id' => $test->item->id, 'agreement_id' => $agreement->id];
return compact('agreement', 'binding', 'stock', 'warehouse');
}
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed) {
$f = perOrderAgreement($this, '100.00', '1.000');
$planning = app(SupplyPlanning::class);
$this->actingAs($this->buyer);
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-GLOBAL-CONTRACT',
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => $cap]));
$this->actingAs($this->finance);
$contract = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
$bindings = [];
foreach ([false, true] as $second) {
$stock = $f['stock'];
$item = $this->item;
if ($second) {
$stock = $stock->replicate();
$stock->forceFill(['code' => 'QA-SECOND-ARTICLE', 'unit' => 'kg'])->save();
$item = $this->item->replicate();
$item->forceFill(['catalogue_snapshot' => ['stock_item_id' => $stock->id], 'unit' => 'kg'])->save();
$this->r->update(['subtotal_minor' => 20000, 'total_minor' => 20000]);
foreach ($this->quotes as $quote) {
$line = $quote->items()->sole()->replicate();
$line->forceFill(['requisition_item_id' => $item->id])->save();
$quote->update(['subtotal_minor' => $quote->subtotal_minor * 2, 'total_minor' => $quote->total_minor * 2]);
}
}
$this->actingAs($this->buyer);
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'stock_item_id' => $stock->id,
'contract_key' => $contract->record_key, 'reference' => 'QA-CONTRACT-ARTICLE-'.($second ? '2' : '1')]));
$this->actingAs($this->finance);
$agreement = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
}
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => $bindings]);
if (! $allowed) {
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
expect(PurchaseOrder::query()->count())->toBe(0);
return;
}
$response->assertRedirect();
$order = PurchaseOrder::query()->sole();
foreach ($order->snapshot['agreement_bindings'] as $row) {
expect($row['contract']['checked_order_value_minor'])->toBe(20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
->and($row['contract']['version'])->toBe($contract->version)->and($row['checked_order_value_minor'])->toBe(10000);
}
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Contrato global: QA-GLOBAL-CONTRACT');
$this->withoutVite()->get('/compras/fornecimento?view=contracts')->assertOk();
$this->get('/compras/fornecimento?view=agreements&linked_contract_key='.$contract->record_key)
->assertOk()->assertInertia(fn (Assert $page) => $page->component('supply/index')->has('records', 2)->where('linkedContractKey', $contract->record_key));
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false]]);
test('per order contract rejects incompatible association and stale approval without changing earlier versions', function () {
$f = perOrderAgreement($this);
$planning = app(SupplyPlanning::class);
$this->actingAs($this->buyer);
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-HEADER',
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => '100.00']));
expect(fn () => $planning->save($this->buyer, 'contract', supplyInput([], 'approve', $draft)))->toThrow(HttpException::class);
$this->actingAs($this->finance);
$tasks = collect(app(WorkflowTaskInbox::class)->build($this->finance, 'procurement'))->where('task', 'contract_review');
expect($tasks->pluck('href')->all())->toContain('/compras/fornecimento?view=contracts&record_id='.$draft->id.'#supply-record-'.$draft->id);
expect($tasks->sole()['reference'])->toBe('QA-HEADER');
$contract = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
foreach ([['currency' => 'USD'], ['supplier_id' => 0], ['contract_version' => 999], ['valid_until' => today()->addMonths(2)->toDateString()]] as $change) {
expect(fn () => app(AgreementOrderLimits::class)->contract([...$f['agreement']->data, 'contract_key' => $contract->record_key, ...$change], $this->tenant->id))->toThrow(ValidationException::class);
}
expect(fn () => app(AgreementOrderLimits::class)->contract([...$f['agreement']->data, 'contract_key' => $contract->record_key], $this->tenant->id + 999))->toThrow(ValidationException::class);
$this->actingAs($this->buyer);
$article = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $contract->record_key]));
expect($article->data['contract_version'])->toBe($contract->version);
$this->actingAs($this->finance);
$approved = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $article));
$this->actingAs($this->buyer);
$policyDraft = $planning->save($this->buyer, 'policy', supplyInput([...supplyPolicy($f), 'agreement_key' => $approved->record_key]));
$this->actingAs($this->finance);
$policy = $planning->save($this->finance, 'policy', supplyInput([], 'approve', $policyDraft));
$this->actingAs($this->buyer);
$pending = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $contract->record_key]));
$this->actingAs($this->finance);
$planning->save($this->finance, 'contract', supplyInput([], 'suspend', $contract));
expect($planning->calendar($policy, today()->toDateString())['lead_time_available'])->toBeFalse();
expect(fn () => $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $pending)))->toThrow(ValidationException::class);
expect($contract->fresh()->state)->toBe('approved')->and($article->fresh()->state)->toBe('draft');
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [['requisition_item_id' => $this->item->id, 'agreement_id' => $approved->id]]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
expect(PurchaseOrder::query()->count())->toBe(0);
});
test('per order limits preserve equality and each independent order can use the full limit again', function (bool $global) {
$f = perOrderAgreement($this);
if ($global) {
$planning = app(SupplyPlanning::class);
$this->actingAs($this->buyer);
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-FULL-AGAIN',
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => '100.00']));
$this->actingAs($this->finance);
$header = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
$this->actingAs($this->buyer);
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $header->record_key]));
$this->actingAs($this->finance);
$f['agreement'] = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
$f['binding']['agreement_id'] = $f['agreement']->id;
}
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertSessionHasNoErrors()->assertRedirect();
$first = PurchaseOrder::query()->sole();
$snapshot = $first->snapshot;
expect($snapshot['agreement_bindings'][$this->item->id]['max_order_value_minor'])->toBe(10000)
->and($snapshot['agreement_bindings'][$this->item->id]['max_order_quantity_milli'])->toBe(1000)
->and($snapshot['agreement_bindings'][$this->item->id]['basis'])->toBe('per_order');
$request = $this->r->replicate();
$request->forceFill(['number' => 'REQ-ORDER-SECOND'])->save();
foreach ($this->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->forceFill(['requisition_id' => $request->id])->save();
}
$item = $this->item->replicate();
$item->forceFill(['requisition_id' => $request->id])->save();
$quotes = [];
foreach ($this->quotes as $quote) {
$copy = $quote->replicate();
$copy->forceFill(['requisition_id' => $request->id])->save();
foreach ($quote->items()->get() as $line) {
$new = $line->replicate();
$new->forceFill(['quotation_id' => $copy->id, 'requisition_item_id' => $item->id])->save();
}
foreach ($quote->evaluations()->get() as $evaluation) {
$new = $evaluation->replicate();
$new->forceFill(['quotation_id' => $copy->id])->save();
}
$quotes[] = $copy;
}
$this->r = $request;
$this->item = $item;
$this->quotes = $quotes;
$this->selection['quotation_id'] = $quotes[0]->id;
$this->awardUrl = '/requisicoes/'.$request->id.'/adjudicacao';
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasNoErrors();
$secondAward = PurchaseAward::query()->where('requisition_id', $request->id)->sole();
approvePurchaseAward($this, $secondAward);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$secondAward->id.'/emitir', ['agreement_bindings' => [['requisition_item_id' => $item->id, 'agreement_id' => $f['agreement']->id]]])->assertSessionHasNoErrors();
expect(PurchaseOrder::query()->count())->toBe(2)->and((int) PurchaseOrder::query()->sum('total_minor'))->toBe(20000)
->and($first->fresh()->snapshot)->toBe($snapshot)->and($f['agreement']->fresh()->data['max_order_value_minor'])->toBe(10000);
if (DB::getDriverName() === 'sqlite') {
// PostgreSQL report snapshots are exercised outside Pest's outer transaction by the existing report worker.
$report = app(ProcurementReviewReport::class)->build($this->buyer, $first->requisition_id);
expect($report['agreement_limits'])->toBe($snapshot['agreement_bindings']);
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Acordo por ordem')->toContain('QA-PER-ORDER');
if ($global) {
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Contrato global por ordem')->toContain('QA-FULL-AGAIN');
expect(array_values($first->snapshot['agreement_bindings'])[0]['contract']['checked_order_value_minor'])->toBe(10000);
}
}
})->with([false, true]);
test('per order limits reject excess and explicit zero before committing any order', function (?string $value, ?string $quantity) {
$f = perOrderAgreement($this, $value, $quantity);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$before = BudgetEntry::query()->get()->toArray();
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
expect(PurchaseOrder::query()->count())->toBe(0)->and(BudgetEntry::query()->get()->toArray())->toBe($before);
})->with([['99.99', '1.000'], ['100.00', '0.999'], ['0', null], [null, '0']]);
test('per order limits keep an absent limit distinct from zero and recover issue without another effect', function () {
$f = perOrderAgreement($this, null, null);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$payload = ['agreement_bindings' => [$f['binding']]];
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', $payload)->assertSessionHasNoErrors();
$order = PurchaseOrder::query()->sole();
$snapshot = $order->snapshot;
$this->post('/adjudicacoes/'.$award->id.'/emitir', $payload)->assertSessionHasNoErrors();
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $f['agreement']->id + 100]]])->assertConflict();
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->fresh()->snapshot)->toBe($snapshot)
->and($snapshot['agreement_bindings'][$this->item->id]['max_order_value_minor'])->toBeNull()
->and(AuditLog::query()->where('action', 'purchase_order.issued')->count())->toBe(1);
});
test('per order limits refuse suspended stale foreign source data and omitted source read permission', function () {
$f = perOrderAgreement($this);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->finance);
app(SupplyPlanning::class)->save($this->finance, 'agreement', supplyInput([], 'suspend', $f['agreement']));
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable();
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'requisition_item_id' => 999999]]])->assertUnprocessable();
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $this->buyer->id)->select('profile_id'))->update(['permissions' => json_encode(['procurement'])]);
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertForbidden();
expect(PurchaseOrder::query()->count())->toBe(0);
});
test('per order quantity limits use the explicit frozen conversion without changing commercial prices', function () {
$f = perOrderAgreement($this, '100.00', '12.000', 'pcs');
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$body = $f['binding'];
$body['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem contratual sintética', 'version' => 'QA-PACK-1'];
$bad = $body;
$bad['conversion']['denominator'] = '7';
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$bad]])->assertUnprocessable();
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable();
$this->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$body]])->assertSessionHasNoErrors();
$order = PurchaseOrder::query()->sole();
expect($order->total_minor)->toBe(10000)->and($order->items()->sole()->quantity)->toBe('1.000')
->and($order->snapshot['agreement_bindings'][$this->item->id]['agreement_quantity_milli'])->toBe('12000')
->and($order->snapshot['agreement_bindings'][$this->item->id]['conversion'])->toBe($body['conversion']);
});
test('per order limit preparation is exact rejects cumulative modes and is unavailable outside its qa switch', function () {
config(['agreement_order_limits.qa_enabled' => true]);
$limits = app(AgreementOrderLimits::class);
expect($limits->terms(['order_limit_amount' => '123.45', 'order_limit_quantity' => '12.345']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => 12345, 'max_order_quantity_milli' => 12345]);
expect($limits->terms(['order_limit_amount' => '', 'order_limit_quantity' => ' ']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => null, 'max_order_quantity_milli' => null]);
expect($limits->terms(['order_limit_amount' => '10000000000.00', 'order_limit_quantity' => '1000000000.000']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => 1000000000000, 'max_order_quantity_milli' => 1000000000000]);
foreach ([['order_limit_amount' => '1.001'], ['order_limit_quantity' => '1.0001'], ['order_limit_amount' => '-1'], ['order_limit_amount' => '1', 'order_limit_basis' => 'cumulative']] as $body) {
expect(fn () => $limits->terms($body))->toThrow(ValidationException::class);
}
config(['agreement_order_limits.qa_enabled' => false]);
expect(fn () => $limits->terms(['order_limit_amount' => '1']))->toThrow(HttpException::class)
->and($limits->terms(['reference' => 'legacy']))->toBe([]);
});
test('per order limits aggregate all covered lines of the same agreement instead of granting a limit to each line', function (string $amount, string $quantity, bool $allowed) {
$f = perOrderAgreement($this, $amount, $quantity);
$second = $this->item->replicate();
$second->save();
$this->r->update(['subtotal_minor' => 20000, 'total_minor' => 20000]);
foreach ($this->quotes as $quote) {
$line = $quote->items()->sole()->replicate();
$line->forceFill(['requisition_item_id' => $second->id])->save();
$quote->update(['subtotal_minor' => $quote->subtotal_minor * 2, 'total_minor' => $quote->total_minor * 2]);
}
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$payload = ['agreement_bindings' => [$f['binding'], ['requisition_item_id' => $second->id, 'agreement_id' => $f['agreement']->id]]];
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', $payload);
if (! $allowed) {
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
expect(PurchaseOrder::query()->count())->toBe(0);
return;
}
$response->assertRedirect();
$order = PurchaseOrder::query()->sole();
expect($order->total_minor)->toBe(20000)->and($order->snapshot['agreement_bindings'][$this->item->id]['checked_order_value_minor'])->toBe(20000)
->and($order->snapshot['agreement_bindings'][$second->id]['checked_order_quantity_milli'])->toBe('2000');
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Acordos e limites preservados por ordem')->assertSee('QA-PER-ORDER');
})->with([['200.00', '1.500', false], ['150.00', '2.000', false], ['200.00', '2.000', true]]);
test('per order value limit includes taxes rather than only the net amount', function (string $amount, bool $allowed) {
$f = perOrderAgreement($this, $amount, '1.000');
awardPrices($this, 10000, 16);
$this->r->update(['tax_minor' => 1600, 'total_minor' => 11600]);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]]);
if (! $allowed) {
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
expect(PurchaseOrder::query()->count())->toBe(0);
return;
}
$response->assertRedirect();
expect(PurchaseOrder::query()->sole()->snapshot['agreement_bindings'][$this->item->id]['checked_order_value_minor'])->toBe(11600);
})->with([['100.00', false], ['116.00', true]]);
test('per order frozen article and warehouse are reused by receipt without changing documentary quantities', function () {
$f = perOrderAgreement($this);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertSessionHasNoErrors();
$order = PurchaseOrder::query()->sole();
$original = $order->snapshot;
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
supplyGrant($receiver, ['warehouse']);
$this->actingAs($receiver);
$body = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'QA-CONTRACT-RECEIPT', 'received_on' => today()->toDateString(), 'warehouse_id' => null,
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => null]]];
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertUnprocessable();
$body['warehouse_id'] = $f['warehouse']->id;
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
expect(StockMovement::query()->sole()->stock_item_id)->toBe($f['stock']->id)->and(StockMovement::query()->sole()->quantity_milli)->toBe(1000)
->and($order->fresh()->snapshot)->toBe($original)->and($f['agreement']->fresh()->data['max_order_quantity_milli'])->toBe(1000);
});
test('per order agreement search retains selected eligible sources beyond the hundred row window without reviving suspension', function () {
$f = perOrderAgreement($this);
$this->actingAs($this->buyer);
for ($index = 0; $index < 101; $index++) {
$copy = $f['agreement']->replicate();
$copy->forceFill(['record_key' => (string) Str::uuid(), 'version' => 1, 'operation_key' => (string) Str::uuid(),
'created_at' => now(),
'input_hash' => hash('sha256', 'synthetic-pagination-agreement:'.$index),
'reason' => 'Fixture sintética de paginação; não representa aprovação empresarial.',
'data' => [...$f['agreement']->data, 'reference' => 'NEWER-QA-'.$index]])->save();
}
$limits = app(AgreementOrderLimits::class);
expect($limits->options($this->buyer, $this->r, $this->quotes[0]))->toHaveCount(100);
expect($limits->options($this->buyer, $this->r, $this->quotes[0], 'NO-MATCH', [$f['agreement']->id]))->toHaveCount(1);
$this->actingAs($this->finance);
app(SupplyPlanning::class)->save($this->finance, 'agreement', supplyInput([], 'suspend', $f['agreement']));
$this->actingAs($this->buyer);
expect($limits->options($this->buyer, $this->r, $this->quotes[0], 'NO-MATCH', [$f['agreement']->id]))->toBe([]);
});
test('per order source from another company cannot be bound even when its identity is known', function () {
$f = perOrderAgreement($this);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['supply_prepare']);
supplyGrant($foreign['receiver'], ['supply_review']);
$this->actingAs($foreign['issuer']);
$planning = app(SupplyPlanning::class);
$draft = $planning->save($foreign['issuer'], 'agreement', supplyInput(['stock_item_id' => $foreign['stock']->id, 'warehouse_id' => $foreign['warehouse']->id,
'supplier_id' => $foreign['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'FOREIGN-QA', 'order_limit_amount' => '100.00']));
$this->actingAs($foreign['receiver']);
$other = $planning->save($foreign['receiver'], 'agreement', supplyInput([], 'approve', $draft));
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $other->id]]])->assertUnprocessable();
expect(PurchaseOrder::query()->where('tenant_id', $this->tenant->id)->count())->toBe(0);
});
test('per order limits refuse an agreement in another currency without inventing a conversion', function () {
$f = perOrderAgreement($this);
$planning = app(SupplyPlanning::class);
$this->actingAs($this->buyer);
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'currency' => 'USD', 'reference' => 'WRONG-CURRENCY-QA']));
$this->actingAs($this->finance);
$wrong = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $wrong->id]]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
expect(PurchaseOrder::query()->count())->toBe(0);
});
test('mixed currency comparison ranks the frozen mzn reference rather than raw foreign amounts', function () {
$this->actingAs($this->finance);
@@ -97,7 +476,7 @@ test('foreign currency conversion determines final approval thresholds without c
test('foreign order cancellation reverses the mzn commitment while preserving the original foreign document', function () {
$this->actingAs($this->finance);
$exchange = app(\App\Services\QuotationExchange::class);
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
'quoted_on' => today()->toDateString(), 'source' => 'Taxa sintética para testar reversão do compromisso']);
$quote = $this->quotes[0];
@@ -118,7 +497,7 @@ test('foreign order cancellation reverses the mzn commitment while preserving th
$admins[] = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
}
$this->actingAs($admins[0]);
$policyWorkflow = app(\App\Services\OrderCancellationPolicyWorkflow::class);
$policyWorkflow = app(OrderCancellationPolicyWorkflow::class);
$policy = $policyWorkflow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Política exclusivamente sintética para cancelamento']);
foreach (array_slice($admins, 1) as $reviewer) {
@@ -126,7 +505,7 @@ test('foreign order cancellation reverses the mzn commitment while preserving th
$policyWorkflow->review($reviewer, $policy, 'approved', 'Conferência sintética independente');
}
$this->actingAs($this->buyer);
$flow = app(\App\Services\OrderCancellationWorkflow::class);
$flow = app(OrderCancellationWorkflow::class);
$cancellation = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
'reason' => 'Cancelamento sintético antes de qualquer execução', 'evidence' => 'Evidência documental exclusivamente sintética']);
$this->actingAs($this->finance);
+18
View File
@@ -172,6 +172,24 @@ function warehouseCommand($test, $actor, string $action, array $extra = []): arr
return $input;
}
test('production delivery preserves its original reference and uses one native stock issue and print document', function (string $reference) {
$data = $this->draftData;
$data['operation_key'] = (string) Str::uuid();
$data['lines'][0] = [...$data['lines'][0], 'use' => 'production', 'production_reference' => $reference];
$this->r = app(WarehouseRequests::class)->draft($this->f['issuer'], $data);
warehouseCommand($this, $this->f['issuer'], 'submit');
warehouseCommand($this, $this->reviewer, 'authorize');
$input = warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '4.000']]]);
$this->postJson('/stock/requisicoes/'.$this->r->id.'/eventos', $input)->assertRedirect();
$delivery = WarehouseRequestEvent::query()->where('warehouse_request_id', $this->r->id)->where('action', 'deliver')->sole();
expect($delivery->data['lines'][0]['production']['reference'])->toBe($reference)
->and(DB::table('stock_operations')->where('kind', 'issue')->count())->toBe(1)
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(6000);
$this->get('/stock/requisicoes/'.$this->r->id.'/entregas/'.$delivery->id.'/imprimir')->assertOk()->assertSee('Insumos para produção')->assertSee('Referência declarada: '.$reference);
$this->get('/stock/requisicoes.csv')->assertOk();
expect($this->get('/stock/requisicoes.csv')->streamedContent())->toContain('Referência declarada: '.$reference);
})->with(['OP-QA-001', '0']);
test('internal request is the exit document and partial deliveries consume only actual quantities with independent receipt', function () {
warehouseCommand($this, $this->f['issuer'], 'submit', ['partial_allowed' => true]);
warehouseCommand($this, $this->reviewer, 'authorize', ['partial_allowed' => true]);
+18
View File
@@ -52,6 +52,24 @@ test('equipment destination is conditional and selected from the permitted catal
$this->postJson('/stock/requisicoes', $this->data)->assertUnprocessable();
});
test('production input destination freezes a declared reference without requiring an external production order or creating a purchase', function () {
$body = $this->data;
$body['lines'][0] = [...$body['lines'][0], 'use' => 'production', 'production_reference' => 'OP-QA-001'];
$purchases = DB::table('requisitions')->count();
$this->postJson('/stock/requisicoes', $body)->assertRedirect();
$this->postJson('/stock/requisicoes', $body)->assertRedirect();
$record = WarehouseRequest::query()->sole();
expect($record->snapshot['lines'][0]['production'])->toBe(['reference' => 'OP-QA-001', 'verification' => 'user_supplied'])
->and(DB::table('requisitions')->count())->toBe($purchases)->and(DB::table('stock_movements')->count())->toBe(0);
$body['operation_key'] = (string) Str::uuid();
$body['lines'][0]['production_reference'] = null;
$this->postJson('/stock/requisicoes', $body)->assertRedirect();
$body['operation_key'] = (string) Str::uuid();
$body['lines'][0]['use'] = 'internal';
$body['lines'][0]['production_reference'] = 'OP-QA-002';
$this->postJson('/stock/requisicoes', $body)->assertUnprocessable();
});
test('warehouse draft rejects another company sources and revoked access', function () {
$foreign = receiptFixture();
$this->actingAs($this->f['issuer'])->postJson('/stock/requisicoes', [...$this->data, 'warehouse_id' => $foreign['warehouse']->id])->assertNotFound();
+135
View File
@@ -0,0 +1,135 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import AgreementFollowup from '@/pages/supply/agreement-followup';
test.each([null, 0])(
'global contract report keeps its scope and distinguishes absent limit from %s',
(limit) => {
const html = renderToStaticMarkup(
<App
initialPage={{
component: 'supply/agreement-followup',
url: '/compras/acordos/vigencia?kind=contract',
version: null,
props: {
kind: 'contract',
asOf: '2026-11-22',
filters: {
search: '',
validity: 'current',
expires_by: '',
},
records: {
total: 1,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
data: [
{
id: 1,
record_key: 'header',
version: 2,
reference: 'CONTRATO-QA',
supplier: 'Fornecedor sintético',
currency: 'MZN',
max_order_value_minor: limit,
periodicity_days: null,
approved_articles: 2,
valid_from: '2026-11-22',
valid_until: '2026-12-22',
validity: 'current',
approved_policies: 0,
item_code: null,
item: null,
warehouse: null,
href: '/compras/fornecimento?view=contracts&record_id=1',
articles_href:
'/compras/fornecimento?view=agreements&linked_contract_key=header',
policies_href: '/unused',
},
],
},
},
clearHistory: false,
encryptHistory: true,
}}
initialComponent={AgreementFollowup}
/>,
);
expect(html).toContain('Vigência dos contratos globais');
expect(html).toContain('kind=contract');
expect(html).toContain('2 artigo(s) aprovado(s) ligado(s)');
expect(html).toContain('Consultar artigos ligados');
expect(html).toContain('linked_contract_key=header');
expect(html).toContain('Cada ordem pode usar o limite completo');
expect(html).toContain('Não gera ordens automáticas');
expect(html).not.toContain('Código não disponível');
expect(html).not.toContain('href="/unused"');
expect(html.includes('Limite global por ordem: Não definido')).toBe(
limit === null,
);
},
);
test('agreement followup keeps explicit filters in the csv and distinguishes documentary vigency from purchase authority', () => {
const html = renderToStaticMarkup(
<App
initialPage={{
component: 'supply/agreement-followup',
url: '/compras/acordos/vigencia',
version: null,
props: {
asOf: '2026-11-21',
filters: {
search: 'FROZEN',
validity: 'expired',
expires_by: '2026-11-30',
},
records: {
total: 27,
current_page: 2,
last_page: 2,
prev_page_url:
'/compras/acordos/vigencia?page=1&search=FROZEN',
next_page_url: null,
data: [
{
id: 4,
record_key: 'synthetic',
version: 2,
reference: '<unsafe>',
supplier: 'Fornecedor sintético',
item_code: 'TEST-ITEM',
item: 'Artigo',
warehouse: 'Armazém',
valid_from: null,
valid_until: null,
validity: 'unknown',
approved_policies: 2,
href: '/compras/fornecimento?view=agreements&record_id=4',
policies_href:
'/compras/fornecimento?view=calendar&linked_agreement_key=synthetic',
},
],
},
errors: {},
},
clearHistory: false,
encryptHistory: true,
}}
initialComponent={AgreementFollowup}
/>,
);
expect(html).toContain('Vigência dos acordos');
expect(html).toContain('não renova acordos');
expect(html).toContain('search=FROZEN');
expect(html).toContain('expires_by=2026-11-30');
expect(html).toContain('política(s) aprovada(s) ligada(s)');
expect(html).toContain('Datas indeterminadas');
expect(html).toContain('Início: Não disponível');
expect(html).toContain('&lt;unsafe&gt;');
expect(html).not.toContain('<unsafe>');
expect(html).toContain('linked_agreement_key=synthetic');
});
@@ -0,0 +1,106 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import AgreementOrderBindings, {
AgreementOrderLimitSummary,
} from '@/components/agreement-order-bindings';
import type { FrozenOrderAgreement } from '@/types/purchase';
const option = {
contract: {
reference: 'CONTRATO-GLOBAL-ANTES-EMISSAO',
version: 2,
currency: 'MZN',
max_order_value_minor: 20000,
},
id: 7,
version: 2,
reference: 'ACORDO-QA',
stock_item_id: 3,
warehouse: 'Armazém de teste',
unit: 'un',
currency: 'MZN',
max_order_value_minor: 10000,
max_order_quantity_milli: 1000,
};
test('issue form makes association explicit and describes a full limit for each order', () => {
const html = renderToStaticMarkup(
<AgreementOrderBindings
requestId={1}
lines={[
{
id: 4,
description: 'Artigo sintético',
stock_item_id: 3,
unit: 'un',
},
]}
options={[option]}
value={[{ requisition_item_id: 4, agreement_id: 7 }]}
onChange={() => {}}
/>,
);
expect(html).toContain('Cada ordem pode utilizar o limite completo');
expect(html).toContain('sem somar outras ordens');
expect(html).toContain('ACORDO-QA');
expect(html).toContain('Sem acordo associado');
expect(html).toContain('Pesquisar acordos');
expect(html).toContain('CONTRATO-GLOBAL-ANTES-EMISSAO');
expect(html).toContain('Soma todos os artigos ligados ao mesmo contrato');
expect(html).toContain('type="button"');
});
test('a missing selected version is visibly unavailable and a catalogue identity is required instead of a name match', () => {
const html = renderToStaticMarkup(
<AgreementOrderBindings
requestId={1}
lines={[
{
id: 4,
description: 'Artigo sintético',
stock_item_id: null,
unit: 'un',
},
]}
options={[]}
value={[{ requisition_item_id: 4, agreement_id: 7 }]}
onChange={() => {}}
/>,
);
expect(html).toContain('Selecção já não disponível');
expect(html).toContain('disabled');
expect(html).toContain('o nome da linha não comprova essa ligação');
});
test('order summary uses frozen group totals once per agreement and keeps absence separate from zero', () => {
const row: FrozenOrderAgreement = {
contract: {
id: 5,
reference: 'CONTRATO-GLOBAL-QA',
version: 2,
currency: 'MZN',
max_order_value_minor: null,
checked_order_value_minor: 20000,
},
agreement_id: 7,
record_key: 'synthetic',
version: 2,
reference: 'ACORDO-QA',
unit: 'un',
currency: 'MZN',
checked_order_value_minor: 0,
checked_order_quantity_milli: '2000',
max_order_value_minor: null,
max_order_quantity_milli: 0,
};
const html = renderToStaticMarkup(
<AgreementOrderLimitSummary bindings={{ 1: row, 2: row }} />,
);
expect(html.match(/ACORDO-QA/g)).toHaveLength(1);
expect(html.match(/CONTRATO-GLOBAL-QA/g)).toHaveLength(1);
expect(html).toContain('Total com impostos dos artigos ligados');
expect(html).toContain('Não definido');
expect(html).toContain('2,000 un');
expect(html).toContain('0,000 un');
expect(html).toContain('sem acumular outras ordens');
expect(renderToStaticMarkup(<AgreementOrderLimitSummary />)).toBe('');
});
+94
View File
@@ -0,0 +1,94 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { CompanyDetailsSettings } from '@/components/company-details-settings';
function render(ready: boolean) {
return renderToStaticMarkup(
<App
initialComponent={CompanyDetailsSettings}
initialPage={{
component: 'company/parameters',
url: '/administracao/parametrizacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
ready,
version: 3,
errors: {},
details: {
legal_name: 'Empresa sintética <QA>',
nuit: '001234567',
bank_accounts: [
{
id: 'a',
bank: 'Banco sintético A',
account_number: '00001234',
currency: 'MZN',
},
{
id: 'b',
bank: 'Banco sintético B',
account_number: '00005678',
currency: 'USD',
},
],
establishments: [
{
id: 'c',
kind: 'headquarters',
name: 'Sede sintética',
address: 'Endereço A',
},
{
id: 'd',
kind: 'branch',
name: 'Sucursal sintética',
address: 'Endereço B',
},
],
},
},
}}
/>,
);
}
test('company form presents distinct accounts and establishments with Portuguese labels and preserved identifiers', () => {
const html = render(true);
for (const text of [
'Denominação social',
'NUEL',
'NUIT',
'Representante legal',
'Balcão',
'Número de conta',
'NIB',
'IBAN',
'NUIB',
'Titular da conta',
'00001234',
'00005678',
'MZN',
'USD',
'Endereço A',
'Endereço B',
'Adicionar estabelecimento',
'Adicionar conta bancária',
]) {
expect(html).toContain(text);
}
expect(html).toContain('Empresa sintética &lt;QA&gt;');
expect(html).toContain('id="bank-a-account_number"');
expect(html).toContain('id="bank-b-account_number"');
expect(html).toContain('id="establishment-c-name"');
expect(html).toContain('id="establishment-d-name"');
});
test('uninstalled schema explains availability without presenting a form that cannot save', () => {
const html = render(false);
expect(html).toContain('Instalação dos campos da empresa pendente');
expect(html).not.toContain('<form');
expect(html).not.toContain('00001234');
});
@@ -0,0 +1,67 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import RequisitionForm from '@/pages/requisitions/form';
import { money, date } from '@/types/procurement';
test('incomplete draft restores the supplied line and missing amounts without inventing zero prices', () => {
const html = renderToStaticMarkup(
<App
initialComponent={RequisitionForm}
initialPage={{
component: 'requisitions/form',
url: '/requisicoes/9/editar',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
internalRequisitionReady: true,
incompleteDraftsAvailable: true,
costCenters: [],
requisition: {
id: 9,
process_version: 1,
number: 'QA-DRAFT-9',
status: 'draft',
priority: 'normal',
needed_by: null,
justification: 'Ini',
cost_center_id: null,
subtotal_minor: null,
tax_minor: null,
total_minor: null,
created_at: '2026-11-22',
items: [],
steps: [],
draft_input: {
incomplete: true,
values: {
justification: 'Ini',
items: [
{
description: 'Preparação recuperada',
quantity: null,
unit_price: null,
tax_rate: '16.00',
},
],
},
},
},
},
}}
/>,
);
expect(html).toContain('Preparação recuperada');
expect(html).toMatch(/novalidate=""/i);
expect(html).toContain('Por completar');
expect(html).not.toContain('value="null"');
expect(html).not.toContain('value="0.00"');
});
test('unknown money and dates are distinguishable from a genuine zero value', () => {
expect(money(null)).toBe('Por completar');
expect(date(null)).toBe('Por completar');
expect(money(0)).not.toBe('Por completar');
});
+177
View File
@@ -0,0 +1,177 @@
import { readdirSync } from 'node:fs';
import { join, relative } from 'node:path';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import JourneyHelpPanel, {
JourneyHelpContent,
} from '@/components/journey-help';
import { FormErrors } from '@/components/procurement';
import {
helpAudience,
helpForJourney,
journeyHelp,
searchJourneyHelp,
recoveryHints,
} from '@/lib/journey-help';
function pageFiles(root: string): string[] {
return readdirSync(root, { withFileTypes: true }).flatMap((entry) =>
entry.isDirectory()
? pageFiles(join(root, entry.name))
: entry.name.endsWith('.tsx')
? [join(root, entry.name)]
: [],
);
}
test('multiarticle contract preparation has guidance for its global limit and independent article quantities', () => {
const help = helpForJourney(
'supply/index',
'/compras/fornecimento?view=contracts',
);
expect(help.id).toBe('supply-contract');
expect(help.checks.join(' ')).toContain(
'Cada ordem pode usar o limite completo',
);
expect(help.checks.join(' ')).toContain(
'Não some quantidades de unidades diferentes',
);
});
test('every operational page has a specific guide rather than silently falling back to generic instructions', () => {
const root = join(process.cwd(), 'resources/js/pages');
const pages = pageFiles(root)
.map((file) =>
relative(root, file)
.replace(/\\/g, '/')
.replace(/\.tsx$/, ''),
)
.filter((name) => !name.startsWith('preview/'));
const missing = pages.filter(
(name) => !journeyHelp.some((topic) => topic.pages.includes(name)),
);
expect(missing).toEqual([]);
expect(new Set(journeyHelp.map((topic) => topic.id)).size).toBe(
journeyHelp.length,
);
for (const name of pages)
expect(helpForJourney(name, '/').audience).toBe(helpAudience(name));
});
test('the supply guide follows the actual stage including imports calendar and technical alternatives', () => {
expect(
helpForJourney('supply/index', '/compras/fornecimento?view=imports').id,
).toBe('supply-import');
expect(
helpForJourney('supply/index', '/compras/fornecimento?view=calendar')
.id,
).toBe('supply-calendar');
expect(
helpForJourney('supply/index', '/compras/fornecimento?view=agreements')
.id,
).toBe('supply-agreement');
expect(
helpForJourney(
'supply/coordination',
'/compras/fornecimento?view=alternatives',
'alternative',
).id,
).toBe('supply-alternative');
});
test('search is local accent insensitive and confines candidate and authentication help to their own audience', () => {
expect(searchJourneyHelp('FACTURACAO', 'staff')).toEqual([]);
expect(
searchJourneyHelp('factura moeda', 'staff').map((topic) => topic.id),
).toContain('payment');
expect(
searchJourneyHelp('conversao', 'staff').map((topic) => topic.id),
).toContain('receipt');
expect(
searchJourneyHelp('candidatura', 'candidate').every(
(topic) => topic.audience === 'candidate',
),
).toBe(true);
expect(searchJourneyHelp('adjudicacao', 'candidate')).toEqual([]);
expect(searchJourneyHelp('conta', 'auth').map((topic) => topic.id)).toEqual(
['authentication'],
);
});
test('guidance separates payment evidence selection physical receipt and commercial quantities', () => {
const payment = renderToStaticMarkup(
<JourneyHelpContent
topic={helpForJourney('payments/index', '/')}
hasErrors
/>,
);
expect(payment).toContain('não executa uma transferência bancária');
expect(payment).toContain('mesma moeda');
expect(payment).toContain('Há dados por conferir');
const people = renderToStaticMarkup(
<JourneyHelpContent topic={helpForJourney('people/show', '/')} />,
);
expect(people).toContain('não comprovam assinatura ou admissão');
const invoice = renderToStaticMarkup(
<JourneyHelpContent topic={helpForJourney('invoices/index', '/')} />,
);
expect(invoice).toContain('não substitui a quantidade comercial');
});
test('validation help never submits a form and every guide includes recovery and a next action', () => {
const html = renderToStaticMarkup(
<FormErrors errors={{ quantity: 'Confira a quantidade.' }} />,
);
expect(html).toContain('role="alert"');
expect(html).toContain('type="button"');
expect(html).toContain('Consultar ajuda para corrigir e continuar');
expect(html).toContain('Confira a unidade e a quantidade ainda pendente');
for (const topic of journeyHelp) {
expect(topic.steps.length).toBeGreaterThan(0);
expect(topic.checks.length).toBeGreaterThan(0);
expect(topic.recovery.length).toBeGreaterThan(20);
expect(topic.next.length).toBeGreaterThan(20);
}
});
test('field hints address stale submissions quantities lots and bank choice without echoing private data', () => {
expect(
recoveryHints(['items.0.accepted_quantity', 'version']).join(' '),
).toContain('histórico antes de voltar a confirmar');
expect(recoveryHints(['supplier_bank_detail_id'])[0]).toContain(
'na moeda da factura',
);
expect(recoveryHints(['items.0.lots.0.expires_on'])[0]).toContain(
'unidade física',
);
expect(recoveryHints(['private_note'])).toEqual([]);
expect(
recoveryHints(['version', 'quantity', 'bank_id', 'lots']).length,
).toBe(2);
});
test('the contextual trigger is available within the current Inertia page without exposing form values', () => {
const html = renderToStaticMarkup(
<App
initialPage={{
component: 'candidate/profile',
url: '/candidaturas/perfil',
version: null,
props: {
errors: { name: 'Erro' },
privateNote: 'PRIVATE-FORM-CONTENT',
},
clearHistory: false,
encryptHistory: true,
}}
initialComponent={JourneyHelpPanel}
/>,
);
expect(html).toContain(
'Abrir ajuda desta etapa: Preparar o perfil de candidatura',
);
expect(html).toContain('Há dados por conferir');
expect(html).not.toContain('PRIVATE-FORM-CONTENT');
expect(html).not.toContain('adjudicação');
});
@@ -35,6 +35,13 @@ test.each([0, 2])(
],
},
unapproved_past_needed_date: 1,
approval_times: {
measured: 2,
unknown: 1,
total_seconds: 14400,
min_seconds: 3600,
max_seconds: 10800,
},
approved: {
count: 1,
without_registered_quotes: 0,
@@ -56,6 +63,9 @@ test.each([0, 2])(
expect(html).toContain('7 dias de calendário');
expect(html).toContain('não comprova atraso de entrega');
expect(html).toContain('não significam propostas válidas');
expect(html).toContain('Tempos de aprovação concluída');
expect(html).toContain('Média: 2 h');
expect(html).toContain('Não representa dias úteis');
}
expect(html).not.toContain('<form');
},
@@ -0,0 +1,68 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Search from '@/pages/search/procurement';
test('process search separates result groups escapes text and retains page links', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=QA',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'QA',
groups: [
{
key: 'requests',
title: 'Requisições',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=QA&requests_page=2',
data: [
{
id: 7,
title: 'QA <original>',
detail: 'draft',
href: '/requisicoes/7',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('QA &lt;original&gt;');
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');
});
test('empty search explains the minimum input rather than implying that the database is empty', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {}, term: '', groups: [] },
}}
/>,
);
expect(html).toContain('Introduza pelo menos dois caracteres');
expect(html).not.toContain('Nenhum resultado no seu âmbito');
});
+221
View File
@@ -0,0 +1,221 @@
import { afterEach, expect, test, vi } from 'vitest';
import { departureUrl, protectDepartures } from '@/lib/unsaved-navigation';
const state = vi.hoisted(() => ({
before: null as ((event: any) => void) | null,
visit: vi.fn(),
off: vi.fn(),
}));
vi.mock('@inertiajs/react', () => ({
router: {
on: (_name: string, callback: (event: any) => void) => {
state.before = callback;
return state.off;
},
visit: state.visit,
},
}));
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
function fixture() {
const doc = new EventTarget();
const win = Object.assign(new EventTarget(), {
location: {
href: 'http://localhost/requisicoes/criar',
assign: vi.fn(),
},
});
class Link {
href = 'http://localhost/fornecedores?search=QA';
target = '';
download = false;
closest() {
return this;
}
hasAttribute(name: string) {
return name === 'download' && this.download;
}
}
vi.stubGlobal('document', doc);
vi.stubGlobal('window', win);
vi.stubGlobal('Element', Link);
let dirty = true;
let proceed: (() => void) | undefined;
const prompt = vi.fn((next: () => void) => {
proceed = next;
});
const cleanup = protectDepartures(() => dirty, prompt);
const link = new Link();
const click = (extra: Record<string, unknown> = {}) => {
const event = new Event('click', { cancelable: true });
Object.defineProperties(
event,
Object.fromEntries(
Object.entries({
target: link,
button: 0,
ctrlKey: false,
metaKey: false,
shiftKey: false,
altKey: false,
...extra,
}).map(([key, value]) => [key, { value }]),
),
);
doc.dispatchEvent(event);
return event;
};
return {
doc,
win,
link,
prompt,
click,
cleanup,
clean: () => {
dirty = false;
},
proceed: () => proceed?.(),
};
}
test('a dirty form blocks departure to suppliers until the user chooses to leave, retaining the exact destination', () => {
const f = fixture();
expect(f.click().defaultPrevented).toBe(true);
expect(f.win.location.assign).not.toHaveBeenCalled();
expect(f.prompt).toHaveBeenCalledOnce();
f.clean();
f.proceed();
expect(f.win.location.assign).toHaveBeenCalledWith(
'http://localhost/fornecedores?search=QA',
);
f.cleanup();
});
test.each([
{ ctrlKey: true },
{ metaKey: true },
{ shiftKey: true },
{ altKey: true },
{ button: 1 },
])(
'new-tab and modified clicks do not abandon the current form: %j',
(extra) => {
const f = fixture();
expect(f.click(extra).defaultPrevented).toBe(false);
expect(f.prompt).not.toHaveBeenCalled();
f.cleanup();
},
);
test('downloads, other targets, same-page anchors and clean forms continue normally', () => {
const f = fixture();
f.link.download = true;
expect(f.click().defaultPrevented).toBe(false);
f.link.download = false;
f.link.target = '_blank';
expect(f.click().defaultPrevented).toBe(false);
f.link.target = '';
f.link.href = `${f.win.location.href}#linhas`;
expect(f.click().defaultPrevented).toBe(false);
f.link.href = 'http://localhost/stock';
f.clean();
expect(f.click().defaultPrevented).toBe(false);
expect(f.prompt).not.toHaveBeenCalled();
f.cleanup();
});
test('programmatic GET navigation is deferred with filters preserved while saving POST is allowed', () => {
const f = fixture();
const visit = {
method: 'get',
url: new URL('http://localhost/relatorios'),
data: { status: 'pending' },
preserveScroll: true,
};
const preventDefault = vi.fn();
state.before?.({ detail: { visit }, preventDefault });
expect(preventDefault).toHaveBeenCalledOnce();
expect(state.visit).not.toHaveBeenCalled();
f.clean();
f.proceed();
expect(state.visit).toHaveBeenCalledWith(visit.url, visit);
f.cleanup();
const g = fixture();
const allowSave = vi.fn();
state.before?.({
detail: { visit: { ...visit, method: 'post' } },
preventDefault: allowSave,
});
expect(allowSave).not.toHaveBeenCalled();
expect(g.prompt).not.toHaveBeenCalled();
g.cleanup();
});
test('reload prompts while dirty, and cleanup removes the listeners', () => {
const f = fixture();
const reload = new Event('beforeunload', { cancelable: true });
f.win.dispatchEvent(reload);
expect(reload.defaultPrevented).toBe(true);
f.cleanup();
const next = new Event('beforeunload', { cancelable: true });
f.win.dispatchEvent(next);
expect(next.defaultPrevented).toBe(false);
expect(state.off).toHaveBeenCalledOnce();
});
test('departure resolution retains filters and ignores fragment-only, external and non-HTTP links', () => {
expect(
departureUrl('http://localhost/requisicoes?view=mine', '?view=all'),
).toBe('http://localhost/requisicoes?view=all');
expect(
departureUrl('http://localhost/requisicoes?view=mine', '#ajuda'),
).toBeNull();
expect(
departureUrl(
'http://localhost/requisicoes',
'mailto:qa@example.invalid',
),
).toBeNull();
expect(
departureUrl('http://localhost/requisicoes', 'https://example.invalid'),
).toBeNull();
});
test('submitting a GET search does not guard its own values but still protects another edited form', async () => {
const f = fixture();
f.cleanup();
class Form {}
vi.stubGlobal('HTMLFormElement', Form);
const own = new Form();
let anotherDirty = false;
const prompt = vi.fn();
const cleanup = protectDepartures(
(except) => anotherDirty || except !== own,
prompt,
);
const submit = new Event('submit');
Object.defineProperty(submit, 'target', { value: own });
f.doc.dispatchEvent(submit);
const preventDefault = vi.fn();
const event = {
detail: {
visit: {
method: 'get',
url: new URL('http://localhost/compras/pesquisa?q=QA'),
},
},
preventDefault,
};
state.before?.(event);
expect(preventDefault).not.toHaveBeenCalled();
anotherDirty = true;
state.before?.(event);
expect(preventDefault).toHaveBeenCalledOnce();
expect(prompt).toHaveBeenCalledOnce();
await Promise.resolve();
cleanup();
});
@@ -0,0 +1,92 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Requests from '@/pages/stock/requests';
test('production use is available and the stored declared reference is escaped without suggesting external validation', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Requests}
initialPage={{
component: 'stock/requests',
url: '/stock/requisicoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
filters: {
view: 'all',
state: '',
search: '',
warehouse_id: null,
},
views: [],
states: {},
checkedAt: '2026-11-22T12:00:00Z',
ready: true,
canPrepare: true,
items: [],
warehouses: [],
costCenters: [],
equipment: [],
records: {
total: 1,
prev_page_url: null,
next_page_url: null,
data: [
{
id: 9,
status: 'draft',
snapshot: {
requester: { name: 'QA' },
warehouse: { name: 'QA' },
cost_center: { code: 'QA', name: 'QA' },
destination: 'Linha QA',
reason: 'Synthetic data',
priority: 'normal',
lines: [
{
item: {
id: 1,
code: 'QA',
name: 'Insumo QA',
unit: 'kg',
},
quantity_milli: 1000,
use: 'production',
destination: 'Linha QA',
equipment: null,
production: {
reference: 'OP-<QA>',
verification: 'user_supplied',
},
},
],
},
health: {
lines: [],
needs_reservation: false,
needs_check: false,
unconfirmed_deliveries: 0,
delivery_ready: false,
},
actions: {
canSubmit: false,
canReview: false,
canDeliver: false,
canManageReservation: false,
canReceive: false,
},
},
],
},
},
}}
/>,
);
expect(html).toContain('value="production"');
expect(html).toContain('Insumos para produção');
expect(html).toContain('Referência declarada: OP-&lt;QA&gt;');
expect(html).not.toContain('OP-<QA>');
});
@@ -0,0 +1,31 @@
import hashlib
import importlib.util
import json
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("catalogue_generator", ROOT / "scripts/prepare-geography-catalogue.py")
generator = importlib.util.module_from_spec(spec)
spec.loader.exec_module(generator)
class CatalogueBytesTest(unittest.TestCase):
def test_serialization_keeps_unicode_and_approved_line_ending(self):
data = {"name": "Mo\u00e7ambique", "records": []}
result = generator.catalogue_bytes(data)
self.assertEqual(result, b'{"name":"Mo\xc3\xa7ambique","records":[]}\r\n')
self.assertEqual(json.loads(result), data)
def test_real_catalogue_reproduces_the_accepted_artifact_hash(self):
content = (ROOT / "resources/data/geography/cartografia-moz.json").read_bytes()
data = json.loads(content)
expected = "28530f11f528e6f715396991e1294872c7e6a8b260d08a84e7d8fe17e5920457"
self.assertEqual(hashlib.sha256(content).hexdigest(), expected)
self.assertEqual(generator.catalogue_bytes(data), content)
self.assertEqual(len(data["records"]), 20407)
self.assertEqual(data["manifest"]["source_sha256"], "70996d9a9133785a848de90bedb4bf685e24d8f823cd153c0adc43eac642a292")
if __name__ == "__main__":
unittest.main()