commit compras1 2811
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-28 07:11:35 +02:00
parent d58b75c87a
commit eb32c74c56
202 changed files with 17463 additions and 1526 deletions
@@ -0,0 +1,229 @@
<?php
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionAccountAssignments;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase'], true)) {
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$databaseName = getenv('DB_DATABASE') ?: '';
if ($privateRoot === false || $boundary === false || ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $databaseName, $matches)
|| str_replace('\\', '/', $privateRoot) !== str_replace('\\', '/', $boundary).'/rq01-ledger-qa-'.$matches[1]) {
throw new LogicException('Private native review root refused.');
}
$app->useStoragePath($privateRoot.'/storage');
}
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
$source = requisitionLedgerQaSource();
if (! $app->environment('testing') || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $source === null) {
throw new LogicException('Owned common-ledger QA composition required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
config(['requisition-accounts.qa_enabled' => true]);
require_once __DIR__.'/../Support/ReceiptFixture.php';
if ($mode === 'prepare-native-review') {
require_once __DIR__.'/../Support/RequisitionAccountsNativeReview.php';
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-office-purchase') {
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1') {
throw new LogicException('Office HTTP assertions require their explicit synthetic composition.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
Carbon::setTestNow($fixture['clock']);
CarbonImmutable::setTestNow($fixture['clock']);
require_once __DIR__.'/../Support/NativeOfficePurchaseState.php';
try {
$state = DB::transaction(function () use ($fixture) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return nativeOfficePurchaseState($fixture);
});
echo json_encode($state, JSON_THROW_ON_ERROR);
} catch (Throwable $error) {
fwrite(STDERR, get_class($error).': '.$error->getMessage().PHP_EOL);
exit(1);
}
exit;
}
$financial = static function (): string {
$rows = [];
foreach (['gl_accounts', 'gl_journals', 'gl_lines', 'requisitions', 'requisition_items', 'invoices', 'invoice_items', 'external_payments', 'budget_entries', 'stock_movements'] as $table) {
$rows[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
return hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
};
$snapshot = static function (): array {
$frames = [];
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
$name = str_replace('"', '""', $table->tablename);
$rows = DB::select('select row_to_json(t)::text as row from "'.$name.'" t order by row_to_json(t)::text');
$frames[$table->tablename] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($table->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
}
return $frames;
};
if ($mode === 'read-native-sources') {
$frames = DB::transaction(function () use ($snapshot) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return $snapshot();
});
echo json_encode(['snapshot' => $frames], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'prepare-recovery') {
LedgerSchema::install(DB::connection());
$composition = null;
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
}
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$payload = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->whereKey($payload['actor'])->firstOrFail();
auth()->guard()->setUser($actor);
$request = Requisition::query()->whereKey($payload['request'])->firstOrFail();
$service = app(RequisitionAccountAssignments::class);
$first = $service->save($actor, $request, $payload['input']);
$payload['input']['operation_key'] = (string) Str::uuid();
$payload['input']['version'] = 1;
$payload['input']['reason'] = 'Segunda versão explícita preservada no restauro';
$second = $service->save($actor, $request, $payload['input']);
echo json_encode(['payload' => $payload, 'first' => $first->id, 'second' => $second->id, 'snapshot' => $snapshot(), 'integrated_optional_schema' => $composition], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'verify-recovery') {
$fixture = json_decode($argv[3], true, 64, JSON_THROW_ON_ERROR);
$composition = $fixture['integrated_optional_schema'] ?? null;
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1'
&& (! is_array($composition) || count($composition['migrations'] ?? []) !== 5
|| count($composition['verified_tables'] ?? []) !== 12)) {
throw new RuntimeException('Integrated recovery requires the complete optional schema manifest.');
}
if ($snapshot() !== $fixture['snapshot']) {
throw new RuntimeException('Restored account composition differs in tables, columns or rows.');
}
$payload = $fixture['payload'];
$actor = User::query()->whereKey($payload['actor'])->firstOrFail();
auth()->guard()->setUser($actor);
$request = Requisition::query()->whereKey($payload['request'])->firstOrFail();
$service = app(RequisitionAccountAssignments::class);
$replay = $service->save($actor, $request, $payload['input']);
$frozen = $service->freezeForItems($actor, [$payload['input']['item_id']]);
if ($replay->id !== $fixture['second'] || $frozen[$payload['input']['item_id']]['id'] !== $fixture['second']
|| DB::table('supply_records')->where('kind', 'req_account')->count() !== 2 || $snapshot() !== $fixture['snapshot']) {
throw new RuntimeException('Restored account versions, audited origin or replay changed.');
}
echo json_encode(['tables_equal' => count($fixture['snapshot']), 'versions' => 2, 'audited_account_source_verified' => true,
'replay_without_effects' => true, 'chart_and_native_financial_sources_preserved' => true,
'integrated_optional_schema' => $composition], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if ($mode === 'prepare') {
$f = receiptFixture();
$f['r']->update(['status' => 'draft']);
auth()->guard()->setUser($f['issuer']);
DB::table('gl_accounts')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-RACE-ACCOUNT', 'label' => 'Conta fictícia de concorrência', 'currency' => 'MZN', 'is_movement' => true]);
$space = app(RequisitionAccountAssignments::class)->workspace($f['issuer'], $f['r']);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
echo json_encode(['actor' => $f['issuer']->id, 'tenant' => $f['tenant']->id, 'request' => $f['r']->id, 'fingerprint' => $financial(),
'input' => ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'],
'reason' => 'Imputação explícita num ensaio de contenção real', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
'subtotal' => '100.00', 'total' => '100.00']]]], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'write') {
$payload = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_req_account_'.getmypid()]);
$actor = User::query()->findOrFail($payload['actor']);
auth()->guard()->setUser($actor);
try {
$record = app(RequisitionAccountAssignments::class)->save($actor, Requisition::query()->findOrFail($payload['request']), $payload['input']);
echo json_encode(['status' => 200, 'id' => $record->id]);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()]);
}
exit;
}
if ($mode !== 'race') {
throw new InvalidArgumentException('Unknown QA account mode.');
}
LedgerSchema::install(DB::connection());
foreach (['same_operation', 'same_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$payload = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
DB::beginTransaction();
try {
DB::table('tenants')->where('id', $payload['tenant'])->lockForUpdate()->firstOrFail();
for ($i = 0; $i < 2; $i++) {
$input = $payload;
if ($scenario === 'same_version' && $i === 1) {
$input['input']['operation_key'] = (string) Str::uuid();
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
$deadline = microtime(true) + 10;
do {
DB::select('select pg_stat_clear_snapshot()');
$blocked = (int) DB::selectOne("select count(*) n from pg_stat_activity where datname=? and application_name like 'sgc_req_account_%' and wait_event_type='Lock'", [$database])->n;
if ($blocked === 2) {
break;
}
usleep(50000);
} while (microtime(true) < $deadline);
if ($blocked !== 2) {
throw new RuntimeException('Both account writers must demonstrably wait on the company lock.');
}
DB::commit();
$statuses = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException('Synthetic account writer failed: '.$worker->getErrorOutput());
}
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
}
sort($statuses);
$count = DB::table('supply_records')->where('tenant_id', $payload['tenant'])->where('kind', 'req_account')->count();
$audits = DB::table('audit_logs')->where('tenant_id', $payload['tenant'])->where('action', 'requisition.accounts_assigned')->count();
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $count !== 1 || $audits !== 1 || $financial() !== $payload['fingerprint']) {
throw new RuntimeException('Account contention lost replay/version/source guarantees.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers' => $blocked, 'versions' => $count, 'audits' => $audits, 'financial_sources_unchanged' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if (DB::transactionLevel() > 0) {
DB::rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
@@ -3,6 +3,7 @@
use App\Models\Requisition;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -23,6 +24,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
}
config(['requisition-expiry.qa_enabled' => true]);
$expenses = ($argv[2] ?? '') === 'recover-expenses';
$urgent = ($argv[2] ?? '') === 'recover-urgent';
require_once __DIR__.'/../Support/ReceiptFixture.php';
receiptFixture();
$fingerprint = static function (Connection $connection): array {
@@ -51,7 +53,7 @@ $pg = static function (string $binary, array $arguments) use ($connectionConfig)
$preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
$prepare = new Process([PHP_BINARY, __DIR__.'/requisition-cycle-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __DIR__.'/requisition-cycle-worker.php', $database, 'prepare', ...($urgent ? ['urgent'] : [])], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($input['clock']);
@@ -62,7 +64,7 @@ $workflow = app(RequisitionWorkflow::class);
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
$request->refresh();
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version,
'cost_center_id' => $request->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'cost_center_id' => $request->cost_center_id, 'priority' => $urgent ? 'urgent' : 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'justification' => 'Synthetic revised request retained through recovery',
'items' => [['description' => 'Synthetic revised item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '120.00', 'tax_rate' => '0.00']]], $request);
$submission = (string) Str::uuid();
@@ -105,6 +107,15 @@ try {
|| $restored->table('approval_steps')->where('requisition_id', $request->id)->where('decision', 'expired')->count() !== 1) {
throw new RuntimeException('Restored native expiry/submission replay changed history or reservation.');
}
if ($urgent) {
$deadline = app(RequisitionExpiry::class)->deadline($request->fresh());
if (($deadline['timing'] ?? null) !== 'urgent_override'
|| Carbon::parse($deadline['started_at'])->diffInSeconds(Carbon::parse($deadline['expires_at'])) != 300
|| $request->fresh()->approval_snapshot['approval_expiry']['request_priority'] !== 'urgent') {
throw new RuntimeException('Restored urgent submission lost its explicit frozen timing.');
}
echo json_encode(['urgent_policy_frozen_restored' => true, 'urgent_expire_seconds_restored' => 300], JSON_THROW_ON_ERROR).PHP_EOL;
}
if ($expenses) {
$expenseActor = User::query()->whereKey($expenseFixture['f']['validator']->id)->firstOrFail();
auth()->guard()->setUser($expenseActor);
@@ -95,6 +95,7 @@ if ($mode === 'legacy-cycles') {
}
if ($mode === 'prepare') {
$urgent = ($argv[3] ?? '') === 'urgent';
if (! $db->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
@@ -107,16 +108,17 @@ if ($mode === 'prepare') {
Budget::query()->create(['tenant_id' => $owner->tenant_id, 'cost_center_id' => $f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating',
'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Synthetic concurrent cycle budget', 'created_by' => $admin->id, 'approved_by' => $finance->id]);
app(RequisitionExpiry::class)->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []]],
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => [],
...($urgent ? ['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => null, 'urgent_escalation_minutes' => null] : [])]],
'reason' => 'Explicit synthetic concurrent expiry policy']);
auth()->guard()->setUser($owner);
$workflow = app(RequisitionWorkflow::class);
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => $urgent ? 'urgent' : 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic simultaneous expiry and decision',
'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
Carbon::setTestNow(now()->addMinutes(31));
Carbon::setTestNow(now()->addMinutes($urgent ? 6 : 31));
echo json_encode(['tenant' => $owner->tenant_id, 'owner' => $owner->id, 'head' => $head->id, 'request' => $request->id,
'version' => $request->process_version, 'clock' => now()->toIso8601String(),
'basis' => app(RequisitionExpiry::class)->deadline($request)['basis_hash'], 'operation' => (string) Str::uuid()], JSON_THROW_ON_ERROR);
+77 -1
View File
@@ -7,6 +7,26 @@ use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
function auditMetadataRows(string $csv): array
{
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new LogicException('Synthetic CSV stream unavailable.');
}
try {
fwrite($stream, $csv);
rewind($stream);
$rows = [];
while (($row = fgetcsv($stream, 0, ';', '"', '')) !== false) {
$rows[] = $row;
}
return array_slice($rows, 2);
} finally {
fclose($stream);
}
}
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
@@ -35,7 +55,8 @@ test('audit metadata block exports the complete filtered scope independently of
$query = '?action=people.selected&actor_id='.$this->f['receiver']->id.'&from=2026-11-01&to=2026-11-01';
$this->get('/auditoria/eventos'.$query)->assertOk()->assertInertia(fn (Assert $p) => $p->where('events.total', 10));
$csv = $this->get('/auditoria/eventos.csv'.$query.'&page=2')->assertOk()->streamedContent();
expect(substr_count($csv, 'people.selected'))->toBe(10)->and($csv)->not->toContain('receipt.confirmed', 'PRIVATE-BEFORE', 'PRIVATE-AFTER');
expect(array_count_values(array_column(auditMetadataRows($csv), 2))['people.selected'])->toBe(10)
->and($csv)->not->toContain('receipt.confirmed', 'PRIVATE-BEFORE', 'PRIVATE-AFTER');
$this->get('/auditoria/eventos?to=2026-11-01')->assertOk();
$this->getJson('/auditoria/eventos?from=2026-11-02&to=2026-11-01')->assertUnprocessable();
DB::table('audit_logs')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id, 'action' => '=1+1', 'created_at' => now(), 'after' => '{}']);
@@ -76,3 +97,58 @@ test('audit metadata block isolates companies and adds no grants or audit events
}
expect(array_key_exists('audit_metadata_read', OrganizationAccess::PERMISSIONS))->toBeTrue();
});
test('auditor investigates one exact request across pages exports the full same scope and opens only an independently visible process', function () {
$own = $this->f;
$source = $own['r'];
$source->update(['number' => 'QA%_AUDIT-REQUEST']);
foreach (range(1, 131) as $index) {
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $source->id, 'user_id' => $own['receiver']->id,
'action' => 'requisition.synthetic_checked', 'created_at' => '2026-11-01 12:00:00',
'before' => json_encode(['private' => 'PRIVATE-BEFORE']), 'after' => json_encode(['private' => 'PRIVATE-AFTER'])]);
}
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $source->id, 'user_id' => $own['receiver']->id,
'action' => 'requisition.synthetic_checked', 'created_at' => '2026-10-31 12:00:00', 'after' => '{}']);
$foreign = receiptFixture();
$foreign['r']->update(['number' => 'FOREIGN-AUDIT-ONLY']);
// Deliberately malformed synthetic linkage must not expose another company's request through an own-tenant event.
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $foreign['r']->id, 'user_id' => $own['receiver']->id,
'action' => 'malformed.foreign_link', 'created_at' => '2026-11-01 12:00:00', 'after' => '{}']);
$this->actingAs($own['receiver']);
$query = '?request_reference='.urlencode($source->number).'&action=requisition.synthetic_checked&actor_id='.$own['receiver']->id.'&from=2026-11-01&to=2026-11-01';
$before = [];
foreach (['audit_logs', 'requisitions', 'users', 'organization_profiles', 'organization_memberships', 'budget_entries', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/auditoria/eventos'.$query)->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->where('events.total', 131)->has('events.data', 25)
->where('requestContext', null)->missing('events.data.0.before')->missing('events.data.0.after'));
$this->get('/auditoria/eventos'.$query.'&page=2')->assertInertia(fn (Assert $page) => $page->where('events.current_page', 2)->has('events.data', 25));
$csv = $this->get('/auditoria/eventos.csv'.$query.'&page=6')->assertOk()->streamedContent();
expect(auditMetadataRows($csv))->toHaveCount(131)
->and(array_unique(array_column(auditMetadataRows($csv), 2)))->toBe(['requisition.synthetic_checked'])
->and($csv)->toContain('QA%_AUDIT-REQUEST', '2026-11-01')->not->toContain('PRIVATE-BEFORE', 'PRIVATE-AFTER');
$this->get('/requisicoes/'.$source->id)->assertNotFound();
foreach (['FOREIGN-AUDIT-ONLY', 'QA', '0'] as $unknown) {
$this->get('/auditoria/eventos?request_reference='.urlencode($unknown))->assertInertia(fn (Assert $page) => $page
->where('events.total', 0)->where('requestContext', null));
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$auditProfile = DB::table('organization_memberships')->where('user_id', $own['receiver']->id)->value('profile_id');
supplyGrant($own['receiver'], ['finance']);
$this->get('/auditoria/eventos'.$query)->assertInertia(fn (Assert $page) => $page
->where('requestContext.number', $source->number)->where('requestContext.href', '/requisicoes/'.$source->id.'#requisition-history'));
$this->get('/requisicoes/'.$source->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canReadAuditMetadata', true));
DB::table('organization_memberships')->where('user_id', $own['receiver']->id)->where('profile_id', $auditProfile)->update(['expires_at' => now()->subSecond()]);
$this->get('/requisicoes/'.$source->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canReadAuditMetadata', false));
$this->get('/auditoria/eventos'.$query)->assertForbidden();
});
test('literal zero action remains an exact audit filter and malformed references are refused', function () {
DB::table('audit_logs')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id, 'action' => '0', 'created_at' => now(), 'after' => '{}']);
$this->get('/auditoria/eventos?action=0')->assertInertia(fn (Assert $page) => $page->where('events.total', 1)->where('events.data.0.action', '0'));
$this->getJson('/auditoria/eventos?request_reference='.str_repeat('x', 101))->assertUnprocessable();
$this->getJson('/auditoria/eventos?request_reference[]=QA')->assertUnprocessable();
});
+19
View File
@@ -70,6 +70,25 @@ test('asset references reuse a physical equipment identity and reject duplicate
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => ['invalid']]))->toThrow(ValidationException::class);
});
test('equipment backlink revalidates current register access without exposing a reference after revocation', function () {
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(),
'code' => 'LINK-QA', 'name' => 'Ensaio de ligação', 'criteria' => 'Dados sintéticos', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id,
'code' => 'EQ-LINK-QA', 'description' => 'Identidade sintética de equipamento', 'area' => 'Ensaio', 'status' => 'active',
'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
$service = app(CapitalRegister::class);
$source = $service->save($this->f['issuer'], [...$this->input, 'type' => 'asset', 'code' => 'ASSET-LINK-QA', 'equipment_id' => $equipment->id]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment)['record_key'])->toBe($source->record_key);
supplyGrant($this->f['issuer'], ['admin']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => true]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => false]);
DB::table('organization_profiles')->where('tenant_id', $this->f['tenant']->id)->update(['permissions' => json_encode(['requester'])]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
auth()->logout();
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
});
test('native register page is encrypted private paginated and gated off outside QA', function () {
app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$this->get('/projectos-imobilizado')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
+14
View File
@@ -77,6 +77,20 @@ test('corrections append history preserve the original assertion and reject stal
$this->get('/conflitos/'.$original->id)->assertInertia(fn (Assert $page) => $page->has('history', 3));
});
test('personal conflict consultation protects browser history and cache without changing declarations or audit', function () {
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
$declaration = ConflictDeclaration::query()->firstOrFail();
$before = ConflictDeclaration::query()->get()->toArray();
$audit = AuditLog::query()->get()->toArray();
foreach (['/conflitos', '/conflitos/'.$declaration->id] as $url) {
$response = $this->get($url)->assertOk();
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
}
expect(ConflictDeclaration::query()->get()->toArray())->toBe($before)
->and(AuditLog::query()->get()->toArray())->toBe($audit);
});
test('corrections cannot remove conflicts change scope author or company', function (string $field, mixed $value) {
$this->post('/conflitos', personalConflict($this->supplier->id));
$declaration = ConflictDeclaration::query()->firstOrFail();
+12
View File
@@ -205,6 +205,18 @@ test('catalogue requires explicit minimum and supports optimistic audited update
$this->postJson('/equipamentos/pecas', $payload)->assertUnprocessable()->assertJsonValidationErrors('version');
});
test('equipment preparation consultation protects browser history without catalogue or stock writes', function () {
$before = [];
foreach (['equipment', 'spare_parts', 'equipment_spare_parts', 'stock_operations', 'stock_movements', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->map(fn (object $row) => (array) $row)->all();
}
$response = $this->get('/equipamentos')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->map(fn (object $row) => (array) $row)->all())->toBe($rows);
}
});
test('warehouse stock drives minimum alert without duplicate inventory balances', function () {
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->get('/equipamentos')->assertInertia(fn (Assert $p) => $p->component('equipment/index')->where('parts.0.balance_milli', 1000)->where('parts.0.below_minimum', true));
+50
View File
@@ -12,6 +12,8 @@ use App\Services\ImportLandedCosts;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\ImportTariffCodes;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionSubmissionPreview;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Database\Eloquent\ModelNotFoundException;
@@ -22,6 +24,7 @@ use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -153,6 +156,11 @@ test('native submission approves the full estimate reserves goods and extras onc
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000];
$estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
$workflow = app(RequisitionWorkflow::class);
$preview = app(RequisitionSubmissionPreview::class)->for($this->f['issuer'], $this->draft->fresh());
expect($preview['state'])->toBe('planned')->and($preview['total_minor'])->toBe('10000')
->and($preview['approval_amount_minor'])->toBe('11000')->and($preview['import_basis'])->toBeTrue()
->and(array_column($preview['steps'], 'role'))->toBe(['department_head', 'procurement', 'finance'])
->and(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0);
$workflow->submit($this->f['issuer'], $this->draft);
$submitted = $this->draft->fresh();
expect($submitted->status)->toBe('pending')->and($submitted->total_minor)->toBe(10000)
@@ -171,6 +179,48 @@ test('native submission approves the full estimate reserves goods and extras onc
->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0);
});
test('expired import cycle preserves its actual landed estimate routing amount in historical consultation', function () {
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
$this->markTestSkipped('Authorised cycle composition required.');
}
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
config(['requisition-expiry.qa_enabled' => true]);
$this->f['tenant']->update(['first_limit_minor' => 10500, 'second_limit_minor' => 10800]);
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($admin);
$expiry = app(RequisitionExpiry::class);
$expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []]],
'reason' => 'Synthetic explicit deadline for historical import estimate consultation']);
$this->actingAs($this->f['issuer']);
$input = $this->input;
foreach ($input['components'] as &$component) {
$component['status'] = 'not_applicable';
}
unset($component);
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000];
app(ImportEstimates::class)->save($this->f['issuer'], $this->draft->fresh(), $input);
$workflow = app(RequisitionWorkflow::class);
$request = $this->draft->fresh();
$workflow->submit($this->f['issuer'], $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->travel(31)->minutes();
$deadline = $expiry->deadline($request);
$workflow->expire($this->f['issuer'], $request, $deadline['basis_hash'], (string) Str::uuid(), $request->process_version);
$before = [];
foreach (['budget_entries', 'budget_landed_entries', 'budget_requisition_cycles', 'supply_records', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page
->where('requisition.approval_cycle', 2)->where('history.data.0.request.total_minor', 10000)
->where('history.data.0.approval_amount_minor', 11000)->where('history.data.0.approval_uses_separate_basis', true)
->where('history.data.0.rules.first_limit_minor', 10500)->has('history.data.0.steps', 3));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('unknown or stale estimate prevents native submission without partial reservations or approval steps', function () {
app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $this->input);
try {
+25 -4
View File
@@ -24,14 +24,27 @@ use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
beforeEach(function () {
if (! class_exists(BudgetLandedCostPlan::class)) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
$source = requisitionLedgerQaSource();
if ($source === null) {
throw new LogicException('Integrated import costs require the dedicated actual-ledger QA runner.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
expect($composition['verified_tables'])->toHaveCount(12);
}
config(['import-landed-costs.qa_enabled' => true]);
Storage::fake('local');
$this->f = receiptFixture();
@@ -94,7 +107,9 @@ test('technical inspection detects private import evidence loss alteration and o
});
test('cost to item references are frozen in reviewed preparations without stock valuation or financial effects', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$selection = [...importCostSelection($this, $document), 'item_references' => [
@@ -299,7 +314,9 @@ test('a documentary correction preserves both original bytes and values and inva
});
test('the native independently reviewed cost plan reserves commits and consumes the additional origin once', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
@@ -344,7 +361,9 @@ function approvedImportCostPreparation(object $test): array
}
test('logistics progression does not revoke a reviewed cost preparation or require another financial approval', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
[, $approved] = approvedImportCostPreparation($this);
$service = app(ImportLandedCosts::class);
$service->financial($this->finance, $this->import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0,
@@ -362,7 +381,9 @@ test('logistics progression does not revoke a reviewed cost preparation or requi
});
test('a failed native financial receipt rolls back the common journal and its audit together', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
[, $approved] = approvedImportCostPreparation($this);
if (DB::getDriverName() === 'pgsql') {
DB::unprepared("CREATE FUNCTION reject_synthetic_import_cost_receipt() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.kind = 'import_cost_event' THEN RAISE EXCEPTION 'Synthetic receipt failure'; END IF; RETURN NEW; END $$;
+12
View File
@@ -1,5 +1,6 @@
<?php
use App\Models\Requisition;
use App\Models\StockMovement;
use App\Models\StockOperation;
use App\Models\SupplyRecord;
@@ -10,6 +11,7 @@ use App\Services\InventoryDispositions;
use App\Services\InventoryLots;
use App\Services\InventoryReversals;
use App\Services\InvoiceWorkflow;
use App\Services\ProcurementDeliveryInsights;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\StockWorkflow;
@@ -17,6 +19,7 @@ use App\Services\SupplyCoordination;
use App\Services\SupplyHistory;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -128,7 +131,14 @@ test('a reversal outside a closed history period invalidates its signature and c
});
test('receipt reversal restores authorised quantities without deleting acceptance and a new correction receipt is not a duplicate', function () {
supplyGrant($this->f['issuer'], ['procurement']);
$delivery = fn () => app(ProcurementDeliveryInsights::class)->build($this->f['issuer'], Requisition::query()->whereKey($this->f['r']->id),
CarbonImmutable::now(), null, 'all');
$this->actingAs($this->f['issuer']);
expect($delivery()['unverified_receipt_lines'])->toBe(0);
$executed = executeReversal($this, approvedReversal($this, ['source_kind' => 'receipt', 'receipt_item_id' => $this->receiptItem->id]));
$this->actingAs($this->f['issuer']);
expect($delivery()['unverified_receipt_lines'])->toBe(0);
expect(app(ReceiptWorkflow::class)->recordedQuantity($this->f['line']->id, 'received_milli'))->toBe(0)
->and(app(ReceiptWorkflow::class)->recordedQuantity($this->f['line']->id, 'accepted_milli'))->toBe(0)
->and($this->receiptItem->fresh()->accepted_milli)->toBe(10000)
@@ -140,6 +150,8 @@ test('receipt reversal restores authorised quantities without deleting acceptanc
expect(app(ReceiptWorkflow::class)->recordedQuantity($this->f['line']->id, 'accepted_milli'))->toBe(10000)
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(10000)
->and($executed->snapshot['source']['receipt']['accepted_milli'])->toBe(10000);
$this->actingAs($this->f['issuer']);
expect($delivery()['unverified_receipt_lines'])->toBe(0);
});
test('receipt line reversal removes the full documentary quantities but only the accepted physical entry', function () {
+12
View File
@@ -48,6 +48,18 @@ test('policy author cannot approve own proposal', function () {
$this->post('/regras-investimento/'.$policy->id.'/decidir', ['decision' => 'approved', 'reason' => 'Teste'])->assertForbidden();
});
test('investment preparation consultation keeps policy and reviews private without publishing or changing them', function () {
$policy = proposeInvestmentTest($this);
$before = InvestmentPolicy::query()->get()->toArray();
$reviews = InvestmentPolicyReview::query()->get()->toArray();
$response = $this->get('/regras-investimento')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true && $page['props']['canManage'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
$this->actingAs($this->f['issuer'])->get('/regras-investimento')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['canManage'] === false);
expect(InvestmentPolicy::query()->get()->toArray())->toBe($before)
->and(InvestmentPolicyReview::query()->get()->toArray())->toBe($reviews)
->and($policy->fresh()->status)->toBe('pending');
});
test('policy parameters and decisions cannot be rewritten', function () {
$policy = proposeInvestmentTest($this);
expect(fn () => $policy->update(['ceiling_minor' => 1]))->toThrow(LogicException::class);
@@ -49,6 +49,27 @@ afterEach(function () {
}
});
test('company preparation and bootstrap protect history without configuration or access writes', function () {
DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->update(['active' => false]);
$legacyAdmin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['r']->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$starter = User::factory()->create(['tenant_id' => null, 'department_id' => null, 'purchasing_role' => PurchasingRole::Requester]);
$tables = ['tenants', 'departments', 'cost_centers', 'users', 'organization_profiles', 'organization_memberships', 'organization_access', 'audit_logs'];
$snapshot = static function () use ($tables): array {
$frames = [];
foreach ($tables as $table) {
$frames[$table] = DB::table($table)->get()->map(fn (object $row) => json_encode((array) $row, JSON_THROW_ON_ERROR))->sort()->values()->all();
}
return $frames;
};
$before = $snapshot();
foreach ([[$legacyAdmin, '/empresa', 'company/index'], [$starter, '/empresa/iniciar', 'company/setup']] as [$actor, $url, $component]) {
$response = $this->actingAs($actor)->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === $component && $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
}
expect($snapshot())->toBe($before);
});
test('intelligence settings are independently configurable audited and scoped without rewriting processes', function () {
if (DB::getDriverName() === 'pgsql') {
// The real report opens its own read-only snapshot, outside the test wrapper.
+2 -1
View File
@@ -52,7 +52,8 @@ test('contract report preserves unknown legacy associations without writes and e
$this->withoutVite();
$before = [DB::table('purchase_orders')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page->where('contractInsights.coverage.unknown', 1)
->where('contractInsights.coverage.without_contract', 0)->where('contractInsights.currencies.0.amount_minor', '10000'));
->where('contractInsights.coverage.without_contract', 0)->where('contractInsights.currencies.0.amount_minor', '10000')
->where('deliveryInsights.coverage.unknown', 1)->where('deliveryInsights.records.data.0.late_days', null));
$csv = $this->get('/relatorios/contratos.csv')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain('"Associação por determinar";MZN;1;10000')->toContain('não pagamentos')
->and([DB::table('purchase_orders')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
+77
View File
@@ -8,11 +8,13 @@ use App\Models\GoodsReceipt;
use App\Models\Invoice;
use App\Models\Supplier;
use App\Models\User;
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 () {
// The new page is built privately; HTTP scope tests must not require publishing it to the pilot.
@@ -21,6 +23,81 @@ beforeEach(function () {
$this->actingAs($this->f['issuer']);
});
test('global supply search returns only current native agreement and contract references with no private payload or writes', function () {
config(['procurement_search.supply_metadata_enabled' => true, 'agreement_order_limits.qa_enabled' => true]);
supplyGrant($this->f['issuer'], ['supply_prepare']);
$planning = app(SupplyPlanning::class);
$agreement = $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()->addYear()->toDateString(), 'origin' => 'local', 'currency' => 'MZN',
'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'SEARCH-AGREEMENT-OLD']));
$current = $planning->save($this->f['issuer'], 'agreement', supplyInput([...$agreement->data,
'reference' => 'SEARCH-AGREEMENT-NEW'], 'save', $agreement));
$contract = $planning->save($this->f['issuer'], 'contract', supplyInput([
'supplier_id' => $this->f['order']->supplier_id, 'reference' => 'SEARCH-CONTRACT', 'currency' => 'MZN',
'valid_from' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString(),
'periodicity_days' => 30, 'order_limit_amount' => '100.00', 'lead_days' => 3]));
$supplierName = $contract->snapshot['supplier']['name'];
Supplier::query()->findOrFail($this->f['order']->supplier_id)->update(['name' => 'Later supplier name, outside original reference']);
$before = [];
foreach (['supply_records', 'audit_logs', 'requisitions', 'purchase_orders', 'invoices', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/compras/pesquisa?q=SEARCH-')->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)->assertInertia(fn (Assert $page) => $page
->where('supplySearchAvailable', true)->has('groups', 3)
->where('groups.1.records.total', 1)->where('groups.1.records.data.0.id', $current->id)
->where('groups.1.records.data.0.title', 'SEARCH-AGREEMENT-NEW · v2')
->where('groups.1.records.data.0.href', '/compras/fornecimento?view=agreements&record_id='.$current->id.'#supply-record-'.$current->id)
->where('groups.2.records.data.0.id', $contract->id)->missing('groups.2.records.data.0.data')
->missing('groups.2.records.data.0.price_minor')->missing('groups.2.records.data.0.snapshot'));
$this->get('/compras/pesquisa?q=SEARCH-AGREEMENT-OLD')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 0));
$this->get('/compras/pesquisa?q='.urlencode($supplierName))->assertInertia(fn (Assert $page) => $page
->where('groups.1.records.total', 1)->where('groups.2.records.total', 1));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->get('/compras/fornecimento?view=agreements&record_id='.$current->id)->assertOk();
$this->get('/compras/fornecimento?view=contracts&record_id='.$contract->id)->assertOk();
config(['procurement_search.supply_metadata_enabled' => false]);
$this->get('/compras/pesquisa?q=SEARCH-')->assertInertia(fn (Assert $page) => $page->where('supplySearchAvailable', false)->has('groups', 1));
});
test('supply search preserves native isolation literal matching pagination and current access', function () {
config(['procurement_search.supply_metadata_enabled' => true]);
$own = $this->f;
supplyGrant($own['issuer'], ['supply_read', 'supply_prepare']);
$planning = app(SupplyPlanning::class);
$input = ['stock_item_id' => $own['stock']->id, 'warehouse_id' => $own['warehouse']->id,
'supplier_id' => $own['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(),
'valid_until' => today()->addYear()->toDateString(), 'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4];
foreach (range(1, 17) as $index) {
$planning->save($own['issuer'], 'agreement', supplyInput([...$input, 'reference' => 'SUPPLY-PAGE-'.$index]));
}
$literal = $planning->save($own['issuer'], 'agreement', supplyInput([...$input, 'reference' => 'LITERAL%_SUPPLY']));
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['supply_prepare']);
$this->actingAs($foreign['issuer']);
$planning->save($foreign['issuer'], 'agreement', supplyInput([...$input,
'stock_item_id' => $foreign['stock']->id, 'warehouse_id' => $foreign['warehouse']->id,
'supplier_id' => $foreign['order']->supplier_id, 'reference' => 'SUPPLY-PAGE-FOREIGN']));
$this->actingAs($own['issuer'])->get('/compras/pesquisa?q=SUPPLY-PAGE&agreements_page=2')->assertOk()
->assertInertia(fn (Assert $page) => $page->has('groups', 2)->where('groups.1.records.total', 17)
->where('groups.1.records.current_page', 2)->has('groups.1.records.data', 2));
$this->get('/compras/pesquisa?q='.urlencode('%_'))->assertInertia(fn (Assert $page) => $page
->where('groups.1.records.total', 1)->where('groups.1.records.data.0.id', $literal->id));
$this->get('/compras/pesquisa?q=SUPPLY-PAGE&agreements_page=0')->assertSessionHasErrors('agreements_page');
$this->get('/compras/pesquisa?q=SUPPLY-PAGE&contracts_page=0')->assertSessionHasErrors('contracts_page');
$requester = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id,
'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($requester, ['requester']);
$this->actingAs($requester)->get('/compras/pesquisa?q=SUPPLY-PAGE')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('supplySearchAvailable', false)->has('groups', 1));
$this->actingAs($own['issuer']);
DB::table('organization_memberships')->where('user_id', $own['issuer']->id)->update(['expires_at' => now()->subSecond()]);
$this->get('/compras/pesquisa?q=SUPPLY-PAGE')->assertForbidden();
});
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);
+220 -23
View File
@@ -47,6 +47,7 @@ use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementContractInsights;
use App\Services\ProcurementDeliveryInsights;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
@@ -56,12 +57,14 @@ use App\Services\PurchaseRevisionWorkflow;
use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -69,16 +72,17 @@ use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
function nativeCapitalAssignment(object $test): array
function nativeCapitalAssignment(object $test, string $type = 'project'): array
{
config(['capital-register.qa_enabled' => true]);
$test->actingAs($test->buyer);
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => $type,
'code' => 'PRJ-NATIVE-QA', 'name' => 'Projecto sintético da ordem', 'department_id' => $test->department->id,
'equipment_id' => null, 'reference' => 'Documento sintético de investimento', 'state' => 'active', 'reason' => 'Cadastro estritamente sintético da ligação à ordem'];
$source = app(CapitalRegister::class)->save($test->buyer, $input);
@@ -121,6 +125,45 @@ test('native order preserves the capital destination and print after the indepen
expect(DB::table('stock_movements')->get()->toJson())->toBe($before);
});
test('native frozen asset origin connects later equipment registration to its actual order and receipt', function () {
[$source, $assignment, $input] = nativeCapitalAssignment($this, 'asset');
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
expect($order->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'ASSET-QA', 'name' => 'Armazém sintético']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'ASSET-QA', 'name' => 'Artigo sintético', 'unit' => 'un']);
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'ASSET-LATE-LINK-QA',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
$this->actingAs($this->buyer);
$level = CriticalityLevel::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'created_at' => now(),
'code' => 'ASSET-QA', 'name' => 'Criticidade de ensaio', 'criteria' => 'Registo exclusivamente sintético', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'department_id' => $this->department->id,
'code' => 'EQ-LATE-QA', 'description' => 'Equipamento registado após recepção sintética', 'area' => 'Área de ensaio', 'status' => 'active', 'criticality_level_id' => $level->id]);
app(CapitalRegister::class)->save($this->buyer, [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $source->record_key,
'version' => 1, 'equipment_id' => $equipment->id, 'name' => 'Referência actual do activo', 'state' => 'archived']);
$before = [];
foreach (['purchase_orders', 'purchase_order_items', 'goods_receipts', 'goods_receipt_items', 'budget_entries', 'stock_movements', 'audit_logs', 'supply_records'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->withoutVite();
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->where('capitalReference.record_key', $source->record_key)->where('capitalReference.version', 2)
->where('capitalReference.state', 'archived')->missing('capitalReference.reason')->missing('capitalReference.snapshot'));
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('trace.orders.data.0.order_number', $order->number)->where('trace.receipts.data.0.receipt_id', $receipt->id));
expect($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['version'])->toBe(1)
->and($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
config(['capital-register.qa_enabled' => false]);
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('capitalReference', null));
$other = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outra área QA'])->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($other)->get('/equipamentos/'.$equipment->id)->assertNotFound();
});
test('native partial order freezes the same explicit capital origin without changing its financial allocation', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
@@ -815,6 +858,18 @@ function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bo
}
beforeEach(function () {
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
$source = requisitionLedgerQaSource();
if ($source === null) {
throw new LogicException('Integrated orders require the dedicated actual-ledger QA runner.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
expect($composition['verified_tables'])->toHaveCount(12);
}
$this->tenant = Tenant::query()->create(['name' => 'Empresa das ordens']);
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Produção']);
$center = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'PROD', 'name' => 'Produção']);
@@ -880,6 +935,89 @@ test('discount evidence and net prices survive award order and printable report'
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('20.00%');
});
test('native order preserves common ledger account references without creating a journal or changing the chart', function () {
$source = getenv('RQ01_LEDGER_QA_SOURCE');
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
$this->markTestSkipped('Dedicated real common-ledger QA schema required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
config(['requisition-accounts.qa_enabled' => true]);
$id = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->tenant->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-NATIVE-ACCOUNT', 'label' => 'Conta fictícia da necessidade', 'currency' => 'MZN', 'is_movement' => true]);
$this->r->update(['status' => 'draft']);
$this->actingAs($this->owner);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->owner, $this->r);
$record = $service->save($this->owner, $this->r, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Referência contabilística da necessidade sintética',
'allocations' => [['account_id' => $id, 'source_hash' => $space['accounts']['data'][0]['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]]);
$this->r->update(['status' => 'approved']);
$before = DB::table('gl_accounts')->get()->toJson();
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['account_assignments'][$this->item->id]['id'])->toBe($record->id)
->and($order->snapshot['account_assignments'][$this->item->id]['data']['allocations'][0]['account']['code'])->toBe('QA-NATIVE-ACCOUNT')
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_accounts')->get()->toJson())->toBe($before);
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()
->assertSee('QA-NATIVE-ACCOUNT')->assertSee('Parcelas originais');
});
test('native order preserves common ledger across partial and consolidated origins', function (string $mode) {
$source = getenv('RQ01_LEDGER_QA_SOURCE');
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Dedicated common ledger and authorised order-parts QA composition required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
config(['requisition-accounts.qa_enabled' => true]);
DB::table('gl_accounts')->insert(['tenant_id' => $this->tenant->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-ORIGINS-ACCOUNT', 'label' => 'Conta fictícia das origens', 'currency' => 'MZN', 'is_movement' => true]);
$firstAward = nativeOrderPartsAward($this);
$requests = [$this->r];
$secondAward = null;
if ($mode === 'consolidated') {
[$second, $quotes] = secondNativeOrderPartsOrigin($this);
$secondAward = nativeOrderPartsAward($this, $second, $quotes[0]);
$requests[] = $second;
}
$records = [];
foreach ($requests as $request) {
$request->refresh()->update(['status' => 'draft']);
$this->actingAs($this->owner);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->owner, $request);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
$records[$line['id']] = $service->save($this->owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação original explícita no ensaio das origens',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
'subtotal' => (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2), 'total' => (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2)]]]);
$request->update(['status' => 'approved']);
}
$this->actingAs($this->buyer);
$flow = app(OrderPartsWorkflow::class);
if ($secondAward === null) {
$orders = [$flow->issue($this->buyer, nativeOrderPartsInput($this, $firstAward, '0.400', 0)),
$flow->issue($this->buyer, nativeOrderPartsInput($this, $firstAward, '0.600', 1))];
} else {
$a = nativeOrderPartsInput($this, $firstAward, '1.000', 0);
$b = nativeOrderPartsInput($this, $secondAward, '1.000', 0);
$input = [...$a, 'sources' => [...$a['sources'], ...$b['sources']], 'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]];
$input['fingerprint'] = app(OrderPartsPreparation::class)->prepare($this->buyer, $input)['fingerprint'];
$orders = [$flow->issue($this->buyer, $input)];
}
foreach ($orders as $order) {
expect($order->snapshot['account_assignments'])->toHaveCount(count($records));
foreach ($records as $line => $record) {
expect($order->snapshot['account_assignments'][$line]['id'])->toBe($record->id)
->and($order->snapshot['account_assignments'][$line]['data']['allocations'])->toBe($record->data['allocations']);
}
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('QA-ORIGINS-ACCOUNT')->assertSee('Parcelas originais');
}
expect(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_accounts')->count())->toBe(1);
})->with(['partial', 'consolidated']);
test('comparison rule is printed with the order and policy tampering invalidates an approved award', function () {
$policy = [...ComparisonPolicy::DEFAULTS, 'revision' => 1, 'configured' => true];
$this->r->update(['comparison_policy' => $policy]);
@@ -964,12 +1102,25 @@ test('invalid source policy approval or unsupported purchase type cannot be pres
$this->r->update(['approval_snapshot' => null]);
} elseif ($change === 'approval') {
$this->r->steps()->update(['decision' => 'pending']);
} elseif (in_array($change, ['additional', 'routing'], true)) {
// Deliberately inconsistent synthetic history: a frozen level without its decision.
$this->r->update(['approval_snapshot' => [...$this->r->approval_snapshot,
'additional_levels' => ['configured_1' => ['name' => 'Synthetic missing level', 'profile_ids' => [1], 'scope' => 'company']]]]);
if ($change === 'routing') {
$this->r->steps()->create(['tenant_id' => $this->tenant->id, 'position' => $this->r->steps()->count() + 1,
'role' => 'configured_1', 'decision' => 'approved', 'approver_id' => $this->finance->id, 'decided_at' => now(),
'routing' => ['name' => 'Mismatched synthetic routing', 'profile_ids' => [2], 'scope' => 'company']]);
}
} elseif ($change === 'approval_basis') {
// A frozen landed-cost basis cannot be replaced by the lower goods-only amount.
$this->r->update(['approval_snapshot' => [...$this->r->approval_snapshot,
'approval_basis' => ['subtotal_minor' => 1000000000, 'total_minor' => 1000000000]]]);
} else {
$this->item->update(['purchase_type' => $change]);
}
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors($error);
expect(PurchaseAward::query()->count())->toBe(0);
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['additional', 'approvals'], ['routing', 'approvals'], ['approval_basis', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
test('award approvals enforce role order department distinct people and no self approval', function () {
awardPrices($this, 15000001);
@@ -1630,6 +1781,48 @@ function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quant
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('budget consultations use the common balance and protect private history without source writes', function () {
$this->withoutVite();
$centre = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id,
'code' => 'BUD-PRIV-QA', 'name' => 'Synthetic private budget view']);
$this->actingAs($this->finance);
$budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Explicit synthetic budget for private native read regression']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($budget);
$tables = ['budgets', 'budget_entries', 'budget_consumptions', 'audit_logs'];
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
$before = $snapshot();
$response = $this->actingAs($this->finance)->get('/orcamentos')->assertOk()
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('budgets/index')->where('budgets.0.id', $budget)->where('budgets.0.available_minor', 100000));
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store');
$this->actingAs($this->owner)->getJson('/orcamentos')->assertForbidden();
expect($snapshot())->toBe($before);
});
test('purchase control preparations retain native scope encrypted history and private headers without source writes', function () {
$this->withoutVite();
$this->actingAs($this->admin);
app(PurchaseControlPolicyWorkflow::class)->propose($this->admin, ['previous_id' => 0, 'mode' => 'unissued_award',
'enabled' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'reason' => 'Pending disabled synthetic proposal exists before comparing operational and requester visibility']);
$tables = ['requisitions', 'purchase_awards', 'purchase_control_policies', 'purchase_control_reviews', 'award_cancellations',
'purchase_revisions', 'audit_logs', 'budget_entries', 'stock_movements'];
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
$before = $snapshot();
$response = $this->actingAs($this->admin)->get('/revisao-compras')->assertOk()
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('purchase-controls/index')->where('actorId', $this->admin->id)
->has('policies', 1)->where('policies.0.status', 'pending')->where('policies.0.enabled', false));
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store');
$response = $this->actingAs($this->owner)->get('/revisao-compras')->assertOk()
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->where('actorId', $this->owner->id)->has('policies', 0)->has('awards', 0)->has('cancellations', 0));
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store')
->and($snapshot())->toBe($before);
});
test('native partial-order foreign receipts and invoices preserve origin rates and cumulative remainders', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
@@ -1813,10 +2006,12 @@ test('native partial-order issuance commits only forty then sixty and preserves
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
$this->markTestSkipped('Explicit cycle-capable common QA source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
config(['requisition-expiry.qa_enabled' => true]);
$engine = app(CommonBudget::class)->for($this->buyer, [$this->r->id => 1]);
$engine->beginRequisitionCycle($this->r->id, 1, (string) Str::uuid());
@@ -1935,13 +2130,13 @@ function commitNativeReviewReportFixture(object $test): void
$test->committedConsolidatedReportFixture = true;
}
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function () {
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function (bool $afterDue) {
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
$service = app(\App\Services\ProcurementDeliveryInsights::class);
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), \Carbon\CarbonImmutable::now(), null, 'all');
$service = app(ProcurementDeliveryInsights::class);
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), CarbonImmutable::now(), null, 'all');
expect($read()['coverage']['pending'])->toBe(1);
$due = \Carbon\CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
$due = CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
$this->travelTo($due);
expect($read()['coverage']['pending'])->toBe(1);
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
@@ -1952,27 +2147,29 @@ test('native delivery analysis follows the frozen promise partial receipts and a
'received_quantity' => $quantity, 'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.400'));
$this->travel(1)->days();
$this->travel($afterDue ? 1 : 0)->days();
$this->actingAs($this->buyer);
$late = $read();
expect($late['coverage']['pending_late'])->toBe(1)->and($late['records']['data'][0]['late_days'])->toBe(1)
->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
expect($late['coverage'][$afterDue ? 'pending_late' : 'pending'])->toBe(1);
if ($afterDue) {
expect($late['records']['data'][0]['late_days'])->toBe(1)->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
}
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.600'));
$this->actingAs($this->buyer);
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$complete = $read();
expect($complete['coverage']['completed_late'])->toBe(1)->and($complete['pending_lines'])->toBe(0)
->and($complete['records']['data'][0]['late_lines'][0]['completed_on'])->toBe(today()->toDateString())
$completedState = $afterDue ? 'completed_late' : 'completed_on_time';
expect($complete['coverage'][$completedState])->toBe(1)->and($complete['pending_lines'])->toBe(0)
->and([DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
commitNativeReviewReportFixture($this);
$this->withoutVite();
$this->get('/relatorios?delivery_state=completed_late')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('deliveryInsights.coverage.completed_late', 1)->where('deliveryInsights.records.data.0.number', $order->number));
$csv = $this->get('/relatorios/entregas.csv?delivery_state=completed_late')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain($order->number)->toContain('Recepção integral depois da data acordada')->toContain('0.000');
$this->get('/relatorios?delivery_state='.$completedState)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('deliveryInsights.coverage.'.$completedState, 1)->where('deliveryInsights.records.data.0.number', $order->number));
$csv = $this->get('/relatorios/entregas.csv?delivery_state='.$completedState)->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain($order->number)->toContain(ProcurementDeliveryInsights::LABELS[$completedState]);
$this->travelBack();
});
})->with([false, true]);
function secondNativeOrderPartsOrigin(object $test): array
{
@@ -2035,8 +2232,8 @@ test('native consolidated order retains both origins and consumes a single invoi
expect($order->total_minor)->toBe(30000)->and($order->items()->count())->toBe(2)
->and(DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->count())->toBe(2)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->whereKey($order->id)->exists())->toBeTrue();
$delivery = app(\App\Services\ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
\Carbon\CarbonImmutable::now()->addDays(8), null, 'all');
$delivery = app(ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
CarbonImmutable::now()->addDays(8), null, 'all');
expect($delivery['coverage']['pending_late'])->toBe(1)->and($delivery['unknown_lines'])->toBe(0)
->and($delivery['records']['data'][0]['late_lines'])->toHaveCount(1)
->and($delivery['records']['data'][0]['late_lines'][0]['id'])->toBe($order->items()->where('requisition_item_id', $this->item->id)->value('id'));
+6
View File
@@ -22,6 +22,12 @@ beforeEach(function () {
$this->payload = receiptPayload($this->f);
});
test('receipt preparation uses encrypted history without registering a receipt or stock movement', function () {
$this->get($this->url)->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('receipts/order')->where('canConfirm', true));
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
});
test('partial then total receipts preserve pending quantities and credit only accepted stock', function () {
$this->postJson($this->url, receiptPayload($this->f, '0.400'))->assertCreated()->assertJsonPath('status', 'partial');
$first = GoodsReceipt::query()->firstOrFail();
@@ -2,9 +2,14 @@
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\CostCenter;
use App\Models\Department;
use App\Models\Requisition;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\EquipmentWorkflow;
use App\Services\RequisitionApprovalLevels;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowNotices;
@@ -111,6 +116,65 @@ function configuredDecision($test, User $actor, Requisition $record, string $dec
$test->actingAs($actor)->postJson('/requisicoes/'.$record->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $record->fresh()->process_version, 'decision' => $decision, 'comment' => 'Fundamento sintético da decisão.'])->assertRedirect();
}
test('classified machinery follows an explicitly designated direction level at any value through the existing contract', function () {
config(['capital-register.qa_enabled' => true]);
$tenant = $this->f['tenant']->id;
$this->f['tenant']->update(['first_limit_minor' => 100000000, 'second_limit_minor' => 200000000]);
$direction = approvalLevelProfile($tenant, 'Direcção de maquinaria QA', ['requisition_approve']);
approvalLevelMember($this->approvers[0], $direction);
$this->plan['levels'] = [[...$this->plan['levels'][0], 'name' => 'Direcção para maquinaria', 'profile_ids' => [$direction],
'procurement_categories' => ['capital_equipment']]];
$this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect();
$body = $this->body;
$centre = CostCenter::query()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id,
'code' => 'CAP-DIR-QA', 'name' => 'Centro sintético de investimento']);
$this->actingAs($this->financier);
$budget = app(CommonBudget::class)->for($this->financier)->create(['cost_center_id' => $centre->id,
'year' => (int) now()->year, 'kind' => 'investment', 'amount_minor' => 1000000, 'includes_tax' => true,
'reason' => 'Dotação exclusivamente sintética para circuito de capital']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($budget);
$body['cost_center_id'] = $centre->id;
$body['items'][0] = [...$body['items'][0], 'purchase_type' => 'equipment', 'production_area' => 'Produção QA',
'procurement_category' => 'capital_equipment', 'category_reason' => 'Investimento exclusivamente sintético para aprovação multinível'];
$this->postJson('/requisicoes', $body)->assertRedirect();
$request = Requisition::query()->latest('id')->firstOrFail();
$project = app(CapitalRegister::class)->save($this->admin, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'type' => 'project', 'code' => 'PRJ-DIR-QA', 'name' => 'Projecto sintético de maquinaria', 'department_id' => $request->department_id,
'reference' => 'Referência de ensaio sem projecto real', 'state' => 'active', 'reason' => 'Cadastro próprio para ensaio do circuito']);
app(CapitalAssignments::class)->save($this->admin, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $request->items()->sole()->id, 'capital_id' => $project->id, 'reason' => 'Destino expresso de investimento sintético']);
expect(DB::table('budget_entries')->count())->toBe(0);
$this->actingAs($this->head);
$technical = app(EquipmentWorkflow::class);
$technical->review($this->head, $request, $technical->basis($request), 'approved', 'Conferência técnica independente de maquinaria QA');
$this->actingAs($this->admin);
foreach ([0, 1000000000000] as $amount) {
expect(app(RequisitionApprovalLevels::class)->policy($request, $amount)['additional_levels']['configured_1']['profile_ids'])->toBe([$direction]);
}
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])->assertRedirect();
$request->refresh();
expect($request->total_minor)->toBe(11600)->and($request->steps()->orderBy('position')->pluck('role')->all())
->toBe(['department_head', 'finance', 'configured_1'])
->and($request->approval_snapshot['additional_levels']['configured_1']['procurement_categories'])->toBe(['capital_equipment']);
configuredDecision($this, $this->head, $request);
configuredDecision($this, $this->financier, $request);
$this->actingAs($this->admin)->postJson('/administracao/parametrizacao/approval_levels', [
'version' => 2, 'enabled' => false, 'levels' => [], 'reason' => 'Alteração sintética só para pedidos futuros'])->assertRedirect();
approvalLevelMember($this->admin, $direction);
foreach ([$this->admin, $this->approvers[1]] as $ineligible) {
$this->actingAs($ineligible)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Tentativa sintética sem elegibilidade'])->assertForbidden();
}
DB::table('organization_memberships')->where('user_id', $this->approvers[0]->id)->where('profile_id', $direction)->update(['expires_at' => now()->subSecond()]);
expect($request->fresh()->canDecide($this->approvers[0]))->toBeFalse();
DB::table('organization_memberships')->where('user_id', $this->approvers[0]->id)->where('profile_id', $direction)->update(['expires_at' => null]);
configuredDecision($this, $this->approvers[0], $request);
expect($request->fresh()->status)->toBe('approved')->and($request->steps()->where('role', 'configured_1')->sole()->approver_id)->toBe($this->approvers[0]->id)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(11600)
->and(DB::table('stock_movements')->count())->toBe(0);
});
test('native three controls and five configured levels progress sequentially with one eligible person per level', function () {
$r = submitConfiguredRequest($this);
expect($r->steps()->count())->toBe(8)->and($r->approval_snapshot['routing_quorum'])->toBe('one_eligible');
+262 -3
View File
@@ -11,19 +11,36 @@ use App\Services\ProcurementOperationalInsights;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\UrgentRequisitionReviews;
use App\Services\WorkflowNotices;
use App\Services\WorkflowTaskInbox;
use Carbon\CarbonImmutable;
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;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Purchasing\Internal\InternalRequisitions;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
afterEach(function () {
if ($this->committedUrgentReviewFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Urgent review cleanup requires its disposable committed QA fixture.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
@@ -35,9 +52,21 @@ beforeEach(function () {
$this->budget = Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true,
'reason' => 'Dotação aprovada estritamente sintética para ciclos', 'created_by' => $this->f['issuer']->id, 'approved_by' => $this->reviewer->id]);
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
$source = requisitionLedgerQaSource();
if ($source === null) {
throw new LogicException('Integrated cycles require the dedicated actual-ledger QA runner.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
expect($composition['verified_tables'])->toHaveCount(12);
} else {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
config(['requisition-expiry.qa_enabled' => true]);
});
@@ -161,6 +190,217 @@ test('import assumptions release in the old cycle before a separately identified
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
});
test('urgent deadlines are explicitly configured frozen per submission and expire only the selected request', function () {
$owner = $this->f['issuer'];
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Destinatário sintético configurável',
'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
$this->actingAs($admin);
$expiry = app(RequisitionExpiry::class);
$policy = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'reason' => 'Prazos sintéticos explícitos para conferir urgências',
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => 20, 'profile_ids' => [$profile],
'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => 2]]];
$first = $expiry->savePolicy($admin, $policy);
expect($expiry->savePolicy($admin, $policy)->id)->toBe($first->id);
$this->actingAs($owner);
$workflow = app(RequisitionWorkflow::class);
$make = function (string $priority) use ($owner, $workflow) {
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id,
'priority' => $priority, 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade sintética com prioridade expressamente indicada',
'items' => [['description' => 'Material sintético', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000',
'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
return $request->fresh();
};
$normal = $make('normal');
$urgent = $make('urgent');
$normalDeadline = $expiry->deadline($normal);
$urgentDeadline = $expiry->deadline($urgent);
expect($normalDeadline['timing'])->toBe('standard')->and($urgentDeadline['timing'])->toBe('urgent_override')
->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['expires_at'])))->toEqual(300)
->and(CarbonImmutable::parse($normalDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($normalDeadline['expires_at'])))->toEqual(1800)
->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['reminder_at'])))->toEqual(60)
->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['escalation_at'])))->toEqual(120);
$policy['operation_key'] = (string) Str::uuid();
$policy['version'] = 1;
$policy['levels'][0]['urgent_expire_minutes'] = 4;
$this->actingAs($admin);
$expiry->savePolicy($admin, $policy);
$this->actingAs($owner);
expect($expiry->deadline($urgent)['expires_at'])->toBe($urgentDeadline['expires_at']);
$later = $make('urgent');
$laterDeadline = $expiry->deadline($later);
expect(CarbonImmutable::parse($laterDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($laterDeadline['expires_at'])))->toEqual(240);
$this->travel(2)->minutes();
$check = $expiry->check($owner, $urgent, ['operation_key' => (string) Str::uuid(), 'process_version' => $urgent->process_version]);
expect($check['notices_created'])->toBe(1)->and($check['escalation_eligible'])->toBe(0);
$this->travel(3)->minutes();
$deadline = $expiry->deadline($urgent);
expect($deadline['state'])->toBe('expired')->and($expiry->deadline($normal)['state'])->toBe('running');
$this->postJson('/requisicoes/'.$urgent->id.'/expiracao', ['operation_key' => (string) Str::uuid(), 'process_version' => $urgent->process_version,
'basis_hash' => $deadline['basis_hash']])->assertRedirect();
expect($urgent->fresh()->status)->toBe('draft')->and($normal->fresh()->status)->toBe('pending')
->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(20000);
$this->travelBack();
});
test('urgent configuration rejects missing slower or unordered deadlines and preserves legacy replay inputs', function () {
$owner = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($owner);
$expiry = app(RequisitionExpiry::class);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'reason' => 'Política sintética sem alteração dos pedidos antigos',
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]]];
$record = $expiry->savePolicy($owner, $input);
expect($record->data['levels'][0])->not->toHaveKey('urgent_expire_minutes')
->and($expiry->savePolicy($owner, $input)->id)->toBe($record->id);
foreach ([['urgent_expire_minutes' => 30, 'urgent_reminder_minutes' => 1], ['urgent_expire_minutes' => 5],
['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 5], ['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => 2],
['urgent_reminder_minutes' => 1]] as $changes) {
$bad = $input;
$bad['operation_key'] = (string) Str::uuid();
$bad['version'] = 1;
$bad['levels'][0] = [...$bad['levels'][0], ...$changes];
expect(fn () => $expiry->savePolicy($owner, $bad))->toThrow(ValidationException::class);
}
expect(SupplyRecord::query()->where('kind', 'req_expiry_policy')->count())->toBe(1);
});
test('posterior urgent review follows final decisions and preserves each concluded cycle without changing financial sources', function (string $outcome) {
config(['urgent-reviews.qa_enabled' => true]);
$owner = $this->f['issuer'];
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$reviewer = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Procurement]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Direcção de Compras sintética',
'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $owner->tenant_id, 'profile_id' => $profile, 'user_id' => $reviewer->id, 'maintenance' => false]);
$service = app(UrgentRequisitionReviews::class);
$this->actingAs($admin);
$policyInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'profile_ids' => [$profile], 'reason' => 'Designação expressa para a revisão posterior sintética'];
$policy = $service->savePolicy($admin, $policyInput);
expect($service->savePolicy($admin, $policyInput)->id)->toBe($policy->id);
app(RequisitionExpiry::class)->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => [],
'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => null, 'urgent_escalation_minutes' => null]], 'reason' => 'Prazo sintético explícito para conferir expiração e revisão']);
$this->actingAs($owner);
$workflow = app(RequisitionWorkflow::class);
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'urgent',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Urgência sintética que exige revisão posterior do ciclo concluído',
'items' => [['description' => 'Material urgente original', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000',
'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]];
$request = $workflow->save($owner, $input);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->actingAs($reviewer);
expect($service->queue($reviewer)['records']['total'])->toBe(0)
->and(fn () => $service->workspace($reviewer, $request->id, 1))->toThrow(HttpException::class);
if ($outcome === 'expired') {
$this->travel(6)->minutes();
$this->actingAs($owner);
$proof = app(RequisitionExpiry::class)->deadline($request);
$workflow->expire($owner, $request, $proof['basis_hash'], (string) Str::uuid(), $request->process_version);
$request->refresh();
$input['operation_key'] = (string) Str::uuid();
$input['process_version'] = $request->process_version;
$input['priority'] = 'normal';
$input['items'][0]['description'] = 'Nova preparação deliberadamente diferente';
$input['items'][0]['unit_price'] = '120.00';
$request = $workflow->save($owner, $input, $request);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
expect($request->status)->toBe('pending')->and($request->approval_cycle)->toBe(2)
->and((int) DB::table('budget_entries')->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000);
} else {
$this->actingAs($head);
$workflow->decide($head, $request, $outcome, 'Decisão final sintética independente', (string) Str::uuid(), $request->process_version);
}
$this->actingAs($reviewer);
$space = $service->workspace($reviewer, $request->id, 1);
expect($space['source']['outcome'])->toBe($outcome)->and($space['source']['request']['total_minor'])->toBe('10000')
->and($space['source']['items'][0]['description'])->toBe('Material urgente original')->and($space['canReview'])->toBeTrue()
->and($service->queue($reviewer)['coverage']['pending'])->toBe(1);
$this->withoutVite();
$path = '/requisicoes/'.$request->id.'/ciclos/1/revisao-urgencia';
if ($outcome === 'approved' && DB::getDriverName() === 'pgsql') {
if (DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Urgent review native task snapshot requires the guarded QA transaction.');
}
DB::commit();
$this->committedUrgentReviewFixture = true;
$this->get('/requisicoes/tarefas?module=purchases')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('urgentReviewsReady', true)->where('tasks.data', fn ($rows) => collect($rows)->contains('task', 'urgent_requisition_review')));
}
$this->get($path)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page
->component('requisitions/urgent-review')->where('source.outcome', $outcome)->where('canReview', true));
$tasks = app(WorkflowTaskInbox::class)->build($reviewer, 'procurement');
expect(array_column($tasks, 'task'))->toContain('urgent_requisition_review');
$before = [];
foreach (['requisitions', 'requisition_items', 'approval_steps', 'budget_entries', 'stock_movements', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$body = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'source_hash' => $space['source']['fingerprint'], 'notes' => 'Conferência posterior sintética, sem alterar a decisão ou os movimentos'];
$this->postJson($path, $body)->assertRedirect();
$this->postJson($path, $body)->assertRedirect();
expect($service->queue($reviewer)['coverage']['reviewed'])->toBe(1)
->and(SupplyRecord::query()->where('kind', 'urgent_review')->count())->toBe(1)
->and(array_column(app(WorkflowTaskInbox::class)->build($reviewer, 'procurement'), 'task'))->not->toContain('urgent_requisition_review');
$firstReview = SupplyRecord::query()->where('kind', 'urgent_review')->sole();
$this->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'source_hash' => str_repeat('0', 64)])->assertConflict();
$correction = [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'notes' => 'Correcção expressa da revisão, com a primeira versão preservada'];
$this->postJson($path, $correction)->assertRedirect();
$this->postJson($path, $correction)->assertRedirect();
$this->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1])->assertConflict();
expect(SupplyRecord::query()->where('kind', 'urgent_review')->count())->toBe(2)
->and($firstReview->fresh()->data['notes'])->toBe($body['notes'])
->and(DB::table('audit_logs')->where('action', 'urgent.review_recorded')->count())->toBe(2);
if ($outcome === 'expired') {
$latestAudit = DB::table('audit_logs')->where('action', 'urgent.review_recorded')->latest('id')->value('id');
DB::table('audit_logs')->where('id', $latestAudit)->delete();
expect($service->workspace($reviewer, $request->id, 1)['currentVerified'])->toBeFalse()
->and($service->queue($reviewer, null, 'all')['coverage']['indeterminate'])->toBe(1)
->and($service->queue($reviewer, null, 'all')['coverage']['reviewed'])->toBe(0);
$expiration = SupplyRecord::query()->where('kind', 'req_expiration')->sole();
expect(fn () => DB::transaction(fn () => DB::table('supply_records')->where('id', $expiration->id)
->update(['snapshot' => json_encode([...$expiration->snapshot, 'items' => []], JSON_THROW_ON_ERROR)])))->toThrow(QueryException::class)
->and($firstReview->fresh()->snapshot['items'][0]['description'])->toBe('Material urgente original');
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->actingAs($owner)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden();
$this->actingAs($admin)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden();
DB::table('organization_memberships')->where('user_id', $reviewer->id)->update(['expires_at' => now()->subSecond()]);
$this->actingAs($reviewer)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden();
$this->travelBack();
})->with(['approved', 'rejected', 'expired']);
test('urgent review keeps indeterminate coverage and rejects a foreign profile without changing an accepted outcome', function () {
config(['urgent-reviews.qa_enabled' => true]);
$request = $this->f['r'];
$request->update(['priority' => 'urgent']);
$owner = $this->f['issuer'];
$service = app(UrgentRequisitionReviews::class);
$this->actingAs($owner);
$queue = $service->queue($owner, null, 'all');
expect($queue['coverage'])->toBe(['pending' => 0, 'reviewed' => 0, 'indeterminate' => 1])
->and($queue['records']['data'][0]['href'])->toBe('/requisicoes/'.$request->id)
->and(fn () => $service->workspace($owner, $request->id, 1))->toThrow(HttpException::class)
->and($request->fresh()->status)->toBe('approved');
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$foreign = receiptFixture();
$foreignProfile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $foreign['tenant']->id, 'name' => 'Perfil de outra empresa sintética',
'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
$this->actingAs($admin);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'profile_ids' => [$foreignProfile], 'reason' => 'Tentativa sintética de designação fora da empresa'];
expect(fn () => $service->savePolicy($admin, $input))->toThrow(HttpException::class);
$this->withoutVite();
$this->get('/administracao/revisao-urgencias')->assertOk()->assertInertia(fn (Assert $page) => $page->component('organization/urgent-review-policy')->has('profiles', 0));
$this->actingAs($foreign['issuer'])->getJson('/requisicoes/'.$request->id.'/ciclos/1/revisao-urgencia')->assertNotFound();
expect(SupplyRecord::query()->where('kind', 'urgent_review_policy')->count())->toBe(0);
});
test('configured escalation alerts respect current membership and never delegate the pending approval', function () {
$owner = $this->f['issuer'];
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Configured]);
@@ -243,6 +483,10 @@ test('native expiry returns the same request and preserves the approved stage be
->and($request->allSteps()->where('decision', 'expired')->count())->toBe(1)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1);
$this->actingAs($head)->get('/requisicoes?view=decided')->assertInertia(fn (Assert $page) => $page
->where('requisitions.total', 1)->where('requisitions.data.0.id', $request->id)
->has('requisitions.data.0.steps', 0));
$this->actingAs($owner);
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('requisitions/expiry')->where('requisition.approval_cycle', 2)->where('canEdit', true)->has('history.data', 1));
@@ -256,6 +500,21 @@ test('native expiry returns the same request and preserves the approved stage be
->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->sole()->snapshot['request']['total_minor'])->toBe(10000);
$this->f['tenant']->update(['first_limit_minor' => 9000]);
$beforeHistoryRead = [];
foreach (['requisitions', 'approval_steps', 'supply_records', 'audit_logs', 'budget_entries', 'budget_requisition_cycles', 'stock_movements'] as $table) {
$beforeHistoryRead[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('history.data.0.request.total_minor', 10000)->where('history.data.0.request.priority', 'normal')
->where('history.data.0.items.0.description', 'Bem de ensaio')->where('history.data.0.items.0.total_minor', 10000)
->where('history.data.0.rules.first_limit_minor', 5000)->where('history.data.0.rules.approval_includes_tax', true)
->where('history.data.0.approval_amount_minor', 10000)->where('history.data.0.approval_uses_separate_basis', false)
->where('history.data.0.steps.0.approver_id', $head->id)->where('history.data.0.steps.0.comment', 'Conferência sintética do primeiro nível')
->missing('history.data.0.rules.timing')->missing('history.data.0.items.0.category_context'));
foreach ($beforeHistoryRead as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$notices = app(WorkflowNotices::class)->visible($owner);
expect(array_column($notices, 'outcome'))->toContain('expired')
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
@@ -0,0 +1,76 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionDuplicateHints;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function duplicateHintCopy(Requisition $source, array $changes = []): Requisition
{
$copy = $source->replicate();
$copy->fill(['number' => 'REQ-HINT-'.Str::random(12), 'status' => 'draft', ...$changes])->save();
foreach ($source->items as $line) {
$copy->items()->save($line->replicate());
}
return $copy->fresh();
}
test('duplicate advisory is a private native read with no financial or workflow effects', function () {
$f = receiptFixture();
$draft = duplicateHintCopy($f['r']);
$this->actingAs($f['issuer']);
$before = [Requisition::query()->count(), DB::table('audit_logs')->count(), DB::table('budget_entries')->count()];
$this->get('/requisicoes/'.$draft->id)->assertOk()->assertInertia(fn (Assert $page) => $page
->has('duplicateHints.matches', 1)->where('duplicateHints.matches.0.id', $f['r']->id)
->where('duplicateHints.matches.0.status', 'approved')->where('duplicateHints.complete', true)
->missing('duplicateHints.matches.0.items')->missing('duplicateHints.matches.0.justification'));
expect([Requisition::query()->count(), DB::table('audit_logs')->count(), DB::table('budget_entries')->count()])->toBe($before)
->and($draft->fresh()->status)->toBe('draft');
});
test('duplicate advisory excludes different contents dates centres authors and inactive outcomes', function () {
$f = receiptFixture();
$draft = duplicateHintCopy($f['r']);
$this->actingAs($f['issuer']);
$hints = app(RequisitionDuplicateHints::class);
foreach (['cancelled', 'rejected'] as $status) {
$f['r']->update(['status' => $status]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
}
$f['r']->update(['status' => 'pending', 'needed_by' => today()->addDays(20)]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
$f['r']->update(['needed_by' => $draft->needed_by]);
$f['r']->items()->firstOrFail()->update(['description' => 'Outra necessidade sintética']);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
$other = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
$f['r']->items()->firstOrFail()->update(['description' => $draft->items->first()->description]);
$f['r']->update(['requester_id' => $other->id]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
$f['r']->update(['requester_id' => $f['issuer']->id]);
$centre = $draft->costCenter->replicate();
$centre->code = 'OTHER-QA';
$centre->save();
$f['r']->update(['cost_center_id' => $centre->id]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
duplicateHintCopy($draft, ['requester_id' => $other->id]);
expect($hints->for($other, $draft))->toBeNull();
$draft->update(['total_minor' => null]);
expect($hints->for($f['issuer'], $draft))->toBeNull();
});
test('bounded duplicate comparison reports incomplete coverage without pretending absence', function () {
$f = receiptFixture();
$draft = duplicateHintCopy($f['r']);
for ($i = 0; $i < 100; $i++) {
duplicateHintCopy($f['r']);
}
$this->actingAs($f['issuer']);
$result = app(RequisitionDuplicateHints::class)->for($f['issuer'], $draft);
expect($result['complete'])->toBeFalse()->and($result['matches'])->toHaveCount(100);
});
@@ -0,0 +1,508 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CriticalityLevel;
use App\Models\Equipment;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrder;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\StockItem;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\EquipmentWorkflow;
use App\Services\ExpenseAllocations;
use App\Services\ExternalPaymentWorkflow;
use App\Services\InvoiceWorkflow;
use App\Services\ProcurementPaymentInsights;
use App\Services\ProposalComparison;
use App\Services\PurchaseLineAmounts;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\RequisitionWorkflow;
use App\Services\SupplierBankWorkflow;
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;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
beforeEach(function () {
$source = requisitionLedgerQaSource();
if ($source === null) {
$this->markTestSkipped('Use the dedicated ledger QA runner with the real common schema and isolated non-elevated role.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$this->schemaComposition = integratedPurchasingQaSchema();
}
$this->f = receiptFixture();
$this->item = $this->f['r']->items()->firstOrFail();
$this->actingAs($this->f['issuer']);
$this->withoutVite();
config(['requisition-accounts.qa_enabled' => true]);
$this->account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-ONLY-100', 'label' => 'Conta fictícia de movimentos', 'currency' => 'MZN', 'is_movement' => true]);
});
test('pinned private runtime refuses source fallback and mismatched composition without effects', function () {
if (config('common-finance-bundle.manifest_sha256') !== '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df') {
$this->markTestSkipped('This regression requires the exact frozen private composition.');
}
$tables = ['gl_accounts', 'gl_journals', 'requisitions', 'budget_entries', 'supply_records', 'audit_logs'];
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
$before = $snapshot();
$source = getenv('RQ01_LEDGER_QA_SOURCE');
$settings = ['common-finance-bundle.manifest_sha256' => config('common-finance-bundle.manifest_sha256'),
'common-finance-bundle.root' => config('common-finance-bundle.root'), 'general-ledger.path' => config('general-ledger.path')];
try {
foreach (['C:/laragon/www/sgf-tempo/packages/general-ledger', base_path('storage/framework/testing/unapproved-ledger-source')] as $wrong) {
putenv('RQ01_LEDGER_QA_SOURCE='.$wrong);
expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class);
}
putenv('RQ01_LEDGER_QA_SOURCE='.$source);
foreach (['common-finance-bundle.manifest_sha256' => str_repeat('0', 64),
'common-finance-bundle.root' => base_path('storage/framework/testing/unapproved-ledger-source'),
'general-ledger.path' => 'C:/laragon/www/sgf-tempo/packages/general-ledger'] as $key => $wrong) {
config([$key => $wrong]);
expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class);
config($settings);
}
} finally {
putenv('RQ01_LEDGER_QA_SOURCE='.$source);
config($settings);
}
expect($snapshot())->toBe($before);
});
test('minimal purchasing catalogue reads the actual common chart without journals or a second chart', function () {
$service = app(RequisitionLedgerAccounts::class);
$before = [DB::table('gl_accounts')->get()->toJson(), DB::table('gl_journals')->count(), DB::table('audit_logs')->count()];
$page = $service->options($this->f['issuer']);
expect($service->ready())->toBeTrue()->and($page['total'])->toBe(1)
->and(array_keys($page['data'][0]))->toBe(['id', 'code', 'label', 'currency', 'source_hash'])
->and($service->resolve($this->f['issuer'], $this->account, $page['data'][0]['source_hash']))->toBe($page['data'][0])
->and([DB::table('gl_accounts')->get()->toJson(), DB::table('gl_journals')->count(), DB::table('audit_logs')->count()])->toBe($before);
expect($service->options($this->f['issuer'], '%')['total'])->toBe(0);
expect($service->options($this->f['issuer'], 'fictícia')['total'])->toBe(1);
});
test('chart references reject foreign scope summary accounts and stale hashes', function () {
$service = app(RequisitionLedgerAccounts::class);
$hash = $service->options($this->f['issuer'])['data'][0]['source_hash'];
foreach (['company_id' => 8, 'unit_id' => 9, 'tenant_id' => $this->f['tenant']->id + 100, 'is_movement' => false] as $column => $value) {
$other = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-EXCLUDED-'.$column, 'label' => 'Referência sintética fora do catálogo', 'currency' => 'MZN', 'is_movement' => true, $column => $value]);
expect($service->options($this->f['issuer'])['total'])->toBe(1)
->and(fn () => $service->resolve($this->f['issuer'], $other, $hash))->toThrow(HttpException::class);
}
expect(fn () => $service->resolve($this->f['issuer'], $this->account, str_repeat('0', 64)))->toThrow(HttpException::class);
// Common accounts are append-only: corrections cannot silently rename an accepted source.
expect(fn () => DB::transaction(fn () => DB::table('gl_accounts')->where('id', $this->account)->update(['label' => 'Alteração proibida'])))->toThrow(QueryException::class);
config(['requisition-accounts.qa_enabled' => false]);
expect($service->ready())->toBeFalse()->and(fn () => $service->options($this->f['issuer']))->toThrow(HttpException::class);
});
test('native line account assignment conserves exact parcels versions and originals without ledger effects', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft']);
$service = app(RequisitionAccountAssignments::class);
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
$space = $service->workspace($this->f['issuer'], $request);
$account = $space['accounts']['data'][0];
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id,
'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Imputação expressa no ensaio sintético',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]];
$before = [DB::table('gl_journals')->count(), DB::table('gl_lines')->count(), DB::table('budget_entries')->count(), DB::table('stock_movements')->count()];
$path = '/requisicoes/'.$request->id.'/contas';
$this->postJson($path, $input)->assertRedirect();
$this->postJson($path, $input)->assertRedirect();
$this->get($path)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page
->component('requisitions/accounts')->where('current.0.version', 1)->where('items.0.total_minor', '10000')->where('canWrite', true));
$first = SupplyRecord::query()->where('kind', 'req_account')->sole();
expect($first->data['allocations'][0]['total_minor'])->toBe('10000')
->and($service->freezeForItems($this->f['issuer'], [$this->item->id])[$this->item->id]['id'])->toBe($first->id);
$input['operation_key'] = (string) Str::uuid();
$input['version'] = 1;
$input['reason'] = 'Nova conferência documental sintética';
$this->postJson($path, $input)->assertRedirect();
expect(SupplyRecord::query()->where('kind', 'req_account')->count())->toBe(2)
->and($first->fresh()->reason)->toBe('Imputação expressa no ensaio sintético')
->and([DB::table('gl_journals')->count(), DB::table('gl_lines')->count(), DB::table('budget_entries')->count(), DB::table('stock_movements')->count()])->toBe($before);
$input['operation_key'] = (string) Str::uuid();
$this->postJson($path, $input)->assertConflict();
$input['version'] = 2;
$input['allocations'][0]['total'] = '99.99';
$this->postJson($path, $input)->assertUnprocessable();
$request->items()->whereKey($this->item->id)->update(['description' => 'Linha alterada de forma explícita']);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$this->item->id]))->toThrow(HttpException::class);
});
test('classified line requires explicit exact account parcels and rejects another operator', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft']);
$this->item->setAttribute('category_context', ['version' => 1, 'category' => 'other', 'reason' => 'Necessidade sintética sem catálogo']);
$this->item->save();
$service = app(RequisitionAccountAssignments::class);
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
$space = $service->workspace($this->f['issuer'], $request);
$account = $space['accounts']['data'][0];
$secondId = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-ONLY-200', 'label' => 'Segunda conta fictícia', 'currency' => 'MZN', 'is_movement' => true]);
$second = app(RequisitionLedgerAccounts::class)->options($this->f['issuer'])['data'][1];
expect($second['id'])->toBe($secondId);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'],
'reason' => 'Duas parcelas explícitas, sem rateio automático', 'allocations' => [
['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '0.33', 'total' => '0.33'],
['account_id' => $second['id'], 'source_hash' => $second['source_hash'], 'subtotal' => '99.67', 'total' => '99.67']]];
$path = '/requisicoes/'.$request->id.'/contas';
$bad = $input;
$bad['allocations'][1]['subtotal'] = '99.66';
$this->postJson($path, $bad)->assertUnprocessable();
$bad = $input;
$bad['allocations'][1]['account_id'] = $account['id'];
$this->postJson($path, $bad)->assertUnprocessable();
$this->actingAs($this->f['receiver'])->postJson($path, $input)->assertNotFound();
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->postJson($path, $input)->assertForbidden();
$this->actingAs($this->f['issuer'])->postJson($path, $input)->assertRedirect();
$service->assertSubmission($this->f['issuer'], $request);
$source = SupplyRecord::query()->where('kind', 'req_account')->sole();
expect(array_column($source->data['allocations'], 'total_minor'))->toBe(['33', '9967'])
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0);
DB::table('audit_logs')->where('action', 'requisition.accounts_assigned')->delete();
expect(fn () => $service->freezeForItems($this->f['issuer'], [$this->item->id]))->toThrow(HttpException::class);
});
test('zero monetary line retains its explicit account without invented compensation', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft', 'subtotal_minor' => 0, 'total_minor' => 0]);
$amounts = PurchaseLineAmounts::portion(1, '0', 0, 1);
$this->item->update(['quantity' => '0.001', 'unit_price_minor' => 1, ...$amounts]);
expect($amounts['total_minor'])->toBe(0);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->f['issuer'], $request);
$account = $space['accounts']['data'][0];
$record = $service->save($this->f['issuer'], $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Conta preservada para linha arredondada a zero',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '0.00', 'total' => '0.00']]]);
expect($record->data['allocations'][0]['total_minor'])->toBe('0')
->and($record->data['allocations'][0]['account']['code'])->toBe('QA-ONLY-100')
->and(DB::table('gl_journals')->count())->toBe(0);
$request->update(['total_minor' => null]);
expect($service->workspace($this->f['issuer'], $request)['canWrite'])->toBeFalse();
});
test('native office purchase reconciles declared accounts through receipt invoice and confirmed payment', function (bool $machinery, bool $withExpiry, bool $higherLimit = false) {
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
expect($this->schemaComposition['migrations'])->toHaveCount(5)
->and($this->schemaComposition['verified_tables'])->toHaveCount(12)
->and(config('requisition-expiry.qa_enabled'))->toBeTrue();
}
$tenant = $this->f['tenant']->id;
$department = $this->f['department']->id;
$staff = fn ($role) => User::factory()->create(['tenant_id' => $tenant, 'department_id' => $department, 'purchasing_role' => $role]);
if ($higherLimit) {
$this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
}
$owner = $staff(PurchasingRole::Requester);
$buyer = $staff(PurchasingRole::Procurement);
$independentBuyer = $staff(PurchasingRole::Procurement);
$head = $staff(PurchasingRole::DepartmentHead);
$finance = $staff(PurchasingRole::Finance);
$reviewer = $staff(PurchasingRole::Finance);
$category = $machinery ? 'Maquinaria QA' : 'Escritório QA';
$description = $machinery ? 'Maquinaria exclusivamente sintética' : 'Material de escritório de ensaio';
$direction = null;
if ($machinery) {
config(['capital-register.qa_enabled' => true, 'requisition_approval.qa_enabled' => true]);
require_once __DIR__.'/../Support/InvestmentFixture.php';
publishInvestmentFixture($tenant, '100.00');
$admin = $staff(PurchasingRole::Admin);
foreach (User::query()->where('tenant_id', $tenant)->get() as $person) {
$nativeProfile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => 'QA function '.$person->id,
'permissions' => json_encode([$person->purchasing_role->value]), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $tenant, 'user_id' => $person->id, 'profile_id' => $nativeProfile, 'maintenance' => false]);
}
$direction = $staff(PurchasingRole::Configured);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => 'QA direction',
'permissions' => json_encode(['requisition_approve']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $tenant, 'user_id' => $direction->id, 'profile_id' => $profile, 'maintenance' => false]);
DB::table('organization_access')->insert(['tenant_id' => $tenant, 'active' => true, 'version' => 1]);
$this->actingAs($admin)->postJson('/administracao/parametrizacao/approval_levels', ['version' => 1, 'enabled' => true,
'reason' => 'Explicit synthetic direction designation for integrated machinery QA', 'levels' => [[
'name' => 'QA direction', 'profile_ids' => [$profile], 'scope' => 'company', 'min_amount' => null,
'categories' => [], 'procurement_categories' => ['capital_equipment'], 'cost_center_ids' => []]]])->assertRedirect();
}
if ($withExpiry) {
$policyAuthor = $machinery ? $admin : $staff(PurchasingRole::Admin);
$this->actingAs($policyAuthor);
app(RequisitionExpiry::class)->savePolicy($policyAuthor, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => null,
'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement', 'finance', 'configured_1']),
'reason' => 'Explicitly synthetic expiry policy for the fully integrated purchase lifecycle']);
}
$this->actingAs($finance);
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $this->f['r']->cost_center_id,
'year' => (int) now()->year, 'kind' => $machinery ? 'investment' : 'operating', 'includes_tax' => true, 'amount_minor' => 100000,
'reason' => 'Dotação sintética de ensaio: '.$category]);
$this->actingAs($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
$this->actingAs($owner)->postJson('/requisicoes', ['operation_key' => (string) Str::uuid(),
'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'justification' => 'Compra exclusivamente sintética: '.$category.', taxa ilustrativa zero sem regra fiscal real',
'items' => [['description' => $description, 'category' => $category, 'purchase_type' => $machinery ? 'equipment' : 'consumable',
'production_area' => $machinery ? 'Synthetic production line' : null,
'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00',
'procurement_category' => $machinery ? 'capital_equipment' : 'office_equipment', 'category_reason' => 'Justificação exclusivamente sintética de aquisição: '.$category]]])->assertRedirect();
$request = Requisition::query()->where('requester_id', $owner->id)->sole();
$line = $request->items()->sole();
if ($machinery) {
$this->actingAs($buyer);
$asset = app(CapitalRegister::class)->save($buyer, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'type' => 'asset', 'code' => 'MACHINERY-FLOW-QA', 'name' => 'Synthetic machinery destination', 'department_id' => $department,
'reference' => 'Synthetic acquisition only', 'state' => 'active', 'reason' => 'Explicit asset destination before synthetic acquisition']);
$this->actingAs($owner);
app(CapitalAssignments::class)->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $line->id, 'capital_id' => $asset->id, 'reason' => 'Explicit synthetic machinery destination']);
$this->actingAs($head);
$technical = app(EquipmentWorkflow::class);
$technical->review($head, $request, $technical->basis($request), 'approved', 'Independent technical check of synthetic machinery');
$this->actingAs($owner);
}
$space = app(RequisitionAccountAssignments::class)->workspace($owner, $request);
$account = $space['accounts']['data'][0];
$this->postJson('/requisicoes/'.$request->id.'/contas', ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $line->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Conta do plano próprio escolhida antes da submissão',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]])->assertRedirect();
$submit = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson('/requisicoes/'.$request->id.'/submeter', $submit)->assertRedirect();
$this->postJson('/requisicoes/'.$request->id.'/submeter', $submit)->assertRedirect();
expect(array_key_exists('approval_expiry', $request->fresh()->approval_snapshot))->toBe($withExpiry);
$this->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Tentativa própria sem competência'])->assertForbidden();
$this->actingAs($head)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Necessidade sintética conferida pela chefia distinta'])->assertRedirect();
if ($higherLimit) {
expect($request->fresh()->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'procurement']);
$this->actingAs($independentBuyer)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Independent procurement check of the synthetic request'])->assertRedirect();
}
if ($machinery) {
expect($request->fresh()->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'finance', 'configured_1']);
foreach ([$finance, $direction] as $actor) {
$this->actingAs($actor)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Independent synthetic machinery approval'])->assertRedirect();
}
$this->actingAs($admin)->postJson('/administracao/parametrizacao/approval_levels', ['version' => 2, 'enabled' => false,
'levels' => [], 'reason' => 'Synthetic future policy change preserves already approved machinery route'])->assertRedirect();
}
expect($request->fresh()->status)->toBe('approved');
$quotes = [];
foreach ([100, 110, 120] as $index => $price) {
$this->actingAs($buyer)->postJson('/fornecedores', ['name' => 'Fornecedor de escritório QA '.($index + 1), 'nuit' => (string) (200000001 + $index),
'contact' => 'Contacto sintético', 'email' => 'office-'.$index.'@example.invalid', 'phone' => '123456789', 'address' => 'Morada sintética',
'category' => $category, 'beneficiaries' => 'Beneficiário sintético', 'document_references' => 'Referências exclusivamente sintéticas',
'diligence_notes' => 'Diligência preparada no ensaio, sem fornecedor real', 'blocked' => false, 'next_review' => today()->addYear()->toDateString()])->assertRedirect();
$supplier = Supplier::query()->where('nuit', (string) (200000001 + $index))->sole();
$this->actingAs($finance)->postJson('/fornecedores/'.$supplier->id.'/validar', ['version' => $supplier->version, 'status' => 'active',
'comment' => 'Conferência financeira independente dos dados sintéticos'])->assertRedirect();
$this->actingAs($buyer)->postJson('/requisicoes/'.$request->id.'/cotacoes', ['currency' => 'MZN', 'supplier_id' => $supplier->id,
'reference' => 'OFFICE-QA-'.($index + 1), 'delivery_days' => 5, 'valid_until' => today()->addMonth()->toDateString(),
'payment_terms' => 'Condições sintéticas de trinta dias', 'no_conflict' => true,
'items' => [['requisition_item_id' => $line->id, 'unit_price' => $price.'.00', 'discount_type' => 'none', 'discount_value' => '0.00']]])->assertRedirect();
$quote = Quotation::query()->where('requisition_id', $request->id)->where('supplier_id', $supplier->id)->sole();
foreach ([$head, $reviewer] as $evaluator) {
$this->actingAs($evaluator)->postJson('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '5', 'history' => '5', 'payment' => '5',
'comment' => 'Avaliação independente e exclusivamente sintética', 'no_conflict' => true])->assertRedirect();
}
$quotes[] = $quote;
}
$comparison = app(ProposalComparison::class)->inspect($request->fresh());
expect($comparison['ready'])->toBeTrue()->and($comparison['top_ids'])->toBe([$quotes[0]->id]);
$this->actingAs($buyer)->postJson('/requisicoes/'.$request->id.'/adjudicacao', ['quotation_id' => $quotes[0]->id,
'justification' => 'Escolha sintética da proposta com maior pontuação pelo circuito vigente',
'delivery_date' => today()->addWeek()->toDateString(), 'delivery_location' => 'Armazém de ensaio'])->assertRedirect();
$award = PurchaseAward::query()->where('requisition_id', $request->id)->sole();
$approvers = ['department_head' => $head, 'procurement' => $independentBuyer, 'finance' => $reviewer];
foreach ($award->approvals()->orderBy('position')->get() as $step) {
if ($step->role === 'procurement') {
$this->actingAs($buyer)->postJson('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved',
'comment' => 'Selector must not approve their own award, even with procurement authority'])->assertForbidden();
expect($award->fresh()->status)->toBe('pending');
}
$this->actingAs($approvers[$step->role])->postJson('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved', 'comment' => 'Conferência sintética do valor final'])->assertRedirect();
}
$this->actingAs($buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
$this->postJson('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
$order = PurchaseOrder::query()->where('purchase_award_id', $award->id)->sole();
expect($order->total_minor)->toBe(10000)->and($order->snapshot['account_assignments'][$line->id]['data']['allocations'][0]['account']['id'])->toBe($account['id']);
$receiver = $this->f['receiver'];
$this->actingAs($receiver);
$stock = StockItem::query()->create(['tenant_id' => $tenant, 'created_by' => $receiver->id, 'code' => 'OFFICE-FLOW-QA',
'name' => $description, 'unit' => 'un']);
$orderLine = $order->items()->sole();
$receiptInput = ['idempotency_key' => (string) Str::uuid(),
'delivery_note' => 'OFFICE-DELIVERY-QA', 'received_on' => today()->toDateString(), 'warehouse_id' => $this->f['warehouse']->id,
'items' => [['purchase_order_item_id' => $orderLine->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000',
'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptInput);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptInput)->id)->toBe($receipt->id);
if ($machinery) {
$this->actingAs($admin)->postJson('/equipamentos/categorias', ['code' => 'FLOW-QA', 'name' => 'Synthetic criticality',
'criteria' => 'Synthetic machinery registration only', 'is_critical' => false])->assertRedirect();
$criticality = CriticalityLevel::query()->where('code', 'FLOW-QA')->sole();
$this->actingAs($buyer)->postJson('/equipamentos/activos', ['code' => 'MACHINERY-FLOW-QA', 'description' => 'Synthetic received machinery',
'area' => 'Synthetic production line', 'serial_number' => 'SYNTHETIC-ONLY', 'status' => 'active', 'department_id' => $department,
'stock_item_id' => $stock->id, 'criticality_level_id' => $criticality->id])->assertRedirect();
$equipment = Equipment::query()->where('code', 'MACHINERY-FLOW-QA')->sole();
$updatedAsset = app(CapitalRegister::class)->save($buyer, [...$asset->data, 'operation_key' => (string) Str::uuid(),
'record_key' => $asset->record_key, 'version' => 1, 'state' => 'active', 'equipment_id' => $equipment->id,
'reason' => 'Link the actual synthetic received machinery without changing original acquisition']);
expect($updatedAsset->version)->toBe(2)
->and($order->fresh()->snapshot['capital_assignments'][$line->id]['snapshot']['source']['version'])->toBe(1)
->and($order->fresh()->snapshot['capital_assignments'][$line->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('capitalReference.record_key', $asset->record_key)->where('capitalReference.version', 2));
$this->get('/projectos-imobilizado?history='.$asset->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('trace.orders.data.0.order_number', $order->number)->where('trace.receipts.data.0.receipt_id', $receipt->id));
}
$this->actingAs($finance);
$invoice = app(InvoiceWorkflow::class)->register($finance, $order, ['number' => 'OFFICE-INVOICE-QA', 'issued_on' => today()->toDateString(),
'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00', 'items' => [['purchase_order_item_id' => $orderLine->id,
'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$this->postJson('/facturas/'.$invoice->id.'/validar')->assertForbidden();
expect($invoice->fresh()->status)->toBe('pending');
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
$supplier = $quotes[0]->supplier;
$this->actingAs($buyer);
$bank = app(SupplierBankWorkflow::class)->propose($buyer, $supplier, ['account_key' => (string) Str::uuid(), 'previous_id' => 0,
'bank_name' => 'Banco estritamente sintético', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Titular sintético',
'account_identifier' => 'OFFICE-ACCOUNT-QA', 'evidence_reference' => 'Evidência bancária apenas para teste', 'reason' => 'Registo de conta fictícia para o ensaio']);
foreach ([$finance, $reviewer] as $bankReviewer) {
$this->actingAs($bankReviewer);
app(SupplierBankWorkflow::class)->review($bankReviewer, $bank, 'approved', 'Conferência independente de evidência fictícia');
}
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'office-process-qa', 'expense-allocations.qa_enabled' => true]);
foreach ([$finance, $reviewer] as $reader) {
DB::table('pa_access')->insert(['tenant_id' => $tenant, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $reader->id,
'person' => 'office-qa-'.$reader->id, 'action' => 'view']);
}
$this->actingAs($finance);
$payments = app(ExternalPaymentWorkflow::class);
$paymentInput = ['supplier_bank_detail_id' => $bank->id, 'amount' => '40.00', 'paid_on' => today()->toDateString(),
'external_reference' => 'OFFICE-PAYMENT-QA', 'evidence_reference' => 'Evidência exclusivamente sintética de pagamento parcial'];
$payment = $payments->register($finance, $invoice, $paymentInput);
expect($payments->register($finance, $invoice, $paymentInput)->id)->toBe($payment->id);
$this->postJson('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'independently_verified' => true,
'reason' => 'Tentativa própria de conferência no ensaio'])->assertForbidden();
expect($payment->fresh()->status)->toBe('pending');
$this->actingAs($reviewer);
$allocations = app(ExpenseAllocations::class);
expect(fn () => $allocations->source($reviewer, $payment->id))->toThrow(HttpException::class);
$payments->review($reviewer, $payment, 'confirmed', 'Confirmação independente de pagamento externo fictício');
$this->actingAs($finance);
expect(fn () => $payments->register($finance, $invoice, [...$paymentInput, 'external_reference' => 'OFFICE-OVERPAY-QA', 'amount' => '60.01']))
->toThrow(ValidationException::class);
$this->actingAs($reviewer);
$source = $allocations->source($reviewer, $payment->id);
$financialRows = [];
foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'budget_consumptions', 'stock_movements', 'gl_journals', 'gl_lines', 'pa_commands'] as $table) {
$financialRows[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$allocation = $allocations->save($reviewer, $payment->id, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'fingerprint' => $source['fingerprint'], 'reason' => 'Imputação expressa do pagamento pela função de Finanças',
'allocations' => [['category' => $category, 'amount' => '40.00']]]);
$insights = app(ProcurementPaymentInsights::class)->build($reviewer, Requisition::query()->whereKey($request->id), null, null);
$balance = app(CommonBudget::class)->for($reviewer)->balance($budget);
expect($balance['reserved_minor'])->toBe(0)->and($balance['committed_minor'])->toBe(0)
->and($balance['consumed_minor'])->toBe(10000)->and($balance['available_minor'])->toBe(90000);
expect($receipt->items()->sole()->accepted_milli)->toBe(1000)->and($invoice->fresh()->status)->toBe('validated')
->and($payment->fresh()->status)->toBe('confirmed')->and($payments->outstanding($invoice))->toBe(6000)
->and($allocation->data['allocations'])->toBe([['category' => $category, 'amount_minor' => '4000']])
->and($insights['currencies'][0]['amount_minor'])->toBe('4000')->and($insights['category_attribution']['groups']['data'][0]['amount_minor'])->toBe('4000')
->and((int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000)
->and(DB::table('gl_journals')->count())->toBe(0);
foreach ($financialRows as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->actingAs($finance);
$finalPayment = $payments->register($finance, $invoice, [...$paymentInput, 'external_reference' => 'OFFICE-FINAL-PAYMENT-QA', 'amount' => '60.00']);
$this->actingAs($reviewer);
$payments->review($reviewer, $finalPayment, 'confirmed', 'Confirmação independente do saldo externo estritamente sintético');
$finalSource = $allocations->source($reviewer, $finalPayment->id);
$allocations->save($reviewer, $finalPayment->id, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'fingerprint' => $finalSource['fingerprint'], 'reason' => 'Imputação explícita do pagamento final por Finanças',
'allocations' => [['category' => $category, 'amount' => '60.00']]]);
$settled = app(ProcurementPaymentInsights::class)->build($reviewer, Requisition::query()->whereKey($request->id), null, null);
$settledBudget = app(CommonBudget::class)->for($reviewer)->balance($budget);
expect($payments->outstanding($invoice))->toBe(0)->and($settled['currencies'][0]['amount_minor'])->toBe('10000')
->and($settled['coverage']['confirmed_payments'])->toBe(2)->and($settled['category_attribution']['coverage']['allocated'])->toBe(2)
->and($settled['category_attribution']['groups']['data'][0]['amount_minor'])->toBe('10000')
->and($settledBudget)->toBe($balance)->and($allocation->fresh()->data['allocations'])->toBe([['category' => $category, 'amount_minor' => '4000']])
->and((int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
$this->actingAs($owner)->get('/requisicoes/'.$request->id.'/processo')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('stages.7.state', 'restricted')->where('stages.8.state', 'restricted')
->missing('invoices')->missing('payments')->missing('bank_snapshot'));
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
expect(DB::table('budget_requisition_cycles')->where('requisition_id', $request->id)->count())->toBe($withExpiry ? 1 : 0)
->and(DB::table('budget_order_commands')->count())->toBe(0)
->and(DB::table('budget_landed_entries')->count())->toBe(0)
->and(DB::table('budget_distribution_entries')->count())->toBe(0);
}
})->with(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1'
? ['office_without_expiry_policy' => [false, false], 'office_with_explicit_expiry_policy' => [false, true],
'machinery_without_expiry_policy' => [true, false], 'machinery_with_explicit_expiry_policy' => [true, true],
'office_with_independent_procurement' => [false, true, true]]
: ['office' => [false, false], 'machinery' => [true, false]]);
test('native submission requires account reference before reserve and approval', function () {
$owner = $this->f['issuer'];
$finance = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Finance]);
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($finance);
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $this->f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação exclusivamente sintética para submissão']);
$this->actingAs($admin);
app(CommonBudget::class)->for($admin)->approve($budget);
$this->actingAs($owner);
$request = app(RequisitionWorkflow::class)->save($owner, ['operation_key' => (string) Str::uuid(),
'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'justification' => 'Pedido sintético de conferência da conta antes da reserva', 'items' => [['description' => 'Material sintético novo', 'category' => 'Material',
'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00',
'procurement_category' => 'other', 'category_reason' => 'Necessidade de texto livre fundamentada no ensaio']]]);
$path = '/requisicoes/'.$request->id;
$submit = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson($path.'/submeter', $submit)->assertUnprocessable()->assertJsonValidationErrors('account_assignment');
expect($request->fresh()->status)->toBe('draft')->and($request->steps()->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0);
$space = app(RequisitionAccountAssignments::class)->workspace($owner, $request);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
$this->postJson($path.'/contas', ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'],
'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação explícita anterior à submissão',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]])->assertRedirect();
$this->postJson($path.'/submeter', $submit)->assertRedirect();
$this->postJson($path.'/submeter', $submit)->assertRedirect();
expect($request->fresh()->status)->toBe('pending')->and($request->steps()->count())->toBe(1)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(10000)
->and(DB::table('gl_journals')->count())->toBe(0);
$this->actingAs($head)->postJson($path.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version,
'decision' => 'approved', 'comment' => 'Decisão sintética pelo aprovador distinto'])->assertRedirect();
expect($request->fresh()->status)->toBe('approved');
});
@@ -0,0 +1,99 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionSubmissionPreview;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
afterEach(function () {
if ($this->committedSubmissionPreviewFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Preview cleanup requires its disposable committed QA fixture.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
function submissionPreviewDraft(array $fixture): Requisition
{
$draft = $fixture['r']->replicate();
$draft->fill(['number' => 'REQ-PREVIEW-'.Str::random(12), 'status' => 'draft'])->save();
foreach ($fixture['r']->items as $line) {
$draft->items()->save($line->replicate());
}
return $draft->fresh();
}
test('submission preview is a private read without reservation approval receipt or audit changes', function () {
$f = receiptFixture();
$draft = submissionPreviewDraft($f);
$this->actingAs($f['issuer']);
$f['tenant']->update(['first_limit_minor' => 10000, 'second_limit_minor' => 20000]);
$tables = ['requisitions', 'requisition_items', 'approval_steps', 'audit_logs', 'budget_entries', 'supply_records'];
$before = collect($tables)->mapWithKeys(fn ($table) => [$table => DB::table($table)->orderBy('id')->get()->toJson()])->all();
if (DB::getDriverName() === 'pgsql') {
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Native read-only preview requires the guarded QA fixture.');
}
DB::commit();
$this->committedSubmissionPreviewFixture = true;
}
$this->get('/requisicoes/'.$draft->id)->assertOk()->assertHeader('cache-control', 'no-cache, private')
->assertInertia(fn (Assert $page) => $page->where('submissionPreview.state', 'planned')
->where('submissionPreview.total_minor', '10000')->where('submissionPreview.approval_amount_minor', '10000')
->has('submissionPreview.steps', 1)->where('submissionPreview.steps.0.role', 'department_head')
->missing('submissionPreview.first_limit_minor')->missing('submissionPreview.additional_levels'));
expect(collect($tables)->mapWithKeys(fn ($table) => [$table => DB::table($table)->orderBy('id')->get()->toJson()])->all())->toBe($before);
});
test('submission preview follows current threshold tax equipment and configured routing without freezing a plan', function () {
$f = receiptFixture();
$draft = submissionPreviewDraft($f);
$this->actingAs($f['issuer']);
$f['tenant']->update(['first_limit_minor' => 9000, 'second_limit_minor' => 9500]);
$service = app(RequisitionSubmissionPreview::class);
expect(array_column($service->for($f['issuer'], $draft)['steps'], 'role'))->toBe(['department_head', 'procurement', 'finance']);
$f['tenant']->update(['first_limit_minor' => 10000, 'second_limit_minor' => 20000, 'approval_includes_tax' => false]);
$draft->update(['subtotal_minor' => 9000, 'tax_minor' => 1000]);
expect($service->for($f['issuer'], $draft)['approval_amount_minor'])->toBe('9000');
$draft->items()->update(['purchase_type' => 'equipment']);
$draft->unsetRelation('items');
expect(array_column($service->for($f['issuer'], $draft)['steps'], 'role'))->toBe(['department_head', 'finance']);
config(['requisition_approval.qa_enabled' => true]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $f['tenant']->id, 'name' => 'Direcção sintética',
'permissions' => json_encode(['requisition_approve']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
$f['tenant']->forceFill(['requisition_approval_policy' => ['enabled' => true, 'revision' => 3, 'levels' => [
['name' => 'Direcção sintética', 'profile_ids' => [$profile], 'scope' => 'company', 'min_minor' => null,
'categories' => [], 'procurement_categories' => [], 'cost_center_ids' => []],
]]])->save();
$preview = $service->for($f['issuer'], $draft);
expect($preview['steps'][2])->toBe(['role' => 'configured_1', 'label' => 'Direcção sintética'])
->and($draft->fresh()->approval_snapshot)->toBe($draft->approval_snapshot);
config(['requisition_approval.qa_enabled' => false]);
expect($service->for($f['issuer'], $draft)['state'])->toBe('unavailable');
});
test('submission preview preserves incomplete unknown and unauthorized states', function () {
$f = receiptFixture();
$draft = submissionPreviewDraft($f);
$this->actingAs($f['issuer']);
$service = app(RequisitionSubmissionPreview::class);
$draft->setAttribute('draft_input', ['incomplete' => true]);
expect($service->for($f['issuer'], $draft)['state'])->toBe('incomplete');
$draft->setAttribute('draft_input', null);
$other = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
expect($service->for($other, $draft))->toBeNull();
$draft->status = 'pending';
expect($service->for($f['issuer'], $draft))->toBeNull();
$foreign = User::factory()->create();
expect($service->for($foreign, $draft))->toBeNull();
});
+15
View File
@@ -3,6 +3,7 @@
use App\Enums\PurchasingRole;
use App\Models\StockMovement;
use App\Models\StockOperation;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
@@ -30,6 +31,20 @@ test('issues are exact, idempotent and cannot make stock negative', function ()
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(400)->and(StockOperation::query()->count())->toBe(1);
});
test('stock preparation consultations keep native visibility private history and source quantities intact', function () {
$before = StockMovement::query()->get()->toArray();
$operations = StockOperation::query()->get()->toArray();
foreach (['/stock', '/stock/operacoes'] as $url) {
$response = $this->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
}
$requester = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($requester)->get('/stock')->assertForbidden();
$this->get('/stock/operacoes')->assertForbidden();
expect(StockMovement::query()->get()->toArray())->toBe($before)
->and(StockOperation::query()->get()->toArray())->toBe($operations);
});
test('transfer creates exactly two opposite ledger entries and rejects repeated references', function () {
$this->p['kind'] = 'transfer';
$this->p['destination_warehouse_id'] = $this->dest->id;
+41 -3
View File
@@ -24,6 +24,28 @@ function maintenanceSupplierData(): array
return ['name' => 'Fornecedor existente', 'nuit' => '123456789', 'contact' => 'Contacto comercial', 'email' => 'fornecedor@example.test', 'phone' => '123456789', 'address' => 'Maputo', 'category' => 'Material', 'beneficiaries' => 'Beneficiário de teste', 'document_references' => 'Documentos verificados no processo de teste.', 'diligence_notes' => 'Documentação conferida para testes de manutenção.', 'blocked' => false, 'next_review' => now()->addYear()->format('Y-m-d')];
}
/** Real synthetic PDF bytes: fake()->create reports a virtual size over an empty file. */
function maintenanceSupplierDocument(string $name): UploadedFile
{
$objects = ['<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Count 1 /Kids [3 0 R] >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R >>', "<< /Length 0 >>\nstream\n\nendstream"];
// The uploader requires at least 1 KB of actual content, rather than a virtual size.
$bytes = "%PDF-1.4\n% ".str_repeat('Synthetic QA evidence only; not an official certificate. ', 24)."\n";
$offsets = [];
foreach ($objects as $index => $object) {
$offsets[] = strlen($bytes);
$bytes .= ($index + 1)." 0 obj\n".$object."\nendobj\n";
}
$xref = strlen($bytes);
$bytes .= "xref\n0 5\n0000000000 65535 f \n";
foreach ($offsets as $offset) {
$bytes .= sprintf("%010d 00000 n \n", $offset);
}
$bytes .= "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n".$xref."\n%%EOF\n";
return UploadedFile::fake()->createWithContent($name, $bytes);
}
beforeEach(function () {
Storage::fake('supplier_documents');
$this->tenant = Tenant::query()->create(['name' => 'Manutenção A']);
@@ -46,6 +68,14 @@ test('procurement can edit and renew a supplier but cannot forge validation or o
expect($audit->before['name'])->toBe('Fornecedor existente')->and($audit->after['name'])->toBe('Nome actualizado');
});
test('supplier edit preparation is encrypted and never renews diligence or changes validation by reading', function () {
$before = $this->supplier->fresh()->getAttributes();
$audits = AuditLog::query()->count();
$this->get($this->url.'/editar')->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('suppliers/edit')->where('supplier.version', 1));
expect($this->supplier->fresh()->getAttributes())->toBe($before)->and(AuditLog::query()->count())->toBe($audits);
});
test('unchanged edits preserve validation and do not create audit noise', function () {
$this->put($this->url, [...maintenanceSupplierData(), 'version' => 1])->assertSessionHasNoErrors();
expect($this->supplier->refresh()->status)->toBe('active')->and($this->supplier->version)->toBe(1);
@@ -73,11 +103,16 @@ test('non procurement roles cannot change suppliers or upload documents', functi
})->with([PurchasingRole::Finance, PurchasingRole::Admin, PurchasingRole::Requester, PurchasingRole::DepartmentHead, PurchasingRole::Warehouse]);
test('private upload saves metadata invalidates validation and audits without leaking storage paths', function () {
$this->post($this->url.'/documentos', ['document_type' => 'license', 'file' => UploadedFile::fake()->create('alvara.pdf', 10, 'application/pdf')])->assertSessionHasNoErrors()->assertRedirect();
$file = maintenanceSupplierDocument('alvara.pdf');
$bytes = file_get_contents($file->getPathname());
expect(strlen($bytes))->toBeGreaterThanOrEqual(1024)->toBeLessThanOrEqual(2097152);
$this->post($this->url.'/documentos', ['document_type' => 'license', 'file' => $file])->assertSessionHasNoErrors()->assertRedirect();
$document = SupplierDocument::query()->firstOrFail();
Storage::disk('supplier_documents')->assertExists($document->path);
expect($document->path)->toStartWith($this->tenant->id.'/'.$this->supplier->id.'/');
expect($document->original_name)->toBe('alvara.pdf')->and(strlen($document->sha256))->toBe(64);
expect((int) $document->size)->toBe(strlen($bytes))->and($document->sha256)->toBe(hash('sha256', $bytes))
->and(Storage::disk('supplier_documents')->get($document->path))->toBe($bytes);
expect($document->toArray())->not->toHaveKey('path');
expect($this->supplier->refresh()->status)->toBe('pending')->and($this->supplier->version)->toBe(2);
expect(AuditLog::query()->where('action', 'supplier.document_uploaded')->firstOrFail()->after['document'])->not->toHaveKey('path');
@@ -86,10 +121,13 @@ test('private upload saves metadata invalidates validation and audits without le
});
test('authorised downloads are attachments and recorded in audit', function (PurchasingRole $role) {
$this->post($this->url.'/documentos', ['document_type' => 'tax', 'file' => UploadedFile::fake()->create('certidao.pdf', 10, 'application/pdf')]);
$file = maintenanceSupplierDocument('certidao.pdf');
$bytes = file_get_contents($file->getPathname());
$this->post($this->url.'/documentos', ['document_type' => 'tax', 'file' => $file])->assertSessionHasNoErrors();
$document = SupplierDocument::query()->firstOrFail();
$user = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => $role]);
$this->actingAs($user)->get($this->url.'/documentos/'.$document->id)->assertOk()->assertDownload('certidao.pdf')->assertHeader('X-Content-Type-Options', 'nosniff')->assertHeader('Content-Type', 'application/octet-stream');
$response = $this->actingAs($user)->get($this->url.'/documentos/'.$document->id)->assertOk()->assertDownload('certidao.pdf')->assertHeader('X-Content-Type-Options', 'nosniff')->assertHeader('Content-Type', 'application/octet-stream');
expect($response->streamedContent())->toBe($bytes);
expect(AuditLog::query()->where('action', 'supplier.document_downloaded')->count())->toBe(1);
})->with([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]);
+91
View File
@@ -1,9 +1,14 @@
<?php
use App\Models\CostCenter;
use App\Models\CriticalityLevel;
use App\Models\Department;
use App\Models\Equipment;
use App\Models\User;
use App\Models\WarehouseRequest;
use App\Services\RequisitionWorkflow;
use App\Services\WarehouseFulfilment;
use App\Services\WarehouseWorkdesk;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
@@ -20,6 +25,92 @@ beforeEach(function () {
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '2.500', 'use' => 'internal', 'equipment_id' => null]]];
});
test('warehouse list and detail agree when an owner no longer has preparation or department review authority', function () {
$this->withoutVite();
$this->postJson('/stock/requisicoes', $this->data)->assertRedirect();
$record = WarehouseRequest::query()->sole();
$actor = $this->f['issuer'];
$desk = app(WarehouseWorkdesk::class);
expect($desk->canView($actor, $record))->toBeTrue();
DB::table('organization_memberships')->where('user_id', $actor->id)->update(['expires_at' => now()->subSecond()]);
supplyGrant($actor, ['warehouse_request_deliver']);
expect($desk->canView($actor, $record))->toBeFalse();
$this->get('/stock/requisicoes/'.$record->id)->assertForbidden();
expect($desk->visible($actor)->whereKey($record->id)->exists())->toBeFalse();
$this->get('/stock/requisicoes')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
supplyGrant($actor, ['warehouse_request_read']);
expect($desk->canView($actor, $record))->toBeTrue();
$this->get('/stock/requisicoes')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.total', 1));
});
test('global warehouse search uses native references event state literal terms and pagination without effects', function () {
$this->withoutVite();
config(['procurement_search.warehouse_requests_metadata_enabled' => true]);
$this->postJson('/stock/requisicoes', [...$this->data, 'destination' => 'GLOBAL-WAREHOUSE%_QA'])->assertRedirect();
$record = WarehouseRequest::query()->sole();
$this->postJson('/stock/requisicoes/'.$record->id.'/eventos', ['operation_key' => (string) Str::uuid(),
'version' => app(WarehouseFulfilment::class)->progress($record)['version'], 'action' => 'submit',
'reason' => 'Submissão sintética para conferir a projecção de pesquisa'])->assertRedirect();
foreach (range(1, 16) as $index) {
$this->postJson('/stock/requisicoes', [...$this->data, 'operation_key' => (string) Str::uuid(),
'destination' => 'PAGE-WAREHOUSE-'.$index])->assertRedirect();
}
$name = $record->snapshot['requester']['name'];
$this->f['issuer']->update(['name' => 'Current name changed after request']);
$before = [];
foreach (['warehouse_requests', 'warehouse_request_events', 'audit_logs', 'stock_movements', 'requisitions', 'budget_entries'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/compras/pesquisa?q=RA-'.$record->id)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)->assertInertia(fn (Assert $page) => $page
->where('warehouseRequestSearchAvailable', true)->where('groups.1.key', 'warehouse_requests')->where('groups.1.records.total', 1)
->where('groups.1.records.data.0.title', 'RA-'.$record->id)->where('groups.1.records.data.0.detail', 'submitted')
->where('groups.1.records.data.0.href', '/stock/requisicoes/'.$record->id)
->missing('groups.1.records.data.0.snapshot')->missing('groups.1.records.data.0.destination'));
$this->get('/compras/pesquisa?q='.urlencode('%_'))->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
$this->get('/compras/pesquisa?q='.urlencode($name))->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 17));
$this->get('/compras/pesquisa?q=PAGE-WAREHOUSE&warehouse_requests_page=2')->assertInertia(fn (Assert $page) => $page
->where('groups.1.records.total', 16)->where('groups.1.records.current_page', 2)->has('groups.1.records.data', 1));
$this->get('/compras/pesquisa?q=PAGE-WAREHOUSE&warehouse_requests_page=0')->assertSessionHasErrors('warehouse_requests_page');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->get('/stock/requisicoes/'.$record->id)->assertOk();
config(['procurement_search.warehouse_requests_metadata_enabled' => false]);
$this->get('/compras/pesquisa?q=RA-'.$record->id)->assertInertia(fn (Assert $page) => $page
->where('warehouseRequestSearchAvailable', false)->has('groups', 1));
});
test('global warehouse search and native read predicate agree across departments companies and withdrawn authority', function () {
$this->withoutVite();
config(['procurement_search.warehouse_requests_metadata_enabled' => true]);
$own = $this->f;
$this->postJson('/stock/requisicoes', [...$this->data, 'destination' => 'GLOBAL-SCOPE-OWN'])->assertRedirect();
$record = WarehouseRequest::query()->sole();
$department = Department::query()->create(['tenant_id' => $own['tenant']->id, 'name' => 'Other synthetic department']);
$centre = CostCenter::query()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $department->id, 'code' => 'SCOPE-QA', 'name' => 'Other synthetic centre']);
$otherOwner = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $department->id]);
supplyGrant($otherOwner, ['warehouse_request_prepare']);
$this->actingAs($otherOwner)->postJson('/stock/requisicoes', [...$this->data, 'operation_key' => (string) Str::uuid(),
'cost_center_id' => $centre->id, 'destination' => 'GLOBAL-SCOPE-OTHER-DEPARTMENT'])->assertRedirect();
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['warehouse_request_prepare']);
$this->actingAs($foreign['issuer'])->postJson('/stock/requisicoes', [...$this->data, 'operation_key' => (string) Str::uuid(),
'warehouse_id' => $foreign['warehouse']->id, 'cost_center_id' => $foreign['r']->cost_center_id, 'destination' => 'GLOBAL-SCOPE-OTHER-COMPANY',
'lines' => [['stock_item_id' => $foreign['stock']->id, 'quantity' => '1.000', 'use' => 'internal', 'equipment_id' => null]]])->assertRedirect();
$this->actingAs($own['issuer'])->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
$reviewer = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id]);
supplyGrant($reviewer, ['warehouse_request_review']);
$this->actingAs($reviewer)->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
supplyGrant($reviewer, ['warehouse_request_read']);
$this->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 2));
$this->actingAs($own['issuer']);
DB::table('organization_memberships')->where('user_id', $own['issuer']->id)->update(['expires_at' => now()->subSecond()]);
supplyGrant($own['issuer'], ['warehouse_request_deliver']);
$this->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 0));
expect(app(WarehouseWorkdesk::class)->canView($own['issuer'], $record))->toBeFalse();
});
test('warehouse draft freezes catalogue and destination once without stock budget or purchase effects', function () {
$moves = DB::table('stock_movements')->count();
$purchases = DB::table('requisitions')->count();
@@ -0,0 +1,6 @@
[
{"lines":[{"quantity":"0.29","unit_price":"0.50","tax_rate":"0"}],"minor":"15"},
{"lines":[{"quantity":"1","unit_price":"0.01","tax_rate":"50"},{"quantity":"1","unit_price":"0.01","tax_rate":"50"}],"minor":"4"},
{"lines":[{"quantity":"0.001","unit_price":"0.01","tax_rate":"16"}],"minor":"0"},
{"lines":[{"quantity":"1000000","unit_price":"100000000.00","tax_rate":"100"}],"minor":"20000000000000000"}
]
@@ -0,0 +1,52 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Compose already-authorised optional contracts only in the owned non-elevated ledger QA database. */
function integratedPurchasingQaSchema(): array
{
LedgerSchema::assertSynthetic(DB::connection());
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| DB::connection()->getConfig('port') !== '55439'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())) {
throw new LogicException('Integrated purchasing schema requires the dedicated owned QA composition.');
}
$migrations = [
'2026_11_22_000004_create_budget_distributions.php',
'2026_11_22_000007_create_budget_order_parts.php',
'2026_11_22_000008_create_purchase_order_sources.php',
'2026_11_22_000009_create_budget_landed_costs.php',
'2026_11_27_000001_add_requisition_cycles.php',
];
$tables = ['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions',
'budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions',
'purchase_order_sources', 'budget_landed_commands', 'budget_landed_entries', 'budget_requisition_cycles'];
foreach ($tables as $table) {
if (Schema::hasTable($table)) {
throw new LogicException('Never reinstall or repair a partial integrated QA schema implicitly.');
}
}
$columns = ['requisitions' => 'approval_cycle', 'approval_steps' => 'approval_cycle', 'budget_entries' => 'requisition_cycle',
'budget_distributions' => 'requisition_cycle', 'purchase_orders' => 'order_key'];
DB::transaction(function () use ($migrations, $tables, $columns) {
foreach ($migrations as $migration) {
(require base_path('database/qa-migrations/'.$migration))->up();
}
foreach ($tables as $table) {
if (! Schema::hasTable($table)) {
throw new LogicException('An integrated QA contract table was not created.');
}
}
foreach ($columns as $table => $column) {
if (! Schema::hasColumn($table, $column)) {
throw new LogicException('An integrated QA contract column was not created.');
}
}
});
config(['requisition-expiry.qa_enabled' => true]);
return ['migrations' => array_map(fn ($name) => ['name' => $name, 'sha256' => hash_file('sha256', base_path('database/qa-migrations/'.$name))], $migrations),
'verified_tables' => $tables, 'verified_columns' => $columns];
}
+3 -1
View File
@@ -36,11 +36,13 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return true;
}
if (in_array($mode, ['recover-cycles', 'recover-expenses'], true)) {
if (in_array($mode, ['recover-cycles', 'recover-expenses', 'recover-urgent'], true)) {
return $contains(fn ($row) => ($row['cycle_post_extension_all_tables_equal'] ?? false) === true
&& ($row['cycle_native_replays_without_effects'] ?? false) === true && ($row['cycle_history_and_reserve_restored'] ?? false) === true
&& ($row['cycle_reserved_minor'] ?? null) === 12000 && ($row['cycle_pre_extension_all_tables_equal'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true)
&& ($mode !== 'recover-urgent' || $contains(fn ($row) => ($row['urgent_policy_frozen_restored'] ?? false) === true
&& ($row['urgent_expire_seconds_restored'] ?? null) === 300))
&& ($mode !== 'recover-expenses' || $contains(fn ($row) => ($row['expense_versions_restored'] ?? null) === 2
&& ($row['expense_native_sources_verified'] ?? false) === true && ($row['expense_replay_without_effects'] ?? false) === true
&& ($row['expense_explicit_amounts_restored'] ?? null) === ['Material' => '1000', 'Serviços' => '3000']));
@@ -0,0 +1,80 @@
<?php
use App\Models\ExternalPayment;
use App\Models\GoodsReceipt;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrder;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\StockItem;
use App\Models\User;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPaymentInsights;
use Illuminate\Support\Facades\DB;
/** Assertion-only projection; every business mutation in the office journey must use native HTTP. */
function nativeOfficePurchaseState(array $fixture): array
{
$office = $fixture['office_journey'] ?? null;
if (! app()->environment('testing') || getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1' || ! is_array($office)
|| DB::transactionLevel() !== 1 || DB::selectOne('SHOW transaction_read_only')->transaction_read_only !== 'on') {
throw new LogicException('Owned office journey assertions require a top-level read-only transaction.');
}
$tenant = $fixture['tenant_id'];
$actor = User::query()->where('tenant_id', $tenant)->findOrFail($office['actors']['reviewer']['id']);
auth()->guard()->setUser($actor);
config(['common-payables.enabled' => true, 'common-payables.source_instance' => $office['source_instance'], 'expense-allocations.qa_enabled' => true]);
$requests = Requisition::query()->where('requester_id', $office['actors']['owner']['id'])->get();
if ($requests->count() > 1) {
throw new LogicException('The dedicated HTTP requester has more than one synthetic source.');
}
$request = $requests->first();
$budget = DB::table('budgets')->where('tenant_id', $tenant)->where('cost_center_id', $office['cost_center_id'])->where('kind', 'operating')->first();
$quotes = $request ? Quotation::query()->where('requisition_id', $request->id)->orderBy('id')->get() : collect();
$award = $request ? PurchaseAward::query()->where('requisition_id', $request->id)->first() : null;
$order = $award ? PurchaseOrder::query()->where('purchase_award_id', $award->id)->first() : null;
$invoice = $order ? Invoice::query()->where('purchase_order_id', $order->id)->first() : null;
$payments = $invoice ? ExternalPayment::query()->where('invoice_id', $invoice->id)->orderBy('id')->get() : collect();
$stock = StockItem::query()->where('code', 'HTTP-OFFICE-QA')->first();
$bank = $order ? DB::table('supplier_bank_details')->where('tenant_id', $tenant)->where('supplier_id', $order->supplier_id)->orderByDesc('id')->first(['id', 'revision']) : null;
$frames = [];
foreach (DB::select("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename") as $table) {
$name = $table->tablename;
if ($name !== 'budgets' && ! str_starts_with($name, 'budget_') && ! str_starts_with($name, 'gl_') && ! str_starts_with($name, 'pa_')
&& ! in_array($name, ['purchase_orders', 'purchase_order_items', 'purchase_order_sources', 'invoices', 'invoice_items', 'external_payments', 'stock_movements'], true)) {
continue;
}
$quoted = str_replace('"', '""', $name);
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.$quoted.'" t ORDER BY row_to_json(t)::text');
$frames[$name] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($name), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
}
$analytics = $request && $payments->where('status', 'confirmed')->isNotEmpty()
? app(ProcurementPaymentInsights::class)->build($actor, Requisition::query()->whereKey($request->id), null, null) : null;
return [
'budget' => $budget ? ['id' => $budget->id, 'created_by' => $budget->created_by, 'approved_by' => $budget->approved_by] : null,
'request' => $request ? ['id' => $request->id, 'status' => $request->status, 'process_version' => $request->process_version,
'approval_cycle' => $request->approval_cycle, 'total_minor' => $request->total_minor,
'items' => $request->items()->orderBy('id')->get(['id', 'category'])->toArray(),
'steps' => $request->steps()->orderBy('position')->get(['id', 'role', 'decision'])->toArray()] : null,
'suppliers' => DB::table('suppliers')->where('tenant_id', $tenant)->whereIn('nuit', ['300000001', '300000002', '300000003'])
->orderBy('id')->get(['id', 'nuit', 'version'])->map(fn ($row) => (array) $row)->all(),
'quotes' => $quotes->map(fn ($quote) => ['id' => $quote->id, 'supplier_id' => $quote->supplier_id, 'total_minor' => $quote->total_minor])->all(),
'award' => $award ? ['id' => $award->id, 'status' => $award->status,
'steps' => $award->approvals()->orderBy('position')->get(['id', 'role', 'decision'])->toArray()] : null,
'order' => $order ? ['id' => $order->id, 'total_minor' => $order->total_minor,
'items' => $order->items()->orderBy('id')->get(['id', 'quantity'])->toArray(),
'account_assignments' => $order->snapshot['account_assignments'] ?? null,
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->orderBy('id')->get(['id', 'status'])->toArray()] : null,
'stock' => $stock ? ['id' => $stock->id, 'quantity_milli' => (int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'),
'movements' => DB::table('stock_movements')->where('stock_item_id', $stock->id)->count()] : null,
'invoice' => $invoice ? ['id' => $invoice->id, 'status' => $invoice->status, 'total_minor' => $invoice->total_minor,
'outstanding_minor' => app(ExternalPaymentWorkflow::class)->outstanding($invoice)] : null,
'bank' => $bank ? ['id' => $bank->id, 'revision' => $bank->revision,
'approved_reviews' => DB::table('supplier_bank_reviews')->where('supplier_bank_detail_id', $bank->id)->where('decision', 'approved')->count()] : null,
'payments' => $payments->map(fn ($payment) => ['id' => $payment->id, 'amount_minor' => $payment->amount_minor, 'status' => $payment->status])->all(),
'analytics' => $analytics === null ? null : array_intersect_key($analytics, array_flip(['currencies', 'coverage', 'category_attribution'])),
'journals' => DB::table('gl_journals')->count(), 'financial_fingerprint' => hash('sha256', json_encode($frames, JSON_THROW_ON_ERROR)),
];
}
@@ -0,0 +1,259 @@
<?php
use App\Enums\PurchasingRole;
use App\Http\Controllers\AuditMetadataController;
use App\Models\CostCenter;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\UrgentRequisitionReviews;
use App\Services\WarehouseFulfilment;
use App\Services\WarehouseRequests;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Strictly guarded native synthetic composition; no real identities, source data or grants. */
function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $officeJourney = false): array
{
LedgerSchema::install(DB::connection());
$composition = null;
if ($integrated) {
require_once __DIR__.'/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
} else {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
$f = receiptFixture();
$f['tenant']->update(['name' => 'QA isolada de Compras — contas e urgências']);
config(['requisition-expiry.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true,
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
'procurement_search.warehouse_requests_metadata_enabled' => true]);
$people = [];
$profiles = [];
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
if ($officeJourney) {
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
'office_procurement_reviewer' => ['procurement']];
}
foreach ($functions as $key => $permissions) {
$people[$key] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'purchasing_role' => PurchasingRole::Configured, 'name' => 'QA '.$key, 'email' => 'qa-'.$key.'@example.invalid']);
$profiles[$key] = DB::table('organization_profiles')->insertGetId(['tenant_id' => $f['tenant']->id, 'name' => 'QA '.$key,
'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $f['tenant']->id, 'user_id' => $people[$key]->id,
'profile_id' => $profiles[$key], 'maintenance' => false]);
}
DB::table('organization_access')->insert(['tenant_id' => $f['tenant']->id, 'active' => true, 'version' => 1]);
foreach (['QA-100' => 'Materiais de ensaio', 'QA-200' => 'Outras necessidades de ensaio'] as $code => $label) {
DB::table('gl_accounts')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true]);
}
auth()->guard()->setUser($people['finance']);
$budget = app(CommonBudget::class)->for($people['finance'])->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação inteiramente fictícia da revisão nativa isolada']);
auth()->guard()->setUser($people['reviewer']);
app(CommonBudget::class)->for($people['reviewer'])->approve($budget);
app(PurchaseControlPolicyWorkflow::class)->propose($people['reviewer'], ['previous_id' => 0, 'mode' => 'unissued_award',
'enabled' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'reason' => 'Proposta exclusivamente sintética e desactivada para conferir o isolamento de consulta; sem aprovação ou publicação']);
app(RequisitionExpiry::class)->savePolicy($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => [],
'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => null]],
'reason' => 'Prazos explicitamente sintéticos para revisão de apresentação e gravação']);
app(UrgentRequisitionReviews::class)->savePolicy($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
'enabled' => true, 'profile_ids' => [$profiles['reviewer']], 'reason' => 'Designação de identidade inteiramente sintética para a revisão nativa']);
$workflow = app(RequisitionWorkflow::class);
$make = function (User $owner, string $priority, string $description, string $price = '100.00') use ($f, $workflow): array {
auth()->guard()->setUser($owner);
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => $priority,
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Dados inteiramente sintéticos para conferência local do percurso de Compras',
'items' => [['description' => $description, 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un',
'unit_price' => $price, 'tax_rate' => '0.00', 'procurement_category' => 'other', 'category_reason' => 'Texto livre exclusivamente sintético para ensaio de apresentação']]];
return [$workflow->save($owner, $input), $input];
};
$assign = function (User $owner, $request): void {
auth()->guard()->setUser($owner);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($owner, $request);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
$service->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'],
'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação fictícia confirmada antes da submissão nativa',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
'subtotal' => (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2),
'total' => (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2)]]]);
};
[$draft] = $make($people['reviewer'], 'normal', 'Material para conferir a atribuição de contas');
[$approved] = $make($people['requester'], 'urgent', 'Urgência sintética aprovada');
$assign($people['requester'], $approved);
$workflow->submit($people['requester'], $approved, (string) Str::uuid(), $approved->process_version);
$approved->refresh();
auth()->guard()->setUser($people['head']);
$workflow->decide($people['head'], $approved, 'approved', 'Decisão fictícia pelo aprovador independente', (string) Str::uuid(), $approved->process_version);
[$expired, $revision] = $make($people['requester'], 'urgent', 'Urgência original que será expirada');
$assign($people['requester'], $expired);
$workflow->submit($people['requester'], $expired, (string) Str::uuid(), $expired->process_version);
$expired->refresh();
// Fixed synthetic clock keeps this native visual fixture stable across requests.
CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(6));
Carbon::setTestNow(CarbonImmutable::now());
$deadline = app(RequisitionExpiry::class)->deadline($expired);
$workflow->expire($people['requester'], $expired, $deadline['basis_hash'], (string) Str::uuid(), $expired->process_version);
$expired->refresh();
$revision['operation_key'] = (string) Str::uuid();
$revision['process_version'] = $expired->process_version;
$revision['priority'] = 'normal';
$revision['items'][0]['description'] = 'Nova preparação depois da expiração — 120 MZN';
$revision['items'][0]['unit_price'] = '120.00';
$expired = $workflow->save($people['requester'], $revision, $expired);
$assign($people['requester'], $expired);
$workflow->submit($people['requester'], $expired, (string) Str::uuid(), $expired->process_version);
// Separate normal-cycle example: a real first decision remains visible after the second level expires.
auth()->guard()->setUser($people['reviewer']);
$f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
app(RequisitionExpiry::class)->savePolicy($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 1, 'enabled' => true,
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => 10,
'escalation_minutes' => null, 'profile_ids' => [], 'urgent_expire_minutes' => 5,
'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => null], ['department_head', 'procurement']),
'reason' => 'Configuração exclusivamente sintética para conferir autoria e documento dos ciclos anteriores']);
[$historyRequest, $historyInput] = $make($people['requester'], 'normal', 'Documento original do ciclo — 100 MZN');
$assign($people['requester'], $historyRequest);
$workflow->submit($people['requester'], $historyRequest, (string) Str::uuid(), $historyRequest->process_version);
auth()->guard()->setUser($people['head']);
$workflow->decide($people['head'], $historyRequest->fresh(), 'approved', 'Fundamento original da chefia — conferência inteiramente sintética',
(string) Str::uuid(), $historyRequest->fresh()->process_version);
CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(31));
Carbon::setTestNow(CarbonImmutable::now());
auth()->guard()->setUser($people['requester']);
$historyRequest->refresh();
$deadline = app(RequisitionExpiry::class)->deadline($historyRequest);
$workflow->expire($people['requester'], $historyRequest, $deadline['basis_hash'], (string) Str::uuid(), $historyRequest->process_version);
$historyInput['operation_key'] = (string) Str::uuid();
$historyInput['process_version'] = $historyRequest->fresh()->process_version;
$historyInput['items'][0]['description'] = 'Documento da nova submissão — 120 MZN';
$historyInput['items'][0]['unit_price'] = '120.00';
$historyRequest = $workflow->save($people['requester'], $historyInput, $historyRequest->fresh());
$assign($people['requester'], $historyRequest);
$workflow->submit($people['requester'], $historyRequest, (string) Str::uuid(), $historyRequest->process_version);
[$pending] = $make($people['requester'], 'urgent', 'Urgência para conferir os prazos próprios');
$assign($people['requester'], $pending);
$workflow->submit($people['requester'], $pending, (string) Str::uuid(), $pending->process_version);
require_once __DIR__.'/SupplyFixture.php';
auth()->guard()->setUser($people['reviewer']);
$planning = app(SupplyPlanning::class);
$agreement = $planning->save($people['reviewer'], '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()->addYear()->toDateString(),
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'QA-VISUAL-AGREEMENT']));
$contract = $planning->save($people['reviewer'], 'contract', supplyInput([
'supplier_id' => $f['order']->supplier_id, 'reference' => 'QA-VISUAL-CONTRACT', 'currency' => 'MZN',
'valid_from' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString(),
'periodicity_days' => 30, 'order_limit_amount' => '100.00', 'lead_days' => 3]));
auth()->guard()->setUser($people['head']);
$agreement = $planning->save($people['head'], 'agreement', supplyInput([], 'approve', $agreement));
$contract = $planning->save($people['head'], 'contract', supplyInput([], 'approve', $contract));
auth()->guard()->setUser($people['reviewer']);
$internal = app(WarehouseRequests::class)->draft($people['reviewer'], ['operation_key' => (string) Str::uuid(),
'warehouse_id' => $f['warehouse']->id, 'cost_center_id' => $f['r']->cost_center_id,
'destination' => 'QA-VISUAL-INTERNAL — destino exclusivamente sintético', 'reason' => 'Ensaio de pesquisa e leitura sem entrega física', 'priority' => 'normal',
'lines' => [['stock_item_id' => $f['stock']->id, 'quantity' => '1.000', 'use' => 'internal', 'equipment_id' => null]]]);
$fulfilment = app(WarehouseFulfilment::class);
$fulfilment->command($people['reviewer'], $internal->id, ['operation_key' => (string) Str::uuid(),
'version' => $fulfilment->progress($internal)['version'], 'action' => 'submit', 'reason' => 'Pedido sintético para conferir a projecção da pesquisa']);
if ($agreement->state !== 'approved' || $contract->state !== 'approved' || $fulfilment->progress($internal)['state'] !== 'submitted') {
throw new LogicException('Native search review fixture did not reach its required states.');
}
$historical = app(RequisitionExpiry::class)->workspace($people['reviewer'], $historyRequest->fresh());
$frozen = $historical['history']->getCollection()->first();
if ($frozen['request']['total_minor'] !== 10000 || $frozen['approval_amount_minor'] !== 10000
|| $frozen['steps'][0]['approver_id'] !== $people['head']->id || $frozen['rules']['first_limit_minor'] !== 5000
|| $historyRequest->fresh()->total_minor !== 12000 || $historical['canExpire']) {
throw new LogicException('Native historical decision fixture did not preserve its original document and independent new cycle.');
}
if (DB::transactionLevel() !== 0) {
throw new LogicException('Audit native review requires top-level native readonly transactions.');
}
$readonlyTransactions = 0;
DB::listen(function ($query) use (&$readonlyTransactions) {
if (str_starts_with($query->sql, 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY')
&& DB::selectOne('SHOW transaction_read_only')->transaction_read_only === 'on') {
$readonlyTransactions++;
}
});
$auditReadBefore = [];
foreach (['audit_logs', 'requisitions', 'approval_steps', 'supply_records', 'budget_entries', 'stock_movements', 'users', 'organization_profiles', 'organization_memberships'] as $table) {
$auditReadBefore[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
foreach (['reviewer' => true, 'auditor' => false] as $key => $canOpen) {
auth()->guard()->setUser($people[$key]);
$query = Request::create('/auditoria/eventos', 'GET', ['request_reference' => $historyRequest->number]);
$query->setUserResolver(fn () => $people[$key]);
$query->headers->set('X-Inertia', 'true');
$response = app(AuditMetadataController::class)->index($query);
$page = json_decode($response->getContent(), true, 64, JSON_THROW_ON_ERROR);
if (($page['props']['requestContext'] !== null) !== $canOpen || $page['props']['events']['total'] < 1) {
throw new LogicException('Audit metadata and native process scope were not kept independent.');
}
foreach ($page['props']['events']['data'] as $event) {
if (array_keys($event) !== ['id', 'created_at', 'action', 'user_id']) {
throw new LogicException('Audit metadata review exposed fields outside its native scope.');
}
}
}
$csvQuery = Request::create('/auditoria/eventos.csv', 'GET', ['request_reference' => $historyRequest->number]);
$csvQuery->setUserResolver(fn () => $people['auditor']);
ob_start();
try {
app(AuditMetadataController::class)->csv($csvQuery)->sendContent();
$csv = ob_get_contents();
} finally {
ob_end_clean();
}
if (! is_string($csv) || ! str_contains($csv, $historyRequest->number) || $readonlyTransactions !== 3 || DB::transactionLevel() !== 0) {
throw new LogicException('Native audit page/CSV did not complete three readonly transactions.');
}
foreach ($auditReadBefore as $table => $rows) {
if (DB::table($table)->orderBy('id')->get()->toJson() !== $rows) {
throw new LogicException('Native audit consultation changed its source rows.');
}
}
auth()->guard()->setUser($people['reviewer']);
$office = null;
if ($officeJourney) {
$centre = CostCenter::query()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'code' => 'HTTP-OFFICE-QA', 'name' => 'Centro exclusivamente sintético do percurso HTTP']);
foreach ([$people['finance'], $people['office_finance_reviewer']] as $reader) {
DB::table('pa_access')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $reader->id, 'person' => 'http-office-qa-'.$reader->id, 'action' => 'view']);
}
$office = ['cost_center_id' => $centre->id, 'warehouse_id' => $f['warehouse']->id, 'category' => 'Escritório QA HTTP',
'source_instance' => 'native-http-office-qa', 'actors' => []];
foreach (['owner' => 'office_requester', 'buyer' => 'reviewer', 'head' => 'head', 'finance' => 'finance',
'reviewer' => 'office_finance_reviewer', 'warehouse' => 'office_warehouse', 'procurement_reviewer' => 'office_procurement_reviewer'] as $function => $key) {
$office['actors'][$function] = ['id' => $people[$key]->id, 'email' => $people[$key]->email];
}
}
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
'office_journey' => $office,
'integrated_optional_schema' => $composition,
'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
'audit_request_reference' => $historyRequest->number, 'audit_native_readonly_transactions' => $readonlyTransactions,
'search_agreement' => $agreement->id, 'search_contract' => $contract->id, 'warehouse_search_request' => $internal->id,
'historical_decision_request' => $historyRequest->id, 'historical_decision_verified' => true,
'draft_request' => $draft->id, 'approved_request' => $approved->id, 'expired_request' => $expired->id,
'urgent_pending_request' => $pending->id, 'clock' => CarbonImmutable::now()->toIso8601String(), 'synthetic_only' => true];
}
@@ -0,0 +1,48 @@
<?php
use Illuminate\Support\Facades\DB;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Composition\Bundle;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\Payables\PayablesSchema;
/** Only the canonical QA source or the exact verified private runtime is accepted. */
function requisitionLedgerQaSource(): ?string
{
$source = getenv('RQ01_LEDGER_QA_SOURCE');
if (! is_string($source) || $source === '') {
return null;
}
if ($source === 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
if (config('common-finance-bundle.manifest_sha256') === '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df') {
throw new LogicException('A pinned private composition cannot fall back to the canonical development source.');
}
return $source;
}
$root = base_path('storage/framework/testing/requisition-ledger-runtime-qa-182e10ceec556e12');
$pin = '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df';
$normal = static fn ($value) => is_string($value) && realpath($value) !== false ? str_replace('\\', '/', realpath($value)) : null;
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| DB::connection()->getConfig('port') !== '55439'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())
|| $normal($source) !== $normal($root.'/general-ledger')
|| $normal(config('common-finance-bundle.root')) !== $normal($root)
|| config('common-finance-bundle.manifest_sha256') !== $pin
|| $normal(config('general-ledger.path')) !== $normal($source)) {
throw new LogicException('Only the pinned independently verified private ledger runtime is allowed.');
}
// AppServiceProvider already verified the pinned loader before loading Bundle or Payables.
Bundle::verify($root, $pin);
require_once $source.'/bootstrap.php';
foreach ([LedgerSchema::class => $root.'/general-ledger',
BudgetControl::class => base_path('storage/framework/testing/requisition-cycles-qa-35701ec1614f871e/budget-control'),
PayablesSchema::class => $root.'/payables'] as $class => $boundary) {
$file = (new ReflectionClass($class))->getFileName();
if (! is_string($file) || ! str_starts_with($normal($file) ?? '', ($normal($boundary) ?? 'unavailable').'/')) {
throw new LogicException('A financial class escaped the pinned private composition.');
}
}
return $source;
}
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { test } from 'node:test';
import { createNativeInertiaClient } from '../../scripts/lib/native-inertia-client.mjs';
test('owned native client drains large closed responses while preserving body headers cookies and manual redirects', async () => {
const payload = { synthetic_only: true, content: 'x'.repeat(2 * 1024 * 1024) };
let cookiesSeen = '';
const server = createServer((request, response) => {
response.setHeader('Connection', 'close');
if (request.url === '/cookies') {
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
}
if (request.url === '/empty') { response.writeHead(204); response.end(); return; }
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
cookiesSeen = request.headers.cookie ?? '';
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(payload));
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
const origin = `http://127.0.0.1:${server.address().port}`;
const client = createNativeInertiaClient(origin, assert.ok);
// Deliberately leave the returned body unread, matching status/header-only checks.
const first = await client.request('/large');
assert.equal(first.status, 200);
assert.equal(first.bodyUsed, false);
assert.equal(first.url, origin + '/large');
await client.request('/cookies');
const next = await client.request('/large');
assert.match(cookiesSeen, /QA_SESSION=first/);
assert.match(cookiesSeen, /QA_CONTEXT=second/);
assert.deepEqual(await next.json(), payload);
assert.equal(first.headers.get('Content-Type'), 'application/json');
assert.deepEqual(await first.json(), payload);
const empty = await client.request('/empty');
assert.equal(empty.status, 204);
assert.equal(await empty.text(), '');
const redirect = await client.request('/redirect');
assert.equal(redirect.status, 302);
assert.equal(redirect.headers.get('Location'), '/large');
assert.equal(await redirect.text(), 'Synthetic redirect');
await assert.rejects(client.request('//example.test/foreign'), /External HTTP destination refused/);
} finally {
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
}
});
@@ -0,0 +1,47 @@
<?php
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
$root = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$database = getenv('DB_DATABASE') ?: '';
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
if (getenv('APP_ENV') !== 'testing' || getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $database, $matches)
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_REQUISITION_QA_PORT')
|| $root === false || $boundary === false || str_replace('\\', '/', $root) !== str_replace('\\', '/', $boundary).'/rq01-ledger-qa-'.$matches[1]) {
http_response_code(503);
exit;
}
require __DIR__.'/../../vendor/autoload.php';
$public = $root.'/public';
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$asset = realpath($public.'/'.ltrim(rawurldecode($requestPath), '/'));
$types = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
&& isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
readfile($asset);
exit;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->useStoragePath($root.'/storage');
$app->usePublicPath($root.'/public');
$app->booted(function () use ($root, $database) {
abort_unless(config('database.default') === 'pgsql' && config('database.connections.pgsql.database') === $database, 503);
$fixture = json_decode(file_get_contents($root.'/native-review.json'), true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($fixture['clock']);
CarbonImmutable::setTestNow($fixture['clock']);
config(['requisition-expiry.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true,
'order_cancellation.enabled' => true,
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
'procurement_search.warehouse_requests_metadata_enabled' => true,
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
'session.secure' => false, 'cache.default' => 'array']);
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1') {
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'native-http-office-qa',
'expense-allocations.qa_enabled' => true]);
}
});
$app->handleRequest(Request::capture());
+12
View File
@@ -65,6 +65,18 @@ test('cycle recovery requires exact table restoration replay and disposal receip
expect(landedQaReceiptsVerified($command, json_encode($valid, JSON_THROW_ON_ERROR)."\n".$cleanup))->toBeFalse();
});
test('urgent recovery receipts require the frozen shorter policy as well as exact recovery and disposal', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'recover-urgent'];
$rows = [['cycle_post_extension_all_tables_equal' => true, 'cycle_native_replays_without_effects' => true,
'cycle_history_and_reserve_restored' => true, 'cycle_reserved_minor' => 12000, 'cycle_pre_extension_all_tables_equal' => true],
['isolated_restore_removed' => true], ['urgent_policy_frozen_restored' => true, 'urgent_expire_seconds_restored' => 300]];
$output = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
expect(landedQaReceiptsVerified($command, $output($rows)))->toBeTrue()
->and(landedQaReceiptsVerified($command, $output(array_slice($rows, 0, 2))))->toBeFalse();
$rows[2]['urgent_expire_seconds_restored'] = 1800;
expect(landedQaReceiptsVerified($command, $output($rows)))->toBeFalse();
});
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-estimate'];
$rows = [['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => true,
@@ -0,0 +1,16 @@
<?php
use Tempo\Purchasing\Internal\InternalRequisitions;
require_once __DIR__.'/../../packages/purchasing/bootstrap.php';
test('browser estimate vectors match the authoritative requisition line amounts', function () {
$vectors = json_decode(file_get_contents(__DIR__.'/../Fixtures/requisition-estimates.json'), true, flags: JSON_THROW_ON_ERROR);
foreach ($vectors as $vector) {
$total = 0;
foreach ($vector['lines'] as $line) {
$total += InternalRequisitions::line($line['quantity'], $line['unit_price'], $line['tax_rate'])['total_minor'];
}
expect((string) $total)->toBe($vector['minor']);
}
});
@@ -0,0 +1,120 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import OrderAmendment from '@/pages/purchases/order-parts-amendment';
import DistributionAmendment from '@/pages/purchases/distribution-amendment';
afterEach(() => vi.restoreAllMocks());
const allocation = {
allocation_key: 'synthetic-allocation',
line_id: 8,
centre_id: 9,
subtotal: '100.00',
total: '100.00',
};
const source = {
origin: 3,
version: 1,
plan_hash: 'synthetic-plan',
allocations: [allocation],
};
const preparedSource = {
...source,
allocations: source.allocations.map(
({ allocation_key, subtotal, total }) => ({
allocation_key,
subtotal,
total,
}),
),
};
const order = { id: 2, number: 'OC-QA', currency: 'MZN' };
function render(parts: boolean, actor = 7, plan = 'synthetic-plan') {
const component = parts ? OrderAmendment : DistributionAmendment;
return renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'purchases/amendment',
url: '/ordens/2/reafectacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: 4 } },
order,
history: [],
sources: [{ ...source, plan_hash: plan }],
planHash: plan,
version: 1,
options: [
{
...allocation,
line_label: 'Synthetic line',
centre_label: 'Synthetic centre',
},
],
},
}}
/>,
);
}
test.each([true, false])(
'restored Finance preparation remains dirty without submitting (%s)',
(parts) => {
const key = parts
? 'order-parts-amendment:4:7:2:3:1:synthetic-plan:data'
: 'distribution-amendment:4:7:2:synthetic-plan:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: '00000000-0000-4000-8000-000000000001',
reason: 'FINANCE-QA-NOT-SUBMITTED',
...(parts
? { sources: [preparedSource] }
: {
expected_plan_hash: 'synthetic-plan',
budget_distribution_preparation: [allocation],
}),
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render(parts);
expect(html).toContain('FINANCE-QA-NOT-SUBMITTED');
expect(html).toContain('data-preparation-dirty="true"');
expect(render(parts, 8)).not.toContain('FINANCE-QA-NOT-SUBMITTED');
expect(render(parts, 7, 'new-plan')).not.toContain(
'FINANCE-QA-NOT-SUBMITTED',
);
expect(post).not.toHaveBeenCalled();
},
);
test.each([true, false])(
'regenerated operation identity alone does not mark Finance preparation dirty (%s)',
(parts) => {
const key = parts
? 'order-parts-amendment:4:7:2:3:1:synthetic-plan:data'
: 'distribution-amendment:4:7:2:synthetic-plan:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: '00000000-0000-4000-8000-000000000001',
reason: '',
...(parts
? { sources: [preparedSource] }
: {
expected_plan_hash: 'synthetic-plan',
budget_distribution_preparation: [allocation],
}),
}
: undefined,
);
expect(render(parts)).toContain('data-preparation-dirty="false"');
},
);
+66
View File
@@ -0,0 +1,66 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ApprovalTimeouts from '@/pages/organization/approval-timeouts';
test('optional urgent timing has no default values and keeps explicit recipients visible for urgent-only escalation', () => {
const props: ComponentProps<typeof ApprovalTimeouts> = {
actorId: 1,
tenantId: 1,
roles: { department_head: 'Chefia' },
profiles: [{ id: 2, name: 'Perfil sintético' }],
history: { data: [], prev_page_url: null, next_page_url: null },
current: {
id: 3,
version: 1,
state: 'active',
reason: 'Política sintética',
data: {
enabled: true,
levels: [
{
role: 'department_head',
expire_minutes: 30,
reminder_minutes: 10,
escalation_minutes: null,
profile_ids: [],
},
],
},
},
};
function render() {
function Screen() {
return <ApprovalTimeouts {...props} />;
}
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'organization/approval-timeouts',
url: '/administracao/prazos-aprovacao',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
}
const unconfigured = render();
expect(unconfigured).toContain('Prazos reduzidos para urgências');
expect(unconfigured).not.toMatch(/<details[^>]*open=/);
expect(unconfigured).not.toContain('Perfis destinatários do escalamento');
props.current!.data.levels[0] = {
...props.current!.data.levels[0],
urgent_expire_minutes: 5,
urgent_reminder_minutes: 1,
urgent_escalation_minutes: 2,
profile_ids: [2],
};
const configured = render();
expect(configured).toMatch(/<details[^>]*open=/);
expect(configured).toContain('Perfis destinatários do escalamento');
expect(configured).toContain('Perfil sintético');
});
@@ -0,0 +1,71 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Metadata from '@/pages/audit/metadata';
function render(allowed: boolean) {
return renderToStaticMarkup(
<App
initialComponent={Metadata}
initialPage={{
component: 'audit/metadata',
url: '/auditoria/eventos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
filters: {
request_reference: 'QA<REQ>%_',
action: '0',
actor_id: 7,
from: '2026-11-01',
to: '2026-11-01',
page: 2,
},
requestContext: allowed
? {
number: 'QA<REQ>%_',
href: '/requisicoes/7#requisition-history',
}
: null,
events: {
data: [
{
id: 4,
action: '0',
created_at: '2026-11-01T12:00:00Z',
user_id: 7,
},
],
total: 131,
current_page: 2,
last_page: 6,
prev_page_url:
'/auditoria/eventos?request_reference=QA&page=1',
next_page_url: null,
},
},
}}
/>,
);
}
test('audit investigation carries applied criteria into the whole-scope CSV and escapes the reference', () => {
const html = render(false);
expect(html).toContain('Referência exacta da requisição');
expect(html).toContain('QA&lt;REQ&gt;%_');
expect(html).toContain(
'/auditoria/eventos.csv?request_reference=QA%3CREQ%3E%25_&amp;action=0&amp;actor_id=7&amp;from=2026-11-01&amp;to=2026-11-01',
);
expect(html).not.toContain('/requisicoes/7');
expect(html).not.toContain('PRIVATE-');
});
test('only an independently authorised native process locator is rendered', () => {
const html = render(true);
expect(html).toContain('href="/requisicoes/7#requisition-history"');
expect(html).toContain(
'Consultar o processo e o histórico de QA&lt;REQ&gt;%_',
);
});
+137
View File
@@ -0,0 +1,137 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Budgets from '@/pages/budgets/index';
afterEach(() => vi.restoreAllMocks());
const identity = 'budgets:4:7:finance:admin,finance';
function render(
actor = 7,
tenant = 4,
context = 'finance',
permissions = ['finance', 'admin'],
budgetId = 3,
reviewId = 9,
) {
return renderToStaticMarkup(
<App
initialComponent={Budgets}
initialPage={{
component: 'budgets/index',
url: '/orcamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions },
centers: [{ id: 1, code: 'CC-QA', name: 'Synthetic' }],
budgets: [
{
id: budgetId,
cost_center_id: 1,
year: 2026,
amount_minor: 10000,
reserved_minor: 0,
committed_minor: 0,
consumed_minor: 0,
available_minor: 10000,
created_by: 8,
approved_by: 8,
reason: 'Synthetic budget',
includes_tax: false,
reinforced_minor: 0,
approved_total_minor: 10000,
kind: 'operating',
},
],
reinforcements: {
data: [
{
id: reviewId,
budget_id: budgetId,
reference: 'QA',
amount_minor: 1000,
reason: 'Synthetic reinforcement',
status: 'pending',
created_by: 99,
reviewed_by: null,
review_reason: null,
},
],
prev_page_url: null,
next_page_url: null,
},
},
}}
/>,
);
}
test.each([
[
'allocation',
{
cost_center_id: '1',
year: 2026,
amount: '123.45',
reason: 'ALLOCATION-DRAFT-QA',
includes_tax: '0',
kind: 'investment',
},
'ALLOCATION-DRAFT-QA',
],
[
'reinforcement:3',
{
reference: 'REF-QA',
amount: '12.34',
reason: 'REINFORCEMENT-DRAFT-QA',
},
'REINFORCEMENT-DRAFT-QA',
],
[
'reinforcement-review:9',
{ decision: 'rejected', reason: 'REVIEW-DRAFT-QA' },
'REVIEW-DRAFT-QA',
],
])(
'budget %s preparation restores only its private actor/company/context/capability scope without a command',
(suffix, data, marker) => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:${suffix}:data` ? data : undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html.match(new RegExp(marker, 'g'))).toHaveLength(1);
expect(html).toContain('data-preparation-dirty="true"');
expect(render(8)).not.toContain(marker);
expect(render(7, 5)).not.toContain(marker);
expect(render(7, 4, 'procurement.internal')).not.toContain(marker);
expect(render(7, 4, 'finance', ['finance'])).not.toContain(marker);
expect(render(7, 4, 'finance', ['admin', 'finance'])).toContain(marker);
if (suffix.startsWith('reinforcement:'))
expect(
render(7, 4, 'finance', ['admin', 'finance'], 4),
).not.toContain(marker);
if (suffix.startsWith('reinforcement-review:'))
expect(
render(7, 4, 'finance', ['admin', 'finance'], 3, 10),
).not.toContain(marker);
expect(post).not.toHaveBeenCalled();
},
);
test('unchanged budget forms are clean and do not choose the company tax or classification decision', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).not.toContain('data-preparation-dirty="true"');
expect(html.match(/data-preparation-dirty="false"/g)).toHaveLength(3);
expect(
html.match(/<option value="" selected="">Decisão da empresa/g),
).toHaveLength(2);
expect(post).not.toHaveBeenCalled();
});
@@ -0,0 +1,250 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { CompanyDetailsSettings } from '@/components/company-details-settings';
import { WorkContextSettings } from '@/components/work-context-settings';
import { IntelligenceSettings } from '@/components/intelligence-settings';
import { AiPlanSettings } from '@/components/ai-plan-settings';
import { RequisitionApprovalSettings } from '@/components/requisition-approval-settings';
import { CompanyAdministrativeLocation } from '@/components/administrative-location';
afterEach(() => vi.restoreAllMocks());
const base = 'procurement-preparations:4:7:procurement.internal:admin';
const context = {
enforced: false,
active: 'procurement.internal',
available: ['procurement.internal'],
purchased: ['procurement.internal'],
paths: [],
sharedPaths: [],
permissions: [],
options: {
'procurement.internal': {
area: 'procurement',
areaLabel: 'Compras',
label: 'Compras internas',
operational: true,
},
},
};
const plan = {
state: 'draft' as const,
provider: 'none' as const,
model: '',
domains: [],
data_scopes: [],
monthly_budget_usd: '1.00',
monthly_requests: 10,
max_input_bytes: 1000,
max_output_tokens: 1000,
};
const components = {
details: CompanyDetailsSettings,
context: WorkContextSettings,
intelligence: IntelligenceSettings,
ai: AiPlanSettings,
approvals: RequisitionApprovalSettings,
geography: CompanyAdministrativeLocation,
};
function render(
kind: keyof typeof components,
overrides = {},
actor = 7,
tenant = 4,
active = 'procurement.internal',
) {
return renderToStaticMarkup(
<App
initialComponent={components[kind]}
initialPage={{
component: 'test',
url: '/test',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active },
organizationAccess: { permissions: ['admin'] },
version: 1,
ready: true,
details: null,
context,
enabled: [],
policy: {
revision: 1,
configured: true,
procurement_brief: true,
people_brief: true,
},
plan:
kind === 'approvals'
? {
revision: 1,
enabled: false,
quorum: 'one_eligible',
levels: [],
}
: plan,
profiles: [
{
id: 2,
name: 'Approval QA',
permissions: ['requisition_approve'],
},
],
costCenters: [],
domains: {},
scopes: {},
geography: null,
...overrides,
},
}}
/>,
);
}
test.each([
[
'details',
'company-details:1:true',
{
legal_name: 'COMPANY-POLICY-PREP-QA',
nuel: '',
address: '',
nuit: '',
phone: '',
email: '',
legal_representative: '',
bank_accounts: [],
establishments: [],
version: 1,
reason: 'Prepared company data',
},
],
[
'context',
'work-contexts:1:procurement.internal',
{
version: 1,
enabled: ['procurement.internal'],
confirm: true,
reason: 'COMPANY-POLICY-PREP-QA',
},
],
[
'intelligence',
'intelligence:1:true:1',
{
version: 1,
procurement_brief: true,
people_brief: true,
reason: 'COMPANY-POLICY-PREP-QA',
},
],
[
'ai',
'ai-plan:1:true',
{
version: 1,
provider: 'none',
model: 'COMPANY-POLICY-PREP-QA',
domains: [],
data_scopes: [],
monthly_budget_usd: '1.00',
monthly_requests: 10,
max_input_bytes: 1000,
max_output_tokens: 1000,
reason: 'Prepared plan only',
},
],
[
'approvals',
'approval-settings:1:1:true',
{
version: 1,
enabled: false,
levels: [],
reason: 'COMPANY-POLICY-PREP-QA',
},
],
] as const)(
'%s preparation is private version scoped and never applies a company policy on recovery',
(kind, scope, prepared) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:${scope}:data` ? prepared : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(kind)).toContain('COMPANY-POLICY-PREP-QA');
expect(render(kind)).toContain('data-preparation-dirty="true"');
expect(render(kind, {}, 8)).not.toContain('COMPANY-POLICY-PREP-QA');
expect(render(kind, {}, 7, 5)).not.toContain('COMPANY-POLICY-PREP-QA');
expect(render(kind, {}, 7, 4, 'finance')).not.toContain(
'COMPANY-POLICY-PREP-QA',
);
expect(render(kind, { version: 2 })).not.toContain(
'COMPANY-POLICY-PREP-QA',
);
expect(post).not.toHaveBeenCalled();
},
);
test('approval preparation cannot cross a native plan revision', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:approval-settings:1:1:true:data`
? {
version: 1,
enabled: false,
levels: [],
reason: 'APPROVAL-DRAFT-QA',
}
: undefined,
);
expect(render('approvals')).toContain('APPROVAL-DRAFT-QA');
expect(
render('approvals', {
plan: {
revision: 2,
enabled: false,
quorum: 'one_eligible',
levels: [],
},
}),
).not.toContain('APPROVAL-DRAFT-QA');
});
test('company location preparation stays bound to its original concurrency reference', () => {
const reference = {
country: 'MZ',
catalogue: 'qa-catalogue',
record_id: '11',
};
const geography = { reference, path: [], requires_review: false };
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-location:${JSON.stringify(reference)}:data`
? {
geography_reference: { ...reference, record_id: '12' },
expected_reference: reference,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('geography', { geography })).toContain(
'data-preparation-dirty="true"',
);
expect(
render('geography', {
geography: {
...geography,
reference: { ...reference, record_id: '13' },
},
}),
).toContain('data-preparation-dirty="false"');
expect(render('geography', { geography }, 8)).toContain(
'data-preparation-dirty="false"',
);
expect(post).not.toHaveBeenCalled();
});
test('unchanged company policy forms stay clean', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
for (const kind of Object.keys(components) as (keyof typeof components)[])
expect(render(kind)).not.toContain('data-preparation-dirty="true"');
});
+303
View File
@@ -0,0 +1,303 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Setup from '@/pages/company/setup';
import Team from '@/pages/company/index';
import Parameters from '@/pages/company/parameters';
afterEach(() => vi.restoreAllMocks());
const base = 'procurement-preparations:4:7:procurement.internal:admin';
const root = `${base}:company-parameters:1:true:true`;
const comparison = {
revision: 1,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
};
const profile = {
id: 2,
name: 'Original finance profile',
permissions: ['finance'],
work_contexts: [],
};
const parameterProps = {
companyDetails: null,
companyDetailsReady: false,
ready: true,
active: true,
version: 1,
permissions: {
admin: 'Administração',
finance: 'Finanças',
requester: 'Requisitante',
},
profiles: [profile],
memberships: [],
users: [
{
id: 8,
name: 'Existing QA',
email: 'existing@example.test',
department_id: 1,
},
],
departments: [{ id: 1, name: 'Department QA' }],
costCenters: [{ id: 1, code: 'CC-QA', name: 'Centre QA' }],
companyRules: {
first_limit: '100.00',
second_limit: '1000.00',
includes_tax: true,
provisional: false,
default_tax_rate: '16',
},
comparisonPolicy: comparison,
};
function render(
kind: 'setup' | 'team' | 'parameters',
overrides = {},
actor = 7,
tenant: number | null = 4,
context = 'procurement.internal',
) {
return renderToStaticMarkup(
<App
initialComponent={
kind === 'setup' ? Setup : kind === 'team' ? Team : Parameters
}
initialPage={{
component: `company/${kind}`,
url: '/empresa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['admin'] },
...(kind === 'parameters'
? parameterProps
: {
company: {
id: 4,
name: 'Company QA',
first_limit_minor: 10000,
second_limit_minor: 100000,
approval_includes_tax: true,
rules_provisional: false,
},
departments: [{ id: 1, name: 'Department QA' }],
costCenters: [],
users: [],
roles: [
{ value: 'requester', label: 'Requisitante' },
],
}),
...overrides,
},
}}
/>,
);
}
test.each([
['department', { name: 'DEPARTMENT-PREP-QA' }, 'DEPARTMENT-PREP-QA'],
[
'center',
{ department_id: '1', code: 'CENTER-PREP-QA', name: 'Centre' },
'CENTER-PREP-QA',
],
[
'user',
{
version: 1,
name: 'USER-PREP-QA',
email: 'prepared@example.test',
department_id: '1',
profile_ids: [2],
reason: 'Synthetic account proposal',
},
'USER-PREP-QA',
],
[
'rules',
{
version: 1,
first_limit: '100.00',
second_limit: '1000.00',
includes_tax: false,
reason: 'RULES-PREP-QA',
},
'RULES-PREP-QA',
],
[
'tax',
{ version: 1, default_tax_rate: '16', reason: 'TAX-PREP-QA' },
'TAX-PREP-QA',
],
[
'comparison',
{
version: 1,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: comparison.weights,
reason: 'COMPARISON-PREP-QA',
},
'COMPARISON-PREP-QA',
],
] as const)(
'company %s preparation is isolated by actor company context and exact configuration version without a command',
(suffix, data, marker) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${root}:${suffix}:data` ? data : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('parameters')).toContain(marker);
expect(render('parameters')).toContain('data-preparation-dirty="true"');
expect(render('parameters', {}, 9)).not.toContain(marker);
expect(render('parameters', {}, 7, 5)).not.toContain(marker);
expect(render('parameters', {}, 7, 4, 'finance')).not.toContain(marker);
expect(render('parameters', { version: 2 })).not.toContain(marker);
expect(post).not.toHaveBeenCalled();
},
);
test('profile preparation follows selected source while the original profile remains unchanged', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${root}:selected-profile`
? '2'
: k === `${root}:profile:2:data`
? {
version: 1,
id: '2',
name: 'PROFILE-PREP-QA',
permissions: ['finance'],
work_contexts: [],
}
: undefined,
);
expect(render('parameters')).toContain('PROFILE-PREP-QA');
expect(render('parameters')).toContain('Original finance profile');
expect(render('parameters', { version: 2 })).not.toContain(
'PROFILE-PREP-QA',
);
expect(render('parameters', { profiles: [] })).toContain(
'Perfil seleccionado indisponível',
);
});
test('access assignment preparation follows its person and native version without granting access', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-assignment:8:1:data`
? {
version: 1,
user_id: 8,
profile_ids: [2],
maintenance: false,
expires_at: '',
reason: 'ASSIGNMENT-PREP-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('parameters')).toContain('ASSIGNMENT-PREP-QA');
expect(render('parameters', { version: 2 })).not.toContain(
'ASSIGNMENT-PREP-QA',
);
expect(render('parameters', { users: [] })).not.toContain(
'ASSIGNMENT-PREP-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('activation preparation remains explicit and does not activate the company on restore', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-parameters:1:false:true:activate:data`
? { version: 1, confirm: true, reason: 'ACTIVATION-PREP-QA' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('parameters', { active: false })).toContain(
'ACTIVATION-PREP-QA',
);
expect(render('parameters', { active: false, version: 2 })).not.toContain(
'ACTIVATION-PREP-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('bootstrap restores company metadata for the exact account and leaves passwords empty', () => {
const key =
'procurement-preparations:null:7:procurement.internal:admin:company-setup';
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${key}:data`
? {
name: 'SETUP-PREP-QA',
department: 'Department',
second_name: 'Second QA',
second_email: 'second@example.test',
first_limit: '100.00',
second_limit: '1000.00',
includes_tax: true,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('setup', {}, 7, null);
expect(html).toContain('SETUP-PREP-QA');
expect(html.match(/type="password"[^>]*value=""/g)).toHaveLength(2);
expect(render('setup', {}, 9, null)).not.toContain('SETUP-PREP-QA');
expect(post).not.toHaveBeenCalled();
});
test('legacy team account metadata is private without restoring a password', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-team:4:user:data`
? {
name: 'TEAM-PREP-QA',
email: 'team@example.test',
department_id: '1',
purchasing_role: 'requester',
}
: undefined,
);
const html = render('team');
expect(html).toContain('TEAM-PREP-QA');
expect(html.match(/type="password"[^>]*value=""/g)).toHaveLength(2);
expect(render('team', {}, 9)).not.toContain('TEAM-PREP-QA');
});
test('omitted non-remembered password fields do not make clean metadata dirty', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${root}:user:data`
? {
version: 1,
name: '',
email: '',
department_id: '',
profile_ids: [],
reason: '',
}
: k === `${base}:company-team:4:user:data`
? {
name: '',
email: '',
department_id: '',
purchasing_role: 'requester',
}
: k ===
'procurement-preparations:null:7:procurement.internal:admin:company-setup:data'
? {
name: '',
department: '',
second_name: '',
second_email: '',
first_limit: '',
second_limit: '',
includes_tax: true,
}
: undefined,
);
const parameters = render('parameters');
expect(parameters).not.toContain('data-preparation-dirty="true"');
expect(parameters.match(/type="password"[^>]*value=""/g)).toHaveLength(2);
expect(render('team')).not.toContain('data-preparation-dirty="true"');
expect(render('setup', {}, 7, null)).not.toContain(
'data-preparation-dirty="true"',
);
});
@@ -0,0 +1,120 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Conflicts from '@/pages/conflicts/index';
import History from '@/pages/conflicts/show';
afterEach(() => vi.restoreAllMocks());
const identity = 'conflicts:4:7:finance:finance';
const declaration = {
id: 3,
user_id: 7,
supplier_id: 1,
requisition_id: null,
has_conflict: true,
known_since: '2026-01-01',
declared_at: '2026-11-28T00:00:00Z',
reason: 'Original synthetic conflict',
previous_id: null,
root_id: null,
author: { name: 'Synthetic actor' },
supplier: { name: 'Synthetic supplier' },
requisition: null,
};
function render(
history = false,
actor = 7,
tenant = 4,
context = 'finance',
canCorrect = true,
sourceId = 3,
) {
return renderToStaticMarkup(
<App
initialComponent={history ? History : Conflicts}
initialPage={{
component: history ? 'conflicts/show' : 'conflicts/index',
url: '/conflitos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: {
user: {
id: actor,
tenant_id: tenant,
name: 'Synthetic actor',
},
},
workContext: { active: context },
organizationAccess: { permissions: ['finance'] },
history: [{ ...declaration, id: sourceId }],
canCorrect,
declarations: {
data: [],
prev_page_url: null,
next_page_url: null,
},
suppliers: [{ id: 1, name: 'Synthetic supplier' }],
requisitions: [],
},
}}
/>,
);
}
test('personal declaration preparation remains private to its actor company and context without submitting', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:new:data`
? {
scope: 'supplier',
supplier_id: '1',
requisition_id: '',
has_conflict: '1',
known_since: '2026-01-01',
reason: 'PERSONAL-DRAFT-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('PERSONAL-DRAFT-QA');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render(false, 8)).not.toContain('PERSONAL-DRAFT-QA');
expect(render(false, 7, 5)).not.toContain('PERSONAL-DRAFT-QA');
expect(render(false, 7, 4, 'procurement.internal')).not.toContain(
'PERSONAL-DRAFT-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('correction preparation follows the immutable source version and current correction authority', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:correction:3:${declaration.declared_at}:true:data`
? {
reason: 'CORRECTION-DRAFT-QA',
known_since: '2026-02-01',
}
: undefined,
);
const put = vi.spyOn(router, 'put');
const html = render(true);
expect(html).toContain('CORRECTION-DRAFT-QA');
expect(html).toContain('Original synthetic conflict');
expect(html).toContain('data-preparation-dirty="true"');
expect(render(true, 8)).not.toContain('CORRECTION-DRAFT-QA');
expect(render(true, 7, 5)).not.toContain('CORRECTION-DRAFT-QA');
expect(render(true, 7, 4, 'finance', false)).not.toContain(
'CORRECTION-DRAFT-QA',
);
expect(render(true, 7, 4, 'finance', true, 4)).not.toContain(
'CORRECTION-DRAFT-QA',
);
expect(put).not.toHaveBeenCalled();
});
test('unchanged declaration and correction do not mark a preparation dirty', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
expect(render()).toContain('data-preparation-dirty="false"');
expect(render(true)).toContain('data-preparation-dirty="false"');
expect(render(true, 7, 4, 'finance', false)).not.toContain(
'data-preparation-dirty',
);
});
+76
View File
@@ -0,0 +1,76 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
ProcurementDeliveryInsights,
type DeliveryInsights,
} from '@/components/procurement-delivery-insights';
test('delivery review preserves unknown dates, native quantities and independent filters', () => {
const data: DeliveryInsights = {
view: 'attention',
coverage: { unknown: 1 },
pending_lines: 1,
unknown_lines: 1,
unverified_receipt_lines: 1,
records: {
current_page: 2,
last_page: 3,
total: 41,
data: [
{
id: 4,
number: 'OC-QA-4',
state: 'unknown',
pending_lines: 1,
unknown_lines: 1,
unverified_receipt_lines: 1,
late_days: null,
quality_pending: false,
href: '/ordens/4',
late_lines: [],
},
],
},
};
const html = renderToStaticMarkup(
<ProcurementDeliveryInsights
data={data}
pageHref="/relatorios?status=approved&supplier_page=2"
exportHref="/relatorios/entregas.csv?status=approved"
/>,
);
expect(html).toContain('Maior atraso documentado: por determinar');
expect(html).not.toContain('0 dia(s)');
expect(html).toContain('datas de recepção');
expect(html).toContain(
'status=approved&amp;supplier_page=2&amp;delivery_state=attention&amp;delivery_page=3',
);
expect(html).toContain('/relatorios/entregas.csv?status=approved');
data.records.data[0] = {
...data.records.data[0],
state: 'completed_late',
late_days: 2,
quality_pending: true,
late_lines: [
{
id: 8,
description: 'Peça & suporte',
unit: 'kg',
promised_on: '2026-11-20',
completed_on: '2026-11-22',
pending_quantity: '0.000',
},
],
};
const completed = renderToStaticMarkup(
<ProcurementDeliveryInsights
data={data}
pageHref="/relatorios"
exportHref="/relatorios/entregas.csv"
/>,
);
expect(completed).toContain('2 dia(s)');
expect(completed).toContain('qualidade ou aceitação permanece pendente');
expect(completed).toContain('0.000 kg');
expect(completed).toContain('Peça &amp; suporte');
});
@@ -0,0 +1,144 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { QuotationExchangePanel } from '@/components/quotation-exchange-panel';
import Cancellation from '@/components/order-cancellation-request';
afterEach(() => vi.restoreAllMocks());
const identity = 'procurement-preparations:4:7:finance:finance';
function render(
exchange: boolean,
overrides = {},
actor = 7,
tenant = 4,
context = 'finance',
) {
return renderToStaticMarkup(
<App
initialComponent={exchange ? QuotationExchangePanel : Cancellation}
initialPage={{
component: 'test',
url: '/test',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['finance'] },
requisitionId: 3,
processVersion: 2,
rates: [],
canRecord: true,
orderId: 11,
state: { enabled: true, state: 'issued', canRequest: true },
...overrides,
},
}}
/>,
);
}
test('documentary FX preparation follows process version and capability without freezing a rate', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:quotation-exchange:3:2:true:data`
? {
operation_id: 'saved-qa-operation',
currency: 'USD',
rate: '60.1234567890',
quoted_on: '2026-11-28',
source: 'FX-PREPARATION-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(true)).toContain('FX-PREPARATION-QA');
expect(render(true)).toContain('data-preparation-dirty="true"');
expect(render(true, {}, 8)).not.toContain('FX-PREPARATION-QA');
expect(render(true, {}, 7, 5)).not.toContain('FX-PREPARATION-QA');
expect(render(true, {}, 7, 4, 'procurement.internal')).not.toContain(
'FX-PREPARATION-QA',
);
expect(render(true, { requisitionId: 4 })).not.toContain(
'FX-PREPARATION-QA',
);
expect(render(true, { processVersion: 3 })).not.toContain(
'FX-PREPARATION-QA',
);
expect(render(true, { canRecord: false })).not.toContain(
'FX-PREPARATION-QA',
);
expect(
render(true, {
rates: [
{
id: 8,
currency: 'EUR',
rate: '70',
quoted_on: '2026-11-28',
source: 'Synthetic prior basis',
recorded_by: 9,
},
],
}),
).toContain('FX-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
});
test('cancellation request preparation is isolated by order and current native eligibility', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:order-cancellation:11:true:issued:true:data`
? {
operation_key: 'saved-qa-operation',
reason: 'CANCELLATION-PREPARATION-QA',
evidence: 'Synthetic documentary evidence',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(false)).toContain('CANCELLATION-PREPARATION-QA');
expect(render(false)).toContain('data-preparation-dirty="true"');
expect(render(false, {}, 8)).not.toContain('CANCELLATION-PREPARATION-QA');
expect(render(false, {}, 7, 5)).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
expect(render(false, {}, 7, 4, 'warehouse')).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
expect(render(false, { orderId: 12 })).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
for (const state of [
{ enabled: true, state: 'issued', canRequest: false },
{ enabled: false, state: 'issued', canRequest: false },
{ enabled: true, state: 'cancellation_pending', canRequest: false },
]) {
expect(render(false, { state })).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
}
expect(post).not.toHaveBeenCalled();
});
test.each([true, false])(
'restored UUID alone stays clean for documentary command exchange=%s',
(exchange) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:quotation-exchange:3:2:true:data`
? {
operation_id: 'saved-qa-operation',
currency: '',
rate: '',
quoted_on: '',
source: '',
}
: k ===
`${identity}:order-cancellation:11:true:issued:true:data`
? {
operation_key: 'saved-qa-operation',
reason: '',
evidence: '',
}
: undefined,
);
expect(render(exchange)).toContain('data-preparation-dirty="false"');
},
);
@@ -0,0 +1,74 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import EquipmentShow from '@/pages/equipment/show';
const page = {
data: [],
total: 0,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
};
function render(
reference: {
record_key: string;
code: string;
name: string;
version: number;
state: string;
href: string;
} | null,
) {
return renderToStaticMarkup(
<App
initialComponent={EquipmentShow}
initialPage={{
component: 'equipment/show',
url: '/equipamentos/1',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
equipment: {
id: 1,
code: 'EQ-QA',
description: 'Equipamento sintético',
area: 'Ensaio',
status: 'active',
},
purchases: page,
movements: page,
capitalReference: reference,
},
}}
/>,
);
}
test('equipment shows an explicit current asset reference and its existing purchase trace without rewriting its origins', () => {
const html = render({
record_key: 'qa-key',
code: 'ASSET-QA',
name: 'Nome actual <QA>',
version: 2,
state: 'archived',
href: '/projectos-imobilizado?history=qa-key',
});
expect(html).toContain('ASSET-QA');
expect(html).toContain('Nome actual &lt;QA&gt;');
expect(html).toContain('versão 2 · arquivada');
expect(html).toContain('href="/projectos-imobilizado?history=qa-key"');
expect(html).toContain('Consultar aquisição e recepções');
expect(html).toContain('documentos de compra conservam a referência');
expect(html).toContain('Requisições de compra associadas');
});
test('an unavailable or unauthorized asset reference does not introduce an empty panel or action', () => {
const html = render(null);
expect(html).not.toContain('Imobilizado no cadastro de Compras');
expect(html).not.toContain('Consultar aquisição e recepções');
expect(html).toContain('Equipamento sintético');
});
@@ -0,0 +1,188 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Equipment, { EquipmentDemo } from '@/pages/equipment/index';
afterEach(() => vi.restoreAllMocks());
const identity = 'inventory-events:4:7:warehouse:/equipamentos:true:true:false';
const asset = {
id: 3,
version: 2,
code: 'EQ-QA',
description: 'Original synthetic equipment',
area: 'Production',
serial_number: null,
department_id: 1,
stock_item_id: null,
criticality_level_id: 1,
status: 'active',
};
const part = {
id: 4,
version: 2,
stock_item_id: 1,
criticality_level_id: 1,
minimum_milli: 1000,
balance_milli: 0,
below_minimum: true,
};
function render(overrides = {}, actor = 7, tenant = 4, context = 'warehouse') {
return renderToStaticMarkup(
<App
initialComponent={Equipment}
initialPage={{
component: 'equipment/index',
url: '/equipamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
equipment: [asset],
parts: [part],
levels: [
{
id: 1,
code: 'L-QA',
name: 'Synthetic level',
criteria: 'Synthetic criteria',
is_critical: true,
},
],
links: [],
items: [
{
id: 1,
code: 'ITEM-QA',
name: 'Synthetic item',
unit: 'un',
},
],
departments: [{ id: 1, name: 'Production' }],
history: {
data: [],
prev_page_url: null,
next_page_url: null,
},
canManage: true,
canConfigure: true,
...overrides,
},
}}
/>,
);
}
test('asset preparation follows selected immutable source and never overwrites the original catalogue display', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:selected-asset`
? '3'
: k === `${identity}:asset:3:2:data`
? {
geography_reference: null,
id: '3',
version: '2',
code: 'PRIVATE-ASSET-DRAFT',
description: 'Prepared description',
area: 'Production',
serial_number: '',
department_id: '1',
stock_item_id: '',
criticality_level_id: '1',
status: 'stopped',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('PRIVATE-ASSET-DRAFT');
expect(render()).toContain('Original synthetic equipment');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({ equipment: [{ ...asset, version: 3 }] })).not.toContain(
'PRIVATE-ASSET-DRAFT',
);
expect(render({}, 8)).not.toContain('PRIVATE-ASSET-DRAFT');
expect(render({}, 7, 5)).not.toContain('PRIVATE-ASSET-DRAFT');
expect(render({}, 7, 4, 'finance')).not.toContain('PRIVATE-ASSET-DRAFT');
expect(render({ canManage: false })).not.toContain('PRIVATE-ASSET-DRAFT');
expect(post).not.toHaveBeenCalled();
});
test('part preparation restores by selected part and version independently of asset editing', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:selected-part`
? '4'
: k === `${identity}:part:4:2:data`
? {
id: '4',
version: '2',
stock_item_id: '1',
criticality_level_id: '1',
minimum_quantity: '4.567',
}
: undefined,
);
expect(render()).toContain('value="4.567"');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({ parts: [{ ...part, version: 3 }] })).not.toContain(
'value="4.567"',
);
expect(render({}, 8)).not.toContain('value="4.567"');
});
test('category preparation does not confer configuration rights', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:category:data`
? {
code: 'CAT-QA',
name: 'CATEGORY-DRAFT-QA',
criteria: 'Synthetic criterion',
is_critical: '1',
}
: undefined,
);
expect(render()).toContain('CATEGORY-DRAFT-QA');
expect(render({ canConfigure: false })).not.toContain('CATEGORY-DRAFT-QA');
});
test('equipment part association preparation retains explicit native selections without associating them', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:association:data`
? { equipment_id: '3', spare_part_id: '4' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('<option value="3" selected=""');
expect(render()).toContain('<option value="4" selected=""');
expect(post).not.toHaveBeenCalled();
});
test('a remembered source absent from the native catalogue cannot turn into a new record implicitly', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:selected-asset`
? '99'
: k === `${identity}:selected-part`
? '98'
: undefined,
);
const html = render();
expect(html.match(/Ficha seleccionada indisponível/g)).toHaveLength(2);
expect(html).not.toContain('Guardar equipamento');
});
test('equipment demonstration renders without private identity and unmodified private forms are clean', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
expect(render()).not.toContain('data-preparation-dirty="true"');
expect(
renderToStaticMarkup(
<App
initialComponent={EquipmentDemo}
initialPage={{
component: 'preview/index',
url: '/preview',
version: null,
clearHistory: false,
encryptHistory: false,
props: { errors: {} },
}}
/>,
),
).toContain('Equipamentos e peças sobressalentes');
expect(post).not.toHaveBeenCalled();
});
+40
View File
@@ -0,0 +1,40 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { FormErrors } from '@/components/procurement';
import { focusFormError } from '@/lib/form-error-focus';
afterEach(() => vi.unstubAllGlobals());
test('only mapped validation errors offer field links and all messages remain escaped', () => {
const html = renderToStaticMarkup(
<FormErrors
errors={{ quantity: '<Quantidade>', version: 'Actualize a versão' }}
targets={{ quantity: 'quantity-line-a' }}
/>,
);
expect(html).toContain('href="#quantity-line-a"');
expect(html).toContain('&lt;Quantidade&gt;');
expect(html).not.toContain('href="#version"');
expect(html).toContain('Actualize a versão');
});
test('field navigation opens collapsed ancestors before focusing and scrolling', () => {
const steps: string[] = [];
const details = {
tagName: 'DETAILS',
parentElement: null,
setAttribute: (name: string) => steps.push(name),
};
const target = {
parentElement: { tagName: 'DIV', parentElement: details },
focus: () => steps.push('focus'),
scrollIntoView: () => steps.push('scroll'),
};
vi.stubGlobal('document', {
getElementById: (id: string) => (id === 'field' ? target : null),
});
expect(focusFormError('missing')).toBe(false);
expect(steps).toEqual([]);
expect(focusFormError('field')).toBe(true);
expect(steps).toEqual(['open', 'focus', 'scroll']);
});
@@ -0,0 +1,135 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { InventoryEventActions } from '@/components/inventory-event-actions';
afterEach(() => vi.restoreAllMocks());
function render(
action: string,
overrides = {},
actor = 7,
tenant = 4,
context = 'warehouse',
) {
const props = {
route: '/stock/estornos',
record: { record_key: 'record-qa', version: 2 },
choices: [{ value: action, label: 'Explicit synthetic action' }],
today: '2026-11-28',
data: { lot_id: 5 },
...overrides,
};
return renderToStaticMarkup(
<App
initialComponent={InventoryEventActions}
initialPage={{
component: 'stock/reversals',
url: '/stock/estornos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
actorId: actor,
workContext: { active: context },
...props,
},
}}
/>,
);
}
const key = (action: string) =>
`inventory-events:4:7:warehouse:/stock/estornos:record-qa:2:${action}:[["lot_id",5]]:${action}:data`;
test.each(['approve', 'execute', 'hold'])(
'%s preparation follows actor context source version and eligible action without executing',
(action) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === key(action)
? {
operation_key: 'saved-operation-qa',
record_key: 'record-qa',
version: 2,
action,
reason: 'INVENTORY-PREPARATION-QA',
data: {
lot_id: 5,
...(action === 'execute'
? {
event_on: '2026-11-27',
evidence: 'Synthetic physical evidence',
}
: {}),
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(action)).toContain('INVENTORY-PREPARATION-QA');
expect(render(action)).toContain('data-preparation-dirty="true"');
expect(render(action, {}, 8)).not.toContain('INVENTORY-PREPARATION-QA');
expect(render(action, {}, 7, 5)).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(render(action, {}, 7, 4, 'finance')).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(
render(action, { record: { record_key: 'record-qa', version: 3 } }),
).not.toContain('INVENTORY-PREPARATION-QA');
expect(render(action, { route: '/stock/lotes' })).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(render(action, { data: { lot_id: 6 } })).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(render(action, { choices: [] })).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(post).not.toHaveBeenCalled();
},
);
test('restored operation key alone does not mark stock preparation dirty', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === key('hold')
? {
operation_key: 'saved-operation-qa',
record_key: 'record-qa',
version: 2,
action: 'hold',
reason: '',
data: { lot_id: 5 },
}
: undefined,
);
expect(render('hold')).toContain('data-preparation-dirty="false"');
});
test('explicit action selection restores only while that exact capability set remains available', () => {
const identity =
'inventory-events:4:7:warehouse:/stock/estornos:record-qa:2:approve,return:[["lot_id",5]]';
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:action`
? 'return'
: k === `${identity}:return:data`
? {
operation_key: 'qa-operation',
record_key: 'record-qa',
version: 2,
action: 'return',
reason: 'RETURN-PREPARATION-QA',
data: { lot_id: 5 },
}
: undefined,
);
const choices = [
{ value: 'approve', label: 'Approve' },
{ value: 'return', label: 'Return' },
];
expect(render('approve', { choices })).toContain('RETURN-PREPARATION-QA');
expect(render('approve', { choices: [...choices].reverse() })).toContain(
'RETURN-PREPARATION-QA',
);
expect(render('approve', { choices: [choices[0]] })).not.toContain(
'RETURN-PREPARATION-QA',
);
});
@@ -0,0 +1,220 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Lots from '@/pages/stock/lots';
import Reversals from '@/pages/stock/reversals';
import Dispositions from '@/pages/stock/dispositions';
afterEach(() => vi.restoreAllMocks());
const cases = [
[
'lots',
'/stock/lotes',
{
stock_item_id: '1',
warehouse_id: '2',
requires_expiry: true,
quarantine_on_receipt: true,
minimum_remaining_days: '7',
lots: [],
},
],
[
'reversals',
'/stock/estornos',
{
reference: 'SOURCE-DRAFT-QA',
source_kind: 'operation',
source_operation_id: '99',
receipt_item_id: '',
},
],
[
'dispositions',
'/stock/ocorrencias',
{
kind: 'supplier_return',
stock_item_id: '1',
warehouse_id: '2',
lot_id: '',
receipt_item_id: '99',
quantity: '1',
reference: 'SOURCE-DRAFT-QA',
},
],
] as const;
function render(
kind: string,
overrides = {},
actor = 7,
tenant = 4,
context = 'warehouse',
) {
return renderToStaticMarkup(
<App
initialComponent={
kind === 'lots'
? Lots
: kind === 'reversals'
? Reversals
: Dispositions
}
initialPage={{
component: `stock/${kind}`,
url: '/stock',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
actorId: actor,
ready: true,
capabilities: { prepare: true },
records: [],
history: kind === 'lots' ? [] : {},
contexts: {},
items: [
{
id: 1,
code: 'ITEM-QA',
name: 'Synthetic item',
unit: 'un',
},
],
warehouses: [
{ id: 2, code: 'WH-QA', name: 'Synthetic warehouse' },
],
receipts: [],
operations: [],
lots: [],
filters: { search: '', state: '' },
today: '2026-11-28',
canViewReversals: false,
canViewDispositions: false,
canViewOperations: false,
...overrides,
},
}}
/>,
);
}
test.each(cases)(
'%s preparation restores only its actor/company/context and preserves the source pending lookup',
(kind, route, data) => {
const key = `inventory-events:4:7:warehouse:${route}:prepare:new:0:new:[["prepare",true]]:data`;
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === key
? {
operation_key: 'saved-qa-operation',
version: 0,
action: kind === 'lots' ? 'prepare' : 'save',
reason: 'PRIVATE-STOCK-DRAFT-QA',
data,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render(kind);
expect(html).toContain('PRIVATE-STOCK-DRAFT-QA');
expect(html).toContain('data-preparation-dirty="true"');
if (kind !== 'lots')
expect(html).toContain(
'Origem seleccionada — pesquisar para conferir disponibilidade',
);
expect(render(kind, {}, 8)).not.toContain('PRIVATE-STOCK-DRAFT-QA');
expect(render(kind, {}, 7, 5)).not.toContain('PRIVATE-STOCK-DRAFT-QA');
expect(render(kind, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-STOCK-DRAFT-QA',
);
expect(
render(kind, { capabilities: { prepare: false } }),
).not.toContain('PRIVATE-STOCK-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
},
);
test('lot identification preparation follows the immutable metadata version and current native authority', () => {
const record = {
id: 1,
record_key: 'setup-qa',
version: 1,
kind: 'setup',
state: 'active',
reason: 'Original setup',
created_at: '2026-11-28',
data: {
stock_item_id: 1,
warehouse_id: 2,
requires_expiry: true,
minimum_remaining_days: 0,
quarantine_on_receipt: true,
lots: [],
},
snapshot: {
contributors: [],
actor: { name: 'Synthetic' },
item: { code: 'ITEM-QA', name: 'Synthetic item', unit: 'un' },
warehouse: { name: 'Synthetic warehouse' },
balance: { quantity: 1000, version: 1 },
},
};
const lot = {
id: 5,
record_key: 'lot-qa',
version: 2,
metadata_id: 5,
data: {
code: 'ORIGINAL-QA',
expires_on: '2027-01-01',
no_expiry: false,
quantity_milli: 1000,
},
quantity_milli: 1000,
usable_milli: 0,
eligible: false,
state: 'held',
state_version: 1,
contributors: [],
last_usable_on: null,
quality_released: false,
canIdentify: true,
canRelease: false,
canHold: false,
};
const props = (version = 2, canIdentify = true) => ({
records: [record],
contexts: {
'setup-qa': {
reconciled: true,
physical: { quantity: 1000 },
usable_milli: 0,
blocked_milli: 1000,
lots: [{ ...lot, version, canIdentify }],
},
},
});
vi.spyOn(router, 'restore').mockImplementation((k) =>
k ===
'inventory-events:4:7:warehouse:/stock/lotes:identify:lot-qa:2:data'
? {
operation_key: 'qa-operation',
record_key: 'lot-qa',
version: 2,
action: 'identify',
reason: 'IDENTIFY-DRAFT-QA',
data: {
code: 'NEW-CODE-QA',
expires_on: '2027-02-01',
no_expiry: false,
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('lots', props())).toContain('IDENTIFY-DRAFT-QA');
expect(render('lots', props())).toContain('ORIGINAL-QA');
expect(render('lots', props(3))).not.toContain('IDENTIFY-DRAFT-QA');
expect(render('lots', props(2, false))).not.toContain('IDENTIFY-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
});
@@ -0,0 +1,100 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Investment from '@/pages/investment/index';
afterEach(() => vi.restoreAllMocks());
const identity = 'investment:4:7:finance:true:admin';
function render(
overrides = {},
actor = 7,
tenant = 4,
context = 'finance',
id = 3,
) {
return renderToStaticMarkup(
<App
initialComponent={Investment}
initialPage={{
component: 'investment/index',
url: '/regras-investimento',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['admin'] },
canManage: true,
policies: [
{
id,
created_by: 9,
revision: 1,
status: 'pending',
mode: 'ceiling',
scope: 'process_total',
currency: 'MZN',
ceiling_minor: 10000,
includes_tax: true,
valid_from: '2026-11-01',
valid_until: '2026-12-31',
reason: 'Synthetic policy',
},
],
reviews: [],
currentPolicyId: null,
...overrides,
},
}}
/>,
);
}
test.each([
[
'proposal:3',
{
previous_id: 3,
mode: 'ceiling',
scope: 'process_total',
currency: 'MZN',
ceiling: '123.45',
includes_tax: '0',
valid_from: '2026-12-01',
valid_until: '2026-12-31',
reason: 'INVESTMENT-DRAFT-QA',
},
],
['review:3', { decision: 'rejected', reason: 'INVESTMENT-DRAFT-QA' }],
])(
'%s preparation stays private to identity capability and immutable predecessor or policy',
(suffix, data) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:${suffix}:data` ? data : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('INVESTMENT-DRAFT-QA');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('INVESTMENT-DRAFT-QA');
expect(render({}, 7, 5)).not.toContain('INVESTMENT-DRAFT-QA');
expect(render({}, 7, 4, 'procurement.internal')).not.toContain(
'INVESTMENT-DRAFT-QA',
);
expect(render({}, 7, 4, 'finance', 4)).not.toContain(
'INVESTMENT-DRAFT-QA',
);
expect(render({ canManage: false })).not.toContain(
'INVESTMENT-DRAFT-QA',
);
expect(post).not.toHaveBeenCalled();
},
);
test('unmodified policy preparation stays clean and leaves company parameters undecided', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).not.toContain('data-preparation-dirty="true"');
expect(html).toContain('value="" selected=""');
expect(post).not.toHaveBeenCalled();
});
+156
View File
@@ -0,0 +1,156 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Payments from '@/pages/payments/index';
afterEach(() => vi.restoreAllMocks());
const base = 'payments:4:7:finance:finance';
const identity = `${base}:true:all:all`;
const invoice = {
id: 3,
number: 'INV-QA',
supplier_id: 1,
supplier_name: 'Synthetic supplier',
total_minor: 10000,
outstanding_minor: 10000,
currency: 'MZN',
bank_id: 5,
bank_revision: 2,
bank_state: 'approved',
banks: [
{
id: 5,
revision: 2,
label: 'Synthetic bank',
currency: 'MZN',
state: 'approved',
},
],
};
function render(overrides = {}, actor = 7, tenant = 4, context = 'finance') {
return renderToStaticMarkup(
<App
initialComponent={Payments}
initialPage={{
component: 'payments/index',
url: '/pagamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['finance'] },
canManage: true,
invoices: [invoice],
payments: {
data: [
{
id: 9,
invoice_id: 3,
created_by: 8,
status: 'pending',
amount_minor: 4000,
currency: 'MZN',
paid_on: '2026-11-28',
external_reference: null,
evidence_reference: null,
supplier_bank_detail_id: 5,
canReview: true,
},
],
prev_page_url: null,
next_page_url: null,
},
...overrides,
},
}}
/>,
);
}
test('external payment preparation restores its selected invoice without carrying values to another source or bank version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) => {
if (key === `${identity}:invoice`) return '3';
if (
key ===
`${identity}:registration:3:5:2:approved:10000:5.2.approved:data`
)
return {
supplier_bank_detail_id: 5,
amount: '40.00',
paid_on: '2026-11-28',
external_reference: 'EXTERNAL-DRAFT-QA',
evidence_reference: 'Synthetic documentary evidence',
};
return undefined;
});
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('EXTERNAL-DRAFT-QA');
expect(html).toContain('value="3" selected=""');
expect(html).toContain('form="external-payment-registration"');
expect(html).toContain('<form id="external-payment-registration"');
expect(html).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('EXTERNAL-DRAFT-QA');
expect(render({}, 7, 5)).not.toContain('EXTERNAL-DRAFT-QA');
expect(render({}, 7, 4, 'procurement.internal')).not.toContain(
'EXTERNAL-DRAFT-QA',
);
expect(render({ invoices: [{ ...invoice, id: 4 }] })).not.toContain(
'EXTERNAL-DRAFT-QA',
);
expect(
render({ invoices: [{ ...invoice, bank_revision: 3 }] }),
).not.toContain('EXTERNAL-DRAFT-QA');
expect(
render({ invoices: [{ ...invoice, outstanding_minor: 6000 }] }),
).not.toContain('EXTERNAL-DRAFT-QA');
expect(render({ canManage: false })).not.toContain('EXTERNAL-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
});
test('independent review restores only its pending payment and remains separate from registration', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${base}:review:9:pending:4000:5:true:data`
? {
decision: 'rejected',
reason: 'REVIEW-DRAFT-QA',
independently_verified: true,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('REVIEW-DRAFT-QA');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('REVIEW-DRAFT-QA');
expect(render({}, 7, 5)).not.toContain('REVIEW-DRAFT-QA');
expect(render({}, 7, 4, 'procurement.internal')).not.toContain(
'REVIEW-DRAFT-QA',
);
expect(
render({
payments: { data: [], prev_page_url: null, next_page_url: null },
}),
).not.toContain('REVIEW-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
});
test('missing or settled remembered invoice is explicit and cannot enable registration', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:invoice` ? '3' : undefined,
);
for (const invoices of [[], [{ ...invoice, outstanding_minor: 0 }]]) {
const html = render({ invoices });
expect(html).toContain(
'Factura seleccionada indisponível ou sem saldo',
);
expect(html).toMatch(
/<button[^>]*disabled=""[^>]*>Registar para conferência independente/,
);
}
});
test('unmodified payment forms remain clean without sending a command', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
expect(render()).not.toContain('data-preparation-dirty="true"');
expect(post).not.toHaveBeenCalled();
});
+72
View File
@@ -0,0 +1,72 @@
import { expect, test } from 'vitest';
import {
connectedDirtyForms,
markPreparationDirty,
} from '@/lib/preparation-forms';
function form(connected = true): HTMLFormElement {
const attributes = new Map<string, string>();
return {
isConnected: connected,
setAttribute: (key: string, value: string) =>
attributes.set(key, value),
getAttribute: (key: string) => attributes.get(key) ?? null,
} as unknown as HTMLFormElement;
}
function root(forms: HTMLFormElement[]): Pick<Document, 'querySelectorAll'> {
return {
querySelectorAll: () =>
forms.filter(
(node) =>
node.getAttribute('data-preparation-dirty') === 'true',
),
} as unknown as Pick<Document, 'querySelectorAll'>;
}
test('a restored dirty preparation is protected even before any input event or listener registration', () => {
const restored = form();
markPreparationDirty(restored, true);
expect(connectedDirtyForms([], root([restored]))).toEqual([restored]);
expect(connectedDirtyForms(new Set([restored]), root([restored]))).toEqual([
restored,
]);
});
test('cleaned unmounted and explicitly discarded preparations do not leave false guards', () => {
const cleaned = form();
const unmounted = form(false);
const legacy = form();
markPreparationDirty(cleaned, false);
markPreparationDirty(unmounted, true);
expect(
connectedDirtyForms(
[cleaned, unmounted, legacy],
root([cleaned, unmounted]),
),
).toEqual([legacy]);
markPreparationDirty(legacy, false);
expect(
connectedDirtyForms(
[cleaned, unmounted, legacy],
root([cleaned, unmounted, legacy]),
),
).toEqual([]);
});
test('one submitted form does not remove another dirty preparation from the departure check', () => {
const submitted = form();
const other = form();
markPreparationDirty(submitted, true);
markPreparationDirty(other, true);
expect(
connectedDirtyForms([], root([submitted, other])).some(
(node) => node !== submitted,
),
).toBe(true);
markPreparationDirty(other, false);
expect(
connectedDirtyForms([], root([submitted, other])).some(
(node) => node !== submitted,
),
).toBe(false);
});
@@ -3,6 +3,102 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Search from '@/pages/search/procurement';
test('warehouse search preserves the distinct internal reference event state and result page', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=RA-9',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'RA-9',
warehouseRequestSearchAvailable: true,
groups: [
{
key: 'warehouse_requests',
title: 'Requisições internas de armazém',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=RA&warehouse_requests_page=2',
data: [
{
id: 9,
title: 'RA-9',
detail: 'partial',
href: '/stock/requisicoes/9',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('Requisições internas de armazém');
expect(html).toContain('RA-9');
expect(html).toContain('Entrega parcial');
expect(html).toContain('warehouse_requests_page=2');
expect(html).toContain('/stock/requisicoes/9');
expect(html).toContain('nome do requisitante preservado');
});
test('supply reference search shows current versions native targets and its own pagination', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=AG',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'AG',
supplySearchAvailable: true,
groups: [
{
key: 'agreements',
title: 'Acordos',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=AG&agreements_page=2',
data: [
{
id: 5,
title: 'AG <QA> · v2',
detail: 'suspended',
href: '/compras/fornecimento?view=agreements&record_id=5#supply-record-5',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('AG &lt;QA&gt; · v2');
expect(html).toContain('Suspenso');
expect(html).toContain('agreements_page=2');
expect(html).toContain('view=agreements&amp;record_id=5#supply-record-5');
expect(html).toContain('nome do fornecedor preservado');
expect(html).not.toContain('acesso financeiro');
});
test('process search separates result groups escapes text and retains page links', () => {
const html = renderToStaticMarkup(
<App
@@ -0,0 +1,276 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Controls from '@/pages/purchase-controls/index';
import Orders from '@/pages/purchase-controls/orders';
afterEach(() => vi.restoreAllMocks());
const permissions = ['admin', 'finance', 'procurement'];
const policy = {
id: 3,
revision: 2,
status: 'pending',
created_by: 9,
enabled: false,
valid_from: '2026-11-01',
valid_until: '2026-12-31',
canReview: true,
};
const original = {
role: 'configured',
actorId: 7,
permissions,
policies: [policy],
reviews: [],
awards: [{ id: 4, requisition_id: 8, status: 'approved' }],
cancellations: [],
sources: [{ id: 7, number: 'REQ-QA', revision_id: null }],
};
const order = {
id: 11,
order_number: 'PO-QA',
purchase_order_id: 23,
source_href: '/ordens/23',
status: 'pending',
reason: 'Original synthetic request',
evidence: 'Synthetic evidence',
review_reason: null,
revised_requisition_id: null,
canDecide: true,
canRevise: false,
};
const issued = {
canAdminister: true,
policies: [policy],
records: {
data: [
order,
{
...order,
id: 12,
status: 'approved',
canDecide: false,
canRevise: true,
},
],
prev_page_url: null,
next_page_url: null,
},
};
const originalKey = 'purchase-controls:4:7:legacy:admin,finance,procurement';
const issuedKey = 'order-cancellations:4:7:legacy:true';
function render(
kind: 'original' | 'issued',
overrides = {},
actor = 7,
tenant = 4,
) {
return renderToStaticMarkup(
<App
initialComponent={kind === 'original' ? Controls : Orders}
initialPage={{
component:
kind === 'original'
? 'purchase-controls/index'
: 'purchase-controls/orders',
url:
kind === 'original'
? '/revisao-compras'
: '/ordens/cancelamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...(kind === 'original' ? original : issued),
actorId: actor,
...overrides,
},
}}
/>,
);
}
test('unissued cancellation preparation restores once for its award without requesting cancellation', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${originalKey}:reason:/adjudicacoes/4/cancelamento:false:data`
? { reason: 'CANCELLATION-REQUEST-QA', decision: 'approved' }
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('original');
expect(html.match(/CANCELLATION-REQUEST-QA/g)).toHaveLength(1);
expect(html).toContain('data-preparation-dirty="true"');
expect(render('original', {}, 8)).not.toContain('CANCELLATION-REQUEST-QA');
expect(render('original', {}, 7, 5)).not.toContain(
'CANCELLATION-REQUEST-QA',
);
expect(
render('original', { workContext: { active: 'procurement.internal' } }),
).not.toContain('CANCELLATION-REQUEST-QA');
expect(
render('original', {
awards: [{ id: 5, requisition_id: 8, status: 'approved' }],
}),
).not.toContain('CANCELLATION-REQUEST-QA');
expect(
render('original', {
permissions: ['procurement', 'admin', 'finance'],
}),
).toContain('CANCELLATION-REQUEST-QA');
expect(post).not.toHaveBeenCalled();
});
test('unissued policy proposal stays separate from policy review and from a later predecessor', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${originalKey}:policy:3:data`
? {
previous_id: 3,
mode: 'unissued_award',
enabled: true,
valid_from: '2026-12-01',
valid_until: '2026-12-31',
reason: 'POLICY-PROPOSAL-QA',
}
: key ===
`${originalKey}:reason:/revisao-compras/politicas/3/decidir:true:data`
? { reason: 'INDEPENDENT-POLICY-REVIEW-QA', decision: 'rejected' }
: undefined,
);
const html = render('original');
expect(html).toContain('POLICY-PROPOSAL-QA');
expect(html).toContain('INDEPENDENT-POLICY-REVIEW-QA');
expect(html).toContain('<option value="rejected" selected="">');
expect(
render('original', { policies: [{ ...policy, id: 4 }] }),
).not.toContain('POLICY-PROPOSAL-QA');
expect(
render('original', { permissions: ['finance', 'procurement'] }),
).not.toContain('POLICY-PROPOSAL-QA');
expect(
render('original', { permissions: ['finance', 'procurement'] }),
).not.toContain('INDEPENDENT-POLICY-REVIEW-QA');
});
test('unissued revision conserves only the new date and justification for the same cancelled source', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${originalKey}:revision:7:data`
? {
needed_by: '2026-12-15',
justification: 'NEW-REQUEST-JUSTIFICATION-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('original')).toContain('NEW-REQUEST-JUSTIFICATION-QA');
expect(render('original')).toContain('value="2026-12-15"');
expect(
render('original', {
sources: [{ id: 8, number: 'OTHER-QA', revision_id: null }],
}),
).not.toContain('NEW-REQUEST-JUSTIFICATION-QA');
expect(
render('original', {
sources: [{ id: 7, number: 'REQ-QA', revision_id: 99 }],
}),
).not.toContain('NEW-REQUEST-JUSTIFICATION-QA');
expect(post).not.toHaveBeenCalled();
});
test('issued order decision restores independently without confirming or cancelling automatically', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${issuedKey}:decision:/ordens/cancelamentos/11/decidir:data`
? { decision: 'approved', reason: 'ISSUED-ORDER-DECISION-QA' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('issued')).toContain('ISSUED-ORDER-DECISION-QA');
expect(render('issued')).toContain('<option value="approved" selected="">');
expect(render('issued', {}, 8)).not.toContain('ISSUED-ORDER-DECISION-QA');
expect(render('issued', {}, 7, 5)).not.toContain(
'ISSUED-ORDER-DECISION-QA',
);
expect(
render('issued', { workContext: { active: 'procurement.internal' } }),
).not.toContain('ISSUED-ORDER-DECISION-QA');
expect(
render('issued', {
records: {
...issued.records,
data: [{ ...order, canDecide: false }],
},
}),
).not.toContain('ISSUED-ORDER-DECISION-QA');
expect(post).not.toHaveBeenCalled();
});
test('issued policy proposal and its independent review cannot reuse each other or the next policy', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${issuedKey}:policy:3:data`
? {
previous_id: 3,
mode: 'issued_order',
enabled: true,
valid_from: '2026-12-01',
valid_until: '2026-12-31',
reason: 'ISSUED-POLICY-PROPOSAL-QA',
}
: key ===
`${issuedKey}:decision:/ordens/cancelamentos/politicas/3/decidir:data`
? { decision: 'rejected', reason: 'ISSUED-POLICY-REVIEW-QA' }
: undefined,
);
expect(render('issued')).toContain('ISSUED-POLICY-PROPOSAL-QA');
expect(render('issued')).toContain('ISSUED-POLICY-REVIEW-QA');
expect(
render('issued', { policies: [{ ...policy, id: 4 }] }),
).not.toContain('ISSUED-POLICY-PROPOSAL-QA');
expect(
render('issued', { policies: [{ ...policy, canReview: false }] }),
).not.toContain('ISSUED-POLICY-REVIEW-QA');
expect(render('issued', { canAdminister: false })).not.toContain(
'ISSUED-POLICY-PROPOSAL-QA',
);
});
test('issued revision preparation is tied to the approved cancellation and disappears once linked', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${issuedKey}:revision:12:approved:0:data`
? {
needed_by: '2026-12-16',
reason: 'ISSUED-REVISION-PREPARATION-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('issued')).toContain('ISSUED-REVISION-PREPARATION-QA');
expect(
render('issued', {
records: {
...issued.records,
data: [
{ ...issued.records.data[1], revised_requisition_id: 99 },
],
},
}),
).not.toContain('ISSUED-REVISION-PREPARATION-QA');
expect(
render('issued', {
records: {
...issued.records,
data: [{ ...issued.records.data[1], id: 13 }],
},
}),
).not.toContain('ISSUED-REVISION-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
});
test.each(['original', 'issued'] as const)(
'empty %s preparations stay clean and do not enable a policy',
(kind) => {
const html = render(kind);
expect(html).not.toContain('data-preparation-dirty="true"');
expect(html).not.toContain('checked=""');
},
);
+203
View File
@@ -0,0 +1,203 @@
import { App, router } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Comparison from '@/pages/quotations/show';
import { QuotationEvaluationForm } from '@/components/quotation-evaluation-form';
afterEach(() => vi.restoreAllMocks());
const policy = {
revision: 1,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
};
const data = {
currency: 'USD',
supplier_id: '7',
reference: 'QA-PREPARACAO-EXACTA',
delivery_days: '8',
valid_until: '2026-12-15',
payment_terms: 'Texto sintético por guardar',
no_conflict: false,
items: [
{
requisition_item_id: 10,
unit_price: '12.34',
discount_type: 'amount',
discount_value: '0.20',
},
],
};
function renderComparison(
tenant = 3,
actor = 7,
version = 4,
canCreate = true,
choicesAvailable = true,
) {
const props: ComponentProps<typeof Comparison> = {
requisition: {
id: 42,
process_version: version,
number: 'REQ-QA-42',
justification: 'Dados sintéticos',
items: [
{
id: 10,
description: 'Artigo sintético',
quantity: '1.000',
tax_rate: '16.00',
unit_price_minor: 100,
total_minor: 116,
},
],
},
quotations: [],
suppliers: choicesAvailable
? [{ id: 7, name: 'Fornecedor sintético' }]
: [],
canCreate,
canEvaluate: false,
ready: false,
topIds: [],
comparisonPolicy: policy,
exchangeAvailable: true,
exchangeRates: choicesAvailable
? [
{
id: 2,
currency: 'USD',
rate: '60.0000000000',
quoted_on: '2026-11-27',
source: 'Fonte sintética',
recorded_by: 9,
},
]
: [],
};
return renderToStaticMarkup(
<App
initialComponent={Comparison}
initialPage={{
component: 'quotations/show',
url: '/requisicoes/42/cotacoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...props,
},
}}
/>,
);
}
test('quotation preparation restores original currency prices discounts and text without saving or opening an unauthorized form', () => {
const spy = vi.spyOn(router, 'post');
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-preparation:3:7:42:4:adding'
? true
: key === 'quotation-preparation:3:7:42:4:data'
? data
: undefined,
);
const html = renderComparison();
expect(html).toContain('QA-PREPARACAO-EXACTA');
expect(html).toContain('Texto sintético por guardar');
expect(html).toContain('value="12.34"');
expect(html).toContain('value="0.20"');
expect(html).toContain('value="USD" selected');
expect(renderComparison(3, 7, 4, false)).not.toContain(
'QA-PREPARACAO-EXACTA',
);
expect(spy).not.toHaveBeenCalled();
});
test('quotation preparation never crosses actor company or source version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-preparation:3:7:42:4:adding'
? true
: key === 'quotation-preparation:3:7:42:4:data'
? data
: undefined,
);
expect(renderComparison(3, 8)).not.toContain('QA-PREPARACAO-EXACTA');
expect(renderComparison(4, 7)).not.toContain('QA-PREPARACAO-EXACTA');
expect(renderComparison(3, 7, 5)).not.toContain('QA-PREPARACAO-EXACTA');
});
test('a remembered unavailable supplier or currency remains explicit without inventing eligibility or an exchange rate', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-preparation:3:7:42:4:adding'
? true
: key === 'quotation-preparation:3:7:42:4:data'
? data
: undefined,
);
const html = renderComparison(3, 7, 4, true, false);
expect(html).toContain('value="USD" selected');
expect(html).toContain('taxa indisponível nesta consulta');
expect(html).toContain('Fornecedor preservado · confirme a elegibilidade');
expect(html).toContain('QA-PREPARACAO-EXACTA');
expect(html).not.toContain('taxa 0 MZN');
});
function renderEvaluation(quotationId: number, actor = 7, tenant = 3) {
function Screen() {
return (
<QuotationEvaluationForm
requisitionId={42}
quotationId={quotationId}
/>
);
}
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'quotations/show',
url: '/requisicoes/42/cotacoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
},
}}
/>,
);
}
test('each independent proposal evaluation recovers only its own remembered preparation', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-evaluation:3:7:42:11:data'
? {
quality: '8.25',
history: '6',
payment: '7',
comment: 'Fundamento sintético por guardar da proposta onze',
no_conflict: false,
}
: undefined,
);
expect(renderEvaluation(11)).toContain(
'Fundamento sintético por guardar da proposta onze',
);
expect(renderEvaluation(11)).toContain('value="8.25"');
expect(renderEvaluation(12)).not.toContain(
'Fundamento sintético por guardar da proposta onze',
);
expect(renderEvaluation(11, 8)).not.toContain(
'Fundamento sintético por guardar da proposta onze',
);
expect(renderEvaluation(11, 7, 4)).not.toContain(
'Fundamento sintético por guardar da proposta onze',
);
});
+195
View File
@@ -0,0 +1,195 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import ReceiveOrder from '@/pages/receipts/order';
import {
receiptPreparationChanged,
receiptPreparationKey,
} from '@/lib/receipt-preparation';
import type { ReceiptProgress } from '@/types/inventory';
afterEach(() => vi.restoreAllMocks());
const progress: ReceiptProgress = {
state: 'not_received',
has_divergences: false,
lines: [
{
id: 10,
description: 'Artigo sintético',
unit: 'UN',
purchase_type: 'consumable',
ordered_milli: 10000,
received_milli: 0,
accepted_milli: 0,
rejected_milli: 0,
delivery_pending_milli: 10000,
acceptance_pending_milli: 10000,
stock_item_id: 1,
},
],
};
const data = {
idempotency_key: '11111111-1111-4111-8111-111111111111',
delivery_note: 'GUIA-QA-POR-GUARDAR',
received_on: '2026-11-27',
warehouse_id: '1',
items: [
{
include: true,
purchase_order_item_id: 10,
received_quantity: '0.600',
accepted_quantity: '0.500',
quality_status: 'reservations',
notes: 'Conferência sintética por guardar',
stock_item_id: '1',
conversion: {
numerator: '',
denominator: '',
source: '',
version: '',
},
lots: [],
},
],
};
function render(
tenant = 3,
actor = 7,
order = 42,
source = progress,
canConfirm = true,
) {
return renderToStaticMarkup(
<App
initialComponent={ReceiveOrder}
initialPage={{
component: 'receipts/order',
url: `/ordens/${order}/recepcoes`,
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
order: { id: order, number: 'OC-QA-42' },
supplier_name: 'Fornecedor sintético',
progress: source,
receipts: [],
warehouses: [
{ id: 1, code: 'ARM-QA', name: 'Armazém sintético' },
],
stockItems: [
{
id: 1,
code: 'ART-QA',
name: 'Artigo sintético',
unit: 'UN',
},
],
canConfirm,
lotScopes: [],
},
}}
/>,
);
}
test('receipt preparation restores selected line quantities notes and document without an automatic receipt', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${receiptPreparationKey(3, 7, 42, progress)}:data`
? data
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('GUIA-QA-POR-GUARDAR');
expect(html).toContain('value="0.600"');
expect(html).toContain('value="0.500"');
expect(html).toContain('value="reservations" selected');
expect(html).toContain('Conferência sintética por guardar');
expect(render(3, 7, 42, progress, false)).not.toContain(
'GUIA-QA-POR-GUARDAR',
);
expect(post).not.toHaveBeenCalled();
});
test('receipt preparation stays with its actor tenant order and physical progress', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${receiptPreparationKey(3, 7, 42, progress)}:data`
? data
: undefined,
);
expect(render(4)).not.toContain('GUIA-QA-POR-GUARDAR');
expect(render(3, 8)).not.toContain('GUIA-QA-POR-GUARDAR');
expect(render(3, 7, 43)).not.toContain('GUIA-QA-POR-GUARDAR');
const changed = {
...progress,
state: 'partial',
has_divergences: true,
lines: [
{
...progress.lines[0],
received_milli: 600,
accepted_milli: 500,
rejected_milli: 100,
delivery_pending_milli: 9400,
acceptance_pending_milli: 9500,
},
],
};
expect(render(3, 7, 42, changed)).not.toContain('GUIA-QA-POR-GUARDAR');
expect(
receiptPreparationKey(3, 7, 42, {
...changed,
lines: [
{
...changed.lines[0],
supplier_returned_milli: 300,
effective_accepted_milli: 200,
acceptance_pending_milli: 9800,
},
],
}),
).not.toBe(receiptPreparationKey(3, 7, 42, changed));
});
test('only a regenerated receipt UUID is clean while changed quantities and lot preparation remain dirty', () => {
expect(
receiptPreparationChanged(data, {
...data,
idempotency_key: '22222222-2222-4222-8222-222222222222',
}),
).toBe(false);
expect(
receiptPreparationChanged(data, {
...data,
items: [{ ...data.items[0], accepted_quantity: '0.400' }],
}),
).toBe(true);
expect(
receiptPreparationChanged(data, {
...data,
items: [
{
...data.items[0],
lots: [
{
code: 'LOTE-QA',
quantity: '0.500',
expires_on: '',
no_expiry: true,
},
],
},
],
}),
).toBe(true);
expect(
receiptPreparationChanged(data, {
...data,
delivery_note: 'Outra guia sintética',
}),
).toBe(true);
});
@@ -0,0 +1,104 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Accounts from '@/pages/requisitions/accounts';
import Summary from '@/components/requisition-account-summary';
const account = {
id: 7,
code: 'QA-7',
label: 'Conta & material',
currency: 'MZN',
source_hash: 'a'.repeat(64),
};
const props: ComponentProps<typeof Accounts> = {
requisition: { id: 1, number: 'REQ-QA', status: 'draft' },
actorId: 1,
tenantId: 1,
canWrite: true,
search: '',
items: [
{
id: 2,
description: 'Material sintético',
subtotal_minor: '10000',
total_minor: '10000',
basis_hash: 'b'.repeat(64),
},
],
accounts: {
data: [account],
prev_page_url: null,
next_page_url: '/requisicoes/1/contas?accounts_page=2',
},
current: [],
history: { data: [], prev_page_url: null, next_page_url: null },
};
function render(value: typeof props) {
function Screen() {
return <Accounts {...value} />;
}
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'requisitions/accounts',
url: '/requisicoes/1/contas',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
}
test('account assignment begins with an explicit line and preserves catalogue pagination', () => {
const html = render(props);
expect(html).toContain('Seleccione a linha');
expect(html).toContain('Adicionar conta à linha');
expect(html).toContain('/requisicoes/1/contas?accounts_page=2');
expect(html).toContain('Conta &amp; material');
expect(html).not.toContain('Reutilizar parcelas actuais');
expect(html).not.toContain('Base sem IVA (MZN)');
});
test('read-only history keeps exact original money and does not expose an editing form', () => {
const row = {
id: 9,
version: 2,
reason: 'Conferência sintética',
data: {
requisition_item_id: 2,
allocations: [
{
account,
subtotal_minor: '9007199254740993',
total_minor: '9007199254740993',
},
],
},
};
const html = render({
...props,
canWrite: false,
accounts: null,
current: [row],
history: { data: [row], prev_page_url: null, next_page_url: null },
});
expect(html).toContain('90.071.992.547.409,93 MZN');
expect(html).toContain('Versão 2');
expect(html).not.toContain('Guardar versão');
expect(html).not.toContain('Adicionar conta à linha');
const summary = renderToStaticMarkup(
<Summary
records={{
'2': {
...row,
snapshot: { line: { description: 'Necessidade original' } },
},
}}
/>,
);
expect(summary).toContain('90.071.992.547.409,93 MZN');
expect(summary).toContain('não representam valores contabilizados');
});
@@ -69,6 +69,8 @@ test('explicit RQ01 group conditions are separate from original article categori
expect(html).toContain('Categorias exactas do artigo');
expect(html).toContain('Equipamento de escritório');
expect(html).toContain('Maquinaria');
expect(html).toContain('Preparar nível de direcção para maquinaria');
expect(html).toContain('qualquer valor e centro de custo');
expect(html).toContain('não são classificados automaticamente');
const groups = html.slice(
html.indexOf('Categoria da necessidade (RQ-01)'),
@@ -76,6 +78,9 @@ test('explicit RQ01 group conditions are separate from original article categori
);
expect(groups).toContain('checked=""');
expect(render(true)).not.toContain('Categoria da necessidade (RQ-01)');
expect(render(true)).not.toContain(
'Preparar nível de direcção para maquinaria',
);
});
test('approval settings retain exact threshold and selected revoked profiles so the administrator can reconcile the plan', () => {
@@ -0,0 +1,74 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import RequisitionShow from '@/pages/requisitions/show';
test.each([false, true])(
'draft review keeps advisory submission and exposes audit navigation only with its explicit capability (%s)',
(canReadAuditMetadata) => {
const props: ComponentProps<typeof RequisitionShow> = {
requisition: {
id: 1,
number: 'REQ-QA-1',
status: 'draft',
priority: 'normal',
needed_by: '2026-12-01',
justification: 'Somente dados sintéticos',
cost_center_id: 1,
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
created_at: '2026-11-27T10:00:00Z',
items: [],
steps: [],
},
comparisonPolicy: {
revision: 1,
configured: false,
minimum_proposals: 3,
minimum_evaluators: 1,
weights: {
price: 40,
quality: 20,
delivery: 20,
history: 10,
payment: 10,
},
},
canEdit: true,
canReadAuditMetadata,
canDecide: false,
conflictBlocked: false,
audit: [],
duplicateHints: {
matches: [{ id: 2, number: 'REQ-QA-2', status: 'pending' }],
complete: false,
},
};
function Screen() {
return <RequisitionShow {...props} />;
}
const html = renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'requisitions/show',
url: '/requisicoes/1',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
expect(html).toContain('Conferir possíveis pedidos repetidos');
expect(html).toContain('href="/requisicoes/2"');
expect(html).toContain('não bloqueia a submissão');
expect(html).toContain('100 candidatos');
expect(html).toContain('Submeter');
expect(
html.includes('/auditoria/eventos?request_reference=REQ-QA-1'),
).toBe(canReadAuditMetadata);
},
);
@@ -0,0 +1,35 @@
import { expect, test } from 'vitest';
import vectors from '../Fixtures/requisition-estimates.json';
import { requisitionEstimate } from '@/lib/requisition-estimate';
test.each(vectors)(
'preserves exact native line rounding: $minor',
({ lines, minor }) => {
expect(requisitionEstimate(lines)).toBe(minor);
},
);
test.each(['', '-1', '1e2', '0', '1.0001', '1000001', 'x'])(
'keeps invalid or incomplete quantity indeterminate: %s',
(quantity) => {
expect(
requisitionEstimate([{ quantity, unit_price: '1', tax_rate: '0' }]),
).toBeNull();
},
);
test('requires complete valid lines while accepting leading zeros and calculated zero', () => {
expect(requisitionEstimate([])).toBeNull();
for (const field of ['unit_price', 'tax_rate']) {
expect(
requisitionEstimate([
{ quantity: '1', unit_price: '1', tax_rate: '0', [field]: '' },
]),
).toBeNull();
}
expect(
requisitionEstimate([
{ quantity: '000.001', unit_price: '00.01', tax_rate: '00.00' },
]),
).toBe('0');
});
+169 -25
View File
@@ -1,15 +1,15 @@
import { App } from "@inertiajs/react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, test } from "vitest";
import Expiry from "../../resources/js/pages/requisitions/expiry";
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Expiry from '../../resources/js/pages/requisitions/expiry';
function render(extra: object) {
return renderToStaticMarkup(
<App
initialComponent={Expiry}
initialPage={{
component: "requisitions/expiry",
url: "/requisicoes/1/prazos",
component: 'requisitions/expiry',
url: '/requisicoes/1/prazos',
version: null,
clearHistory: false,
encryptHistory: true,
@@ -17,13 +17,13 @@ function render(extra: object) {
errors: {},
requisition: {
id: 1,
number: "REQ-QA",
status: "draft",
number: 'REQ-QA',
status: 'draft',
process_version: 4,
approval_cycle: 2,
},
deadline: {
state: "inactive",
state: 'inactive',
step_id: null,
expires_at: null,
basis_hash: null,
@@ -38,14 +38,14 @@ function render(extra: object) {
{
id: 1,
data: { cycle: 1, next_cycle: 2 },
reason: "<script>synthetic</script>",
request: { number: "REQ-QA" },
reason: '<script>synthetic</script>',
request: { number: 'REQ-QA' },
steps: [
{
id: 1,
position: 1,
role: "department_head",
decision: "approved",
role: 'department_head',
decision: 'approved',
},
],
},
@@ -60,26 +60,170 @@ function render(extra: object) {
);
}
test("returned owner sees the same draft and preserved approval without expiry controls", () => {
test('returned owner sees the same draft and preserved approval without expiry controls', () => {
const html = render({});
expect(html).toContain("/requisicoes/1/editar");
expect(html).toContain("Aprovação preservada");
expect(html).toContain("&lt;script&gt;synthetic&lt;/script&gt;");
expect(html).not.toContain("<form");
expect(html).toContain('/requisicoes/1/editar');
expect(html).toContain('Aprovação preservada');
expect(html).toContain('&lt;script&gt;synthetic&lt;/script&gt;');
expect(html).not.toContain('<form');
});
test("a pending configured deadline exposes due actions only when allowed", () => {
test('prior cycle exposes the original document rules and independent decision without reusing it in the new submission', () => {
const html = render({
history: {
prev_page_url: null,
next_page_url: null,
data: [
{
id: 8,
data: { cycle: 1, next_cycle: 2 },
created_at: '2026-11-27T12:31:00Z',
reason: 'Devolução sintética',
request: {
number: 'REQ-QA',
priority: 'normal',
submitted_at: '2026-11-27T12:00:00Z',
needed_by: '2026-12-01',
justification: 'ORIGINAL-QA-JUSTIFICATION',
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
},
rules: {
first_limit_minor: 5000,
second_limit_minor: 20000,
approval_includes_tax: false,
rules_provisional: true,
},
items: [
{
id: 3,
description: 'ORIGINAL-QA-ITEM',
quantity: '1.000',
unit: 'un',
unit_price_minor: 10000,
tax_rate: '0.00',
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
},
],
steps: [
{
id: 4,
position: 1,
role: 'configured_1',
routing: { name: 'Direcção preservada' },
decision: 'approved',
approver_id: 7,
decided_at: '2026-11-27T12:05:00Z',
comment: '<script>ORIGINAL-QA-DECISION</script>',
},
{
id: 5,
position: 2,
role: 'procurement',
decision: 'pending',
},
],
},
],
},
});
expect(html).toContain('ORIGINAL-QA-JUSTIFICATION');
expect(html).toContain('ORIGINAL-QA-ITEM');
expect(html).toContain('100,00');
expect(html).toContain('sem IVA');
expect(html).toContain('Regras provisórias na submissão original');
expect(html).toContain('Direcção preservada');
expect(html).toContain('Utilizador #7');
expect(html).toContain('&lt;script&gt;ORIGINAL-QA-DECISION&lt;/script&gt;');
expect(html).toContain('Etapa pendente no momento da devolução');
expect(html).toContain('não são as aprovações da nova');
expect(html).not.toContain('<form');
});
test('missing historical values remain unknown instead of becoming zero or current rules', () => {
const html = render({});
expect(html).toContain('Não preservado');
expect(html).toContain('Artigos não preservados neste registo');
expect(html).not.toContain('0,00');
expect(html).not.toContain('Regras provisórias na submissão original');
});
test('historical routing amount remains distinct from goods and a preserved zero remains zero', () => {
const history = {
prev_page_url: null,
next_page_url: null,
data: [
{
id: 8,
data: { cycle: 1, next_cycle: 2 },
reason: 'Synthetic source',
request: {
number: 'REQ-QA',
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
},
approval_amount_minor: 11000,
approval_uses_separate_basis: true,
rules: {
approval_includes_tax: true,
routing_plan_revision: 3,
},
steps: [],
items: [],
},
],
};
const html = render({ history });
expect(html).toContain('100,00');
expect(html).toContain('110,00');
expect(html).toContain('Base adicional preservada');
expect(html).toContain('Plano de encaminhamento · versão 3');
const zero = render({
history: {
...history,
data: [{ ...history.data[0], approval_amount_minor: 0 }],
},
});
expect(zero).toContain('Valor usado no encaminhamento: 0,00');
});
test('a pending configured deadline exposes due actions only when allowed', () => {
const html = render({
canEdit: false,
canCheck: true,
deadline: {
state: "running",
state: 'running',
step_id: 2,
expires_at: "2026-11-27T12:30:00Z",
basis_hash: "a".repeat(64),
expires_at: '2026-11-27T12:30:00Z',
basis_hash: 'a'.repeat(64),
},
});
expect(html).toContain("Verificar e executar acções devidas");
expect(html).not.toContain("Rever rascunho");
expect(html).not.toContain("Devolver ao requisitante</button>");
expect(html).toContain('Verificar e executar acções devidas');
expect(html).not.toContain('Rever rascunho');
expect(html).not.toContain('Devolver ao requisitante</button>');
});
test('urgent deadline explains the frozen shorter policy without exposing a new approval grant', () => {
const html = render({
canEdit: false,
canCheck: true,
deadline: {
state: 'running',
step_id: 2,
timing: 'urgent_override',
expires_at: '2026-11-27T12:05:00Z',
reminder_at: '2026-11-27T12:01:00Z',
escalation_at: '2026-11-27T12:02:00Z',
basis_hash: 'a'.repeat(64),
},
});
expect(html).toContain(
'Prazos reduzidos para urgência, preservados na submissão.',
);
expect(html).toContain('Escalamento previsto');
expect(html).not.toContain('Aprovar');
});
+52 -2
View File
@@ -113,7 +113,7 @@ const restored = {
],
};
function render(userId = 7, tenantId = 3) {
function render(userId = 7, tenantId = 3, errors: Record<string, string> = {}) {
return renderToStaticMarkup(
<App
initialComponent={RequisitionForm}
@@ -124,7 +124,7 @@ function render(userId = 7, tenantId = 3) {
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
errors,
auth: { user: { id: userId, tenant_id: tenantId } },
internalRequisitionReady: true,
incompleteDraftsAvailable: true,
@@ -145,6 +145,27 @@ test('native remembered history restores unfinished fields and line values witho
expect(html).toContain('Artigo ainda por gravar');
expect(html).toContain('value="2.000"');
expect(html).not.toContain('value="0.00"');
expect(html).toContain('Por completar');
expect(html).toContain('data-preparation-dirty="true"');
});
test('the native form displays the exact half-cent estimate from remembered decimal inputs', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'requisition:3:7:new:0:data'
? {
...restored,
items: [
{
...restored.items[0],
quantity: '0.29',
unit_price: '0.50',
tax_rate: '0',
},
],
}
: undefined,
);
expect(render()).toContain('0,15 MZN');
});
test('remembered preparation is separated by user and company', () => {
@@ -152,5 +173,34 @@ test('remembered preparation is separated by user and company', () => {
key === 'requisition:3:7:new:0:data' ? restored : undefined,
);
expect(render(8, 3)).not.toContain('Artigo ainda por gravar');
expect(render(8, 3)).toContain('data-preparation-dirty="false"');
expect(render(7, 4)).not.toContain('Artigo ainda por gravar');
});
test('native validation links address the restored line and retain process errors without a false field destination', () => {
const errors = {
'items.0.quantity': 'Corrija a quantidade',
'items.0.equipment_id': 'Confira o equipamento',
cost_center_id: 'Escolha o centro',
process_version: 'Actualize a versão',
};
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'requisition:3:7:new:0:data'
? restored
: key === 'requisition:3:7:new:0:errors'
? errors
: undefined,
);
const html = render(7, 3, errors);
expect(html).toContain('href="#quantity-kept-line"');
expect(html).toContain('id="quantity-kept-line"');
expect(html).toContain('href="#requisition-line-kept-line"');
expect(html).toContain('id="requisition-line-kept-line"');
expect(html).toContain('href="#cost-center"');
expect(html).toContain('aria-describedby="error-items.0.quantity"');
expect(html).toContain('id="error-items.0.quantity"');
expect(html).toContain('id="error-items.0.equipment_id"');
expect(html).toContain('id="error-cost_center_id"');
expect(html).not.toContain('href="#process_version"');
expect(html).toContain('Actualize a versão');
});
@@ -0,0 +1,66 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
SubmissionPreviewDetails,
RequisitionSubmissionConfirmation,
type SubmissionPreview,
} from '@/components/requisition-submission-confirmation';
const preview: SubmissionPreview = {
state: 'planned',
process_version: 3,
subtotal_minor: '10000',
total_minor: '11600',
approval_amount_minor: '13000',
includes_tax: true,
provisional_rules: true,
import_basis: true,
steps: [
{ role: 'department_head', label: null },
{ role: 'configured_1', label: 'Direcção <QA>' },
],
};
test('confirmation names the exact document and approval bases and ordered routing without treating preview as submission', () => {
const html = renderToStaticMarkup(
<SubmissionPreviewDetails number="REQ-QA-1" preview={preview} />,
);
expect(html).toContain('116,00 MZN');
expect(html).toContain('130,00 MZN');
expect(html).toContain('estimativa de importação');
expect(html).toContain('provisórias');
expect(html).toContain('Chefe de departamento');
expect(html).toContain('Direcção &lt;QA&gt;');
expect(html).toContain('não cria reservas nem aprovações');
expect(html).not.toContain('configured_1');
});
test('unknown routing does not display a zero or invent approval stages', () => {
const html = renderToStaticMarkup(
<SubmissionPreviewDetails
number="REQ-QA-2"
preview={{ state: 'unavailable', message: 'Reveja a estimativa' }}
/>,
);
expect(html).toContain('Reveja a estimativa');
expect(html).not.toContain('0,00 MZN');
expect(html).not.toContain('<ol');
});
test('opening confirmation does not invoke the submission callback during rendering', () => {
let submitted = false;
const html = renderToStaticMarkup(
<RequisitionSubmissionConfirmation
number="REQ-QA-1"
preview={preview}
processing={false}
errors={[]}
onConfirm={() => {
submitted = true;
}}
/>,
);
expect(submitted).toBe(false);
expect(html).toContain('Submeter para aprovação');
expect(html).not.toContain('Confirmar e submeter');
});
@@ -0,0 +1,239 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Stock from '@/pages/stock/index';
import Operations, { OperationsDemo } from '@/pages/stock/operations';
vi.mock('@/components/administrative-location', () => ({
AdministrativeLocation: ({ value }: { value: unknown }) => (
<div>{JSON.stringify(value)}</div>
),
}));
afterEach(() => vi.restoreAllMocks());
const base = 'inventory-events:4:7:warehouse';
const operationIdentity = `${base}:/stock/operacoes:true:false`;
const initialOperation = {
kind: 'issue',
reference: '',
idempotency_key: 'saved-qa-operation',
stock_item_id: '1',
warehouse_id: '2',
destination_warehouse_id: '',
responsible_id: '',
destination: '',
reason: '',
quantity: '',
count_id: '',
ledger_version: 0,
equipment_id: '',
};
function render(
operations = false,
overrides = {},
actor = 7,
tenant = 4,
context = 'warehouse',
) {
return renderToStaticMarkup(
<App
initialComponent={operations ? Operations : Stock}
initialPage={{
component: operations ? 'stock/operations' : 'stock/index',
url: '/stock',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
items: [
{
id: 1,
code: 'ITEM-QA',
name: 'Synthetic item',
unit: 'un',
},
],
warehouses: [
{ id: 2, code: 'WH-QA', name: 'Synthetic warehouse' },
],
balances: [],
movements: {
data: [],
prev_page_url: null,
next_page_url: null,
},
filters: {},
canManage: true,
users: [],
operations: {
data: [],
prev_page_url: null,
next_page_url: null,
},
counts: [],
canOperate: true,
...overrides,
},
}}
/>,
);
}
test.each([
[
'item',
{ code: 'NEW-ITEM-QA', name: 'PRIVATE-CATALOGUE-DRAFT', unit: 'un' },
],
[
'warehouse',
{
code: 'NEW-WH-QA',
name: 'PRIVATE-CATALOGUE-DRAFT',
geography_reference: null,
},
],
])(
'stock %s preparation remains isolated from other actors companies contexts and capabilities',
(suffix, data) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:/stock:catalogue:true:false:${suffix}:data`
? data
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('PRIVATE-CATALOGUE-DRAFT');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render(false, {}, 8)).not.toContain('PRIVATE-CATALOGUE-DRAFT');
expect(render(false, {}, 7, 5)).not.toContain(
'PRIVATE-CATALOGUE-DRAFT',
);
expect(render(false, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-CATALOGUE-DRAFT',
);
expect(render(false, { canManage: false })).not.toContain(
'PRIVATE-CATALOGUE-DRAFT',
);
expect(post).not.toHaveBeenCalled();
},
);
test('warehouse location preparation preserves the expected original reference and is source scoped', () => {
const reference = {
catalogue: 'qa-catalogue',
record_id: '11',
country: 'MZ',
};
vi.spyOn(router, 'restore').mockImplementation((k) =>
k ===
`${base}:/stock/warehouse-location:2:${JSON.stringify(reference)}:data`
? {
expected_reference: reference,
geography_reference: {
...reference,
record_id: 'PRIVATE-LOCATION-QA',
},
}
: undefined,
);
const props = {
geographyEnabled: true,
warehouseGeography: { 2: { reference, path: [] } },
};
expect(render(false, props)).toContain('PRIVATE-LOCATION-QA');
expect(render(false, props)).toContain('data-preparation-dirty="true"');
expect(
render(false, {
...props,
warehouseGeography: {
2: { reference: { ...reference, record_id: '12' }, path: [] },
},
}),
).not.toContain('PRIVATE-LOCATION-QA');
expect(render(false, props, 8)).not.toContain('PRIVATE-LOCATION-QA');
});
test('stock movement preparation retains native idempotency data only in the authorised actor context', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${operationIdentity}:data`
? {
...initialOperation,
reference: 'PRIVATE-MOVEMENT-QA',
quantity: '1.234',
reason: 'Synthetic physical evidence',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(true)).toContain('PRIVATE-MOVEMENT-QA');
expect(render(true)).toContain('data-preparation-dirty="true"');
expect(render(true, {}, 8)).not.toContain('PRIVATE-MOVEMENT-QA');
expect(render(true, {}, 7, 5)).not.toContain('PRIVATE-MOVEMENT-QA');
expect(render(true, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-MOVEMENT-QA',
);
expect(render(true, { canOperate: false })).not.toContain(
'PRIVATE-MOVEMENT-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('lot count input recovery requires the exact native baseline hash', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${operationIdentity}:data`
? { ...initialOperation, kind: 'count' }
: k === `${operationIdentity}:lot-count-inputs`
? {
'baseline-qa': [
{
lot_id: 5,
new_key: null,
quantity: '7.321',
code: 'LOT-QA',
expires_on: '2027-01-01',
no_expiry: false,
},
],
}
: undefined,
);
const source = {
stock_item_id: 1,
warehouse_id: 2,
hash: 'baseline-qa',
lots: [
{
lot_id: 5,
metadata_id: 5,
quantity_milli: 1000,
code: 'LOT-QA',
expires_on: '2027-01-01',
no_expiry: false,
},
],
};
expect(render(true, { lotCounts: [source] })).toContain('value="7.321"');
expect(
render(true, { lotCounts: [{ ...source, hash: 'new-baseline-qa' }] }),
).not.toContain('value="7.321"');
});
test('restored idempotency alone stays clean and the demonstration remains independently renderable', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${operationIdentity}:data` ? initialOperation : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(true)).toContain('data-preparation-dirty="false"');
expect(
renderToStaticMarkup(
<App
initialComponent={OperationsDemo}
initialPage={{
component: 'preview/index',
url: '/preview',
version: null,
clearHistory: false,
encryptHistory: false,
props: { errors: {} },
}}
/>,
),
).toContain('Saídas, transferências e inventários');
expect(post).not.toHaveBeenCalled();
});
@@ -0,0 +1,123 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Bank from '@/pages/suppliers/bank';
afterEach(() => vi.restoreAllMocks());
const identity = 'supplier-bank:4:7:2:legacy:3:true:true';
const proposal = {
previous_id: 3,
account_key: null,
bank_name: 'BANK-QA-NOT-SUBMITTED',
country: 'MZ',
currency: 'MZN',
beneficiary: 'Synthetic beneficiary',
account_identifier: 'SYNTHETIC-IDENTIFIER',
evidence_reference: 'Synthetic evidence',
reason: 'Unsubmitted synthetic proposal',
};
function render(
actor = 7,
tenant = 4,
version = 3,
canPropose = true,
canReview = true,
accountKey: string | null = null,
) {
return renderToStaticMarkup(
<App
initialComponent={Bank}
initialPage={{
component: 'suppliers/bank',
url: '/fornecedores/2/dados-bancarios',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
actorId: actor,
supplier: { id: 2, name: 'Synthetic supplier' },
currentId: version,
state: 'pending',
accountKey,
multiAccountsAvailable: true,
current: {
id: version,
revision: 1,
bank_name: 'Current synthetic bank',
country: 'MZ',
currency: 'MZN',
beneficiary: 'Current synthetic beneficiary',
account_identifier: 'CURRENT-QA',
evidence_reference: 'Current synthetic evidence',
reason: 'Current synthetic reason',
},
history: [],
reviews: [],
canPropose,
canReview,
},
}}
/>,
);
}
test('unsubmitted bank proposal is restored privately without proposing or reviewing automatically', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:proposal:data` ? proposal : undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('BANK-QA-NOT-SUBMITTED');
expect(html).toContain('SYNTHETIC-IDENTIFIER');
expect(html).toContain('data-preparation-dirty="true"');
expect(post).not.toHaveBeenCalled();
expect(render(8)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(render(7, 5)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(render(7, 4, 4)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(render(7, 4, 3, false)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(
render(7, 4, 3, true, true, '00000000-0000-4000-8000-000000000002'),
).not.toContain('BANK-QA-NOT-SUBMITTED');
});
test('independent account preparation restores its pending identity and mode without creating the account', () => {
const accountKey = '00000000-0000-4000-8000-000000000002';
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:adding`
? true
: key === `${identity}:proposal:data`
? { ...proposal, previous_id: 0, account_key: accountKey }
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('Propor conta independente');
expect(html).toContain('BANK-QA-NOT-SUBMITTED');
expect(post).not.toHaveBeenCalled();
});
test('bank review preparation remains tied to the same reviewer and exact bank version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:review:data`
? {
decision: 'rejected',
reason: 'REVIEW-QA-NOT-SUBMITTED',
independently_verified: true,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('REVIEW-QA-NOT-SUBMITTED');
expect(render(8)).not.toContain('REVIEW-QA-NOT-SUBMITTED');
expect(render(7, 4, 4)).not.toContain('REVIEW-QA-NOT-SUBMITTED');
expect(render(7, 4, 3, true, false)).not.toContain(
'REVIEW-QA-NOT-SUBMITTED',
);
expect(post).not.toHaveBeenCalled();
});
test('empty bank preparation stays clean', () => {
expect(render()).not.toContain('data-preparation-dirty="true"');
});
@@ -0,0 +1,303 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Responses from '@/components/supplier-responses';
import Improvements from '@/components/supplier-improvements';
import Supplier from '@/pages/suppliers/show';
afterEach(() => vi.restoreAllMocks());
const base = 'procurement-preparations:4:7:procurement.internal:procurement';
const response = {
id: 11,
version: 2,
status: 'draft',
payload: {
title: 'Original response',
received_on: '2026-11-28',
source_reference: 'REF-QA',
statement: 'Original statement',
},
decision: null,
created_by: 9,
reviewed_by: null,
reviewed_at: null,
review_reason: null,
canEdit: true,
canReview: false,
};
const measure = {
id: 12,
version: 2,
status: 'open',
title: 'Original measure',
description: 'Original plan',
responsible_id: 9,
due_on: '2026-12-31',
result: null,
evidence: null,
reviewed_by: null,
review_reason: null,
reviewed_at: null,
canPlan: true,
canExecute: true,
canReview: true,
};
const supplier = {
id: 13,
version: 2,
name: 'Synthetic supplier',
nuit: '123456789',
contact: 'Synthetic',
email: 'qa@example.test',
phone: '123',
address: 'Synthetic location',
category: 'Other',
beneficiaries: 'Synthetic',
document_references: 'REF-QA',
diligence_notes: 'Synthetic',
blocked: false,
next_review: '2027-01-01',
status: 'active',
review_comment: null,
};
function render(
kind: 'responses' | 'improvements' | 'supplier',
overrides = {},
actor = 7,
tenant = 4,
context = 'procurement.internal',
) {
const data =
kind === 'responses'
? {
ready: true,
canCreate: true,
records: [response],
history: null,
}
: {
ready: true,
canCreate: true,
records: [measure],
assignees: [
{ id: 7, name: 'Current' },
{ id: 9, name: 'Other' },
],
today: '2026-11-28',
history: null,
};
return renderToStaticMarkup(
<App
initialComponent={
kind === 'responses'
? Responses
: kind === 'improvements'
? Improvements
: Supplier
}
initialPage={{
component: 'test',
url: '/test',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['procurement'] },
data,
evaluationId: 3,
names: { 7: 'Current', 9: 'Other' },
reportOnly: false,
generatedAt: '2026-11-28T00:00:00Z',
supplier,
documents: [],
canEdit: true,
canDocuments: true,
canReview: true,
...overrides,
},
}}
/>,
);
}
test.each([
[
'responses',
':create',
{
payload: {
title: 'PRIVATE-SUPPLIER-PREPARATION',
received_on: '2026-11-28',
source_reference: 'REF-QA',
statement: 'Prepared statement',
},
},
],
[
'responses',
':record:11:2:draft:true:false:edit',
{
version: 2,
payload: {
...response.payload,
statement: 'PRIVATE-SUPPLIER-PREPARATION',
},
},
],
[
'improvements',
':create',
{
title: 'PRIVATE-SUPPLIER-PREPARATION',
description: 'Prepared plan',
responsible_id: '7',
due_on: '2026-12-31',
},
],
[
'improvements',
':record:12:2:open:true:true:true:plan',
{
version: 2,
title: 'PRIVATE-SUPPLIER-PREPARATION',
description: 'Prepared plan',
responsible_id: '7',
due_on: '2026-12-31',
reason: 'Synthetic reason',
},
],
[
'improvements',
':record:12:2:open:true:true:true:progress',
{
version: 2,
result: 'PRIVATE-SUPPLIER-PREPARATION',
evidence: 'Synthetic evidence',
},
],
[
'improvements',
':record:12:2:open:true:true:true:decision',
{ version: 2, reason: 'PRIVATE-SUPPLIER-PREPARATION' },
],
] as const)(
'%s %s preparation stays in its actor/company/context/evaluation and outside report mode',
(kind, suffix, prepared) => {
const identity = `${base}:supplier-${kind}:3:true:true:false`;
const restore = vi
.spyOn(router, 'restore')
.mockImplementation((k) =>
k === `${identity}${suffix}:data`
? prepared
: k === `${identity}:operation`
? '11111111-1111-4111-8111-111111111111'
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(kind)).toContain('PRIVATE-SUPPLIER-PREPARATION');
expect(render(kind)).toContain('data-preparation-dirty="true"');
expect(render(kind, {}, 8)).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, {}, 7, 5)).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, { evaluationId: 4 })).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, { reportOnly: true })).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
if (suffix.startsWith(':record')) {
const data =
kind === 'responses'
? {
ready: true,
canCreate: true,
records: [{ ...response, version: 3 }],
history: null,
}
: {
ready: true,
canCreate: true,
records: [{ ...measure, version: 3 }],
assignees: [],
today: '2026-11-28',
history: null,
};
expect(render(kind, { data })).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
}
expect(restore).toHaveBeenCalledWith(`${identity}:operation`);
expect(post).not.toHaveBeenCalled();
},
);
test('independent response analysis is source/version scoped without replacing the original record', () => {
const reviewing = {
...response,
status: 'review',
canEdit: false,
canReview: true,
};
const data = {
ready: true,
canCreate: true,
records: [reviewing],
history: null,
};
vi.spyOn(router, 'restore').mockImplementation((k) =>
k ===
`${base}:supplier-responses:3:true:true:false:record:11:2:review:false:true:review:data`
? {
version: 2,
outcome: 'accepted',
reason: 'RESPONSE-REVIEW-QA',
follow_up: 'Synthetic follow-up',
response_reference: 'REF-QA',
}
: undefined,
);
expect(render('responses', { data })).toContain('RESPONSE-REVIEW-QA');
expect(render('responses', { data })).toContain('Original statement');
expect(
render('responses', {
data: { ...data, records: [{ ...reviewing, version: 3 }] },
}),
).not.toContain('RESPONSE-REVIEW-QA');
expect(
render('responses', {
data: { ...data, records: [{ ...reviewing, canReview: false }] },
}),
).not.toContain('RESPONSE-REVIEW-QA');
});
test('supplier validation preparation follows its exact native version without remembering uploads', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:supplier-review:13:2:data`
? { status: 'active', comment: 'SUPPLIER-REVIEW-QA' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('supplier')).toContain('SUPPLIER-REVIEW-QA');
expect(
render('supplier', { supplier: { ...supplier, version: 3 } }),
).not.toContain('SUPPLIER-REVIEW-QA');
expect(render('supplier', { canReview: false })).not.toContain(
'SUPPLIER-REVIEW-QA',
);
expect(render('supplier', {}, 8)).not.toContain('SUPPLIER-REVIEW-QA');
expect(post).not.toHaveBeenCalled();
});
test('unchanged native supplier forms remain clean', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
expect(render('responses')).not.toContain('data-preparation-dirty="true"');
expect(render('improvements')).not.toContain(
'data-preparation-dirty="true"',
);
expect(render('supplier')).not.toContain('data-preparation-dirty="true"');
});
@@ -0,0 +1,85 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import EditSupplier from '@/pages/suppliers/edit';
import type { Supplier } from '@/types/supplier';
afterEach(() => vi.restoreAllMocks());
const supplier: Supplier = {
id: 42,
name: 'Fornecedor sintético',
nuit: '123456789',
contact: 'Contacto sintético',
email: 'qa@example.invalid',
phone: '123456789',
address: 'Morada sintética',
category: 'Material',
beneficiaries: 'Beneficiário sintético',
document_references: 'Referências documentais sintéticas',
diligence_notes: 'Conferência sintética anterior',
next_review: '2027-01-01',
blocked: false,
version: 1,
status: 'active',
review_comment: null,
};
const preparation = {
geography_reference: null,
name: 'NOME-QA-POR-GUARDAR',
nuit: supplier.nuit,
contact: supplier.contact,
email: supplier.email,
phone: supplier.phone,
address: 'Morada por guardar',
category: supplier.category,
beneficiaries: supplier.beneficiaries,
document_references: supplier.document_references,
diligence_notes: 'Preparação de diligência ainda não submetida',
next_review: supplier.next_review,
blocked: false,
version: 1,
};
function render(tenant = 3, actor = 7, id = 42, version = 1) {
return renderToStaticMarkup(
<App
initialComponent={EditSupplier}
initialPage={{
component: 'suppliers/edit',
url: `/fornecedores/${id}/editar`,
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
supplier: { ...supplier, id, version },
},
}}
/>,
);
}
test('supplier editing recovers the same private preparation without renewing diligence or saving automatically', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'supplier-preparation:3:7:42:1:data' ? preparation : undefined,
);
const put = vi.spyOn(router, 'put');
const html = render();
expect(html).toContain('NOME-QA-POR-GUARDAR');
expect(html).toContain('Morada por guardar');
expect(html).toContain('Preparação de diligência ainda não submetida');
expect(html).toContain('Alterações à ficha retiram a validação actual');
expect(put).not.toHaveBeenCalled();
});
test('supplier preparation does not cross actor company supplier identity or a changed server version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'supplier-preparation:3:7:42:1:data' ? preparation : undefined,
);
expect(render(4)).not.toContain('NOME-QA-POR-GUARDAR');
expect(render(3, 8)).not.toContain('NOME-QA-POR-GUARDAR');
expect(render(3, 7, 43)).not.toContain('NOME-QA-POR-GUARDAR');
expect(render(3, 7, 42, 2)).not.toContain('NOME-QA-POR-GUARDAR');
});
@@ -0,0 +1,243 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Coordination from '@/pages/supply/coordination';
afterEach(() => vi.restoreAllMocks());
const props = {
kind: 'delivery',
ready: true,
canPrepare: true,
canReview: true,
conversionQaEnabled: true,
eligible: {},
pending: {},
records: [],
history: {},
items: [{ id: 1, code: 'QA', name: 'Synthetic item', unit: 'un' }],
warehouses: [],
requestLines: [],
orderLines: [
{
id: 3,
label: 'Synthetic source',
unit: 'box',
stock_item_id: 1,
quantity_milli: 2000,
},
],
operations: [],
};
function render(overrides = {}, actor = 7, tenant = 4) {
return renderToStaticMarkup(
<App
initialComponent={Coordination}
initialPage={{
component: 'supply/coordination',
url: '/compras/fornecimento?view=deliveries',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...props,
...overrides,
},
}}
/>,
);
}
test('confirmed delivery preparation restores documentary quantity and explicit conversion independently', () => {
const key =
'supply-coordination:4:7:delivery:true:true:true:true:new:0:new::prepare';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === `${key}:data`
? {
operation_key: 'synthetic-delivery',
version: 0,
action: 'save',
reason: 'DELIVERY-EVIDENCE-QA',
data: {
purchase_order_item_id: '3',
stock_item_id: '1',
warehouse_id: '',
quantity: '1.500',
expected_on: '2026-12-15',
confirmed_on: '2026-11-28',
evidence: 'SYNTHETIC-CARRIER-QA',
},
}
: candidate === `${key}:conversion`
? {
numerator: '12',
denominator: '1',
source: 'UNSUBMITTED-CONVERSION-SOURCE',
version: 'source-v2',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('value="1.500"');
expect(html).toContain('UNSUBMITTED-CONVERSION-SOURCE');
expect(html).toContain('source-v2');
expect(html).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('UNSUBMITTED-CONVERSION-SOURCE');
expect(render({}, 7, 5)).not.toContain('UNSUBMITTED-CONVERSION-SOURCE');
expect(render({ conversionQaEnabled: false })).not.toContain(
'DELIVERY-EVIDENCE-QA',
);
expect(render({ canReview: false })).not.toContain('DELIVERY-EVIDENCE-QA');
expect(post).not.toHaveBeenCalled();
});
test.each(['reservation', 'alternative'])(
'%s preparation restores in its own source journey',
(kind) => {
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate ===
`supply-coordination:4:7:${kind}:true:true:true:true:new:0:new::prepare:data`
? {
operation_key: 'synthetic-prepare',
version: 0,
action: 'save',
reason: 'COORDINATION-PREPARATION-QA',
data: {
stock_item_id: '1',
warehouse_id: '',
quantity: '1.500',
needed_on: '2026-12-15',
reference: 'Synthetic reference',
compatibility: 'pending',
application: 'Synthetic machine',
evidence: 'Synthetic evidence',
conditions: 'Synthetic conditions',
factor_numerator: 1,
factor_denominator: 1,
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render({ kind })).toContain('COORDINATION-PREPARATION-QA');
expect(render()).not.toContain('COORDINATION-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
},
);
test('coordination data and conversion never cross the active work context', () => {
const key =
'supply-coordination:4:7:delivery:true:true:true:true:new:0:new::context:procurement.internal:prepare';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === `${key}:data`
? {
operation_key: 'synthetic-context',
version: 0,
action: 'save',
reason: 'CONTEXT-SPECIFIC-DELIVERY-QA',
data: {
purchase_order_item_id: '3',
stock_item_id: '1',
warehouse_id: '',
quantity: '1.500',
expected_on: '2026-12-15',
confirmed_on: '2026-11-28',
evidence: 'Synthetic evidence',
},
}
: candidate === `${key}:conversion`
? {
numerator: '12',
denominator: '1',
source: 'CONTEXT-SPECIFIC-CONVERSION-QA',
version: 'v2',
}
: undefined,
);
const html = render({ workContext: { active: 'procurement.internal' } });
expect(html).toContain('CONTEXT-SPECIFIC-DELIVERY-QA');
expect(html).toContain('CONTEXT-SPECIFIC-CONVERSION-QA');
const other = render({
workContext: { active: 'procurement.third_party' },
});
expect(other).not.toContain('CONTEXT-SPECIFIC-DELIVERY-QA');
expect(other).not.toContain('CONTEXT-SPECIFIC-CONVERSION-QA');
expect(render()).not.toContain('CONTEXT-SPECIFIC-DELIVERY-QA');
});
const record = {
id: 9,
record_key: 'qa-reservation',
version: 2,
state: 'active',
reason: 'Original synthetic reservation',
created_at: '2026-11-28',
canApprove: false,
canReturn: false,
canSuspend: false,
canEdit: true,
canFulfil: true,
canCancel: true,
data: {
stock_item_id: 1,
warehouse_id: 2,
quantity_milli: 2000,
applications: [],
},
snapshot: {
item: { code: 'QA', name: 'Synthetic item', unit: 'un' },
warehouse: { name: 'Synthetic warehouse' },
},
};
test('unsubmitted fulfilment restores only for the same pending quantity and eligible version', () => {
const key =
'supply-coordination:4:7:reservation:true:true:true:true:qa-reservation:2:active:2000:action:false:false:false:true:true:true:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-fulfilment',
record_key: record.record_key,
version: 2,
action: 'fulfil',
reason: 'PENDING-ALLOCATION-QA',
quantity: '0.500',
data: { stock_operation_id: '12', quantity_milli: 0 },
}
: undefined,
);
const base = {
kind: 'reservation',
records: [record],
pending: { 'qa-reservation': 2000 },
operations: [
{
id: 12,
reference: 'Synthetic issue',
stock_item_id: 1,
warehouse_id: 2,
quantity_milli: 500,
},
],
};
const post = vi.spyOn(router, 'post');
expect(render(base)).toContain('PENDING-ALLOCATION-QA');
expect(render(base)).toContain('value="0.500"');
expect(
render({ ...base, pending: { 'qa-reservation': 1500 } }),
).not.toContain('PENDING-ALLOCATION-QA');
expect(
render({ ...base, records: [{ ...record, version: 3 }] }),
).not.toContain('PENDING-ALLOCATION-QA');
expect(
render({ ...base, records: [{ ...record, canFulfil: false }] }),
).not.toContain('PENDING-ALLOCATION-QA');
expect(post).not.toHaveBeenCalled();
});
test.each(['delivery', 'reservation', 'alternative'])(
'unchanged %s preparation is clean',
(kind) => {
expect(render({ kind })).not.toContain('data-preparation-dirty="true"');
},
);
@@ -0,0 +1,343 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import History from '@/pages/supply/history';
import Suggestions from '@/pages/supply/suggestions';
afterEach(() => vi.restoreAllMocks());
const historyProps = {
ready: true,
actorId: 7,
canPrepare: true,
canReview: true,
records: [],
history: {},
items: [],
warehouses: [],
defaultPeriod: { from: '2026-10-01', until: '2026-10-31' },
};
const suggestionProps = {
ready: true,
actorId: 7,
canPrepare: true,
canReview: true,
canConvert: true,
records: [],
policies: [
{
key: 'policy-qa',
version: 2,
label: 'Synthetic policy',
issue: null,
unit_price: '12.50',
tax_rate: '0.00',
},
],
excess: {},
costCenters: [],
requestLinks: {},
history: {},
};
function render(
kind: 'history' | 'suggestions',
overrides = {},
actor = 7,
tenant = 4,
) {
return renderToStaticMarkup(
<App
initialComponent={kind === 'history' ? History : Suggestions}
initialPage={{
component: `supply/${kind}`,
url: `/compras/fornecimento?view=${kind}`,
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...(kind === 'history' ? historyProps : suggestionProps),
actorId: actor,
...overrides,
},
}}
/>,
);
}
test('consumption evidence and its explicit period restore without calculating or approving', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'supply-history:4:7:true:true:true:new:0:new:prepare:data'
? {
operation_key: 'synthetic-history',
version: 0,
action: 'save',
reason: 'HISTORY-EVIDENCE-QA',
data: {
stock_item_id: '',
warehouse_id: '',
purpose: 'internal',
period_from: '2026-09-01',
period_until: '2026-09-30',
quality: 'incomplete',
pattern: 'seasonal',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('history');
expect(html).toContain('HISTORY-EVIDENCE-QA');
expect(html).toContain('value="2026-09-01"');
expect(html).toContain('<option value="incomplete" selected="">');
expect(html).toContain('data-preparation-dirty="true"');
expect(render('history', {}, 8)).not.toContain('HISTORY-EVIDENCE-QA');
expect(render('history', {}, 7, 5)).not.toContain('HISTORY-EVIDENCE-QA');
expect(render('history', { canReview: false })).not.toContain(
'HISTORY-EVIDENCE-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('suggestion restores one policy selection with its deliberately edited estimates and manual plan', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
'supply-suggestion:4:7:true:true:true:true:new:0:new:prepare:data'
? {
operation_key: 'synthetic-suggestion',
version: 0,
action: 'save',
reason: 'SUGGESTION-EVIDENCE-QA',
data: {
policy_key: 'policy-qa',
unit_price: '14.25',
tax_rate: '0.00',
quantity: '3.500',
delivery_on: '2026-12-15',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('suggestions');
expect(html).toContain('<option value="policy-qa" selected="">');
expect(html).toContain('value="14.25"');
expect(html).toContain('value="0.00"');
expect(html).toContain('value="3.500"');
expect(html).toContain('value="2026-12-15"');
expect(html).toContain('SUGGESTION-EVIDENCE-QA');
expect(render('suggestions', {}, 8)).not.toContain(
'SUGGESTION-EVIDENCE-QA',
);
expect(render('suggestions', {}, 7, 5)).not.toContain(
'SUGGESTION-EVIDENCE-QA',
);
expect(render('suggestions', { canConvert: false })).not.toContain(
'SUGGESTION-EVIDENCE-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('a restored policy outside the current search remains visibly selected without inventing eligibility', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
'supply-suggestion:4:7:true:true:true:true:new:0:new:prepare:data'
? {
operation_key: 'synthetic-suggestion',
version: 0,
action: 'save',
reason: 'Pending explicit policy verification',
data: {
policy_key: 'not-in-current-results',
unit_price: '14.25',
tax_rate: '0.00',
quantity: '',
delivery_on: '',
},
}
: undefined,
);
expect(render('suggestions', { policies: [] })).toContain(
'<option value="not-in-current-results" selected="">',
);
expect(render('suggestions', { policies: [] })).toContain(
'procurar para conferir',
);
});
test.each(['history', 'suggestions'] as const)(
'empty %s preparations remain clean',
(kind) => {
expect(render(kind)).not.toContain('data-preparation-dirty="true"');
},
);
test.each(['history', 'suggestions'] as const)(
'%s preparation is isolated by active work context',
(kind) => {
const key =
kind === 'history'
? 'supply-history:4:7:true:true:true:new:0:new:context:procurement.internal:prepare:data'
: 'supply-suggestion:4:7:true:true:true:true:new:0:new:context:procurement.internal:prepare:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-context',
version: 0,
action: 'save',
reason: 'CONTEXT-SPECIFIC-FOLLOWUP-QA',
data:
kind === 'history'
? {
stock_item_id: '',
warehouse_id: '',
purpose: 'internal',
period_from: '2026-10-01',
period_until: '2026-10-31',
quality: 'unknown',
pattern: 'unknown',
}
: {
policy_key: 'policy-qa',
unit_price: '12.50',
tax_rate: '0.00',
quantity: '',
delivery_on: '',
},
}
: undefined,
);
expect(
render(kind, { workContext: { active: 'procurement.internal' } }),
).toContain('CONTEXT-SPECIFIC-FOLLOWUP-QA');
expect(
render(kind, {
workContext: { active: 'procurement.third_party' },
}),
).not.toContain('CONTEXT-SPECIFIC-FOLLOWUP-QA');
expect(render(kind)).not.toContain('CONTEXT-SPECIFIC-FOLLOWUP-QA');
},
);
const baseRecord = {
id: 9,
record_key: 'qa-record',
version: 2,
state: 'draft',
reason: 'Original synthetic evidence',
created_at: '2026-11-28',
canApprove: true,
canReturn: true,
canSuspend: false,
canConvert: false,
canCancel: true,
canClose: false,
};
const snapshot = {
item: { code: 'QA', name: 'Synthetic item', unit: 'un' },
warehouse: { name: 'Synthetic warehouse' },
contributors: [],
actor: { name: 'Synthetic author' },
};
const historyRecord = {
...baseRecord,
data: {
stock_item_id: 1,
warehouse_id: 2,
purpose: 'internal',
period_from: '2026-10-01',
period_until: '2026-10-31',
quality: 'complete',
pattern: 'regular',
},
snapshot: {
...snapshot,
analysis: {
days: 31,
total_milli: 1000,
daily_mean_milli: '32.258064516',
active_days: 1,
zero_balance_days: 0,
negative_balance_days: 0,
invalid_issue: false,
opening_milli: 2000,
movement_count: 1,
movement_types: { issue: 1 },
convention: 'Synthetic analysis',
series: [],
},
},
};
const suggestionRecord = {
...baseRecord,
data: {
policy_key: 'policy-qa',
policy_version: 2,
quantity_milli: 1000,
delivery_on: '2026-12-15',
unit_price: '12.50',
tax_rate: '0.00',
manual_plan: true,
price_source: 'Synthetic estimate',
tax_source: 'Illustrative zero',
},
snapshot: {
...snapshot,
prepared_on: '2026-11-28',
balance: { quantity: 2000 },
policy: { purpose: 'internal', origin: 'local' },
events: { reservations: [], receipts: [], warnings: [] },
projection: { available: true, series: [] },
},
};
test.each(['history', 'suggestions'] as const)(
'%s independent decision recovers only for the same source and eligibility',
(kind) => {
const key =
kind === 'history'
? 'supply-history:4:7:true:true:true:qa-record:2:draft:decision:true:true:false:data'
: 'supply-suggestion:4:7:true:true:true:true:qa-record:2:draft:decision:true:true:false:true:false:false:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-decision',
record_key: 'qa-record',
version: 2,
action: 'return',
reason: 'INDEPENDENT-DECISION-QA',
data:
kind === 'history'
? { confirm_scope: false }
: {
cost_center_id: '',
confirm_exception: false,
},
}
: undefined,
);
const source = kind === 'history' ? historyRecord : suggestionRecord;
const post = vi.spyOn(router, 'post');
const html = render(kind, { records: [source] });
expect(html).toContain('INDEPENDENT-DECISION-QA');
expect(html).toContain('data-preparation-dirty="true"');
expect(
render(kind, { records: [{ ...source, version: 3 }] }),
).not.toContain('INDEPENDENT-DECISION-QA');
expect(
render(kind, { records: [{ ...source, canReturn: false }] }),
).not.toContain('INDEPENDENT-DECISION-QA');
expect(render(kind, { records: [source] }, 8)).not.toContain(
'INDEPENDENT-DECISION-QA',
);
if (kind === 'suggestions')
expect(
render(kind, {
records: [source],
excess: { 'qa-record': true },
}),
).not.toContain('INDEPENDENT-DECISION-QA');
expect(post).not.toHaveBeenCalled();
},
);
+285
View File
@@ -0,0 +1,285 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Supply from '@/pages/supply/index';
afterEach(() => vi.restoreAllMocks());
const record = {
id: 9,
record_key: 'synthetic-agreement',
version: 2,
state: 'draft',
data: { reference: 'Original reference', currency: 'MZN' },
reason: 'Original synthetic preparation',
created_at: '2026-11-28T00:00:00Z',
snapshot: {},
canApprove: true,
canReturn: true,
canSuspend: false,
};
const props = {
kind: 'agreement',
view: 'agreements',
ready: true,
orderLimitsReady: false,
asOf: '2026-11-28',
canPrepare: true,
canReview: true,
canCustoms: false,
records: [record],
history: {},
projections: {},
items: [],
warehouses: [],
suppliers: [],
orders: [],
histories: [],
agreements: [],
contracts: [],
};
function identity(key = 'new', version = 0, state = 'new') {
return `supply:4:7:agreement:agreements:::true:true:true:false:false:${key}:${version}:${state}`;
}
function render(overrides = {}, actor = 7, tenant = 4) {
return renderToStaticMarkup(
<App
initialComponent={Supply}
initialPage={{
component: 'supply/index',
url: '/compras/fornecimento?view=agreements',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...props,
...overrides,
},
}}
/>,
);
}
test('new supply preparation restores without saving and is isolated by identity, source and capabilities', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity()}:prepare:data`
? {
operation_key: 'synthetic-pending-command',
version: 0,
action: 'save',
reason: 'UNSUBMITTED-SUPPLY-QA',
data: {
reference: 'PRIVATE-SUPPLY-REFERENCE',
currency: 'MZN',
habitual: true,
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('PRIVATE-SUPPLY-REFERENCE');
expect(html).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('PRIVATE-SUPPLY-REFERENCE');
expect(render({}, 7, 5)).not.toContain('PRIVATE-SUPPLY-REFERENCE');
for (const change of [
{ kind: 'contract', view: 'contracts' },
{ linkedContractKey: 'another-contract' },
{ linkedAgreementKey: 'another-agreement' },
{ canReview: false },
{ canCustoms: true },
{ orderLimitsReady: true },
]) {
expect(render(change)).not.toContain('PRIVATE-SUPPLY-REFERENCE');
}
expect(post).not.toHaveBeenCalled();
});
test('editing a supply version restores separately from a new preparation or later version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity(record.record_key, 2, 'draft')}:prepare:data`
? {
operation_key: 'synthetic-edit-command',
record_key: record.record_key,
version: 2,
action: 'save',
reason: 'EDIT-PREPARATION-QA',
data: { reference: 'EDITED-REFERENCE-QA', currency: 'MZN' },
}
: undefined,
);
const html = render();
expect(html.match(/EDITED-REFERENCE-QA/g)).toHaveLength(1);
expect(render({ records: [{ ...record, version: 3 }] })).not.toContain(
'EDITED-REFERENCE-QA',
);
expect(
render({ records: [{ ...record, record_key: 'other-record' }] }),
).not.toContain('EDITED-REFERENCE-QA');
});
test('independent review restores its selected action and reason only for the exact authorised version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
`${identity(record.record_key, 2, 'draft')}:action:true:true:false:data`
? {
operation_key: 'synthetic-review-command',
record_key: record.record_key,
version: 2,
action: 'return',
reason: 'UNSUBMITTED-REVIEW-QA',
data: { evidence: '', event_date: '' },
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('UNSUBMITTED-REVIEW-QA');
expect(render()).toContain('<option value="return" selected="">');
expect(
render({ records: [{ ...record, canReturn: false }] }),
).not.toContain('UNSUBMITTED-REVIEW-QA');
expect(render({ records: [{ ...record, version: 3 }] })).not.toContain(
'UNSUBMITTED-REVIEW-QA',
);
expect(
render({ records: [{ ...record, state: 'approved' }] }),
).not.toContain('UNSUBMITTED-REVIEW-QA');
expect(render({}, 8)).not.toContain('UNSUBMITTED-REVIEW-QA');
expect(post).not.toHaveBeenCalled();
});
test('unchanged supply forms remain clean despite newly generated command identities', () => {
expect(render()).not.toContain('data-preparation-dirty="true"');
});
test('active work contexts never share an unsubmitted supply preparation', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity()}:context:procurement.internal:prepare:data`
? {
operation_key: 'synthetic-context-command',
version: 0,
action: 'save',
reason: 'CONTEXT-SPECIFIC-SUPPLY-QA',
data: {
reference: 'Synthetic internal preparation',
currency: 'MZN',
habitual: true,
},
}
: undefined,
);
expect(
render({ workContext: { active: 'procurement.internal' } }),
).toContain('CONTEXT-SPECIFIC-SUPPLY-QA');
expect(
render({ workContext: { active: 'procurement.third_party' } }),
).not.toContain('CONTEXT-SPECIFIC-SUPPLY-QA');
expect(render()).not.toContain('CONTEXT-SPECIFIC-SUPPLY-QA');
});
test.each([
['contract', 'contracts'],
['policy', 'calendar'],
['import', 'imports'],
])(
'restores %s preparation in its own journey without a command',
(kind, view) => {
const key = `supply:4:7:${kind}:${view}:::true:true:true:false:false:new:0:new:prepare:data`;
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-pending-command',
version: 0,
action: 'save',
reason: 'SHARED-PREPARATION-QA',
data: {
reference: 'Synthetic reference',
currency: 'MZN',
jurisdiction: 'Synthetic jurisdiction',
purpose: 'internal',
safety: '0',
minimum: '0',
pack: '1',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render({ kind, view, records: [] })).toContain(
'SHARED-PREPARATION-QA',
);
expect(render()).not.toContain('SHARED-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
},
);
test('replacement policy restores a new proposal without overwriting its approved predecessor', () => {
const key =
'supply:4:7:policy:calendar:::true:true:true:false:false:synthetic-agreement:2:approved:copy:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-replacement-command',
version: 0,
action: 'save',
reason: 'REPLACEMENT-ONLY-QA',
data: {
purpose: 'internal',
basis: 'NEW-POLICY-BASIS-QA',
safety: '0',
minimum: '0',
pack: '1',
},
}
: undefined,
);
const html = render({
kind: 'policy',
view: 'calendar',
records: [{ ...record, state: 'approved' }],
});
expect(html).toContain('NEW-POLICY-BASIS-QA');
expect(html).toContain('Original synthetic preparation');
expect(html).toContain('data-preparation-dirty="true"');
expect(
render({
kind: 'policy',
view: 'calendar',
records: [{ ...record, state: 'approved', version: 3 }],
}),
).not.toContain('NEW-POLICY-BASIS-QA');
});
test('logistics preparation restores its dated evidence without registering the milestone', () => {
const key =
'supply:4:7:import:imports:::true:true:true:true:false:synthetic-agreement:2:transit:action:true:true:false:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-logistics-command',
record_key: record.record_key,
version: 2,
action: 'arrive',
reason: 'LOGISTICS-PREPARATION-QA',
data: {
evidence: 'UNSUBMITTED-SHIPPING-EVIDENCE',
event_date: '2026-11-27',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render({
kind: 'import',
view: 'imports',
canCustoms: true,
records: [{ ...record, state: 'transit' }],
});
expect(html).toContain('UNSUBMITTED-SHIPPING-EVIDENCE');
expect(html).toContain('value="2026-11-27"');
expect(html).toContain('<option value="arrive" selected="">');
expect(html).toContain('data-preparation-dirty="true"');
expect(post).not.toHaveBeenCalled();
});
+127
View File
@@ -0,0 +1,127 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Review from '@/pages/requisitions/urgent-review';
import Queue from '@/pages/requisitions/urgent-reviews';
import Policy from '@/pages/organization/urgent-review-policy';
function render(
component: Parameters<typeof App>[0]['initialComponent'],
props: object,
) {
return renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/requisicoes/urgencias/revisoes',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
}
const props: ComponentProps<typeof Review> = {
actorId: 1,
tenantId: 1,
canReview: true,
currentVerified: true,
current: null,
history: { data: [], prev_page_url: null, next_page_url: null },
source: {
cycle: 1,
outcome: 'expired',
fingerprint: 'a'.repeat(64),
closed_at: '2026-11-27T12:00:00Z',
request: {
id: 3,
number: 'REQ-QA',
justification: 'Necessidade original <script>de teste</script>',
total_minor: '9007199254740993',
},
items: [
{
id: 1,
description: 'Material original',
quantity: '1.000',
unit: 'un',
total_minor: '9007199254740993',
},
],
steps: [
{
id: 1,
role: 'department_head',
decision: 'pending',
comment: null,
},
],
},
};
test('expired cycle review distinguishes its original values from a later preparation and escapes source text', () => {
const html = render(Review, props);
expect(html).toContain('90.071.992.547.409,93 MZN');
expect(html).toContain('Estes dados pertencem ao ciclo expirado');
expect(html).toContain('Sem decisão antes da conclusão do ciclo');
expect(html).toContain('&lt;script&gt;de teste&lt;/script&gt;');
expect(html).toContain('Registar revisão posterior');
expect(html).not.toContain('Aprovar');
});
test('unverified historical review is identified without offering a new approval or review command', () => {
const html = render(Review, {
...props,
canReview: false,
currentVerified: false,
current: {
id: 7,
version: 1,
data: { notes: 'Texto sintético preservado' },
snapshot: { fingerprint: 'a'.repeat(64) },
},
});
expect(html).toContain('não é apresentado como revisto');
expect(html).toContain('Texto sintético preservado');
expect(html).not.toContain('<form');
});
test('review queue keeps coverage and its own pagination while profile designation remains explicit', () => {
const html = render(Queue, {
coverage: { pending: 1, reviewed: 2, indeterminate: 1 },
state: 'pending',
canReview: false,
canConfigure: true,
records: {
data: [
{
key: '3:1',
number: 'REQ-QA',
cycle: 1,
outcome: 'expired',
status: 'pending',
closed_at: '2026-11-27T12:00:00Z',
href: '/requisicoes/3/ciclos/1/revisao-urgencia',
},
],
total: 21,
current_page: 1,
last_page: 2,
},
});
expect(html).toContain('Origem por conferir');
expect(html).toContain(
'/requisicoes/urgencias/revisoes?state=pending&amp;page=2',
);
expect(html).toContain('Expirada e devolvida ao requisitante');
const settings = render(Policy, {
actorId: 1,
tenantId: 1,
current: null,
profiles: [],
history: { data: [], prev_page_url: null, next_page_url: null },
});
expect(settings).toContain('não concede permissões');
expect(settings).toContain('incluindo rejeição ou expiração');
expect(settings).toContain('Configure os perfis da empresa');
});