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

This commit is contained in:
2026-11-29 05:28:30 +02:00
parent 1ddabbbdcc
commit 448948a487
137 changed files with 9481 additions and 1926 deletions
@@ -1,11 +1,20 @@
<?php
use App\Models\ConflictDeclaration;
use App\Models\ConflictRelease;
use App\Models\OrderCancellation;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\OrderCancellationWorkflow;
use App\Services\ProposalComparison;
use App\Services\RequisitionAccountAssignments;
use App\Services\UrgentQuotationBasis;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
@@ -14,7 +23,7 @@ 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', 'describe-private-audit-schema'], true)) {
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase', 'describe-private-audit-schema', 'read-native-conflict-release', 'read-native-urgent-stock', 'read-native-cancellation'], true)) {
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$databaseName = getenv('DB_DATABASE') ?: '';
@@ -78,6 +87,116 @@ if ($mode === 'read-office-purchase') {
}
exit;
}
if ($mode === 'read-native-conflict-release') {
if (getenv('RQ01_QA_CONFLICT_RELEASE') !== '1') {
throw new LogicException('Conflict assertions require their own synthetic preview.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
$context = $fixture['conflict_review'];
config(['conflict-releases.qa_enabled' => true]);
auth()->guard()->setUser(User::query()->findOrFail($context['author_id']));
$state = DB::transaction(function () use ($context) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$originals = ConflictDeclaration::query()->where('user_id', $context['author_id'])->orderBy('id')->get();
if (hash('sha256', $originals->toJson()) !== $context['originals_sha256']) {
throw new LogicException('Native release must preserve both original declarations.');
}
foreach ($context['protected_frames'] as $table => $expected) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
if (hash('sha256', $rows->toJson()) !== $expected) {
throw new LogicException('Native release changed protected financial, stock or authority frame: '.$table);
}
}
$release = ConflictRelease::query()->sole();
$guard = app(ConflictGuard::class);
$supplierBlocked = $guard->hasConflict($context['author_id'], $context['supplier_id'], null);
$otherProcessBlocked = $guard->hasConflict($context['author_id'], $context['supplier_id'], $context['requisition_id']);
if ($release->declaration_id !== $context['declaration_id'] || $release->authorised_by !== $context['direction_id']
|| Arr::sortRecursive($release->snapshot) !== Arr::sortRecursive($originals->first()->toArray()) || $supplierBlocked || ! $otherProcessBlocked
|| DB::table('audit_logs')->where('action', 'conflict.release_authorised')->count() !== 1) {
throw new LogicException('Native direction decision must release only the selected chain once.');
}
return ['release_id' => $release->id, 'declaration_id' => $release->declaration_id,
'direction_id' => $release->authorised_by, 'originals_preserved' => true,
'financial_stock_and_authority_frames_preserved' => count($context['protected_frames']),
'selected_supplier_impediment_released' => ! $supplierBlocked, 'other_process_impediment_still_blocks' => $otherProcessBlocked,
'release_audit_count' => 1, 'readonly_transaction' => DB::selectOne('SHOW transaction_read_only')->transaction_read_only === 'on',
'synthetic_only' => true, 'operational_changes' => false];
});
echo json_encode($state, JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-native-urgent-stock') {
if (getenv('RQ01_QA_URGENT_STOCK') !== '1') {
throw new LogicException('Urgent stock assertions require their own synthetic preview.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
$context = $fixture['urgent_stock_review'];
config(['urgent-quotations.qa_enabled' => true]);
auth()->guard()->setUser(User::query()->findOrFail($context['actor_id']));
$state = DB::transaction(function () use ($context) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
foreach ($context['protected_frames'] as $table => $expected) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
if (hash('sha256', $rows->toJson()) !== $expected) {
throw new LogicException('Urgent evidence changed a protected frame: '.$table);
}
}
$request = Requisition::query()->findOrFail($context['request_id']);
$eligible = app(UrgentQuotationBasis::class)->eligible($request);
$policy = app(ProposalComparison::class)->inspect($request)['policy'];
if (count($eligible) !== 1 || $policy['minimum_proposals'] !== 1 || $policy['normal_minimum_proposals'] !== 3 || $policy['minimum_evaluators'] !== 2
|| DB::table('audit_logs')->where('action', 'urgent.stock_minimum_recorded')->where('requisition_id', $request->id)->count() !== 1) {
throw new LogicException('Native urgent conference must preserve one valid evidence and independent evaluations.');
}
return ['eligible_evidence' => 1, 'minimum_proposals' => 1, 'normal_minimum_proposals' => 3, 'minimum_evaluators' => 2,
'protected_frames_preserved' => count($context['protected_frames']), 'single_audit' => true, 'readonly_transaction' => true, 'synthetic_only' => true];
});
echo json_encode($state, JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-native-cancellation') {
if (getenv('RQ01_QA_ORDER_CANCELLATION') !== '1') {
throw new LogicException('Cancellation assertions require their own synthetic preview.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
$context = $fixture['cancellation_review'];
config(['order_cancellation.enabled' => true]);
auth()->guard()->setUser(User::query()->findOrFail($context['finance_id']));
$state = DB::transaction(function () use ($context) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
foreach ($context['protected_frames'] as $table => $expected) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
if (hash('sha256', $rows->toJson()) !== $expected) {
throw new LogicException('Legacy cancellation changed a protected frame: '.$table);
}
}
$order = PurchaseOrder::query()->findOrFail($context['order_id']);
$request = Requisition::query()->findOrFail($context['request_id']);
$record = OrderCancellation::query()->where('purchase_order_id', $order->id)->sole();
$currentSource = Arr::except($request->getAttributes(), ['status', 'updated_at']);
$originalSource = Arr::except($context['original_request'], ['status', 'updated_at']);
if ($record->status !== 'approved' || $record->created_by !== $context['author_id'] || $record->reviewed_by !== $context['finance_id']
|| $request->status !== 'cancelled' || $currentSource !== $originalSource || $order->status !== 'issued'
|| hash('sha256', json_encode($order->getAttributes(), JSON_THROW_ON_ERROR)) !== $context['original_order_sha256']
|| app(OrderCancellationWorkflow::class)->state($order) !== 'cancelled') {
throw new LogicException('Native cancellation must preserve the issued original and independent decision.');
}
foreach (['requested', 'approved'] as $action) {
if (DB::table('audit_logs')->where('action', 'order_cancellation.'.$action)->where('requisition_id', $request->id)->count() !== 1) {
throw new LogicException('Native cancellation must create one request and one decision audit.');
}
}
return ['original_order_preserved' => true, 'original_status' => 'issued', 'operational_status' => 'cancelled',
'source_request_cancelled_only' => true, 'independent_finance_decision' => true, 'protected_frames_preserved' => count($context['protected_frames']),
'no_fabricated_legacy_reversal' => true, 'one_request_one_decision' => true, 'readonly_transaction' => true, 'synthetic_only' => true];
});
echo json_encode($state, JSON_THROW_ON_ERROR);
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) {
+68
View File
@@ -1,8 +1,10 @@
<?php
use App\Models\CriticalityLevel;
use App\Models\Department;
use App\Models\Equipment;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use Illuminate\Database\Eloquent\ModelNotFoundException;
@@ -27,6 +29,72 @@ beforeEach(function () {
'reason' => 'Preparação de referência sintética para testes de compras'];
});
test('capital search returns current metadata literal matches pagination and native history links without business writes', function () {
$service = app(CapitalRegister::class);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$old = $service->save($this->f['issuer'], [...$this->input, 'name' => 'OLD-CAPITAL-SEARCH']);
$current = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $old->record_key, 'version' => 1, 'name' => 'NEW-CAPITAL%_SEARCH', 'state' => 'archived']);
$read = function (string $query) {
$response = $this->get('/compras/pesquisa?'.$query)->assertOk()
->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$props = $response->viewData('page')['props'];
expect($props['capitalSearchAvailable'])->toBeTrue();
expect($props['capitalRegisterAvailable'])->toBeTrue();
return collect($props['groups'])->firstWhere('key', 'capital')['records'];
};
expect($read('q=OLD-CAPITAL-SEARCH')['total'])->toBe(0);
$literal = $read('q='.urlencode('%_'));
expect($literal['total'])->toBe(1)->and($literal['data'][0]['id'])->toBe($current->id)
->and($literal['data'][0]['detail'])->toBe('archived')
->and($literal['data'][0]['title'])->toContain('NEW-CAPITAL%_SEARCH', 'v2')
->and(array_keys($literal['data'][0]))->toBe(['id', 'title', 'detail', 'href'])
->and($literal['data'][0]['href'])->toBe('/projectos-imobilizado?history='.$old->record_key);
$this->get($literal['data'][0]['href'])->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 2));
foreach (range(1, 17) as $index) {
$service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'code' => 'CAP-PAGE-'.$index]);
}
$firstPage = $read('q=CAP-PAGE-');
expect($firstPage['total'])->toBe(17)->and($firstPage['data'])->toHaveCount(15)
->and($firstPage['next_page_url'])->toContain('q=CAP-PAGE-', 'capital_page=2');
expect($read('q=CAP-PAGE-&capital_page=2')['data'])->toHaveCount(2);
$asset = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'code' => 'CAP-ASSET', 'type' => 'asset']);
expect($read('q=CAP-ASSET')['data'][0]['title'])->toContain('Imobilizado CAP-ASSET');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->getJson('/compras/pesquisa?q=CAP&capital_page=0')->assertUnprocessable();
});
test('capital search retains tenant departmental permission and QA boundaries', function () {
$service = app(CapitalRegister::class);
$own = $this->f;
$service->save($own['issuer'], $this->input);
$foreign = receiptFixture();
$this->actingAs($foreign['issuer']);
expect($service->searchQuery($foreign['issuer'])?->count())->toBe(0)
->and($service->searchQuery($own['issuer']))->toBeNull();
$this->actingAs($own['issuer']);
$department = Department::query()->create(['tenant_id' => $own['tenant']->id, 'code' => 'OTHER-CAP', 'name' => 'Outro departamento QA']);
$service->save($own['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'code' => 'CAP-OTHER', 'department_id' => $department->id]);
$head = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id]);
supplyGrant($head, ['department_head']);
$this->actingAs($head);
expect($service->searchQuery($head)?->count())->toBe(1);
$this->get('/compras/pesquisa?q=CAP-OTHER')->assertOk()->assertViewHas('page', fn (array $page) => collect($page['props']['groups'])->firstWhere('key', 'capital')['records']['total'] === 0);
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $head->id)->pluck('profile_id'))
->update(['permissions' => json_encode(['requester'])]);
$this->get('/compras/pesquisa?q=PRJ')->assertInertia(fn (Assert $page) => $page->where('capitalSearchAvailable', false)->where('capitalRegisterAvailable', false)
->where('groups', fn ($groups) => ! collect($groups)->contains('key', 'capital')));
config(['capital-register.qa_enabled' => false]);
supplyGrant($own['issuer'], ['procurement']);
$this->actingAs($own['issuer'])->get('/compras/pesquisa?q=PRJ')->assertInertia(fn (Assert $page) => $page->where('capitalSearchAvailable', false));
});
test('own project register versions preserves identity and replay without financial or stock effects', function () {
$service = app(CapitalRegister::class);
$before = [];
+30
View File
@@ -53,11 +53,41 @@ test('direction release preserves declarations applies to the complete correctio
->and(ConflictRelease::query()->count())->toBe(1)
->and(AuditLog::query()->where('action', 'conflict.release_authorised')->count())->toBe(1);
$this->get('/conflitos/'.$root->id)->assertInertia(fn (Assert $page) => $page->where('canAuthoriseRelease', false)->where('release.declaration_id', $latest->id));
$this->get('/conflitos')->assertInertia(fn (Assert $page) => $page->where('releasedRoots', [$root->id])->where('declarations.data.0.has_conflict', true));
$this->actingAs($this->owner)->get('/conflitos')->assertForbidden();
$this->actingAs($this->admin);
$this->post('/conflitos/'.$latest->id.'/levantamento', [...$input, 'reason' => 'Alteração indevida do fundamento após decisão.'])->assertConflict();
ConflictDeclaration::query()->create([...$root->only(['tenant_id', 'user_id', 'supplier_id', 'requisition_id', 'has_conflict', 'known_since', 'reason']), 'declared_at' => now()]);
expect($guard->hasConflict($this->buyer->id, $this->supplier->id, $this->r->id))->toBeTrue();
});
test('release consultation is limited to the roots on the visible declaration page', function () {
config(['conflict-releases.qa_enabled' => true]);
for ($index = 0; $index < 16; $index++) {
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
}
$first = ConflictDeclaration::query()->oldest('id')->firstOrFail();
$last = ConflictDeclaration::query()->latest('id')->firstOrFail();
$this->actingAs($this->owner)->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
$other = ConflictDeclaration::query()->latest('id')->firstOrFail();
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $this->tenant->id, 'name' => 'Compras exclusivamente sintéticas',
'permissions' => json_encode(['procurement']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
DB::table('organization_memberships')->insert(['tenant_id' => $this->tenant->id, 'user_id' => $this->buyer->id,
'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
configureConflictDirection($this->admin);
$this->actingAs($this->admin);
foreach ([$first, $last, $other] as $row) {
$this->post('/conflitos/'.$row->id.'/levantamento', ['operation_key' => (string) Str::uuid(),
'reason' => 'Decisão exclusivamente sintética para conferir a consulta paginada.'])->assertSessionHasNoErrors();
}
$originals = ConflictDeclaration::query()->orderBy('id')->get()->toJson();
$auditCount = AuditLog::query()->count();
$this->actingAs($this->buyer)->get('/conflitos')->assertOk()->assertInertia(fn (Assert $page) => $page->has('declarations.data', 15)->where('releasedRoots', [$last->id]));
$this->get('/conflitos?page=2')->assertOk()->assertInertia(fn (Assert $page) => $page->has('declarations.data', 1)->where('releasedRoots', [$first->id]));
expect(ConflictDeclaration::query()->orderBy('id')->get()->toJson())->toBe($originals)
->and(AuditLog::query()->count())->toBe($auditCount);
});
test('direction authority is current scoped and never inherited from admin or finance', function () {
config(['conflict-releases.qa_enabled' => true]);
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
@@ -8,6 +8,7 @@ use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
@@ -83,3 +84,97 @@ test('an unknown edition never inherits parameters from its title or citation',
'snapshot' => ['evidence' => ['sha256' => hash('sha256', 'different edition')]]]);
expect(app(ImportLegalReferenceDrafts::class)->forSource($source))->toBe([]);
});
test('the documentary VAT rate requires explicit classification and valuation before a draft can be saved', function () {
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/alteracao CIVA 2023.pdf';
if (! is_file($path)) {
test()->markTestSkipped('The supplied BR250 edition is required for this real-source integration.');
}
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::VAT_EDITION_SHA256);
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$service = app(ImportLegalRules::class);
$source = $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Lei 22/2022; BR I Série250, 28/12/2022, exemplar partilhado',
'reason' => 'Exemplar partilhado copiado apenas para QA sintético, sem publicação de taxa.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$drafts = $service->workspace($this->f['issuer'], $this->f['r'])['referenceDrafts'];
expect($drafts)->toHaveCount(1);
$draft = $drafts[0];
expect($draft['match_code'])->toBe('')->and($draft['suggested_code'])->toBe('')
->and($draft['valid_from'])->toBe('2023-01-01')->and($draft['valid_until'])->toBeNull()
->and($draft['citation'])->toContain('2238', '2239')->and($draft['charges'][0]['kind'])->toBe('vat')
->and($draft['charges'][0]['rate_percent'])->toBe('16')->and($draft['charges'][0]['basis_reference'])->toBe('')
->and(array_column(array_slice($draft['charges'], 1), 'method'))->toBe(['unknown', 'unknown', 'unknown']);
$input = [...array_intersect_key($draft, array_flip(['source_id', 'title', 'official_reference', 'official_url', 'citation', 'valid_from', 'valid_until', 'obligations', 'charges', 'match_code', 'suggested_code'])),
'operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'document_types' => [], 'reason' => 'Preparação exclusivamente sintética para conferir os parâmetros explícitos.'];
expect(fn () => $service->save($this->f['issuer'], $input))->toThrow(ValidationException::class);
$input['match_code'] = $input['suggested_code'] = 'SYNTHETIC-VAT-QA';
expect(fn () => $service->save($this->f['issuer'], $input))->toThrow(ValidationException::class);
expect(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
$input['charges'][0]['basis_reference'] = 'Base declarada exclusivamente sintética de100MZN; não representa valoração de uma importação real.';
$saved = $service->save($this->f['issuer'], $input);
expect($saved->state)->toBe('draft')->and($saved->data['charges'][0]['rate_percent'])->toBe('16.000000')
->and($saved->data['match_code'])->toBe('SYNTHETIC-VAT-QA');
$estimate = app(ImportLegalAmounts::class)->calculate($saved->data['charges'], ['vat_normal_documentary' => [
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic illustrative base, not a real assessment']]);
expect($estimate['known_subtotal_minor'])->toBe(1600)->and($estimate['complete'])->toBeFalse()
->and($estimate['total_minor'])->toBeNull()->and($estimate['financial_effects'])->toBeFalse();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-QA-VAT-COPY');
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['referenceDrafts'])->toBe([])->and($workspace['referenceDraftWarnings'])->toHaveCount(1)
->and(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::VAT_EDITION_SHA256);
});
test('the official second supplement supplies only its eleven ICE positions and explicit two-year period', function () {
$path = base_path('tmp/pdfs/import-legal-source-review-20261128/law7-2025-official-second-supplement.pdf');
if (! is_file($path)) {
test()->markTestSkipped('The separately retained official second supplement is required.');
}
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::ICE_EDITION_SHA256);
$service = app(ImportLegalRules::class);
$source = $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Lei 7/2025, BR I Série 248, 2.º suplemento, 2180-(21 a 22)',
'reason' => 'Official original used only in disposable synthetic QA; no rule activation.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$drafts = $service->workspace($this->f['issuer'], $this->f['r'])['referenceDrafts'];
$expected = ['8702.10.10' => '20', '8702.10.20' => '25', '8702.20.00' => '20', '8702.30.00' => '20',
'8702.40.10' => '0', '8702.40.20' => '0', '8702.90.10' => '20', '8702.90.20' => '25', '8702.90.90' => '0',
'8703.80.10' => '5', '8703.80.20' => '15'];
expect(array_column($drafts, 'rate_percent', 'code'))->toBe($expected);
foreach ($drafts as $draft) {
expect($draft['valid_from'])->toBe('2026-01-01')->and($draft['valid_until'])->toBe('2027-12-31')
->and($draft['source_id'])->toBe($source->id)->and($draft['source_sha256'])->toBe(ImportLegalReferenceDrafts::ICE_EDITION_SHA256)
->and($draft['citation'])->toContain('2.º suplemento', '2180-(22)', $draft['code'])
->and($draft['charges'][0]['kind'])->toBe('ice')->and($draft['charges'][0]['rate_percent'])->toBe($expected[$draft['code']])
->and(array_column(array_slice($draft['charges'], 1), 'method'))->toBe(['unknown', 'unknown', 'unknown']);
$estimate = app(ImportLegalAmounts::class)->calculate($draft['charges'], ['ice_documentary' => [
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic 100 MZN illustrative base only']]);
expect($estimate['known_subtotal_minor'])->toBe(((int) $expected[$draft['code']]) * 100)
->and($estimate['complete'])->toBeFalse()->and($estimate['total_minor'])->toBeNull()->and($estimate['financial_effects'])->toBeFalse();
}
expect(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
$draft = collect($drafts)->firstWhere('code', '8703.80.10');
$saved = $service->save($this->f['issuer'], [...array_intersect_key($draft, array_flip(['source_id', 'title', 'official_reference', 'official_url', 'citation', 'valid_from', 'valid_until', 'obligations', 'charges'])),
'operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'match_code' => $draft['code'], 'suggested_code' => $draft['code'], 'document_types' => [],
'reason' => 'Explicit synthetic QA preparation of documentary ICE; not publication.']);
expect($saved->state)->toBe('draft')->and($saved->data['valid_until'])->toBe('2027-12-31')
->and($saved->data['charges'][0]['rate_percent'])->toBe('5.000000');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-QA-SECOND-SUPPLEMENT');
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['referenceDrafts'])->toBe([])->and($workspace['referenceDraftWarnings'])->toHaveCount(1);
});
+74
View File
@@ -26,6 +26,80 @@ beforeEach(function () {
$this->actingAs($this->admin);
});
test('operational order search retains literal matching pagination and opens the selected native source beyond the first page', function () {
config(['operational-orders.qa_enabled' => true]);
$service = app(OperationalOrders::class);
$service->configure($this->admin, $this->policy);
$this->actingAs($this->f['issuer']);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$old = $service->save($this->f['issuer'], [...$this->input, 'reference' => 'OP-FOUND-OLD']);
foreach (range(1, 17) as $index) {
$service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'reference' => 'OP-PAGE-'.$index]);
}
$literal = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'reference' => 'OP%_LITERAL']);
$sourceRows = SupplyRecord::query()->where('kind', 'op_order')->orderBy('id')->get()->toJson();
$read = function (string $query) {
$response = $this->get('/compras/pesquisa?'.$query)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$props = $response->viewData('page')['props'];
expect($props['operationalOrderSearchAvailable'])->toBeTrue();
return collect($props['groups'])->firstWhere('key', 'operational_orders')['records'];
};
$page = $read('q=OP-PAGE-');
expect($page['total'])->toBe(17)->and($page['data'])->toHaveCount(15)
->and($page['next_page_url'])->toContain('q=OP-PAGE-', 'operational_orders_page=2');
expect($read('q=OP-PAGE-&operational_orders_page=2')['data'])->toHaveCount(2);
$match = $read('q='.urlencode('%_'));
expect($match['total'])->toBe(1)->and($match['data'][0]['id'])->toBe($literal->id)
->and($match['data'][0]['detail'])->toBe('recorded')->and($match['data'][0]['title'])->toContain('Produção OP%_LITERAL', 'v1')
->and(array_keys($match['data'][0]))->toBe(['id', 'title', 'detail', 'href']);
$oldMatch = $read('q=OP-FOUND-OLD')['data'][0];
expect($oldMatch['href'])->toBe('/ordens-operacionais?order_id='.$old->id.'#op-order-'.$old->id);
$this->get($oldMatch['href'])->assertOk()->assertInertia(fn (Assert $page) => $page->has('orders.data', 1)
->where('orders.data.0.id', $old->id)->where('selectedOrderId', $old->id));
$this->get('/ordens-operacionais?order_id='.$old->id.'&page=999')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('orders.current_page', 1)->has('orders.data', 1)->where('orders.data.0.id', $old->id));
$this->get('/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page->has('orders.data', 15)->where('selectedOrderId', null));
$this->getJson('/compras/pesquisa?q=OP&operational_orders_page=0')->assertUnprocessable();
$this->getJson('/ordens-operacionais?order_id=0')->assertUnprocessable();
expect(SupplyRecord::query()->where('kind', 'op_order')->orderBy('id')->get()->toJson())->toBe($sourceRows);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('operational order search and direct source selection retain native departmental tenant and current capability boundaries', function () {
config(['operational-orders.qa_enabled' => true]);
$service = app(OperationalOrders::class);
$service->configure($this->admin, $this->policy);
supplyGrant($this->f['issuer'], ['procurement']);
$this->actingAs($this->f['issuer']);
$own = $service->save($this->f['issuer'], $this->input);
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'code' => 'OP-OTHER', 'name' => 'Outro departamento sintético']);
$other = $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(), 'department_id' => $department->id, 'reference' => 'OP-OTHER-SECRET']);
$viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id]);
supplyGrant($viewer, ['production_order_prepare']);
$this->actingAs($viewer);
expect($service->searchQuery($viewer)?->pluck('id')->all())->toBe([$own->id]);
$this->get('/compras/pesquisa?q=OP-OTHER-SECRET')->assertOk()->assertViewHas('page', fn (array $page) => collect($page['props']['groups'])->firstWhere('key', 'operational_orders')['records']['total'] === 0);
$this->get('/ordens-operacionais?order_id='.$other->id)->assertNotFound();
$this->get('/ordens-operacionais?order_id='.$own->id)->assertOk();
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $viewer->id)->pluck('profile_id'))
->update(['permissions' => json_encode(['finance'])]);
$this->get('/compras/pesquisa?q=OP')->assertInertia(fn (Assert $page) => $page->where('operationalOrderSearchAvailable', false)
->where('groups', fn ($groups) => ! collect($groups)->contains('key', 'operational_orders')));
$this->get('/ordens-operacionais?order_id='.$own->id)->assertForbidden();
$foreign = receiptFixture();
$this->actingAs($foreign['issuer']);
expect($service->searchQuery($foreign['issuer'])?->count())->toBe(0)->and($service->searchQuery($this->f['issuer']))->toBeNull();
$this->get('/ordens-operacionais?order_id='.$own->id)->assertNotFound();
config(['operational-orders.qa_enabled' => false]);
expect($service->searchQuery($foreign['issuer']))->toBeNull();
});
test('operational register requires explicit origin mode preserves sources and has no financial or stock effects', function () {
$this->get('/ordens-operacionais')->assertStatus(503);
config(['operational-orders.qa_enabled' => true]);
@@ -0,0 +1,64 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\ReceiptWorkflow;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('order and receipt consultations link the exact authorised financial context without business effects', function () {
$f = receiptFixture('1.000');
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$receipt = app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f));
$before = [];
foreach (['purchase_orders', 'purchase_order_items', 'invoices', 'external_payments', 'stock_movements', 'budget_entries', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$href = '/facturas?purchase_order_id='.$f['order']->id.'#invoice-documents';
$this->actingAs($finance)->get('/ordens/'.$f['order']->id)->assertOk()
->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)->assertInertia(fn (Assert $p) => $p
->component('purchases/show')->where('financialDocumentsHref', $href)
->has('relatedProcesses', 1)->where('relatedProcesses.0.id', $f['r']->id)
->where('relatedProcesses.0.href', '/requisicoes/'.$f['r']->id.'/processo'));
$this->get('/ordens/'.$f['order']->id.'/recepcoes')->assertOk()->assertInertia(fn (Assert $p) => $p
->component('receipts/order')->where('financialDocumentsHref', $href));
$this->get('/recepcoes/'.$receipt->id)->assertOk()->assertInertia(fn (Assert $p) => $p
->component('receipts/show')->where('financialDocumentsHref', $href));
$this->get($href)->assertOk()->assertInertia(fn (Assert $p) => $p->where('focusOrderId', $f['order']->id));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('context links do not grant procurement warehouse or foreign identities access to financial documents', function () {
$f = receiptFixture();
$receipt = app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f));
$this->actingAs($f['issuer'])->get('/ordens/'.$f['order']->id)->assertOk()->assertInertia(fn (Assert $p) => $p
->where('financialDocumentsHref', null)->has('relatedProcesses', 1));
$this->get('/facturas?purchase_order_id='.$f['order']->id)->assertForbidden();
$this->actingAs($f['receiver'])->get('/ordens/'.$f['order']->id.'/recepcoes')->assertOk()->assertInertia(fn (Assert $p) => $p
->where('financialDocumentsHref', null));
$this->get('/recepcoes/'.$receipt->id)->assertOk()->assertInertia(fn (Assert $p) => $p
->where('financialDocumentsHref', null));
$this->get('/facturas?purchase_order_id='.$f['order']->id)->assertForbidden();
$foreign = receiptFixture();
$other = User::factory()->create(['tenant_id' => $foreign['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($other)->get('/ordens/'.$f['order']->id)->assertNotFound();
$this->get('/recepcoes/'.$receipt->id)->assertNotFound();
$this->getJson('/facturas?purchase_order_id='.$f['order']->id)->assertUnprocessable();
});
test('print navigation leaves Inertia only after checking the current order access', function () {
$f = receiptFixture();
$page = $this->actingAs($f['issuer'])->get('/ordens/'.$f['order']->id)->assertOk()->viewData('page');
$headers = ['X-Inertia' => 'true'];
if ($page['version'] !== null) {
$headers['X-Inertia-Version'] = $page['version'];
}
$route = '/ordens/'.$f['order']->id.'/imprimir';
$this->get($route, $headers)->assertStatus(409)->assertHeader('X-Inertia-Location', $route);
$this->get($route)->assertOk()->assertSee($f['order']->number);
$this->actingAs($f['receiver'])->get($route, $headers)->assertForbidden()->assertHeaderMissing('X-Inertia-Location');
});
@@ -1,6 +1,7 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\PrivateAuditExport;
use App\Models\SupplierDocument;
use App\Models\User;
@@ -46,6 +47,11 @@ afterEach(function () {
test('private audit creates a verified immutable package and replays without duplicating or changing business facts', function () {
$before = DB::table('purchase_orders')->orderBy('id')->get()->toJson();
foreach (['supplier_evaluation.approved', 'supplier_improvement.closed', 'supplier_response.decided', 'supplier.bank_viewed',
'planning.created', 'order_cancellation.approved', 'warehouse_return.confirmed'] as $action) {
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => $action,
'after' => ['evidence' => 'SYNTHETIC-EVENT-PAYLOAD-NOT-EXPORTED'], 'created_at' => now()]);
}
$input = ['operation_key' => (string) Str::uuid(), 'families' => ['configuration', 'purchasing', 'stock', 'finance'], 'purpose' => 'Synthetic QA audit'];
$service = app(PrivateAuditExporter::class);
$export = $service->generate($this->actor, $input);
@@ -55,6 +61,12 @@ test('private audit creates a verified immutable package and replays without dup
try {
$manifest = json_decode($zip->getFromName('manifesto.json'), true, 512, JSON_THROW_ON_ERROR);
expect($manifest['families'])->toHaveCount(4);
$events = $zip->getFromName('dados/purchasing/eventos.ndjson');
expect($events)->toBeString()->toContain('supplier_evaluation.approved')->toContain('supplier_improvement.closed')->toContain('supplier_response.decided')
->toContain('planning.created')->toContain('order_cancellation.approved')
->not->toContain('warehouse_return.confirmed')->not->toContain('supplier.bank_viewed')->not->toContain('SYNTHETIC-EVENT-PAYLOAD-NOT-EXPORTED');
expect($zip->getFromName('dados/stock/eventos.ndjson'))->toContain('warehouse_return.confirmed')
->not->toContain('planning.created')->not->toContain('order_cancellation.approved');
foreach ($manifest['datasets'] as $dataset) {
if ($dataset['state'] === 'not_installed') {
expect($dataset['records'])->toBeNull();
+51
View File
@@ -101,6 +101,57 @@ test('private audit preserves ordinary data while excluding bank coordinates cre
expect($event)->toHaveKey('after_projected')->not->toHaveKey('after');
});
test('purchasing audit includes supplier follow up events without bank events or foreign company history', function () {
$included = ['supplier.created', 'supplier.updated', 'supplier.reviewed', 'supplier.document_uploaded', 'supplier.document_downloaded',
'supplier_evaluation.approved', 'supplier_improvement.closed', 'supplier_response.decided'];
$excluded = ['supplier.bank_viewed', 'supplier.bank_proposed', 'supplier.bank_approved', 'supplier.bank_rejected', 'supplier.future_private_action'];
$foreign = Tenant::query()->create(['name' => 'FOREIGN-SUPPLIER-AUDIT']);
$foreignActor = User::factory()->create(['tenant_id' => $foreign->id]);
foreach ([...$included, ...$excluded] as $action) {
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id,
'action' => $action, 'after' => ['evidence' => 'SYNTHETIC-PRIVATE-PAYLOAD'], 'created_at' => now()]);
AuditLog::query()->create(['tenant_id' => $foreign->id, 'user_id' => $foreignActor->id, 'action' => $action,
'after' => ['evidence' => 'FOREIGN-SYNTHETIC-PRIVATE-PAYLOAD'], 'created_at' => now()]);
}
$before = DB::table('audit_logs')->orderBy('id')->get()->toJson();
$sources = collectedPrivateAuditSources($this->actor, ['purchasing']);
$events = $sources['purchasing:audit_logs']['rows'];
foreach ($included as $action) {
$matches = array_values(array_filter($events, fn ($row) => $row['action'] === $action));
expect($matches)->toHaveCount(1)
->and((int) $matches[0]['tenant_id'])->toBe($this->actor->tenant_id)
->and($matches[0])->not->toHaveKey('after')->not->toHaveKey('before');
}
expect(array_column($events, 'action'))->not->toContain(...$excluded)
->and(json_encode($events, JSON_THROW_ON_ERROR))->not->toContain('SYNTHETIC-PRIVATE-PAYLOAD')
->and(DB::table('audit_logs')->orderBy('id')->get()->toJson())->toBe($before);
foreach (['stock', 'finance', 'configuration'] as $family) {
$other = collectedPrivateAuditSources($this->actor, [$family]);
expect(array_column($other[$family.':audit_logs']['rows'], 'action'))->not->toContain(...$included);
}
});
test('audit links planning cancellation and warehouse return events to their own source family', function () {
$families = ['purchasing' => ['planning.created', 'planning.linked', 'purchase_control.approved', 'cancellation.approved',
'order_cancellation.approved', 'order_cancellation_policy.approved'],
'stock' => ['warehouse_return.prepared', 'warehouse_return.confirmed', 'warehouse_return.cancelled']];
foreach ($families as $actions) {
foreach ($actions as $action) {
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id,
'action' => $action, 'after' => ['synthetic' => true], 'created_at' => now()]);
}
}
$before = DB::table('audit_logs')->orderBy('id')->get()->toJson();
$sources = collectedPrivateAuditSources($this->actor, ['purchasing', 'stock', 'finance', 'configuration']);
foreach ($families as $family => $actions) {
expect(array_column($sources[$family.':audit_logs']['rows'], 'action'))->toContain(...$actions);
foreach (array_diff(['purchasing', 'stock', 'finance', 'configuration'], [$family]) as $other) {
expect(array_column($sources[$other.':audit_logs']['rows'], 'action'))->not->toContain(...$actions);
}
}
expect(DB::table('audit_logs')->orderBy('id')->get()->toJson())->toBe($before);
});
test('private audit exposes installed empty data separately from uninstalled optional common sources without calculations or writes', function () {
$before = [];
foreach (['budget_entries', 'stock_movements', 'external_payments', 'invoices', 'purchase_orders', 'audit_logs'] as $table) {
+24 -1
View File
@@ -340,11 +340,33 @@ test('a partial native order retains its confirmed imported item classification
->and(StockMovement::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(400);
});
test('ordinary controlled order preserves the common budget confirmation and its original on replay', function () {
$adapter = app(CommonBudget::class);
$this->actingAs($this->finance);
$id = $adapter->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Dotação exclusivamente sintética para conferir o documento de emissão.']);
$this->actingAs($this->admin);
$adapter->for($this->admin)->approve($id);
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$this->actingAs($this->buyer);
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['budget_checked'])->toBeTrue()->and($order->snapshot['budget_control']['budget_id'])->toBe($id);
$original = $order->snapshot;
$entries = DB::table('budget_entries')->count();
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
expect($order->fresh()->snapshot)->toBe($original)->and(DB::table('budget_entries')->count())->toBe($entries);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Controlo orçamental registado na emissão.');
});
test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Unpublished common source requires explicit QA selection.');
}
budgetDistributionFixtureSchema();
if (! DB::getSchemaBuilder()->hasTable('budget_distributions')) {
budgetDistributionFixtureSchema();
}
config(['budget-distributions.qa_enabled' => true]);
$this->withoutVite();
$second = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'QA-SPLIT', 'name' => 'Segundo centro sintético']);
@@ -370,6 +392,7 @@ test('distributed approved synthetic requisition follows native adjudication app
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['budget_control']['phase'])->toBe('commit')
->and($order->snapshot['budget_checked'])->toBeTrue()
->and(DB::table('budget_distribution_entries')->where('kind', 'commit')->count())->toBe(2)
->and(DB::table('budget_entries')->where('requisition_id', $this->r->id)->count())->toBe(0);
$before = DB::table('budget_distribution_entries')->count();
@@ -350,7 +350,8 @@ test('native office purchase reconciles declared accounts through receipt invoic
$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']);
expect($order->total_minor)->toBe(10000)->and($order->snapshot['budget_checked'])->toBeTrue()
->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',
+16 -2
View File
@@ -102,14 +102,28 @@ test('insufficient evidence remains explicit and needs correction before indepen
expect(AuditLog::query()->where('action', 'supplier_evaluation.return')->sole()->after['review_reason'])->toContain('Completar');
});
test('approved report keeps its reviewer identity when the selected history page is empty', function () {
$evaluation = submittedEvaluation($this);
$this->actingAs($this->reviewer)->post('/fornecedores/avaliacoes/'.$evaluation->id.'/approve', [
'version' => 2, 'reason' => 'Revisão independente com identidade preservada no relatório.',
])->assertRedirect();
$before = DB::table('audit_logs')->orderBy('id')->get()->toJson();
$this->actingAs($this->f['issuer'])->get('/fornecedores/avaliacoes/'.$evaluation->id.'/relatorio?history_page=99')
->assertOk()->assertInertia(fn (Assert $p) => $p->where('reportOnly', true)
->where('evaluation.reviewed_by', $this->reviewer->id)
->where('people.'.$this->reviewer->id, $this->reviewer->name)->has('history.data', 0));
expect(DB::table('audit_logs')->orderBy('id')->get()->toJson())->toBe($before);
});
test('approved evaluation is immutable and a new revision preserves the prior approved report', function () {
$e = submittedEvaluation($this);
$url = '/fornecedores/avaliacoes/'.$e->id;
$this->actingAs($this->reviewer)->post($url.'/approve', ['version' => 2, 'reason' => 'Evidências e âmbito conferidos independentemente.'])->assertRedirect();
$e->refresh();
$this->actingAs($this->f['issuer'])->put($url, ['version' => 3, 'payload' => $this->data['payload']])->assertConflict();
expect(fn () => DB::table('supplier_evaluations')->where('id', $e->id)->update(['status' => 'draft']))->toThrow(QueryException::class);
expect(fn () => DB::table('supplier_evaluations')->where('id', $e->id)->delete())->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table('supplier_evaluations')->where('id', $e->id)->update(['status' => 'draft'])))->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table('supplier_evaluations')->where('id', $e->id)->delete()))->toThrow(QueryException::class);
expect($e->fresh()->status)->toBe('approved')->and(SupplierEvaluation::query()->whereKey($e->id)->count())->toBe(1);
$this->post($url.'/rever', ['version' => 3])->assertRedirect();
$child = SupplierEvaluation::query()->where('previous_id', $e->id)->sole();
$this->post($url.'/rever', ['version' => 3])->assertRedirect('/fornecedores/avaliacoes/'.$child->id);
+18 -1
View File
@@ -5,6 +5,7 @@ use App\Models\User;
use App\Services\ReceiptWorkflow;
use App\Services\SupplyCoordination;
use App\Services\SupplyPlanning;
use App\Services\WarehouseReservations;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
@@ -25,11 +26,27 @@ test('availability reuses physical balance without treating planning needs as ph
app(SupplyPlanning::class)->save($f['receiver'], 'policy', supplyInput([], 'approve', $draft));
$movements = DB::table('stock_movements')->count();
$this->get('/stock/disponibilidade?warehouse_id='.$f['warehouse']->id)->assertOk()->assertInertia(fn (Assert $p) => $p
->component('stock/availability')->where('rows.data.0.physical_milli', 10000)->where('rows.data.0.usable_milli', 10000)
->component('stock/availability')->where('reservationsAvailable', true)->where('rows.data.0.physical_milli', 10000)->where('rows.data.0.usable_milli', 10000)
->where('rows.data.0.planned_milli', 20000)->where('rows.data.0.physical_commitment_milli', 0)->where('rows.data.0.free_milli', 10000)->where('rows.data.0.at_minimum', true));
expect(DB::table('stock_movements')->count())->toBe($movements);
});
test('availability does not infer a free balance when physical reservations are unavailable', function () {
$f = receiptFixture('100.000');
$this->actingAs($f['receiver']);
app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f, '10.000'));
$reservations = Mockery::mock(WarehouseReservations::class);
$reservations->shouldReceive('ready')->andReturn(false);
$reservations->shouldNotReceive('committed');
$this->app->instance(WarehouseReservations::class, $reservations);
$movements = DB::table('stock_movements')->count();
$this->get('/stock/disponibilidade?warehouse_id='.$f['warehouse']->id)->assertOk()->assertInertia(fn (Assert $p) => $p
->where('reservationsAvailable', false)->where('rows.data.0.physical_milli', 10000)
->where('rows.data.0.usable_milli', 10000)->where('rows.data.0.physical_commitment_milli', null)
->where('rows.data.0.free_milli', null)->where('rows.data.0.at_minimum', false));
expect(DB::table('stock_movements')->count())->toBe($movements);
});
test('availability is tenant scoped and does not disclose planning without permission', function () {
$f = receiptFixture();
$this->actingAs($f['receiver'])->get('/stock/disponibilidade?warehouse_id='.$f['warehouse']->id)->assertOk()->assertInertia(fn (Assert $p) => $p
@@ -66,6 +66,8 @@ function nativeOfficePurchaseState(array $fixture): array
'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,
'capital_assignments' => $order->snapshot['capital_assignments'] ?? null,
'budget_checked' => $order->snapshot['budget_checked'] ?? 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,
@@ -2,16 +2,31 @@
use App\Enums\PurchasingRole;
use App\Http\Controllers\AuditMetadataController;
use App\Http\Controllers\ConflictDeclarationController;
use App\Models\ConflictDeclaration;
use App\Models\CostCenter;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
use App\Services\ConflictReleases;
use App\Services\ImportBankSupport;
use App\Services\ImportLegalReferenceDrafts;
use App\Services\ImportLegalRules;
use App\Services\OperationalOrders;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\PrivateAuditAccess;
use App\Services\ProposalComparison;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\QuotationParticipation;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\SupplierEvaluationWorkflow;
use App\Services\SupplierImprovementWorkflow;
use App\Services\SupplierResponseWorkflow;
use App\Services\SupplyPlanning;
use App\Services\UrgentRequisitionReviews;
use App\Services\WarehouseFulfilment;
@@ -48,9 +63,23 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
$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']];
$functions['private_auditor'] = array_column(PrivateAuditAccess::FAMILIES, 'permission');
if (getenv('RQ01_QA_ORDER_CANCELLATION') === '1') {
$functions['cancellation_admin_a'] = ['admin'];
$functions['cancellation_admin_b'] = ['admin'];
}
if (getenv('RQ01_QA_URGENT_STOCK') === '1') {
$functions['stock_cataloguer'] = ['warehouse'];
}
if (getenv('RQ01_QA_CONFLICT_RELEASE') === '1') {
config(['conflict-releases.qa_enabled' => true]);
$functions['direction'] = ['conflict_release_authorise'];
}
if ($legalReference) {
$functions['reviewer'][] = 'import_customs';
}
if (getenv('RQ01_QA_IMPORT_DOCUMENTARY') === '1') {
$functions['reviewer'][] = 'import_prepare';
}
if ($officeJourney) {
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
'office_procurement_reviewer' => ['procurement']];
@@ -251,6 +280,9 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
}
$office = ['cost_center_id' => $centre->id, 'warehouse_id' => $f['warehouse']->id, 'category' => 'Escritório QA HTTP',
'source_instance' => 'native-http-office-qa', 'actors' => []];
if (getenv('RQ01_QA_CAPITAL_SEARCH') === '1') {
$office['capital_register'] = ['department_id' => $f['department']->id, 'code' => 'HTTP-PROJECT-QA'];
}
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];
@@ -258,6 +290,8 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
}
$legalReferenceRoute = null;
$vatSourceId = null;
$specificRateRule = null;
if ($legalReference) {
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf';
if (! $integrated || ! is_file($path) || hash_file('sha256', $path) !== ImportLegalReferenceDrafts::EDITION_SHA256) {
@@ -270,17 +304,300 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
'reason' => 'Exemplar oficial partilhado para consulta e preparação em ambiente exclusivamente QA sintético; nenhuma regra publicada.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$legalReferenceRoute = '/requisicoes/'.$f['r']->id.'/base-legal';
if (getenv('RQ01_QA_VAT_REFERENCE') === '1') {
$vatPath = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/alteracao CIVA 2023.pdf';
if (! is_file($vatPath) || hash_file('sha256', $vatPath) !== ImportLegalReferenceDrafts::VAT_EDITION_SHA256) {
throw new LogicException('VAT preview requires the exact supplied BR250 edition.');
}
$vatSource = app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Lei 22/2022; BR I Série 250, 28/12/2022, exemplar partilhado',
'reason' => 'Consulta e preparação em QA sintético; a fonte não publica nem activa uma regra fiscal.'],
new UploadedFile($vatPath, basename($vatPath), 'application/pdf', UPLOAD_ERR_OK, true));
$vatSourceId = $vatSource->id;
}
if (getenv('RQ01_QA_ICE_REFERENCE') === '1') {
$icePath = base_path('tmp/pdfs/import-legal-source-review-20261128/law7-2025-official-second-supplement.pdf');
if (! is_file($icePath) || hash_file('sha256', $icePath) !== ImportLegalReferenceDrafts::ICE_EDITION_SHA256) {
throw new LogicException('The ICE preview requires the exact retained official second supplement.');
}
app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Lei 7/2025, BR I Série 248, 2.º suplemento, 29/12/2025, páginas 2180-(21 a 22)',
'official_url' => 'https://www.at.gov.mz/api/webdav?path=%2FLEGISLA%C3%87%C3%83O%2FLEGISLA%C3%87%C3%83O+ADUANEIRA%2FLEI%2FBR_248_I_SERIE_2%C2%BA+SUPLEMENTO_2025_260116_124640.pdf',
'reason' => 'Consulta do original oficial em QA descartável; nenhuma regra publicada ou taxa real activada.'],
new UploadedFile($icePath, basename($icePath), 'application/pdf', UPLOAD_ERR_OK, true));
}
if (getenv('RQ01_QA_SPECIFIC_RATE') === '1') {
require_once __DIR__.'/ImportLegalQaFixture.php';
app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
$specificSource = app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Exemplar sintético QA — sem diploma ou validade fiscal',
'reason' => 'Fonte sintética separada, registada pelo serviço nativo apenas para conferir precisão decimal; nenhuma taxa publicada.'], importLegalQaFile());
$specificDraft = app(ImportLegalRules::class)->save($people['reviewer'], importLegalQaInput([
'source_id' => $specificSource->id, 'title' => 'QA — coeficiente específico sem validade fiscal',
'official_reference' => $specificSource->data['official_reference'], 'official_url' => null,
'citation' => 'Exemplar exclusivamente sintético para conferir a preparação decimal, sem regra fiscal real.',
'charges' => [[...importLegalQaCharge(), 'label' => 'Coeficiente específico sintético', 'method' => 'specific',
'rate_percent' => null, 'specific_minor' => '0.99', 'quantity_unit' => 'g',
'basis_reference' => 'Base estritamente sintética para testar a preparação; nenhuma taxa publicada ou cálculo activado.']],
]));
$specificRateRule = $specificDraft->only(['id', 'record_key', 'version', 'state']);
}
}
$operationalSearchReference = null;
if (getenv('RQ01_QA_OPERATIONAL_SEARCH') === '1') {
config(['operational-orders.qa_enabled' => true]);
auth()->guard()->setUser($people['reviewer']);
$orders = app(OperationalOrders::class);
$policy = $orders->configure($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
'mode' => 'procurement', 'reason' => 'Configuração exclusivamente sintética do percurso de pesquisa, sem locais reais abrangidos.']);
$source = $orders->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'policy_version' => $policy->version,
'type' => 'production', 'reference' => 'QA-SEARCH-OP-20261128', 'department_id' => $f['department']->id,
'utilisation_location' => 'Linha exclusivamente sintética QA', 'description' => 'Ordem de origem fictícia para conferir pesquisa e abertura directa do registo.',
'reason' => 'Fixture nativa descartável; sem produção, compra ou movimento físico real.']);
$operationalSearchReference = $source->data['reference'];
}
$documentary = null;
if (getenv('RQ01_QA_IMPORT_DOCUMENTARY') === '1') {
config(['import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true]);
auth()->guard()->setUser($people['reviewer']);
$import = $planning->save($people['reviewer'], 'import', supplyInput([
'purchase_order_id' => $f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'QA documental sem operação real',
'origin_country' => 'Origem sintética', 'dispatch_country' => 'Expedição sintética', 'regime' => 'Regime exclusivamente sintético',
]));
require_once __DIR__.'/ImportBankQaFixture.php';
$bankFixture = importBankQaFixture($people['reviewer'], $import);
$bank = app(ImportBankSupport::class)->save($people['reviewer'], $import, $bankFixture['input']);
$documentary = ['import_id' => $import->id, 'bank_id' => $bank->id,
'dossier_route' => '/compras/importacoes/'.$import->id.'/documentos',
'bank_route' => '/compras/importacoes/'.$import->id.'/suporte-bancario',
'synthetic_only' => true, 'document_count' => count($bankFixture['documents'])];
}
$supplierReview = null;
if (getenv('RQ01_QA_SUPPLIER_REVIEW') === '1') {
$evaluations = app(SupplierEvaluationWorkflow::class);
auth()->guard()->setUser($people['reviewer']);
$evaluation = $evaluations->create($people['reviewer'], $f['order']->supplier_id, (string) Str::uuid(), [
'title' => 'Avaliação exclusivamente sintética QA', 'nature' => 'goods',
'scope' => 'Conferência visual do relatório e do histórico, sem avaliação de fornecedor real.',
'period_start' => $f['order']->issued_at->toDateString(), 'period_end' => $f['order']->issued_at->toDateString(), 'order_ids' => [$f['order']->id],
'criteria' => [['label' => 'Conformidade documental sintética', 'result' => 'observed',
'reason' => 'Artigos e condições do exemplo QA conferidos.', 'evidence' => 'Referência estritamente sintética: ordem QA'],
['label' => 'Serviço pós-venda', 'result' => 'not_applicable',
'reason' => 'Fora do âmbito deste exemplo sintético.', 'evidence' => '']],
'conclusion' => 'Conclusão qualitativa sintética; não certifica desempenho ou elegibilidade real.',
'critical_occurrences' => '', 'critical_evidence' => '',
]);
$evaluation = $evaluations->transition($people['reviewer'], $evaluation->id, $evaluation->version, 'submit', null);
auth()->guard()->setUser($people['finance']);
$evaluation = $evaluations->transition($people['finance'], $evaluation->id, $evaluation->version, 'approve',
'Revisão independente exclusivamente sintética para conferir apresentação.');
if ($evaluation->status !== 'approved' || $people['reviewer']->id === $people['finance']->id) {
throw new LogicException('Synthetic evaluation did not preserve independent approval.');
}
$issuedOn = $f['order']->issued_at->toDateString();
if ($evaluation->payload['period_start'] > $issuedOn || $evaluation->payload['period_end'] < $issuedOn) {
throw new LogicException('Synthetic evaluation period must include its issued order.');
}
$approvedOriginal = $evaluation->fresh()->getAttributes();
auth()->guard()->setUser($people['reviewer']);
$measures = app(SupplierImprovementWorkflow::class);
$measure = $measures->execute($people['reviewer'], $evaluation->id, null, 'create', [
'operation_key' => (string) Str::uuid(), 'title' => 'Conferência sintética da identificação dos volumes',
'description' => 'Conservar a referência da ordem nos volumes do exemplo QA.',
'responsible_id' => $people['head']->id, 'due_on' => today()->addWeek()->toDateString(),
]);
auth()->guard()->setUser($people['head']);
$measure = $measures->execute($people['head'], $evaluation->id, $measure->id, 'submit', [
'version' => $measure->version, 'result' => 'Identificação sintética conferida no ensaio.',
'evidence' => 'Referência fictícia QA-VOLUMES, sem documento ou fornecedor real.',
]);
auth()->guard()->setUser($people['finance']);
$measure = $measures->execute($people['finance'], $evaluation->id, $measure->id, 'close', [
'version' => $measure->version, 'reason' => 'Conferência independente exclusivamente sintética do resultado e referência.',
]);
$responses = app(SupplierResponseWorkflow::class);
auth()->guard()->setUser($people['reviewer']);
$response = $responses->execute($people['reviewer'], $evaluation->id, null, 'create', [
'operation_key' => (string) Str::uuid(), 'payload' => [
'title' => 'Argumentos exclusivamente sintéticos sobre a identificação dos volumes',
'received_on' => today()->toDateString(), 'source_reference' => 'QA-ARGUMENTOS-1, referência fictícia',
'statement' => 'O exemplo solicita esclarecimento documental; não representa argumentos de um fornecedor real.',
],
]);
$response = $responses->execute($people['reviewer'], $evaluation->id, $response->id, 'submit', ['version' => $response->version]);
auth()->guard()->setUser($people['finance']);
$response = $responses->execute($people['finance'], $evaluation->id, $response->id, 'decide', [
'version' => $response->version, 'outcome' => 'accepted',
'reason' => 'Argumentos do exemplo conferidos independentemente, sem decisão sobre fornecedor real.',
'follow_up' => 'Conservar os esclarecimentos; qualquer rectificação exige uma nova revisão própria.',
'response_reference' => 'QA-MINUTA-1, sem comunicação externa',
]);
if ($measure->status !== 'closed' || $response->status !== 'decided'
|| $evaluation->fresh()->getAttributes() !== $approvedOriginal) {
throw new LogicException('Synthetic follow-up must preserve the approved evaluation.');
}
auth()->guard()->setUser($people['reviewer']);
$pendingResponse = $responses->execute($people['reviewer'], $evaluation->id, null, 'create', [
'operation_key' => (string) Str::uuid(), 'payload' => [
'title' => 'Contraditório exclusivamente sintético para conclusão nativa',
'received_on' => today()->toDateString(), 'source_reference' => 'QA-DECISAO-NATIVA, documento fictício',
'statement' => 'Argumentos fictícios para verificar conclusão independente e seguimento, sem fornecedor real ou envio externo.',
],
]);
$pendingResponse = $responses->execute($people['reviewer'], $evaluation->id, $pendingResponse->id, 'submit', ['version' => $pendingResponse->version]);
if ($pendingResponse->status !== 'review' || $evaluation->fresh()->getAttributes() !== $approvedOriginal) {
throw new LogicException('Synthetic pending response must preserve the approved evaluation.');
}
$draftRevision = $evaluations->revise($people['reviewer'], $evaluation->id, $evaluation->version);
$pendingEvaluation = $evaluations->create($people['reviewer'], $f['order']->supplier_id, (string) Str::uuid(), [
...$evaluation->payload, 'title' => 'Avaliação QA separada para conferir preparação da decisão',
]);
$pendingEvaluation = $evaluations->transition($people['reviewer'], $pendingEvaluation->id, $pendingEvaluation->version, 'submit', null);
if ($draftRevision->status !== 'draft' || $pendingEvaluation->status !== 'review'
|| $evaluation->fresh()->getAttributes() !== $approvedOriginal) {
throw new LogicException('Synthetic review preparations must preserve their independent original.');
}
$supplierReview = ['evaluation_id' => $evaluation->id, 'version' => $evaluation->version,
'route' => '/fornecedores/avaliacoes/'.$evaluation->id,
'report_route' => '/fornecedores/avaliacoes/'.$evaluation->id.'/relatorio',
'synthetic_only' => true, 'native_service_transitions' => true,
'period_contains_issued_order' => true, 'order_issued_on' => $issuedOn,
'measure_id' => $measure->id, 'measure_state' => $measure->status,
'response_id' => $response->id, 'response_state' => $response->status,
'pending_response_id' => $pendingResponse->id,
'pending_response_route' => '/fornecedores/avaliacoes/'.$evaluation->id.'#contraditorio-'.$pendingResponse->id,
'approved_evaluation_preserved' => true,
'draft_revision_route' => '/fornecedores/avaliacoes/'.$draftRevision->id,
'pending_review_route' => '/fornecedores/avaliacoes/'.$pendingEvaluation->id,
'independent_reviewer_login' => $people['finance']->email];
}
$conflictReview = null;
if (getenv('RQ01_QA_CONFLICT_RELEASE') === '1') {
auth()->guard()->setUser($people['reviewer']);
$controller = app(ConflictDeclarationController::class);
$guard = app(ConflictGuard::class);
foreach (['supplier', 'process_supplier'] as $scope) {
$query = Request::create('/conflitos', 'POST', ['scope' => $scope, 'supplier_id' => $f['order']->supplier_id,
'requisition_id' => $scope === 'supplier' ? null : $f['r']->id,
'has_conflict' => true, 'known_since' => today()->toDateString(),
'reason' => 'Declaração exclusivamente sintética para conferir o levantamento pela direcção, sem conflito real.']);
$query->setUserResolver(fn () => $people['reviewer']);
$controller->store($query, $guard, app(RequisitionWorkflow::class));
}
$declarations = ConflictDeclaration::query()->where('user_id', $people['reviewer']->id)->orderBy('id')->get();
if ($declarations->count() !== 2 || ! $guard->hasConflict($people['reviewer']->id, $f['order']->supplier_id, $f['r']->id)
|| app(ConflictReleases::class)->canAuthorise($people['reviewer'])) {
throw new LogicException('Conflict QA must keep two impediments and exclude automatic Admin authority.');
}
auth()->guard()->setUser($people['direction']);
if (! app(ConflictReleases::class)->canAuthorise($people['direction'])) {
throw new LogicException('Conflict QA direction must have its express own authority.');
}
$frames = [];
foreach (['gl_accounts', 'gl_journals', 'gl_lines', 'requisitions', 'requisition_items', 'invoices', 'invoice_items', 'external_payments', 'budget_entries', 'stock_movements', 'users', 'organization_profiles', 'organization_memberships'] as $table) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
$frames[$table] = hash('sha256', $rows->toJson());
}
$conflictReview = ['author_id' => $people['reviewer']->id, 'direction_id' => $people['direction']->id,
'direction_login' => $people['direction']->email, 'supplier_id' => $f['order']->supplier_id, 'requisition_id' => $f['r']->id,
'declaration_id' => $declarations[0]->id, 'other_declaration_id' => $declarations[1]->id,
'route' => '/conflitos/'.$declarations[0]->id, 'other_route' => '/conflitos/'.$declarations[1]->id,
'originals_sha256' => hash('sha256', $declarations->toJson()), 'protected_frames' => $frames, 'synthetic_only' => true];
}
$urgentStockReview = null;
if (getenv('RQ01_QA_URGENT_STOCK') === '1') {
config(['urgent-quotations.qa_enabled' => true]);
$catalogue = app(RequisitionCatalogue::class);
auth()->guard()->setUser($people['stock_cataloguer']);
$catalogue->save($people['stock_cataloguer'], $f['stock']->id, ['version' => 0, 'stock_basis' => $catalogue->basis($f['stock']),
'category' => 'Material', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Catálogo inteiramente sintético para conferir a origem do mínimo urgente.']);
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $f['stock']->id)->sole();
$f['tenant']->update(['comparison_policy' => app(ComparisonPolicy::class)->checked([
...ComparisonPolicy::DEFAULTS, 'configured' => true, 'revision' => 1, 'urgent_minimum_proposals' => 1])]);
[$urgentStockRequest, $urgentInput] = $make($people['requester'], 'urgent', 'Artigo de catálogo para conferência sintética do mínimo');
$urgentInput['operation_key'] = (string) Str::uuid();
$urgentInput['process_version'] = $urgentStockRequest->process_version;
$urgentInput['items'][0]['catalogue_entry_id'] = $entry->id;
$urgentInput['items'][0]['catalogue_version'] = $entry->version;
$urgentStockRequest = $workflow->save($people['requester'], $urgentInput, $urgentStockRequest);
$assign($people['requester'], $urgentStockRequest);
$workflow->submit($people['requester'], $urgentStockRequest, (string) Str::uuid(), $urgentStockRequest->process_version);
auth()->guard()->setUser($people['head']);
$urgentStockRequest->refresh();
$workflow->decide($people['head'], $urgentStockRequest, 'approved', 'Aprovação independente exclusivamente sintética para a revisão do mínimo.', (string) Str::uuid(), $urgentStockRequest->process_version);
foreach ([$people['reviewer'], $people['finance']] as $approver) {
$urgentStockRequest->refresh();
if ($urgentStockRequest->canDecide($approver)) {
auth()->guard()->setUser($approver);
$workflow->decide($approver, $urgentStockRequest, 'approved', 'Etapa independente inteiramente sintética para a conferência do mínimo.', (string) Str::uuid(), $urgentStockRequest->process_version);
}
}
auth()->guard()->setUser($people['reviewer']);
$urgentStockRequest->refresh();
if ($urgentStockRequest->status !== 'approved' || ! app(QuotationParticipation::class)->canPrepare($people['reviewer'], $urgentStockRequest)) {
throw new LogicException('Urgent preview requires completed native approvals and an authorised quotation preparer.');
}
$policy = $planning->save($people['reviewer'], 'policy', supplyInput([...supplyPolicy($f), 'safety_milli' => 0,
'minimum_stock_milli' => 20000, 'usage_context' => 'Natureza e utilização fictícias: insumo de consumo diário na produção.']));
auth()->guard()->setUser($people['head']);
$policy = $planning->save($people['head'], 'policy', supplyInput([], 'approve', $policy));
$urgentStockRequest->refresh();
if (app(ProposalComparison::class)->inspect($urgentStockRequest)['policy']['minimum_proposals'] !== 3) {
throw new LogicException('Urgent preview must retain the normal count before an explicit stock conference.');
}
$urgentStockReview = ['route' => '/requisicoes/'.$urgentStockRequest->id.'/urgencia-stock', 'request_id' => $urgentStockRequest->id,
'actor_id' => $people['reviewer']->id,
'policy_id' => $policy->id, 'minimum_stock_milli' => 20000, 'normal_count_before_conference' => 3, 'configured_urgent_count' => 1,
'native_submission_and_independent_approval' => true, 'synthetic_only' => true];
$urgentStockReview['protected_frames'] = [];
foreach (['gl_accounts', 'gl_journals', 'gl_lines', 'requisitions', 'requisition_items', 'invoices', 'invoice_items', 'external_payments', 'budget_entries', 'stock_movements', 'users', 'organization_profiles', 'organization_memberships'] as $table) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
$urgentStockReview['protected_frames'][$table] = hash('sha256', $rows->toJson());
}
}
$cancellationReview = null;
if (getenv('RQ01_QA_ORDER_CANCELLATION') === '1') {
config(['order_cancellation.enabled' => true]);
$policyFlow = app(OrderCancellationPolicyWorkflow::class);
auth()->guard()->setUser($people['reviewer']);
$policy = $policyFlow->propose($people['reviewer'], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(),
'reason' => 'Política inteiramente sintética para revisão nativa do cancelamento; sem activação operacional.']);
foreach ([$people['cancellation_admin_a'], $people['cancellation_admin_b']] as $admin) {
auth()->guard()->setUser($admin);
$policyFlow->review($admin, $policy, 'approved', 'Conferência independente da política inteiramente fictícia.');
}
auth()->guard()->setUser($people['reviewer']);
if (! app(OrderCancellationWorkflow::class)->canRequest($people['reviewer'], $f['order'])) {
throw new LogicException('Cancellation preview requires an eligible independent buyer and published synthetic policy.');
}
$cancellationReview = ['order_id' => $f['order']->id, 'request_id' => $f['r']->id, 'author_id' => $people['reviewer']->id,
'finance_id' => $people['finance']->id, 'route' => '/ordens/'.$f['order']->id,
'finance_login' => $people['finance']->email, 'source_is_explicit_uncontrolled_legacy_fixture' => true,
'original_order_sha256' => hash('sha256', json_encode($f['order']->fresh()->getAttributes(), JSON_THROW_ON_ERROR)),
'original_request' => $f['r']->fresh()->getAttributes(), 'protected_frames' => [], 'synthetic_only' => true];
foreach (['purchase_order_items', 'purchase_awards', 'approval_steps', 'gl_accounts', 'gl_journals', 'gl_lines', 'requisition_items', 'invoices', 'invoice_items', 'external_payments', 'budget_entries', 'stock_movements', 'users', 'organization_profiles', 'organization_memberships'] as $table) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
$cancellationReview['protected_frames'][$table] = hash('sha256', $rows->toJson());
}
}
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
'cancellation_review' => $cancellationReview,
'urgent_stock_review' => $urgentStockReview,
'conflict_review' => $conflictReview,
'supplier_review' => $supplierReview,
'import_documentary' => $documentary,
'operational_search_reference' => $operationalSearchReference,
'print_pagination' => $printPagination ? ['order_route' => '/ordens/'.$f['order']->id.'/imprimir', 'lines' => 50, 'total_minor' => 10000, 'fixture_only_not_native_issuance' => true] : null,
'legal_reference_route' => $legalReferenceRoute,
'vat_source_id' => $vatSourceId,
'specific_rate_rule' => $specificRateRule,
'office_journey' => $office,
'integrated_optional_schema' => $composition,
'synthetic_private_audit_login' => $people['private_auditor']->email, 'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
@@ -47,5 +47,14 @@ $app->booted(function () use ($root, $database) {
if (getenv('RQ01_QA_LEGAL_REFERENCE') === '1') {
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
}
if (getenv('RQ01_QA_CAPITAL_SEARCH') === '1') {
config(['capital-register.qa_enabled' => true]);
}
if (getenv('RQ01_QA_IMPORT_DOCUMENTARY') === '1') {
config(['import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true]);
}
if (getenv('RQ01_QA_CONFLICT_RELEASE') === '1') {
config(['conflict-releases.qa_enabled' => true]);
}
});
$app->handleRequest(Request::capture());
@@ -58,6 +58,7 @@ test.each([null, 0])(
initialComponent={AgreementFollowup}
/>,
);
expect(html).toContain('data-query-form="true"');
expect(html).toContain('Vigência dos contratos globais');
expect(html).toContain('kind=contract');
expect(html).toContain('2 artigo(s) aprovado(s) ligado(s)');
@@ -53,6 +53,7 @@ function render(allowed: boolean) {
test('audit investigation carries applied criteria into the whole-scope CSV and escapes the reference', () => {
const html = render(false);
expect(html).toContain('data-query-form="true"');
expect(html).toContain('Referência exacta da requisição');
expect(html).toContain('QA&lt;REQ&gt;%_');
expect(html).toContain(
@@ -4,7 +4,21 @@ import { afterEach, expect, test, vi } from 'vitest';
import Invoices from '@/pages/invoices/index';
afterEach(() => vi.restoreAllMocks());
function render(actorId = 7) {
test.each([true, false])(
'invoice consultation has a focusable document destination and separates registration (%s)',
(canManage) => {
const html = render(7, canManage);
expect(html).toContain('href="#invoice-documents"');
expect(html).toContain('id="invoice-documents" tabindex="-1"');
expect(html).toContain('lg:scroll-mt-72');
expect(html.includes('href="#invoice-registration"')).toBe(canManage);
expect(html.includes('id="invoice-registration"')).toBe(canManage);
expect(html).toContain('Sem facturas disponíveis para esta ordem.');
expect(html).not.toContain('Sem facturas registadas nesta empresa.');
},
);
function render(actorId = 7, canManage = true) {
return renderToStaticMarkup(
<App
initialComponent={Invoices}
@@ -18,7 +32,7 @@ function render(actorId = 7) {
errors: {},
auth: { user: { id: actorId, tenant_id: 3 } },
focusOrderId: 2,
canManage: true,
canManage,
invoices: {
data: [],
current_page: 1,
+22
View File
@@ -65,6 +65,28 @@ test('read-only capital register preserves archived identity and history without
expect(html).toContain('Histórico do registo');
expect(html).toContain('&lt;script&gt;QA&lt;/script&gt;');
expect(html).not.toContain('<form');
expect(html).not.toContain('href="#capital-preparation"');
expect(html).toContain('?history=source#capital-history');
expect(html).toContain('id="capital-history"');
});
test('capital editor links land on a focusable preparation without submitting or changing the original', () => {
const html = render(CapitalRegister, {
records: page([source]),
history: null,
departments: [],
equipment: [],
canManage: true,
actorId: 1,
tenantId: 1,
});
expect(html.match(/href="#capital-preparation"/g)).toHaveLength(2);
expect(html).toMatch(
/<section[^>]*id="capital-preparation"[^>]*tabindex="-1"/,
);
expect(html).toContain('Preparar nova versão');
expect(html).toContain('PRJ-QA');
expect(html).not.toContain('id="capital-history"');
});
test('approved requisitions display the preserved source independently of available new choices', () => {
const html = render(CapitalAssignments, {
@@ -100,6 +100,44 @@ function render(
/>,
);
}
test.each([true, false])(
'parameter shortcuts target only sections present in the current environment (%s)',
(ready) => {
const html = render('parameters', {
ready,
expiryReady: ready,
urgentReviewsReady: ready,
});
const navigation = html.match(
/<nav aria-label="Áreas da parametrização"[\s\S]*?<\/nav>/,
)?.[0];
expect(navigation).toBeDefined();
const targets = [...navigation!.matchAll(/href="#([^"]+)"/g)].map(
(match) => match[1],
);
expect(new Set(targets).size).toBe(targets.length);
for (const id of targets) {
expect(html.split(`id="${id}"`)).toHaveLength(2);
expect(html).toMatch(new RegExp(`id="${id}" tabindex="-1"`));
}
expect(targets).toContain('company-details');
expect(targets).toContain('approval-levels');
expect(targets.includes('company-comparison')).toBe(ready);
expect(targets.includes('company-users')).toBe(ready);
expect(targets).not.toContain('company-geography');
expect(targets).not.toContain('company-ai-plan');
expect(targets).not.toContain('company-work-contexts');
expect(navigation!.includes('/administracao/prazos-aprovacao')).toBe(
ready,
);
expect(navigation!.includes('/administracao/revisao-urgencias')).toBe(
ready,
);
expect(html).toContain('lg:scroll-mt-72');
expect(html.indexOf('<h1')).toBeLessThan(html.indexOf('<nav'));
},
);
test.each([
['department', { name: 'DEPARTMENT-PREP-QA' }, 'DEPARTMENT-PREP-QA'],
[
@@ -35,6 +35,7 @@ function render(
authorised_at: string;
reason: string;
} | null = null,
overrides: Record<string, unknown> = {},
) {
return renderToStaticMarkup(
<App
@@ -67,11 +68,37 @@ function render(
},
suppliers: [{ id: 1, name: 'Synthetic supplier' }],
requisitions: [],
...overrides,
},
}}
/>,
);
}
test('declaration list distinguishes a released chain from an active independent impediment without changing the original statement', () => {
const post = vi.spyOn(router, 'post');
const html = render(false, 7, 4, 'finance', true, 3, false, null, {
declarations: {
data: [
declaration,
{ ...declaration, id: 4, previous_id: 3, root_id: 3 },
{ ...declaration, id: 5 },
{ ...declaration, id: 6, has_conflict: false },
],
prev_page_url: null,
next_page_url: null,
},
releasedRoots: [3],
});
expect(html.match(/Impedimento levantado pela direcção/g)).toHaveLength(2);
expect(html.match(/Impedimento activo/g)).toHaveLength(1);
expect(html.match(/Conflito registado/g)).toHaveLength(3);
expect(html).toContain('Ausência declarada');
expect(html).toContain('autorização expressa da direcção');
expect(html).not.toContain('nem retirada de conflitos nesta etapa');
expect(html).not.toContain('os restantes perfis consultam apenas');
expect(post).not.toHaveBeenCalled();
});
test('direction release preparation requires explicit capability and never submits on recovery', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
@@ -0,0 +1,86 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Dashboard from '@/pages/dashboard';
import Requisitions from '@/pages/requisitions/index';
test('dashboard distinguishes visible pending requests from personal decisions and links to the corresponding lists', () => {
const Screen = () => (
<Dashboard
company={null}
stats={{
total: 7,
pending: 3,
approved: 2,
approvedMinor: 10000,
awaitingMe: 0,
}}
recent={[]}
approvals={[]}
/>
);
const html = renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'dashboard',
url: '/dashboard',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {}, publicNavigation: true },
}}
/>,
);
expect(html).toContain('href="/requisicoes?status=pending"');
expect(html.match(/href="\/requisicoes\?status=approved"/g)).toHaveLength(
2,
);
expect(html).toContain('href="/requisicoes?view=approvals"');
expect(html).toContain('Requisições que aguardam a sua decisão: 0');
expect(html).not.toContain('À espera da sua aprovação');
expect(html).not.toContain('Nova requisição');
});
test.each([
[
{ view: 'approvals' },
'Não há requisições com uma etapa disponível para a sua decisão',
],
[
{ view: 'approvals', status: 'pending' },
'Nenhum pedido corresponde aos filtros neste conjunto',
],
])(
'empty requisition lists explain the selected scope (%j)',
(filters, message) => {
const Screen = () => (
<Requisitions
requisitions={{
data: [],
total: 0,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
}}
filters={filters}
/>
);
const html = renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'requisitions/index',
url: '/requisicoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
expect(html).toContain(message);
expect(html).not.toContain('aparecem aqui depois de criados');
},
);
+113 -8
View File
@@ -1,14 +1,73 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Legal from '../../resources/js/pages/supply/import-legal';
import Legal, {
revealInvalidLegalField,
} from '../../resources/js/pages/supply/import-legal';
test('incomplete legal preparation reveals the first invalid field below the fixed header', () => {
const callbacks: FrameRequestCallback[] = [];
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
callbacks.push(callback);
return callbacks.length;
});
const field = { focus: vi.fn(), scrollIntoView: vi.fn() };
const form = {
querySelector: vi.fn((selector: string) =>
selector === 'input:invalid, select:invalid, textarea:invalid'
? field
: { tagName: 'FIELDSET' },
),
};
try {
revealInvalidLegalField({
currentTarget: form,
target: field,
} as never);
revealInvalidLegalField({ currentTarget: form, target: {} } as never);
expect(callbacks).toHaveLength(1);
expect(field.scrollIntoView).not.toHaveBeenCalled();
callbacks[0](0);
expect(field.focus).toHaveBeenCalledWith({ preventScroll: true });
expect(field.scrollIntoView).toHaveBeenCalledWith({
block: 'center',
behavior: 'instant',
});
} finally {
vi.unstubAllGlobals();
}
});
afterEach(() => vi.restoreAllMocks());
test.each([true, false])(
'legal shortcuts target present focusable sections without exposing management (%s)',
(canManage) => {
const html = renderLegal(canManage);
const navigation = html.match(
/<nav aria-label="Áreas da base legal de importação"[\s\S]*?<\/nav>/,
)?.[0];
expect(navigation).toBeDefined();
const targets = [...navigation!.matchAll(/href="#([^"]+)"/g)].map(
(match) => match[1],
);
for (const id of targets) {
expect(html.split(`id="${id}"`)).toHaveLength(2);
expect(html).toMatch(new RegExp(`id="${id}" tabindex="-1"`));
}
expect(targets.includes('legal-rule-editor')).toBe(canManage);
expect(targets).not.toContain('legal-decision');
expect(html).toContain('data-query-form="true"');
if (canManage) expect(html).toContain('href="#legal-rule-editor"');
},
);
function renderLegal(
canManage: boolean,
withRule = true,
withCharges = false,
withReference = false,
iceReference = false,
vatReference = false,
) {
const data = {
title: '<script>synthetic rule</script>',
@@ -68,18 +127,46 @@ function renderLegal(
? [
{
source_id: 8,
code: '3506.91.20',
description:
'Silicone para selagem de painéis solares',
rate_percent: '20',
title: 'Taxa geral documental',
official_reference: 'Lei 8/2025',
code: iceReference
? '8703.80.10'
: '3506.91.20',
description: iceReference
? 'Automóveis unicamente eléctricos, bateria até 62 kWh'
: 'Silicone para selagem de painéis solares',
rate_percent: iceReference ? '5' : '20',
rate_label: iceReference
? 'ICE 5%'
: undefined,
valid_until: iceReference
? '2027-12-31'
: undefined,
title: iceReference
? 'ICE documental'
: 'Taxa geral documental',
official_reference: iceReference
? 'Lei 7/2025, 2.º suplemento'
: 'Lei 8/2025',
official_url: null,
citation: 'Página 2180-(4)',
citation: iceReference
? 'Página 2180-(22)'
: 'Página 2180-(4)',
valid_from: '2026-01-01',
obligations:
'Conferir o exemplar e o regime aplicável',
charges: [],
...(vatReference
? {
code: 'IVA_ART17',
label: 'IVA — taxa normal; completar código e base',
match_code: '',
suggested_code: '',
rate_percent: '16',
rate_label:
'16% — base por documentar',
valid_from: '2023-01-01',
valid_until: null,
}
: {}),
},
]
: [],
@@ -116,6 +203,24 @@ test('official reference preparation is explicit and only available to the custo
expect(reader).not.toContain('Silicone para selagem');
});
test('ICE reference labels remain distinct from general customs duty', () => {
const html = renderLegal(true, false, false, true, true);
expect(html).toContain('ICE 5%');
expect(html).not.toContain('taxa geral 5%');
expect(html).toContain('fonte, citação e período');
expect(html).toContain('não é uma pauta consolidada');
});
test('the general VAT template has a human label and leaves item classification to explicit preparation', () => {
const post = vi.spyOn(router, 'post');
const html = renderLegal(true, false, false, true, false, true);
expect(html).toContain('IVA — taxa normal; completar código e base');
expect(html).toContain('16% — base por documentar');
expect(html).not.toContain('IVA_ART17 —');
expect(html).not.toMatch(/<input[^>]*value="IVA_ART17"/);
expect(post).not.toHaveBeenCalled();
});
test('remembered legal preparation is preserved and disables replacement by official reference drafts', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'legal-rule:1:1:1:data'
+56
View File
@@ -0,0 +1,56 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ImportTariffs from '@/pages/supply/import-tariffs';
test.each([false, true])(
'tariff lookup remains a consultation while business forms respect authority (%s)',
(canWrite) => {
const page = { data: [], prev_page_url: null, next_page_url: null };
const html = renderToStaticMarkup(
<App
initialComponent={ImportTariffs}
initialPage={{
component: 'supply/import-tariffs',
url: '/requisicoes/1/classificacao-pautal',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
requisition: { id: 1, number: 'REQ-QA' },
actorId: 2,
tenantId: 3,
legalReady: true,
canPropose: canWrite,
canConfirm: canWrite,
masterSearch: 'QA<123',
items: [
{
id: 4,
description: 'Material QA',
quantity: '1',
unit: 'un',
},
],
latest: [],
history: page,
masters: page,
stockItems: page,
},
}}
/>,
);
const forms = html.match(/<form\b[^>]*>/g) ?? [];
expect(
forms.filter((form) => form.includes('data-query-form="true"')),
).toHaveLength(1);
expect(forms.find((form) => form.includes('method="get"'))).toContain(
'data-query-form="true"',
);
expect(forms).toHaveLength(canWrite ? 2 : 1);
expect(html).toContain('QA&lt;123');
expect(html).toContain('/requisicoes/1/base-legal');
expect(html).not.toContain('data-query-form="true" data-preparation');
},
);
@@ -29,6 +29,7 @@ function render(
canConfigure = true,
allowedTypes = ['production', 'maintenance'],
linked = false,
selected = false,
) {
return renderToStaticMarkup(
<App
@@ -58,6 +59,7 @@ function render(
data: { mode: 'procurement' },
},
canConfigure,
selectedOrderId: selected ? source.id : null,
allowedTypes,
departments: [{ id: 1, name: 'Synthetic department' }],
orders: {
@@ -78,6 +80,17 @@ function render(
/>,
);
}
test('a selected operational source is directly focusable and provides the return to the complete authorised registry', () => {
const html = render(7, false, [], false, true);
expect(html).toContain('A consultar uma ordem específica');
expect(html).toContain('href="/ordens-operacionais"');
expect(html).toContain('Ver todas as ordens disponíveis');
expect(html).toContain('id="op-order-5"');
expect(html).toContain('tabindex="-1"');
expect(html).toContain('lg:scroll-mt-72');
expect(html).not.toContain('<script>private-test</script>');
});
test('order preparation restores only its actor context and policy without automatic creation', () => {
const identity =
'procurement-preparations:4:7:procurement.internal:procurement,requester:operational-orders:1:1:production,maintenance:true:0:false';
+38
View File
@@ -2,6 +2,7 @@ import { expect, test } from 'vitest';
import {
connectedDirtyForms,
markPreparationDirty,
usesGenericPreparationTracking,
} from '@/lib/preparation-forms';
function form(connected = true): HTMLFormElement {
@@ -23,6 +24,43 @@ function root(forms: HTMLFormElement[]): Pick<Document, 'querySelectorAll'> {
} as unknown as Pick<Document, 'querySelectorAll'>;
}
test('consultation filters remain outside unsaved business preparations after deferred navigation while other edits stay protected', async () => {
const query = form();
query.setAttribute('data-query-form', 'true');
markPreparationDirty(query, true);
const tracked = new Set([query]);
await Promise.resolve();
expect(connectedDirtyForms(tracked, root([query]))).toEqual([]);
const business = form();
markPreparationDirty(business, true);
tracked.add(business);
expect(connectedDirtyForms(tracked, root([query, business]))).toEqual([
business,
]);
markPreparationDirty(business, false);
expect(connectedDirtyForms(tracked, root([query, business]))).toEqual([]);
});
test('generic input tracking cannot re-dirty a managed form after its own state clears during event propagation', () => {
const managed = form();
const legacy = form();
expect(usesGenericPreparationTracking(legacy)).toBe(true);
markPreparationDirty(managed, true, true);
expect(connectedDirtyForms([managed], root([managed]))).toEqual([managed]);
markPreparationDirty(managed, false, true);
if (usesGenericPreparationTracking(managed))
markPreparationDirty(managed, true);
expect(connectedDirtyForms([managed], root([managed]))).toEqual([]);
if (usesGenericPreparationTracking(legacy))
markPreparationDirty(legacy, true);
expect(
connectedDirtyForms([managed, legacy], root([managed, legacy])),
).toEqual([legacy]);
const query = form();
query.setAttribute('data-query-form', 'true');
expect(usesGenericPreparationTracking(query)).toBe(false);
});
test('a restored dirty preparation is protected even before any input event or listener registration', () => {
const restored = form();
markPreparationDirty(restored, true);
@@ -0,0 +1,290 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { ProcurementMenuResults } from '@/components/procurement-menu-results';
import {
procurementNavigation,
activeProcurementEntry,
type ProcurementGroup,
} from '@/lib/procurement-navigation';
import {
matchesMenuSearch,
searchProcurementMenu,
} from '@/lib/procurement-menu-search';
test.each([
'/compras/fornecimento',
'/compras/fornecimento?view=agreements&record_id=12',
'/compras/fornecimento?view=contracts&record_id=7#supply-record-7',
'/compras/acordos/vigencia?validity=current',
'/compras/acordos/vigencia?kind=contract&search=QA&page=2',
])(
'supply agreements and contracts retain authorised menu context: %s',
(path) => {
for (const role of [
'admin',
'supply_read',
'supply_prepare',
'supply_review',
]) {
expect(
activeProcurementEntry(
procurementNavigation([role], false),
path,
),
).toBe('supply_agreements');
}
expect(
activeProcurementEntry(
procurementNavigation(['requester'], false),
path,
),
).not.toBe('supply_agreements');
expect(
activeProcurementEntry(
procurementNavigation(['admin'], false, ['/dashboard']),
path,
),
).toBeUndefined();
},
);
test('supply menu synonyms find only the existing authorised destination', () => {
const groups = procurementNavigation(['supply_read'], false);
for (const term of [
'acordos',
'CONTRATOS',
'vigencia',
'fornecimento contrato',
]) {
expect(
searchProcurementMenu(groups, term).flatMap((group) =>
group.entries.map((entry) => entry.id),
),
).toEqual(['supply_agreements']);
expect(
searchProcurementMenu(
procurementNavigation(['requester'], false),
term,
),
).toEqual([]);
}
expect(
activeProcurementEntry(groups, '/compras/fornecimento?view=calendar'),
).toBe('supply_calendar');
});
test.each([
'/administracao/prazos-aprovacao',
'/administracao/revisao-urgencias?history=2',
])(
'approval policy subpages retain their authorised administration context: %s',
(path) => {
expect(
activeProcurementEntry(
procurementNavigation(['admin'], false),
path,
),
).toBe('organization_parameters');
expect(
activeProcurementEntry(
procurementNavigation(['requester'], false),
path,
),
).toBeUndefined();
expect(
activeProcurementEntry(
procurementNavigation(['finance'], false),
path,
),
).toBeUndefined();
expect(
activeProcurementEntry(
procurementNavigation(['admin'], false, ['/dashboard']),
path,
),
).toBeUndefined();
},
);
test.each(['classificacao-pautal', 'base-legal', 'estimativa-importacao'])(
'import process pages retain the authorised import menu context: %s',
(page) => {
const path = `/requisicoes/7/${page}`;
expect(
activeProcurementEntry(
procurementNavigation(['import_customs'], false),
path,
),
).toBe('supply_imports');
expect(
activeProcurementEntry(
procurementNavigation(['requester'], false),
path,
),
).not.toBe('supply_imports');
expect(
activeProcurementEntry(
procurementNavigation(['admin'], false, ['/dashboard']),
path,
),
).toBeUndefined();
},
);
test.each([
'documentos',
'documentos/18',
'suporte-bancario',
'acompanhamento',
'custos',
])(
'import documentary page highlights only an existing authorised import entry: %s',
(page) => {
const path = `/compras/importacoes/17/${page}`;
expect(
activeProcurementEntry(
procurementNavigation(['import_prepare'], false),
path,
),
).toBe('supply_imports');
expect(
activeProcurementEntry(
procurementNavigation(['requester'], false),
path,
),
).not.toBe('supply_imports');
expect(
activeProcurementEntry(
procurementNavigation(['admin'], false, ['/dashboard']),
path,
),
).toBeUndefined();
},
);
test('capital register menu is gated by readiness and native reading roles and highlights its history route', () => {
for (const permission of [
'admin',
'procurement',
'finance',
'department_head',
'warehouse',
'requester',
]) {
for (const ready of [false, true]) {
const groups = procurementNavigation(
[permission],
false,
undefined,
false,
false,
false,
ready,
);
const results = searchProcurementMenu(groups, 'projeto patrimonio');
expect(
results.flatMap((group) =>
group.entries.map((entry) => entry.id),
),
).toEqual(
ready && permission !== 'requester' ? ['capital_register'] : [],
);
if (ready && permission !== 'requester') {
expect(
activeProcurementEntry(
groups,
'/projectos-imobilizado?history=qa',
),
).toBe('capital_register');
}
}
}
});
test('menu search finds the authorised import route by singular name, accents and separate words', () => {
const groups = procurementNavigation(['import_customs'], false);
const before = JSON.stringify(groups);
for (const query of [
'IMPORTAÇÃO',
'aduaneira compras',
'transitario',
'pauta',
]) {
expect(
searchProcurementMenu(groups, query).flatMap((g) =>
g.entries.map((e) => e.id),
),
).toEqual(['supply_imports']);
}
expect(JSON.stringify(groups)).toBe(before);
});
test('synonyms cannot reveal audit, finance or operational routes outside the existing authority and flags', () => {
const groups = procurementNavigation(['requester'], false);
for (const query of ['auditoria privada', 'facturas', 'oficina'])
expect(searchProcurementMenu(groups, query)).toEqual([]);
const privateGroups = procurementNavigation(
['audit_private_stock_read'],
false,
undefined,
false,
false,
true,
);
expect(
searchProcurementMenu(privateGroups, 'exportar auditoria').flatMap(
(g) => g.entries.map((e) => e.id),
),
).toEqual(['audit_private']);
});
test('empty search preserves every current entry and dashboard matching accepts words in either order', () => {
const groups = procurementNavigation('admin', true);
expect(searchProcurementMenu(groups, ' ')).toEqual(groups);
expect(
matchesMenuSearch('Painel inicial Visão geral', 'GERAL painel'),
).toBe(true);
expect(
matchesMenuSearch('Painel inicial Visão geral', 'sem correspondência'),
).toBe(false);
});
function renderResults(groups: ProcurementGroup[], dashboard = false) {
const Screen = () => (
<ProcurementMenuResults
groups={groups}
dashboard={dashboard}
onNavigate={() => {}}
onEscape={() => {}}
/>
);
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'qa/menu',
url: '/dashboard',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
}
test('desktop results expose direct links, their area and a clear live empty state', () => {
const groups = searchProcurementMenu(
procurementNavigation(['import_customs'], false),
'importacao',
);
const html = renderResults(groups);
expect(html).toContain('1 opção disponível');
expect(html).toContain('href="/compras/fornecimento?view=imports"');
expect(html).toContain('Importação');
expect(html).toContain('Resultados da pesquisa do menu');
expect(renderResults([])).toContain('Nenhuma opção encontrada');
expect(renderResults([])).toContain('role="status"');
expect(renderResults(groups, true)).toContain('2 opções disponíveis');
});
@@ -0,0 +1,83 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ProcurementReports from '@/pages/reports/procurement';
test.each([false, true])(
'report shortcuts have matching sections and preserve the filtered report without exposing absent financial sections (%s)',
(operational) => {
const Screen = () => (
<ProcurementReports
records={{
data: [],
total: 0,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
}}
counts={{}}
filters={{ status: 'pending', department_id: 7 }}
departments={[]}
generatedAt="2026-11-28T12:00:00Z"
insights={
operational
? {
method: 'procurement_facts_v1',
generated_at: '2026-11-28T12:00:00Z',
processes: 0,
pending: {
count: 0,
unknown_submission_age: 0,
oldest: [],
},
unapproved_past_needed_date: 0,
approved: {
count: 0,
without_registered_quotes: 0,
without_visible_order: 0,
},
}
: undefined
}
/>
);
const html = renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'reports/procurement',
url: '/relatorios?status=pending&department_id=7',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
expect(html).toContain('aria-label="Secções dos relatórios"');
expect(html).toContain('href="#report-filters"');
expect(html).toContain('id="report-filters"');
// The sticky workspace header previously covered anchor destinations.
for (const target of html.matchAll(
/<section\b[^>]*id="report-[^"]+"[^>]*>/g,
)) {
expect(target[0]).toContain('tabindex="-1"');
expect(target[0]).toContain('scroll-mt-24 lg:scroll-mt-72');
}
expect(html.includes('href="#report-operational"')).toBe(operational);
expect(html.includes('id="report-operational"')).toBe(operational);
for (const absent of [
'payables',
'deliveries',
'payments',
'contracts',
]) {
expect(html).not.toContain(`href="#report-${absent}"`);
expect(html).not.toContain(`id="report-${absent}"`);
}
expect(html).toContain(
'/relatorios/compras.csv?status=pending&amp;department_id=7',
);
},
);
+171
View File
@@ -3,6 +3,177 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Search from '@/pages/search/procurement';
test('operational search exposes the native selected-order destination and a registration state without private source bodies', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=OP',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'OP',
operationalOrderSearchAvailable: true,
groups: [
{
key: 'operational_orders',
title: 'Ordens de produção e manutenção',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=OP&operational_orders_page=2',
data: [
{
id: 5,
title: 'Produção OP-QA · v1',
detail: 'recorded',
href: '/ordens-operacionais?order_id=5#op-order-5',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('/ordens-operacionais?order_id=5#op-order-5');
expect(html).toContain('Registada');
expect(html).toContain('operational_orders_page=2');
expect(html).toContain('ordem de origem autorizada');
});
test.each([0, 1])(
'search places matching areas before collapsed empty areas and reports an entirely empty scope (%i)',
(total) => {
const empty = {
total: 0,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
data: [],
};
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=CAP',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'CAP',
groups: [
{
key: 'requests',
title: 'Requisições',
records: empty,
},
{
key: 'capital',
title: 'Projectos e imobilizado',
records: {
...empty,
total,
data: total
? [
{
id: 1,
title: 'PROJECT-HIT',
detail: 'active',
href: '/projectos-imobilizado?history=qa',
},
]
: [],
},
},
],
},
}}
/>,
);
expect(html).toContain('Áreas sem resultados');
expect(html).toContain('data-query-form="true"');
expect(html).not.toContain('<details open');
expect(
html.includes(
'Não foram encontrados resultados para esta pesquisa',
),
).toBe(total === 0);
if (total)
expect(html.indexOf('PROJECT-HIT')).toBeLessThan(
html.indexOf('Áreas sem resultados'),
);
expect(html).not.toContain('Requisições (0)');
},
);
test.each([false, true])(
'capital search presents only supplied register metadata and its native history destination (%s)',
(available) => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=CAP',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'CAP',
capitalSearchAvailable: available,
groups: available
? [
{
key: 'capital',
title: 'Projectos e imobilizado',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=CAP&capital_page=2',
data: [
{
id: 8,
title: 'Projecto CAP <QA> · v2',
detail: 'archived',
href: '/projectos-imobilizado?history=qa-record',
},
],
},
},
]
: [],
},
}}
/>,
);
expect(html.includes('Projectos e imobilizado')).toBe(available);
expect(html.includes('próprios de Compras')).toBe(available);
expect(html.includes('/projectos-imobilizado?history=qa-record')).toBe(
available,
);
if (available) {
expect(html).toContain('Projecto CAP &lt;QA&gt; · v2');
expect(html).toContain('Arquivado');
expect(html).toContain('capital_page=2');
}
},
);
test('warehouse search preserves the distinct internal reference event state and result page', () => {
const html = renderToStaticMarkup(
<App
@@ -27,7 +27,7 @@ const order = {
};
function render(
component: typeof Orders | typeof Show,
component: Parameters<typeof App>[0]['initialComponent'],
props: Record<string, unknown>,
) {
return renderToStaticMarkup(
@@ -64,3 +64,117 @@ test('incomplete detail identifies the missing original and preserves documented
expect(html).toContain('/ordens/1/imprimir');
expect(html).not.toContain('Aprovações do valor final');
});
test.each([
{
state: 'issued',
enabled: true,
canRequest: true,
form: true,
text: 'Ordem emitida.',
},
{
state: 'issued',
enabled: true,
canRequest: false,
form: false,
text: 'Ordem emitida.',
},
{
state: 'cancellation_pending',
enabled: false,
canRequest: false,
form: false,
text: 'Cancelamento pendente.',
},
{
state: 'cancelled',
enabled: true,
canRequest: false,
form: false,
text: 'Ordem cancelada.',
},
])(
'legacy detail preserves operational cancellation status and server authority ($state/$canRequest)',
({ state, enabled, canRequest, form, text }) => {
const html = render(Show, {
order,
history: [],
snapshotComplete: false,
orderCancellation: { state, enabled, canRequest },
});
expect(html).toContain('Estado operacional e cancelamento');
expect(html).toContain(text);
expect(html.includes('Pedir cancelamento integral')).toBe(form);
expect(html).toContain('Documento original incompleto');
expect(html).toContain('Artigo preservado');
expect(html).toContain('100,00');
expect(html).not.toContain('Aprovações do valor final');
},
);
test.each([false, true])(
'existing order documents expose only server-authorised related destinations (%s)',
(finance) => {
const html = render(Show, {
order,
history: [],
snapshotComplete: false,
financialDocumentsHref: finance
? '/facturas?purchase_order_id=1'
: null,
relatedProcesses: [
{ id: 4, number: 'REQ<QA>', href: '/requisicoes/4/processo' },
{
id: 7,
number: 'REQ-SECOND-QA',
href: '/requisicoes/7/processo',
},
],
});
expect(html).toContain('Documentos relacionados da ordem');
expect(html).toContain('href="/requisicoes/4/processo"');
expect(html).toContain('href="/requisicoes/7/processo"');
expect(html).toContain('REQ&lt;QA&gt;');
expect(html.includes('/facturas?purchase_order_id=1')).toBe(finance);
expect(html).toContain('Artigo preservado');
},
);
import ReceiptShow from '@/pages/receipts/show';
test.each([false, true])(
'receipt detail retains the original and only offers the financial link supplied by the server (%s)',
(finance) => {
const html = render(ReceiptShow, {
receipt: {
id: 8,
number: 'REC-QA',
purchase_order_id: 1,
delivery_note: 'GUIA-QA',
received_on: '2026-11-28',
confirmed_at: '2026-11-28T12:00:00Z',
status: 'complete',
snapshot: {
order: { id: 1, number: 'OC-QA' },
supplier: { name: 'Fornecedor QA' },
receiver: { name: 'Armazém QA' },
warehouse: null,
},
items: [],
},
movements: [],
financialDocumentsHref: finance
? '/facturas?purchase_order_id=1#invoice-documents'
: null,
});
expect(
html.includes(
'href="/facturas?purchase_order_id=1#invoice-documents"',
),
).toBe(finance);
expect(html).toContain('GUIA-QA');
expect(html).toContain('Recepção total aceite');
expect(html).toContain('/recepcoes/8/imprimir');
expect(html).toContain('/ordens/1/recepcoes');
},
);
+50 -1
View File
@@ -1,5 +1,6 @@
import { App } from '@inertiajs/react';
import type { Page } from '@inertiajs/core';
import type { ComponentProps } from 'react';
import { renderToString } from 'react-dom/server';
import { expect, test } from 'vitest';
import { QuotationCommercialTerms } from '@/components/quotation-commercial-terms';
@@ -23,7 +24,7 @@ const policy = {
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
};
function render(
Component: typeof Comparison | typeof QuotationExchangePanel,
Component: ComponentProps<typeof App>['initialComponent'],
props: Record<string, unknown>,
) {
const page = {
@@ -39,6 +40,54 @@ function render(
);
}
test.each([true, false])(
'related quotation stages remain grouped and preserve conditional urgency access (%s)',
(urgent) => {
const html = render(Comparison, {
requisition: {
id: 42,
number: 'REQ-42',
justification: 'Synthetic navigation QA',
items: [],
},
suppliers: [],
quotations: [],
canCreate: false,
canEvaluate: false,
ready: false,
topIds: [],
comparisonPolicy: {
...policy,
...(urgent ? { urgent_minimum_proposals: 1 } : {}),
},
urgentQuotationReady: urgent,
});
const group = html.match(
/<details[^>]*>[\s\S]*?Outras etapas e documentos do processo[\s\S]*?<\/details>/,
)?.[0];
expect(group).toBeDefined();
expect(group).not.toMatch(/<details[^>]*\bopen\b/);
expect(group).toContain(
'aria-label="Etapas e documentos relacionados"',
);
expect(group).toContain('grid gap-3 sm:grid-cols-2');
for (const path of [
'abertura',
'qualificacao',
'admissao',
'recomendacao',
'relatorio',
]) {
expect(group).toContain(`/requisicoes/42/${path}`);
}
expect(group).toContain('href="/requisicoes/42"');
expect(group).toContain('href="/conflitos"');
expect(group?.includes('/requisicoes/42/urgencia-stock')).toBe(urgent);
expect(html).toContain('href="/requisicoes/42/adjudicacao"');
expect(html).toContain('Comparação ainda incompleta.');
},
);
test.each([true, false])(
'process rates retain provenance and restrict the finance form (%s)',
(canRecord) => {
@@ -0,0 +1,172 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Evaluation from '@/pages/suppliers/evaluation';
afterEach(() => vi.restoreAllMocks());
const payload = {
title: 'Avaliação QA',
nature: 'goods',
scope: 'Âmbito sintético.',
period_start: '2026-11-28',
period_end: '2026-11-28',
order_ids: [],
criteria: [],
conclusion: 'Conclusão original.',
critical_occurrences: '',
critical_evidence: '',
};
const identity =
'procurement-preparations:4:7:procurement.internal:procurement:supplier-evaluation:1:3';
function render(
kind: 'evidence' | 'decision',
actor = 7,
tenant = 4,
context = 'procurement.internal',
version = 3,
reportOnly = false,
) {
return renderToStaticMarkup(
<App
initialComponent={Evaluation}
initialPage={{
component: 'suppliers/evaluation',
url: '/fornecedores/avaliacoes/1',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['procurement'] },
reportOnly,
canEdit: kind === 'evidence' && !reportOnly,
canReview: kind === 'decision' && !reportOnly,
canRevise: false,
nextRevisionId: null,
orders: [],
people: {},
history: {
data: [],
total: 0,
prev_page_url: null,
next_page_url: null,
},
generatedAt: '2026-11-28T12:00:00Z',
improvements: { ready: false, records: [] },
responses: { ready: false, records: [] },
evaluation: {
id: 1,
supplier_id: 2,
revision: 1,
version,
status: kind === 'evidence' ? 'draft' : 'review',
previous_id: null,
created_by: 9,
contributors: [9],
supplier_snapshot: {
id: 2,
name: 'Fornecedor QA',
nuit: '123456789',
},
payload,
review_reason: null,
reviewed_at: null,
reviewed_by: null,
},
},
}}
/>,
);
}
test.each(['evidence', 'decision'] as const)(
'%s navigation targets only present focusable sections and preserves report boundaries',
(kind) => {
for (const reportOnly of [false, true]) {
const html = render(
kind,
7,
4,
'procurement.internal',
3,
reportOnly,
);
const navigation = html.match(
/<nav aria-label="Áreas da avaliação do fornecedor"[\s\S]*?<\/nav>/,
)?.[0];
expect(navigation).toBeDefined();
const targets = [...navigation!.matchAll(/href="#([^"]+)"/g)].map(
(match) => match[1],
);
for (const id of targets) {
expect(html.split(`id="${id}"`)).toHaveLength(2);
expect(html).toContain(`id="${id}" tabindex="-1"`);
}
expect(targets).toContain('evaluation-evidence');
expect(targets).toContain('evaluation-improvements');
expect(targets).toContain('evaluation-responses');
expect(targets.includes('evaluation-review')).toBe(
kind === 'decision' && !reportOnly,
);
expect(targets.includes('evaluation-history')).toBe(!reportOnly);
expect(targets).not.toContain('evaluation-last-review');
expect(targets).not.toContain('evaluation-revision');
expect(html).toContain(
'class="rounded-xl border bg-card p-4 print:hidden"',
);
expect(html).not.toContain('<details open');
}
},
);
test.each(['evidence', 'decision'] as const)(
'%s preparation recovers only for the same actor company context and source version without submitting',
(kind) => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:${kind}:data`
? kind === 'evidence'
? {
version: 3,
payload: {
...payload,
conclusion: 'PRIVATE-QA-PREPARATION',
},
}
: { version: 3, reason: 'PRIVATE-QA-PREPARATION' }
: undefined,
);
const post = vi.spyOn(router, 'post');
const put = vi.spyOn(router, 'put');
expect(render(kind)).toContain('PRIVATE-QA-PREPARATION');
expect(render(kind)).toContain('data-preparation-dirty="true"');
expect(render(kind, 8)).not.toContain('PRIVATE-QA-PREPARATION');
expect(render(kind, 7, 5)).not.toContain('PRIVATE-QA-PREPARATION');
expect(render(kind, 7, 4, 'finance')).not.toContain(
'PRIVATE-QA-PREPARATION',
);
expect(render(kind, 7, 4, 'procurement.internal', 4)).not.toContain(
'PRIVATE-QA-PREPARATION',
);
expect(
render(kind, 7, 4, 'procurement.internal', 3, true),
).not.toContain('PRIVATE-QA-PREPARATION');
expect(post).not.toHaveBeenCalled();
expect(put).not.toHaveBeenCalled();
},
);
test('a clean recovered evidence form is not dirty because object keys changed order', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:evidence:data`
? {
version: 3,
payload: Object.fromEntries(
Object.entries(payload).reverse(),
),
}
: undefined,
);
expect(render('evidence')).not.toContain('data-preparation-dirty="true"');
});
@@ -0,0 +1,90 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Evaluation from '@/pages/suppliers/evaluation';
test.each([false, true])(
'report preserves the decision and identifies only the recorded reviewer (%s)',
(knownName) => {
const html = renderToStaticMarkup(
<App
initialComponent={Evaluation}
initialPage={{
component: 'suppliers/evaluation',
url: '/fornecedores/avaliacoes/1/relatorio',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
reportOnly: true,
canEdit: false,
canReview: false,
canRevise: false,
nextRevisionId: null,
orders: [],
people: knownName ? { 7: 'Revisor <QA>' } : {},
history: {
data: [],
total: 0,
prev_page_url: null,
next_page_url: null,
},
generatedAt: '2026-11-28T12:00:00Z',
improvements: { ready: false, records: [] },
responses: { ready: false, records: [] },
evaluation: {
id: 1,
supplier_id: 2,
revision: 1,
version: 3,
status: 'approved',
previous_id: null,
created_by: 4,
contributors: [4],
supplier_snapshot: {
id: 2,
name: 'Fornecedor QA',
nuit: '123456789',
},
payload: {
title: 'Avaliação QA',
nature: 'goods',
scope: 'Âmbito sintético.',
period_start: '2026-11-28',
period_end: '2026-11-28',
order_ids: [],
criteria: [],
conclusion: 'Conclusão preservada.',
critical_occurrences: '',
critical_evidence: '',
},
review_reason: 'Fundamento preservado.',
reviewed_by: 7,
reviewed_at: '2026-11-28T12:00:00Z',
},
},
}}
/>,
);
expect(html).toContain('Última decisão documentada');
expect(html).toContain('href="#evaluation-last-review"');
expect(html).toContain('id="evaluation-last-review" tabindex="-1"');
expect(html).not.toContain('href="#evaluation-history"');
expect(html).toContain('Fundamento preservado.');
expect(html).toContain(knownName ? 'Revisor &lt;QA&gt;' : '#7');
expect(html).not.toContain('Revisor <QA>');
expect(html).not.toContain('2026-11-28T12:00:00Z');
expect(html).not.toContain('<form');
const decisionGroup = html.match(
/<div class="print:break-inside-avoid">([\s\S]*?)<\/section><\/div>/,
)?.[1];
expect(decisionGroup).toContain('Fundamento preservado.');
expect(decisionGroup).toContain(
knownName ? 'Revisor &lt;QA&gt;' : '#7',
);
expect(decisionGroup).toContain(
new Date('2026-11-28T12:00:00Z').toLocaleString('pt-MZ'),
);
},
);
@@ -62,6 +62,96 @@ function render(overrides = {}, actor = 7, tenant = 4) {
);
}
test('contract workspace names its own preparation and document reference with separated navigation', () => {
const html = render({
kind: 'contract',
view: 'contracts',
orderLimitsReady: true,
records: [
{
...record,
kind: 'contract',
data: {
...record.data,
reference: '<script>QA-CONTRACT</script>',
},
},
],
});
expect(html).toContain('Novo contrato com vários artigos');
expect(html).not.toContain('Novo acordo de fornecimento');
expect(html).toContain('Contrato &lt;script&gt;QA-CONTRACT&lt;/script&gt;');
expect(html).not.toContain('<script>QA-CONTRACT</script>');
const navigation = html.match(
/<nav aria-label="Consultas e cadastros de fornecimento"[\s\S]*?<\/nav>/,
)?.[0];
expect(navigation).toContain('flex flex-wrap gap-x-4 gap-y-2');
expect(navigation).toContain('/compras/acordos/vigencia?kind=contract');
expect(navigation).toContain('/compras/fornecimento?view=agreements');
});
test('contract without a documentary reference stays explicit and read-only users get no preparation', () => {
const html = render({
kind: 'contract',
view: 'contracts',
canPrepare: false,
records: [
{
...record,
data: { reference: '' },
canApprove: false,
canReturn: false,
},
],
});
expect(html).toContain('Contrato sem referência indicada');
expect(html).not.toContain('Novo contrato com vários artigos');
expect(html).not.toContain('Abrir preparação');
expect(render()).toContain('Novo acordo de fornecimento');
});
test('supply guidance follows the current area and keeps customs responsibilities in imports', () => {
const areas = [
[
'contracts',
'contract',
'limites globais',
'Compras prepara os contratos',
],
[
'agreements',
'agreement',
'condições de fornecimento',
'Compras prepara os acordos',
],
[
'calendar',
'policy',
'parâmetros de stock',
'Compras prepara as políticas',
],
];
for (const [view, kind, description, responsibility] of areas) {
const html = render({ view, kind, records: [], canPrepare: false });
expect(html).toContain(description);
expect(html).toContain(responsibility);
expect(html).not.toContain('responsável aduaneiro');
expect(html).not.toContain('Logística acompanha');
}
const imports = render({
view: 'imports',
kind: 'import',
records: [],
canPrepare: false,
orderLimitsReady: true,
});
expect(imports).toContain('Acompanhe as ordens importadas');
expect(imports).toContain('Logística acompanha embarque e chegada');
expect(imports).toContain('responsável aduaneiro');
expect(imports).not.toContain('Compras prepara os contratos');
expect(imports).not.toContain('Consultas e cadastros de fornecimento');
});
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`
@@ -0,0 +1,66 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Availability from '@/pages/stock/availability';
test.each([true, false])(
'availability explains the actual reservation capability and preserves unknown balances (%s)',
(ready) => {
const Screen = () => (
<Availability
filters={{ warehouse_id: 1 }}
warehouses={[]}
warehouse={{ name: 'Armazém QA' }}
checkedAt="2026-11-28T12:00:00Z"
planningVisible={false}
reservationsAvailable={ready}
rows={{
total: 1,
prev_page_url: null,
next_page_url: null,
data: [
{
id: 1,
code: 'QA-1',
name: 'Material sintético',
unit: 'un',
physical_milli: 10000,
usable_milli: 10000,
blocked_milli: null,
lot_control: false,
reconciled: true,
planned_milli: null,
minimum_milli: null,
at_minimum: false,
physical_commitment_milli: ready ? 3000 : null,
free_milli: ready ? 7000 : null,
},
],
}}
/>
);
const html = renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'stock/availability',
url: '/stock/disponibilidade?warehouse_id=1',
version: null,
props: { errors: {} },
}}
/>,
).replace(/\s+/g, ' ');
expect(html).toContain('data-query-form="true"');
expect(html).not.toContain('ainda não estão implementados');
if (ready) {
expect(html).toContain('menos as reservas físicas registadas');
expect(html).not.toContain('Saldo livre por determinar');
} else {
expect(html).toContain(
'reservas físicas não estão disponíveis nesta consulta',
);
expect(html).toContain('Saldo livre por determinar');
}
expect(html).toContain('Sem acesso ao planeamento');
},
);