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

This commit is contained in:
2026-11-28 15:45:52 +02:00
parent eb32c74c56
commit 060c119ba1
92 changed files with 4936 additions and 43 deletions
@@ -14,7 +14,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'], true)) {
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase', 'describe-private-audit-schema'], true)) {
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$databaseName = getenv('DB_DATABASE') ?: '';
@@ -42,6 +42,21 @@ if ($mode === 'prepare-native-review') {
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'describe-private-audit-schema') {
$columns = DB::transaction(function () {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$schema = DB::getSchemaBuilder();
$result = [];
foreach ($schema->getTableListing() as $table) {
$result[$table] = $schema->getColumnListing($table);
}
ksort($result);
return $result;
});
echo json_encode(['schema_only' => true, 'no_business_values' => true, 'tables' => $columns], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-office-purchase') {
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1') {
throw new LogicException('Office HTTP assertions require their explicit synthetic composition.');
+73
View File
@@ -3,6 +3,7 @@
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\ConflictDeclaration;
use App\Models\ConflictRelease;
use App\Models\CostCenter;
use App\Models\Department;
use App\Models\ProposalEvaluation;
@@ -13,6 +14,8 @@ use App\Models\Tenant;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
function personalConflict(int $supplierId, ?int $requisitionId = null, bool $hasConflict = true): array
@@ -20,6 +23,76 @@ function personalConflict(int $supplierId, ?int $requisitionId = null, bool $has
return ['scope' => $requisitionId ? 'process_supplier' : 'supplier', 'supplier_id' => $supplierId, 'requisition_id' => $requisitionId, 'has_conflict' => $hasConflict, 'known_since' => now()->subYears(3)->format('Y-m-d'), 'reason' => 'Relação pessoal relevante declarada para efeitos de transparência.'];
}
function configureConflictDirection(User $user): int
{
$db = DB::class;
$db::table('organization_access')->insert(['tenant_id' => $user->tenant_id, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
$profile = $db::table('organization_profiles')->insertGetId(['tenant_id' => $user->tenant_id, 'name' => 'Direcção da empresa', 'permissions' => json_encode(['conflict_release_authorise']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
return $db::table('organization_memberships')->insertGetId(['tenant_id' => $user->tenant_id, 'user_id' => $user->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
}
test('direction release preserves declarations applies to the complete correction chain and replays once', function () {
config(['conflict-releases.qa_enabled' => true]);
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
$root = ConflictDeclaration::query()->firstOrFail();
$this->put('/conflitos/'.$root->id, ['reason' => 'Fundamento corrigido antes da decisão da direcção.', 'known_since' => now()->format('Y-m-d')])->assertSessionHasNoErrors();
$latest = ConflictDeclaration::query()->latest('id')->firstOrFail();
$before = ConflictDeclaration::query()->get()->toArray();
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Direcção autoriza expressamente o levantamento deste impedimento.'];
$guard = app(ConflictGuard::class);
expect($guard->hasConflict($this->buyer->id, $this->supplier->id, $this->r->id))->toBeTrue();
$this->actingAs($this->admin)->post('/conflitos/'.$latest->id.'/levantamento', $input)->assertForbidden();
configureConflictDirection($this->admin);
$this->post('/conflitos/'.$root->id.'/levantamento', $input)->assertConflict();
$this->get('/conflitos/'.$root->id)->assertInertia(fn (Assert $page) => $page->where('canAuthoriseRelease', true));
$this->post('/conflitos/'.$latest->id.'/levantamento', $input)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/conflitos/'.$latest->id.'/levantamento', $input)->assertSessionHasNoErrors()->assertRedirect();
expect($guard->hasConflict($this->buyer->id, $this->supplier->id, $this->r->id))->toBeFalse()
->and(ConflictDeclaration::query()->get()->toArray())->toBe($before)
->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->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('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();
$root = ConflictDeclaration::query()->firstOrFail();
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Autorização expressa da direcção para este conflito.'];
$url = '/conflitos/'.$root->id.'/levantamento';
$this->actingAs($this->finance)->post($url, $input)->assertForbidden();
$membership = configureConflictDirection($this->admin);
$this->actingAs($this->admin);
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => now()->subMinute()]);
$this->post($url, $input)->assertForbidden();
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => null, 'maintenance' => true]);
$this->post($url, $input)->assertForbidden();
DB::table('organization_memberships')->where('id', $membership)->update(['maintenance' => false]);
$this->post($url, [...$input, 'reason' => 'curto'])->assertSessionHasErrors('reason');
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
$foreign = User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Configured]);
configureConflictDirection($foreign);
$this->actingAs($foreign)->post($url, $input)->assertNotFound();
expect(ConflictRelease::query()->withoutGlobalScopes()->count())->toBe(0);
});
test('release capability remains disabled by default and release evidence is append only', function () {
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
$root = ConflictDeclaration::query()->firstOrFail();
configureConflictDirection($this->admin);
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Direcção autoriza o levantamento com fundamento registado.'];
$this->actingAs($this->admin)->post('/conflitos/'.$root->id.'/levantamento', $input)->assertStatus(503);
config(['conflict-releases.qa_enabled' => true]);
$this->post('/conflitos/'.$root->id.'/levantamento', $input)->assertSessionHasNoErrors();
$release = ConflictRelease::query()->firstOrFail();
expect(fn () => $release->update(['reason' => 'Outro fundamento']))->toThrow(LogicException::class);
expect(fn () => $release->delete())->toThrow(LogicException::class);
});
beforeEach(function () {
$this->tenant = Tenant::query()->create(['name' => 'Conflitos A']);
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Operações']);
@@ -0,0 +1,65 @@
<?php
use App\Models\SupplyRecord;
use App\Services\ImportLegalReferenceDrafts;
use App\Services\ImportLegalRules;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
Storage::fake('local');
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
$this->actingAs($this->f['issuer']);
});
test('a supplied official edition offers exact documentary drafts without publishing rules or changing financial facts', function () {
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf';
if (! is_file($path)) {
test()->markTestSkipped('The owner supplied original is required for this real-source integration.');
}
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::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' => 'BR I Série 248, suplemento, 29/12/2025; Lei 8/2025',
'reason' => 'Actual supplied official original copied only to synthetic isolated QA; no rule publication.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
$drafts = $workspace['referenceDrafts'];
expect($drafts)->toHaveCount(11)
->and(array_column($drafts, 'code'))->toContain('3506.91.20', '7604.10.10')
->and($drafts[0]['rate_percent'])->toBe('20')
->and($drafts[2]['rate_percent'])->toBe('7.5')
->and($drafts[0]['valid_from'])->toBe('2026-01-01')
->and($drafts[0]['citation'])->toContain('2180-(4)')
->and($drafts[0]['source_id'])->toBe($source->id)
->and($drafts[0]['charges'][0]['kind'])->toBe('duty')
->and($workspace['referenceDraftWarnings'])->toBe([])
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0)
->and(json_encode($workspace['sources'], JSON_THROW_ON_ERROR))->not->toContain('import-legal/');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-SYNTHETIC-COPY');
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['referenceDrafts'])->toBe([])
->and($workspace['referenceDraftWarnings'])->toHaveCount(1)
->and($workspace['referenceDraftWarnings'][0]['source_id'])->toBe($source->id)
->and(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::EDITION_SHA256);
});
test('an unknown edition never inherits parameters from its title or citation', function () {
$source = new SupplyRecord(['kind' => 'import_legal_source', 'data' => ['official_reference' => 'Lei 8/2025'],
'snapshot' => ['evidence' => ['sha256' => hash('sha256', 'different edition')]]]);
expect(app(ImportLegalReferenceDrafts::class)->forSource($source))->toBe([]);
});
+139
View File
@@ -0,0 +1,139 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Department;
use App\Models\SupplyRecord;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationalOrders;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
$this->admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->policy = ['version' => 0, 'mode' => 'procurement', 'reason' => 'Locais ainda não abrangidos pela aplicação de compras.', 'operation_key' => (string) Str::uuid()];
$this->input = ['type' => 'production', 'reference' => 'OP-SYNTHETIC-001', 'department_id' => $this->f['department']->id,
'utilisation_location' => 'Linha de produção exclusivamente sintética', 'description' => 'Produção fictícia para comprovar a ordem de origem.',
'reason' => 'Registo sintético pelo agente de procurement.', 'policy_version' => 1, 'operation_key' => (string) Str::uuid()];
$this->actingAs($this->admin);
});
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]);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertForbidden();
$this->actingAs($this->admin)->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais', $this->input)->assertForbidden();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$order = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
expect($order->snapshot['author']['id'])->toBe($this->f['issuer']->id)
->and($order->snapshot['policy']['data']['mode'])->toBe('procurement')
->and(SupplyRecord::query()->where('kind', 'op_order')->count())->toBe(1);
foreach (SupplyRecord::query()->pluck('kind') as $kind) {
expect(strlen($kind))->toBeLessThanOrEqual(20);
}
$this->post('/ordens-operacionais', [...$this->input, 'description' => 'Payload alterado na mesma operação.'])->assertConflict();
$this->post('/ordens-operacionais', [...$this->input, 'operation_key' => (string) Str::uuid()])->assertConflict();
$response = $this->get('/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page->component('requisitions/operational-orders')->has('orders.data', 1));
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('utilisation mode uses explicit production and workshop responsibilities without a procurement fallback', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', [...$this->policy, 'mode' => 'utilisation'])->assertSessionHasNoErrors()->assertRedirect();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertForbidden();
DB::table('organization_access')->insert(['tenant_id' => $this->f['tenant']->id, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
foreach (['production', 'maintenance'] as $type) {
$person = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $person->tenant_id, 'name' => $type, 'permissions' => json_encode([$type.'_order_prepare']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
$membership = DB::table('organization_memberships')->insertGetId(['tenant_id' => $person->tenant_id, 'user_id' => $person->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
$input = [...$this->input, 'type' => $type, 'reference' => 'SYNTHETIC-'.$type, 'operation_key' => (string) Str::uuid()];
$this->actingAs($person)->post('/ordens-operacionais', $input)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais', [...$input, 'type' => $type === 'production' ? 'maintenance' : 'production', 'operation_key' => (string) Str::uuid()])->assertForbidden();
DB::table('organization_memberships')->where('id', $membership)->update(['expires_at' => now()->subMinute()]);
$this->post('/ordens-operacionais', $input)->assertForbidden();
}
expect(SupplyRecord::query()->where('kind', 'op_order')->count())->toBe(2);
});
test('request links preserve original order and line basis reject stale changes and cannot be changed after submission', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$source = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
$request = $this->f['r'];
$request->update(['status' => 'draft']);
$item = $request->items()->firstOrFail();
$item->update(['category_context' => ['version' => 1, 'category' => 'production_input', 'reason' => null]]);
$service = app(OperationalOrders::class);
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
$input = ['item_id' => $item->id, 'order_id' => $source->id, 'version' => 0, 'reason' => 'Ligação documental à produção solicitada.', 'operation_key' => (string) Str::uuid()];
$url = '/requisicoes/'.$request->id.'/ordens-operacionais';
$this->post($url, $input)->assertSessionHasNoErrors()->assertRedirect();
$this->post($url, $input)->assertSessionHasNoErrors()->assertRedirect();
$service->assertSubmission($this->f['issuer'], $request);
$frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
expect($frozen[$item->id]['snapshot']['source']['id'])->toBe($source->id)
->and($frozen[$item->id]['snapshot']['source']['snapshot']['author']['id'])->toBe($this->f['issuer']->id);
$this->post($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
$item->update(['description' => 'Alteração posterior exige nova ligação.']);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
$this->post($url, [...$input, 'version' => 1, 'operation_key' => (string) Str::uuid()])->assertSessionHasNoErrors()->assertRedirect();
$request->update(['status' => 'pending']);
$this->post($url, [...$input, 'version' => 2, 'operation_key' => (string) Str::uuid()])->assertConflict();
expect(SupplyRecord::query()->where('kind', 'op_order_link')->count())->toBe(2);
config(['operational-orders.qa_enabled' => false]);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
});
test('policy versions and company department isolation are enforced on original orders', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->post('/ordens-operacionais/configuracao', [...$this->policy, 'operation_key' => (string) Str::uuid()])->assertConflict();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', [...$this->input, 'policy_version' => 2])->assertConflict();
$other = Tenant::query()->create(['name' => 'Outra empresa sintética']);
$department = Department::query()->create(['tenant_id' => $other->id, 'name' => 'Outra produção']);
$this->post('/ordens-operacionais', [...$this->input, 'department_id' => $department->id])->assertNotFound();
$foreign = User::factory()->create(['tenant_id' => $other->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Procurement]);
$this->actingAs($foreign)->get('/requisicoes/'.$this->f['r']->id.'/ordens-operacionais')->assertNotFound();
expect(SupplyRecord::query()->withoutGlobalScopes()->where('kind', 'op_order')->count())->toBe(0);
});
test('metadata authority never opens the order register and process readers receive only linked origins', function () {
config(['operational-orders.qa_enabled' => true]);
$this->post('/ordens-operacionais/configuracao', $this->policy)->assertSessionHasNoErrors()->assertRedirect();
$this->actingAs($this->f['issuer'])->post('/ordens-operacionais', $this->input)->assertSessionHasNoErrors()->assertRedirect();
$order = SupplyRecord::query()->where('kind', 'op_order')->firstOrFail();
$request = $this->f['r'];
$request->update(['status' => 'draft']);
app(OperationalOrders::class)->link($this->f['issuer'], $request, ['item_id' => $request->items()->sole()->id, 'order_id' => $order->id,
'version' => 0, 'reason' => 'Origem sintética ligada para a consulta limitada.', 'operation_key' => (string) Str::uuid()]);
$this->post('/ordens-operacionais', [...$this->input, 'reference' => 'UNLINKED-PRIVATE-ORDER', 'operation_key' => (string) Str::uuid()])->assertSessionHasNoErrors()->assertRedirect();
$request->update(['status' => 'approved']);
$metadata = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($metadata, ['audit_metadata_read']);
supplyGrant($finance, ['finance']);
$this->actingAs($metadata)->get('/ordens-operacionais')->assertForbidden();
$this->get('/requisicoes/'.$request->id.'/ordens-operacionais')->assertNotFound();
$this->actingAs($finance)->get('/ordens-operacionais')->assertForbidden();
$this->get('/requisicoes/'.$request->id.'/ordens-operacionais')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('canLink', false)->has('orders.data', 1)->where('orders.data.0.id', $order->id)->has('links', 1));
});
@@ -160,13 +160,16 @@ test('tax configuration is versioned tenant scoped and never rewrites existing p
});
test('comparison policy requires valid weights authority and current version without rewriting existing processes', function () {
$body = ['version' => 1, 'minimum_proposals' => 2, 'minimum_evaluators' => 1, 'weights' => ['price' => 50, 'quality' => 20, 'delivery' => 10, 'history' => 10, 'payment' => 10], 'reason' => 'Regra comercial aprovada para novos processos.'];
$body = ['version' => 1, 'minimum_proposals' => 2, 'minimum_evaluators' => 1, 'urgent_minimum_proposals' => 1, 'weights' => ['price' => 50, 'quality' => 20, 'delivery' => 10, 'history' => 10, 'payment' => 10], 'reason' => 'Regra comercial aprovada para novos processos.'];
$this->postJson($this->base.'/comparison', [...$body, 'weights' => [...$body['weights'], 'price' => 49]])->assertUnprocessable();
expect($this->f['tenant']->fresh()->comparison_policy)->toBeNull();
$this->postJson($this->base.'/comparison', [...$body, 'minimum_evaluators' => 0])->assertUnprocessable();
$this->postJson($this->base.'/comparison', [...$body, 'urgent_minimum_proposals' => 0])->assertUnprocessable();
$this->postJson($this->base.'/comparison', [...$body, 'urgent_minimum_proposals' => 2])->assertUnprocessable();
$this->postJson($this->base.'/comparison', [...$body, 'weights' => [...$body['weights'], 'other' => 0]])->assertUnprocessable();
$this->postJson($this->base.'/comparison', $body)->assertRedirect();
expect($this->f['tenant']->fresh()->comparison_policy['revision'])->toBe(1)->and($this->f['r']->fresh()->comparison_policy)->toBeNull();
expect($this->f['tenant']->fresh()->comparison_policy['urgent_minimum_proposals'])->toBe(1);
$this->postJson($this->base.'/comparison', $body)->assertUnprocessable();
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('comparisonPolicy.minimum_proposals', 2));
expect(AuditLog::query()->where('action', 'organization.comparison')->count())->toBe(1);
+59
View File
@@ -0,0 +1,59 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
$this->f = receiptFixture();
$this->actor = $this->f['issuer'];
$this->actingAs($this->actor);
$this->access = app(PrivateAuditAccess::class);
});
test('private audit requires its explicit family authority and never inherits metadata finance or administration', function (string $permission) {
config(['private-audit.qa_enabled' => true]);
supplyGrant($this->actor, [$permission]);
expect(fn () => $this->access->authorise($this->actor, ['finance']))->toThrow(HttpException::class);
})->with(['audit_metadata_read', 'finance', 'admin']);
test('private audit family grants remain independent and cannot activate banking people or financial commands', function () {
config(['private-audit.qa_enabled' => true]);
supplyGrant($this->actor, ['audit_private_finance_read']);
$scope = $this->access->authorise($this->actor, ['finance', 'finance']);
expect($scope['families'])->toBe(['finance'])->and($scope['context'])->toBe('legacy')
->and($this->actor->hasFunctions(['finance', 'admin', 'procurement']))->toBeFalse();
expect(fn () => $this->access->authorise($this->actor, ['purchasing']))->toThrow(HttpException::class);
expect(fn () => $this->access->authorise($this->actor, ['complete_bank_identifiers']))->toThrow(HttpException::class);
expect(fn () => $this->access->authorise($this->actor, ['people']))->toThrow(HttpException::class);
$this->get('/auditoria/eventos')->assertForbidden();
$this->get('/orcamentos')->assertForbidden();
});
test('private audit revalidates membership expiry revocation and maintenance without updating company rights', function () {
config(['private-audit.qa_enabled' => true]);
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
$before = DB::table('organization_memberships')->orderBy('id')->get()->toJson();
expect($this->access->authorise($this->actor, ['stock', 'purchasing', 'finance', 'configuration'])['families'])
->toBe(['configuration', 'finance', 'purchasing', 'stock']);
expect(DB::table('organization_memberships')->orderBy('id')->get()->toJson())->toBe($before);
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => null, 'maintenance' => true]);
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
DB::table('organization_memberships')->where('user_id', $this->actor->id)->delete();
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
});
test('private audit capability is disabled by default and the caller cannot select a different actor', function () {
supplyGrant($this->actor, ['audit_private_stock_read']);
expect(fn () => $this->access->authorise($this->actor, ['stock']))->toThrow(HttpException::class);
config(['private-audit.qa_enabled' => true]);
$other = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'purchasing_role' => PurchasingRole::Configured]);
expect(fn () => $this->access->authorise($other, ['stock']))->toThrow(HttpException::class);
});
+159
View File
@@ -0,0 +1,159 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\PrivateAuditExport;
use App\Models\SupplierDocument;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditExporter;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['private-audit.qa_enabled' => true]);
Storage::fake('local');
Storage::fake('supplier_documents');
Storage::fake('receipt_documents');
$this->f = receiptFixture();
$this->actor = $this->f['issuer'];
$this->actingAs($this->actor);
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
if (DB::getDriverName() === 'pgsql') {
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Audit fixtures require the owned disposable PostgreSQL database.');
}
DB::commit();
$this->committedAuditFixture = true;
}
});
afterEach(function () {
if ($this->committedAuditFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Audit fixture cleanup requires its disposable PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
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();
$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);
$path = $service->verifiedPath($this->actor, $export);
$zip = new ZipArchive;
expect($zip->open($path, ZipArchive::RDONLY))->toBeTrue();
try {
$manifest = json_decode($zip->getFromName('manifesto.json'), true, 512, JSON_THROW_ON_ERROR);
expect($manifest['families'])->toHaveCount(4);
foreach ($manifest['datasets'] as $dataset) {
if ($dataset['state'] === 'not_installed') {
expect($dataset['records'])->toBeNull();
continue;
}
$bytes = $zip->getFromName($dataset['file']);
expect($bytes)->toBeString()
->and(strlen($bytes))->toBe($dataset['size'])
->and(hash('sha256', $bytes))->toBe($dataset['sha256'])
->and(substr_count($bytes, "\n"))->toBe($dataset['records']);
}
} finally {
$zip->close();
}
expect($service->generate($this->actor, $input)->id)->toBe($export->id)
->and(PrivateAuditExport::query()->count())->toBe(1)
->and(DB::table('audit_logs')->where('action', 'audit.private_export_generated')->count())->toBe(1)
->and(DB::table('purchase_orders')->orderBy('id')->get()->toJson())->toBe($before)
->and(Storage::disk('local')->allFiles())->toBe([$export->path]);
try {
$service->generate($this->actor, [...$input, 'purpose' => 'Changed purpose']);
test()->fail('A different request must not reuse the operation.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(409);
}
});
test('private audit refuses changed package bytes and revoked family authority', function () {
$service = app(PrivateAuditExporter::class);
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']]);
Storage::disk('local')->append($export->path, 'CORRUPTED-SYNTHETIC-QA');
try {
$service->verifiedPath($this->actor, $export);
test()->fail('Changed bytes must be refused.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(409);
}
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
try {
$service->verifiedPath($this->actor, $export);
test()->fail('Revocation must be effective before download.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(403);
}
});
test('private audit verifies original bytes and cleans only its own incomplete preparation', function () {
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
$supplier = $this->f['order']->supplier_id;
$path = $this->actor->tenant_id.'/'.$supplier.'/original.png';
Storage::disk('supplier_documents')->put($path, $bytes);
$document = SupplierDocument::query()->create(['tenant_id' => $this->actor->tenant_id, 'supplier_id' => $supplier,
'uploaded_by' => $this->actor->id, 'document_type' => 'other', 'original_name' => 'original.png', 'path' => $path,
'mime_type' => 'image/png', 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes)]);
$service = app(PrivateAuditExporter::class);
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing']]);
$zip = new ZipArchive;
$zip->open($service->verifiedPath($this->actor, $export), ZipArchive::RDONLY);
try {
expect($zip->getFromName('originais/purchasing/supplier_documents/'.$document->id.'.png'))->toBe($bytes);
} finally {
$zip->close();
}
Storage::disk('local')->put('unrelated/keep.txt', 'PRESERVE');
$before = Storage::disk('local')->allFiles();
Storage::disk('supplier_documents')->put($path, 'ALTERED');
try {
$service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing']]);
test()->fail('An altered original must prevent a ready package.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(409);
}
expect(PrivateAuditExport::query()->count())->toBe(1)
->and(Storage::disk('local')->allFiles())->toBe($before)
->and(Storage::disk('supplier_documents')->get($path))->toBe('ALTERED');
});
test('private audit HTTP preparation download and private headers preserve verified response bytes', function () {
$this->withoutVite();
$this->get('/auditoria/privada')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$this->post('/auditoria/privada', ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']])->assertRedirect('/auditoria/privada')->assertSessionHasNoErrors();
$export = PrivateAuditExport::query()->sole();
$response = $this->get('/auditoria/privada/'.$export->id.'/download')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
Storage::disk('local')->append($export->path, 'LATER-CHANGE');
expect(hash('sha256', $response->streamedContent()))->toBe($export->sha256);
$this->get('/auditoria/privada/'.$export->id.'/download')->assertStatus(409);
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
$this->get('/auditoria/privada')->assertForbidden();
$this->get('/auditoria/privada/'.$export->id.'/download')->assertForbidden();
});
test('private audit packages remain personal to their creator even within the same authorised company', function () {
$service = app(PrivateAuditExporter::class);
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']]);
$other = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'department_id' => $this->actor->department_id,
'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($other, ['audit_private_configuration_read']);
$this->actingAs($other)->get('/auditoria/privada/'.$export->id.'/download')->assertNotFound();
$this->withoutVite()->get('/auditoria/privada')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['exports']['data'] === []);
expect(PrivateAuditExport::query()->count())->toBe(1);
});
+138
View File
@@ -0,0 +1,138 @@
<?php
use App\Models\AuditLog;
use App\Models\Department;
use App\Models\SupplierBankDetail;
use App\Models\SupplyRecord;
use App\Models\Tenant;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditSourceReader;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['private-audit.qa_enabled' => true]);
$this->f = receiptFixture();
$this->actor = $this->f['issuer'];
$this->actingAs($this->actor);
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
if (DB::getDriverName() === 'pgsql') {
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Audit source fixtures require the disposable PostgreSQL database.');
}
DB::commit();
$this->committedAuditSourceFixture = true;
}
});
afterEach(function () {
if ($this->committedAuditSourceFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Audit source cleanup requires its disposable PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
/** Test collector only; the production packager consumes each generator directly. */
function collectedPrivateAuditSources(User $actor, array $families): array
{
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 0) {
return DB::transaction(function () use ($actor, $families) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return collectedPrivateAuditSources($actor, $families);
});
}
$result = [];
foreach (app(PrivateAuditSourceReader::class)->datasets($actor, $families) as $dataset) {
$rows = $dataset['rows'];
$result[$dataset['family'].':'.$dataset['source']] = [...$dataset, 'rows' => $rows === null ? null : iterator_to_array($rows, false)];
}
return $result;
}
test('private audit source pagination includes every selected company row and no other company data', function () {
for ($index = 0; $index < 131; $index++) {
Department::query()->create(['tenant_id' => $this->actor->tenant_id, 'name' => 'AUDIT-DEPARTMENT-'.str_pad((string) $index, 3, '0', STR_PAD_LEFT)]);
}
$foreign = Tenant::query()->create(['name' => 'FOREIGN-AUDIT-COMPANY']);
Department::query()->create(['tenant_id' => $foreign->id, 'name' => 'FOREIGN-AUDIT-DEPARTMENT']);
$before = DB::table('departments')->orderBy('id')->get()->toJson();
$sources = collectedPrivateAuditSources($this->actor, ['configuration']);
$rows = $sources['configuration:departments']['rows'];
expect($rows)->toHaveCount(132)
->and(array_column($rows, 'name'))->toContain('AUDIT-DEPARTMENT-130')
->and(json_encode($sources, JSON_THROW_ON_ERROR))->not->toContain('FOREIGN-AUDIT-DEPARTMENT')->not->toContain('FOREIGN-AUDIT-COMPANY')
->and(DB::table('departments')->orderBy('id')->get()->toJson())->toBe($before);
});
test('private audit preserves ordinary data while excluding bank coordinates credentials people payloads and storage paths', function () {
$this->f['tenant']->update(['company_details' => ['legal_name' => 'AUDIT-LEGAL-NAME', 'bank_accounts' => [['account_number' => 'BANK-FULL-NEVER-EXPORT']], 'establishments' => [['name' => 'AUDIT-LOCATION']]]]);
SupplierBankDetail::query()->create(['tenant_id' => $this->actor->tenant_id, 'supplier_id' => $this->f['order']->supplier_id,
'created_by' => $this->actor->id, 'revision' => 1, 'bank_name' => 'PRIVATE-BANK-NOT-IN-SCOPE', 'country' => 'MZ', 'currency' => 'MZN',
'beneficiary' => 'PRIVATE-BANK-HOLDER', 'account_identifier' => 'BANK-FULL-NEVER-EXPORT', 'evidence_reference' => 'PRIVATE-BANK-EVIDENCE', 'reason' => 'Synthetic bank record outside the approved audit scope.', 'created_at' => now()]);
$snapshot = [...$this->f['order']->snapshot, 'bank_snapshot' => ['account_identifier' => 'BANK-NESTED-NEVER-EXPORT'], 'api_key' => 'API-KEY-NEVER-EXPORT'];
// Synthetic exclusion markers only; documentary values and financial amounts remain unchanged.
DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR)]);
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => 'people.application.created',
'after' => ['candidate_document' => 'PEOPLE-PRIVATE-NEVER-EXPORT'], 'created_at' => now()]);
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => 'organization.profile',
'before' => null, 'after' => ['name' => 'AUDIT-PROFILE-NAME', 'permissions' => ['procurement'], 'password' => 'PASSWORD-NEVER-EXPORT', 'unmapped_private_payload' => 'UNKNOWN-PRIVATE-NEVER-EXPORT'], 'created_at' => now()]);
$sources = collectedPrivateAuditSources($this->actor, ['configuration', 'purchasing', 'stock', 'finance']);
$body = json_encode($sources, JSON_THROW_ON_ERROR);
expect($body)->toContain('AUDIT-LEGAL-NAME')->toContain('AUDIT-LOCATION')->toContain('AUDIT-PROFILE-NAME')
->not->toContain('BANK-FULL-NEVER-EXPORT')->not->toContain('BANK-NESTED-NEVER-EXPORT')
->not->toContain('PRIVATE-BANK-NOT-IN-SCOPE')->not->toContain('PRIVATE-BANK-EVIDENCE')
->not->toContain('API-KEY-NEVER-EXPORT')->not->toContain('PASSWORD-NEVER-EXPORT')
->not->toContain('PEOPLE-PRIVATE-NEVER-EXPORT')->not->toContain('UNKNOWN-PRIVATE-NEVER-EXPORT');
foreach ($sources['configuration:users']['rows'] as $user) {
expect($user)->not->toHaveKey('password')->not->toHaveKey('two_factor_secret')->not->toHaveKey('remember_token');
}
$event = collect($sources['configuration:audit_logs']['rows'])->firstWhere('action', 'organization.profile');
expect($event)->toHaveKey('after_projected')->not->toHaveKey('after');
});
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) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$sources = collectedPrivateAuditSources($this->actor, ['finance']);
expect($sources['finance:external_payments']['state'])->toBe('available')
->and($sources['finance:external_payments']['rows'])->toBe([]);
if (! DB::getSchemaBuilder()->hasTable('pa_obligations')) {
expect($sources['finance:pa_obligations']['state'])->toBe('not_installed')
->and($sources['finance:pa_obligations']['rows'])->toBeNull();
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('private audit includes versioned import document metadata but excludes bank specific documents', function () {
foreach (['packing_list', 'bank_commitment', 'bank_support'] as $type) {
SupplyRecord::query()->create(['tenant_id' => $this->actor->tenant_id, 'kind' => 'import_document',
'record_key' => (string) Str::uuid(), 'version' => 1, 'state' => 'recorded',
'purchase_order_id' => $this->f['order']->id, 'created_by' => $this->actor->id,
'data' => ['type' => $type, 'reference' => 'SYNTHETIC-'.$type],
'snapshot' => ['evidence' => ['path' => 'PRIVATE-PATH-NEVER-EXPORT', 'sha256' => hash('sha256', $type)]],
'reason' => 'Synthetic metadata scope regression; no document download is requested.',
'operation_key' => (string) Str::uuid(), 'input_hash' => hash('sha256', $type), 'created_at' => now()]);
}
$sources = collectedPrivateAuditSources($this->actor, ['purchasing']);
$rows = $sources['purchasing:supply_records']['rows'];
expect($rows)->toHaveCount(1)
->and($rows[0]['data']['type'])->toBe('packing_list')
->and($rows[0]['version'])->toBe(1)
->and($rows[0]['purchase_order_id'])->toBe($this->f['order']->id)
->and(json_encode($rows, JSON_THROW_ON_ERROR))->not->toContain('bank_commitment')->not->toContain('bank_support')->not->toContain('PRIVATE-PATH-NEVER-EXPORT');
});
+89
View File
@@ -41,6 +41,7 @@ use App\Services\EquipmentWorkflow;
use App\Services\FormalAdmission;
use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OperationalOrders;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAmendments;
@@ -62,6 +63,7 @@ use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\UrgentQuotationBasis;
use App\Services\WorkflowTaskInbox;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
@@ -97,6 +99,93 @@ function nativeCapitalAssignment(object $test, string $type = 'project'): array
return [$source, $assignment, $input];
}
test('native orders freeze their production origin in normal and partial issuance', function (bool $partial) {
if ($partial && ! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
}
config(['operational-orders.qa_enabled' => true]);
$service = app(OperationalOrders::class);
$this->actingAs($this->admin);
$service->configure($this->admin, ['version' => 0, 'mode' => 'procurement', 'reason' => 'Origem sintética pelo procurement sem locais abrangidos.', 'operation_key' => (string) Str::uuid()]);
$this->actingAs($this->buyer);
$source = $service->save($this->buyer, ['type' => 'production', 'reference' => 'PRODUCTION-ORIGIN-QA', 'department_id' => $this->department->id,
'utilisation_location' => 'Linha sintética de utilização', 'description' => 'Trabalho fictício preservado na ordem de compra.', 'reason' => 'Registo sintético de produção para teste nativo.', 'policy_version' => 1, 'operation_key' => (string) Str::uuid()]);
// Add the source selected while the existing pre-approved synthetic fixture was a draft.
$this->r->update(['status' => 'draft']);
$this->actingAs($this->owner);
$link = $service->link($this->owner, $this->r, ['item_id' => $this->item->id, 'order_id' => $source->id, 'version' => 0, 'reason' => 'Origem documental escolhida pelo requisitante sintético.', 'operation_key' => (string) Str::uuid()]);
$this->r->update(['status' => 'approved']);
$this->actingAs($this->buyer);
if ($partial) {
$award = nativeOrderPartsAward($this);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
} else {
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
}
expect($order->snapshot['operational_orders'][$this->item->id]['id'])->toBe($link->id)
->and($order->snapshot['operational_orders'][$this->item->id]['snapshot']['source']['id'])->toBe($source->id)
->and($order->total_minor)->toBe($partial ? 4000 : 10000);
$this->actingAs($this->admin);
$service->configure($this->admin, ['version' => 1, 'mode' => 'utilisation', 'reason' => 'Configuração posterior que conserva a origem anterior.', 'operation_key' => (string) Str::uuid()]);
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRODUCTION-ORIGIN-QA')->assertSee('Registada pelo procurement')->assertSee('Linha sintética de utilização');
expect($order->fresh()->snapshot['operational_orders'][$this->item->id]['snapshot']['source']['snapshot']['policy']['data']['mode'])->toBe('procurement');
})->with([false, true]);
test('native urgent order uses only the configured reduced eligible count and preserves stock evidence with independent approvals', function (bool $partial) {
if ($partial && ! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
}
config(['urgent-quotations.qa_enabled' => true]);
$this->actingAs($this->admin);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->admin->id, 'code' => 'URGENT-STOCK-QA', 'name' => $this->item->description, 'unit' => $this->item->unit]);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->admin->id, 'code' => 'URGENT-WH-QA', 'name' => 'Local sintético da urgência']);
app(RequisitionCatalogue::class)->save($this->admin, $stock->id, ['version' => 0, 'stock_basis' => app(RequisitionCatalogue::class)->basis($stock),
'category' => 'Material', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Catálogo sintético antes da redução urgente.']);
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $stock->id)->sole();
$this->actingAs($this->owner);
$resolved = app(RequisitionCatalogue::class)->line($this->owner, ['catalogue_entry_id' => $entry->id, 'catalogue_version' => 1], []);
$this->item->update(['catalogue_entry_id' => $entry->id, 'catalogue_snapshot' => $resolved['catalogue_snapshot']]);
// The initial approved request/three offers are synthetic fixtures. Only one supplier remains eligible before adjudication.
$this->r->update(['priority' => 'urgent', 'justification' => 'Risco sintético de paragem por falta de material no local de utilização.',
'comparison_policy' => app(ComparisonPolicy::class)->checked([...ComparisonPolicy::DEFAULTS, 'configured' => true, 'revision' => 1, 'urgent_minimum_proposals' => 1])]);
foreach ([$this->suppliers[1], $this->suppliers[2]] as $supplier) {
$supplier->update(['status' => 'suspended']);
}
foreach ([$this->owner, $this->buyer, $this->secondBuyer, $this->head, $this->finance, $this->admin] as $person) {
supplyGrant($person, [$person->purchasing_role->value, ...($person->id === $this->buyer->id ? ['supply_prepare'] : []), ...($person->id === $this->finance->id ? ['supply_review'] : [])]);
}
$this->actingAs($this->buyer);
$planning = app(SupplyPlanning::class);
$draft = $planning->save($this->buyer, 'policy', supplyInput(supplyPolicy(['stock' => $stock, 'warehouse' => $warehouse])));
$this->actingAs($this->finance);
$policy = $planning->save($this->finance, 'policy', supplyInput([], 'approve', $draft));
$this->actingAs($this->buyer);
expect(app(ProposalComparison::class)->inspect($this->r)['ready'])->toBeFalse();
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors('comparison');
expect(PurchaseAward::query()->count())->toBe(0);
$proof = app(UrgentQuotationBasis::class)->record($this->buyer, $this->r, ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0,
'reason' => 'URGENT-MINIMUM-NATIVE-QA: mínimo atingido no local sintético.', 'operation_key' => (string) Str::uuid()]);
$comparison = app(ProposalComparison::class)->inspect($this->r);
expect($comparison['ready'])->toBeTrue()->and(count(array_filter($comparison['rows'], fn ($row) => $row['eligible'])))->toBe(1)
->and($comparison['policy']['minimum_evaluators'])->toBe(2);
if ($partial) {
$award = nativeOrderPartsAward($this);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
} else {
$award = selectPurchaseAward($this);
$this->actingAs($this->owner)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
$this->actingAs($this->buyer);
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
$order = issuePurchaseOrder($this, $award);
}
expect($order->snapshot['urgent_quotation_basis'][0]['id'])->toBe($proof->id)
->and($order->snapshot['comparison_policy']['minimum_proposals'])->toBe(1)
->and($order->snapshot['comparison_policy']['normal_minimum_proposals'])->toBe(3)
->and($order->total_minor)->toBe($partial ? 4000 : 10000);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('URGENT-MINIMUM-NATIVE-QA')->assertSee('Local sintético da urgência');
expect($award->approvals()->where('decision', 'approved')->count())->toBeGreaterThan(0);
})->with([false, true]);
test('native order preserves the capital destination and print after the independent register is archived', function () {
[$source, $assignment, $input] = nativeCapitalAssignment($this);
$award = selectPurchaseAward($this);
+21
View File
@@ -12,6 +12,27 @@ require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
test('minimum stock is explicitly configured for the item and its documented use without a fixed universal value', function () {
$f = receiptFixture();
supplyGrant($f['issuer'], ['supply_prepare']);
supplyGrant($f['receiver'], ['supply_review']);
$service = app(SupplyPlanning::class);
$this->actingAs($f['issuer']);
$input = [...supplyPolicy($f), 'purpose' => 'internal', 'minimum_stock_milli' => 25000,
'usage_context' => 'Insumo sintético usado diariamente na linha de produção.', 'basis' => 'Mínimo parametrizado pela natureza do artigo e utilização diária documentada.'];
$draft = $service->save($f['issuer'], 'policy', supplyInput($input));
$this->actingAs($f['receiver']);
$approved = $service->save($f['receiver'], 'policy', supplyInput([], 'approve', $draft));
expect($approved->data['minimum_stock_milli'])->toBe(25000)
->and($approved->data['usage_context'])->toBe($input['usage_context'])
->and($approved->snapshot['item']['id'])->toBe($f['stock']->id);
$before = $approved->fresh()->toArray();
$this->actingAs($f['issuer']);
$alternative = $service->save($f['issuer'], 'policy', supplyInput([...$input, 'minimum_stock_milli' => 35000, 'usage_context' => 'Uso intensivo sintético que exige outro mínimo.']));
expect($alternative->data['minimum_stock_milli'])->toBe(35000)
->and($approved->fresh()->toArray())->toBe($before);
});
test('calendar keeps stock risk but withdraws deadlines when the reused agreement expires or supplier changes', function () {
$f = receiptFixture();
supplyGrant($f['issuer'], ['supply_prepare']);
+125
View File
@@ -0,0 +1,125 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ComparisonPolicy;
use App\Services\ProposalComparison;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionCatalogue;
use App\Services\SupplyPlanning;
use App\Services\UrgentQuotationBasis;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['receiver']);
$catalogue = app(RequisitionCatalogue::class);
$catalogue->save($this->f['receiver'], $this->f['stock']->id, ['version' => 0, 'stock_basis' => $catalogue->basis($this->f['stock']),
'category' => 'Material', 'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Artigo sintético publicado para prova de mínimo.']);
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $this->f['stock']->id)->sole();
$this->actingAs($this->f['issuer']);
$resolved = $catalogue->line($this->f['issuer'], ['catalogue_entry_id' => $entry->id, 'catalogue_version' => 1], []);
$this->request = Requisition::query()->create([...$this->f['r']->only(['tenant_id', 'requester_id', 'department_id', 'cost_center_id', 'needed_by', 'subtotal_minor', 'tax_minor', 'total_minor']),
'number' => 'URGENT-STOCK-QA', 'priority' => 'urgent', 'status' => 'approved', 'justification' => 'Risco sintético de paragem da produção por falta de material.',
'comparison_policy' => app(ComparisonPolicy::class)->checked([...ComparisonPolicy::DEFAULTS, 'configured' => true, 'revision' => 1, 'urgent_minimum_proposals' => 1])]);
$sourceItem = $this->f['r']->items()->sole();
$this->item = $this->request->items()->create([...$sourceItem->only(['tenant_id', 'description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor']),
'catalogue_entry_id' => $entry->id, 'catalogue_snapshot' => $resolved['catalogue_snapshot']]);
supplyGrant($this->f['issuer'], ['procurement', 'supply_prepare']);
supplyGrant($this->f['receiver'], ['warehouse', 'supply_review']);
$this->url = '/requisicoes/'.$this->request->id.'/urgencia-stock';
$this->withoutPolicy = app(ProposalComparison::class)->inspect($this->request);
});
function urgentApprovedStockPolicy(object $test, int $minimum = 20000): SupplyRecord
{
$planning = app(SupplyPlanning::class);
$test->actingAs($test->f['issuer']);
$draft = $planning->save($test->f['issuer'], 'policy', supplyInput([...supplyPolicy($test->f), 'safety_milli' => 0, 'minimum_stock_milli' => $minimum,
'usage_context' => 'Insumo sintético de utilização diária na produção.']));
$test->actingAs($test->f['receiver']);
return $planning->save($test->f['receiver'], 'policy', supplyInput([], 'approve', $draft));
}
test('urgent reduction requires an explicit count and actual company stock minimum evidence for every current line', function () {
config(['urgent-quotations.qa_enabled' => true]);
$policy = urgentApprovedStockPolicy($this);
$input = ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0, 'reason' => 'Conferência sintética de stock mínimo atingido e risco de paragem.', 'operation_key' => (string) Str::uuid()];
$before = [];
foreach (['stock_movements', 'budget_entries', 'purchase_orders', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->actingAs($this->f['issuer']);
expect(app(ProposalComparison::class)->inspect($this->request)['policy']['minimum_proposals'])->toBe(3);
$this->post($this->url, $input)->assertSessionHasNoErrors()->assertRedirect();
$this->post($this->url, $input)->assertSessionHasNoErrors()->assertRedirect();
$service = app(UrgentQuotationBasis::class);
$proof = $service->eligible($this->request);
expect($proof)->toHaveCount(1)
->and($proof[0]['snapshot']['availability']['at_minimum'])->toBeTrue()
->and($proof[0]['snapshot']['stock_policy']['minimum_stock_milli'])->toBe(20000);
$comparison = app(ProposalComparison::class)->inspect($this->request);
expect($comparison['policy']['minimum_proposals'])->toBe(1)
->and($comparison['policy']['normal_minimum_proposals'])->toBe(3)
->and($comparison['policy']['minimum_evaluators'])->toBe(2)
->and($comparison['fingerprint'])->not->toBe($this->withoutPolicy['fingerprint']);
$response = $this->get($this->url)->assertOk()->assertInertia(fn (Assert $page) => $page->component('requisitions/urgent-stock')->has('eligible', 1));
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
$this->post($this->url, [...$input, 'operation_key' => (string) Str::uuid()])->assertConflict();
$reader = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($reader, ['finance']);
$this->actingAs($reader)->get($this->url)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canRecord', false)->has('policies.data', 0)->has('evidence', 1));
$this->actingAs($this->f['issuer']);
$this->request->setAttribute('approval_cycle', 2);
expect($service->eligible($this->request))->toBe([]);
$this->request->setAttribute('approval_cycle', 1);
$this->item->update(['description' => 'Linha alterada exige nova conferência de origem.']);
expect($service->eligible($this->request))->toBe([])
->and(app(ProposalComparison::class)->inspect($this->request)['policy']['minimum_proposals'])->toBe(3);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('unmet minimum and unauthorised actors cannot obtain the urgent quotation reduction', function () {
config(['urgent-quotations.qa_enabled' => true]);
$policy = urgentApprovedStockPolicy($this, 500);
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$input = ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0, 'reason' => 'Tentativa sintética antes de atingir o mínimo.', 'operation_key' => (string) Str::uuid()];
$this->actingAs($this->f['issuer'])->post($this->url, $input)->assertSessionHasErrors('policy_id');
expect(app(UrgentQuotationBasis::class)->eligible($this->request))->toBe([]);
$this->actingAs($this->f['receiver'])->post($this->url, $input)->assertNotFound();
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($finance, ['finance']);
$this->actingAs($finance)->post($this->url, $input)->assertForbidden();
$this->actingAs($this->f['issuer']);
$this->request->update(['priority' => 'normal']);
$this->post($this->url, $input)->assertStatus(422);
config(['urgent-quotations.qa_enabled' => false]);
$this->post($this->url, $input)->assertStatus(503);
});
test('urgent minimum is optional strictly positive and lower than the normal company count', function () {
$service = app(ComparisonPolicy::class);
expect($service->checked(ComparisonPolicy::DEFAULTS))->toBe(ComparisonPolicy::DEFAULTS);
foreach ([0, 3, 4] as $value) {
expect(fn () => $service->checked([...ComparisonPolicy::DEFAULTS, 'urgent_minimum_proposals' => $value]))->toThrow(ValidationException::class);
}
config(['urgent-quotations.qa_enabled' => true]);
$policy = urgentApprovedStockPolicy($this);
$this->request->update(['comparison_policy' => ComparisonPolicy::DEFAULTS]);
$this->actingAs($this->f['issuer'])->post($this->url, ['item_id' => $this->item->id, 'policy_id' => $policy->id, 'version' => 0,
'reason' => 'Não pode inferir um número urgente não configurado.', 'operation_key' => (string) Str::uuid()])->assertStatus(422);
});
@@ -5,6 +5,7 @@ use App\Http\Controllers\AuditMetadataController;
use App\Models\CostCenter;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\PrivateAuditAccess;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
@@ -41,6 +42,7 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
$profiles = [];
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
$functions['private_auditor'] = array_column(PrivateAuditAccess::FAMILIES, 'permission');
if ($officeJourney) {
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
'office_procurement_reviewer' => ['procurement']];
@@ -250,7 +252,7 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
'office_journey' => $office,
'integrated_optional_schema' => $composition,
'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
'synthetic_private_audit_login' => $people['private_auditor']->email, 'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
'audit_request_reference' => $historyRequest->number, 'audit_native_readonly_transactions' => $readonlyTransactions,
'search_agreement' => $agreement->id, 'search_contract' => $contract->id, 'warehouse_search_request' => $internal->id,
'historical_decision_request' => $historyRequest->id, 'historical_decision_verified' => true,
+5 -1
View File
@@ -8,6 +8,7 @@ test('owned native client drains large closed responses while preserving body he
let cookiesSeen = '';
const server = createServer((request, response) => {
response.setHeader('Connection', 'close');
response.useChunkedEncodingByDefault = false;
if (request.url === '/cookies') {
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
}
@@ -15,7 +16,8 @@ test('owned native client drains large closed responses while preserving body he
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
cookiesSeen = request.headers.cookie ?? '';
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(payload));
response.write(JSON.stringify(payload));
response.end();
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
@@ -26,6 +28,8 @@ test('owned native client drains large closed responses while preserving body he
assert.equal(first.status, 200);
assert.equal(first.bodyUsed, false);
assert.equal(first.url, origin + '/large');
assert.equal(first.headers.get('Content-Length'), null);
assert.equal(first.headers.get('Transfer-Encoding'), null);
await client.request('/cookies');
const next = await client.request('/large');
assert.match(cookiesSeen, /QA_SESSION=first/);
@@ -35,6 +35,7 @@ $app->booted(function () use ($root, $database) {
CarbonImmutable::setTestNow($fixture['clock']);
config(['requisition-expiry.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true,
'order_cancellation.enabled' => true,
'operational-orders.qa_enabled' => true, 'urgent-quotations.qa_enabled' => true, 'private-audit.qa_enabled' => true,
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
'procurement_search.warehouse_requests_metadata_enabled' => true,
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
@@ -28,6 +28,13 @@ function render(
context = 'finance',
canCorrect = true,
sourceId = 3,
canAuthoriseRelease = false,
release: {
id: number;
authorised_by: number;
authorised_at: string;
reason: string;
} | null = null,
) {
return renderToStaticMarkup(
<App
@@ -51,6 +58,8 @@ function render(
organizationAccess: { permissions: ['finance'] },
history: [{ ...declaration, id: sourceId }],
canCorrect,
canAuthoriseRelease,
release,
declarations: {
data: [],
prev_page_url: null,
@@ -63,6 +72,42 @@ function render(
/>,
);
}
test('direction release preparation requires explicit capability and never submits on recovery', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
`${identity}:correction:3:${declaration.declared_at}:false:release:data`
? {
reason: 'DIRECTION-RELEASE-DRAFT',
operation_key: 'synthetic-operation',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render(true, 7, 4, 'finance', false, 3, true);
expect(html).toContain('DIRECTION-RELEASE-DRAFT');
expect(html).toContain('Autorizar levantamento');
expect(html).toContain('data-preparation-dirty="true"');
expect(render(true, 8, 4, 'finance', false, 3, true)).not.toContain(
'DIRECTION-RELEASE-DRAFT',
);
expect(render(true, 7, 4, 'finance', false, 3, false)).not.toContain(
'Autorizar levantamento',
);
expect(post).not.toHaveBeenCalled();
});
test('released declaration retains its history and shows the direction decision', () => {
const html = render(true, 7, 4, 'finance', false, 3, false, {
id: 1,
authorised_by: 9,
authorised_at: '2026-11-28T09:00:00Z',
reason: 'DIRECTION-AUTHORISED-QA',
});
expect(html).toContain('Impedimento levantado pela direcção');
expect(html).toContain('Original synthetic conflict');
expect(html).toContain('DIRECTION-AUTHORISED-QA');
expect(html).not.toContain('Autorizar levantamento</button>');
});
test('personal declaration preparation remains private to its actor company and context without submitting', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:new:data`
+37 -1
View File
@@ -3,7 +3,12 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Legal from '../../resources/js/pages/supply/import-legal';
function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
function renderLegal(
canManage: boolean,
withRule = true,
withCharges = false,
withReference = false,
) {
const data = {
title: '<script>synthetic rule</script>',
official_reference: 'Synthetic official edition',
@@ -58,6 +63,25 @@ function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
encryptHistory: true,
props: {
errors: {},
referenceDrafts: withReference
? [
{
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',
official_url: null,
citation: 'Página 2180-(4)',
valid_from: '2026-01-01',
obligations:
'Conferir o exemplar e o regime aplicável',
charges: [],
},
]
: [],
requisition: { id: 1, number: 'QA' },
rules: page,
history: page,
@@ -78,6 +102,18 @@ function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
);
}
test('official reference preparation is explicit and only available to the customs preparer', () => {
const allowed = renderLegal(true, false, false, true);
expect(allowed).toContain('Preparar a partir do exemplar oficial');
expect(allowed).toContain('3506.91.20');
expect(allowed).toContain('taxa geral 20%');
expect(allowed).toContain('não é uma pauta consolidada');
expect(allowed).toContain('não substituir');
const reader = renderLegal(false, false, false, true);
expect(reader).not.toContain('Preparar a partir do exemplar oficial');
expect(reader).not.toContain('Silicone para selagem');
});
test('legal consultation escapes titles preserves periods and offers verified-source downloads without management controls', () => {
const html = renderLegal(false);
expect(html).toContain('&lt;script&gt;synthetic rule&lt;/script&gt;');
+142
View File
@@ -0,0 +1,142 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import OperationalOrders from '@/pages/requisitions/operational-orders';
import Summary from '@/components/operational-order-summary';
import { procurementNavigation } from '@/lib/procurement-navigation';
afterEach(() => vi.restoreAllMocks());
const source = {
id: 5,
version: 1,
created_at: '2026-11-28T10:00:00Z',
reason: 'Synthetic source',
data: {
type: 'production',
reference: 'SOURCE-ORDER-QA',
utilisation_location: 'Synthetic line',
description: '<script>private-test</script>',
department_id: 1,
},
snapshot: {
author: { name: 'Synthetic procurement' },
department: { name: 'Synthetic department' },
policy: { data: { mode: 'procurement' } },
},
};
function render(
actor = 7,
canConfigure = true,
allowedTypes = ['production', 'maintenance'],
linked = false,
) {
return renderToStaticMarkup(
<App
initialComponent={OperationalOrders}
initialPage={{
component: 'requisitions/operational-orders',
url: '/ordens-operacionais',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: {
user: {
id: actor,
tenant_id: 4,
name: 'Synthetic actor',
},
},
workContext: { active: 'procurement.internal' },
organizationAccess: {
permissions: ['procurement', 'requester'],
},
policy: {
id: 1,
version: 1,
data: { mode: 'procurement' },
},
canConfigure,
allowedTypes,
departments: [{ id: 1, name: 'Synthetic department' }],
orders: {
data: [source],
prev_page_url: null,
next_page_url: null,
},
requisition: linked
? { id: 3, number: 'REQ-QA', status: 'draft' }
: null,
items: linked
? [{ id: 8, description: 'Synthetic item' }]
: [],
links: [],
canLink: linked,
},
}}
/>,
);
}
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';
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:new:form:data`
? {
type: 'production',
reference: 'RESTORED-ORDER-DRAFT',
department_id: '1',
utilisation_location: 'Synthetic location',
description: 'Synthetic pending work',
reason: 'Synthetic pending reason',
policy_version: '1',
operation_key: '36cb64ea-0867-4be4-90ea-c0e114ec07b1',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('RESTORED-ORDER-DRAFT');
expect(html).toContain('data-preparation-dirty="true"');
expect(render(8)).not.toContain('RESTORED-ORDER-DRAFT');
expect(post).not.toHaveBeenCalled();
});
test('native capabilities control configuration creation and request linking independently', () => {
const html = render(7, false, [], true);
expect(html).not.toContain('Guardar origem das novas ordens');
expect(html).not.toContain('>Registar ordem</button>');
expect(html).toContain('Ligar ordem à linha');
expect(html).toContain('SOURCE-ORDER-QA');
expect(html).not.toContain('<script>private-test</script>');
});
test('order origin summary preserves the source responsibility and renders no empty section', () => {
expect(renderToStaticMarkup(<Summary />)).toBe('');
const html = renderToStaticMarkup(
<Summary
records={{
8: {
id: 9,
snapshot: {
item: { description: 'Synthetic item' },
source,
},
},
}}
/>,
);
expect(html).toContain('SOURCE-ORDER-QA');
expect(html).toContain('Synthetic procurement');
expect(html).toContain('Registada pelo procurement');
expect(html).not.toContain('<script>private-test</script>');
});
test('operational order navigation requires server readiness and an applicable capability', () => {
const has = (permissions: string[], ready: boolean) =>
procurementNavigation(permissions, false, undefined, false, ready)
.flatMap((group) => group.entries)
.some((entry) => entry.id === 'operational_orders');
expect(has(['production_order_prepare'], true)).toBe(true);
expect(has(['maintenance_order_prepare'], true)).toBe(true);
expect(has(['procurement'], false)).toBe(false);
expect(has(['finance'], true)).toBe(false);
});
+67
View File
@@ -0,0 +1,67 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import PrivateAudit from '@/pages/audit/private';
import { procurementNavigation } from '@/lib/procurement-navigation';
afterEach(() => vi.restoreAllMocks());
test('private audit preparation shows only granted families and does not submit on opening', () => {
const post = vi.spyOn(router, 'post');
const html = renderToStaticMarkup(
<App
initialComponent={PrivateAudit}
initialPage={{
component: 'audit/private',
url: '/auditoria/privada',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: {
user: {
id: 7,
tenant_id: 4,
name: 'Synthetic auditor',
},
},
organizationAccess: {
permissions: ['audit_private_stock_read'],
},
families: [{ key: 'stock', label: 'Stock autorizado' }],
exports: {
data: [],
prev_page_url: null,
next_page_url: null,
},
},
}}
/>,
);
expect(html).toContain('Stock autorizado');
expect(html).not.toContain('value="finance"');
expect(html).toContain('disabled');
expect(post).not.toHaveBeenCalled();
});
test('private audit navigation needs both QA availability and dedicated family authority', () => {
const paths = (permissions: string[], available: boolean) =>
procurementNavigation(
permissions,
false,
undefined,
false,
false,
available,
).flatMap((group) => group.entries.map((entry) => entry.path));
expect(paths(['audit_private_stock_read'], true)).toContain(
'/auditoria/privada',
);
expect(paths(['audit_private_stock_read'], false)).not.toContain(
'/auditoria/privada',
);
for (const permission of ['audit_metadata_read', 'finance', 'admin']) {
expect(paths([permission], true)).not.toContain('/auditoria/privada');
}
});
+16 -1
View File
@@ -30,7 +30,22 @@ function render(
component: 'test',
url: '/teste',
version: null,
props: { errors: {}, ...props },
props: {
errors: {},
auth: {
user: {
id: 12,
tenant_id: 4,
name: 'Synthetic banking reader',
},
},
workContext: { active: 'procurement.internal' },
organizationAccess: {
active: true,
permissions: props.canManage ? ['finance'] : ['admin'],
},
...props,
},
clearHistory: false,
encryptHistory: true,
} satisfies Page;
@@ -0,0 +1,153 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import UrgentStock from '@/pages/requisitions/urgent-stock';
import Summary from '@/components/urgent-quotation-summary';
import { ComparisonPolicySummary } from '@/components/comparison-policy-summary';
afterEach(() => vi.restoreAllMocks());
const policy = {
revision: 2,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
urgent_minimum_proposals: 1,
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
};
const proof = {
id: 9,
version: 1,
created_at: '2026-11-28T10:00:00Z',
reason: 'SYNTHETIC-STOCK-PROOF',
data: { requisition_item_id: 8 },
snapshot: {
item: { description: 'Synthetic material' },
stock_policy: {
minimum_stock_milli: 20000,
usage_context: 'Daily synthetic production',
warehouse: { name: 'Synthetic warehouse' },
},
availability: { free_milli: null },
author: { name: 'Synthetic procurement' },
},
};
function render(
actor = 7,
canRecord = true,
evidence = false,
configured = true,
) {
return renderToStaticMarkup(
<App
initialComponent={UrgentStock}
initialPage={{
component: 'requisitions/urgent-stock',
url: '/requisicoes/3/urgencia-stock',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: {
user: {
id: actor,
tenant_id: 4,
name: 'Synthetic actor',
},
},
workContext: { active: 'procurement.internal' },
organizationAccess: { permissions: ['procurement'] },
requisition: {
id: 3,
number: 'REQ-QA',
priority: 'urgent',
justification: 'Synthetic risk of stopping production.',
},
cycle: 1,
canRecord,
items: [
{
id: 8,
description: 'Synthetic material',
catalogue_snapshot: { stock_item_id: 1 },
},
],
comparisonPolicy: configured
? policy
: { ...policy, urgent_minimum_proposals: undefined },
policies: {
data: [
{
id: 11,
version: 2,
stock_item_id: 1,
item: {
name: 'Synthetic material',
unit: 'un',
},
warehouse: { name: 'Synthetic warehouse' },
minimum_stock_milli: 20000,
usage_context: 'Daily synthetic production',
},
],
prev_page_url: null,
next_page_url: null,
},
evidence: evidence ? [proof] : [],
eligible: evidence ? [proof] : [],
},
}}
/>,
);
}
test('urgent stock preparation is scoped to actor process cycle and immutable evidence version without automatic submission', () => {
const identity =
'procurement-preparations:4:7:procurement.internal:procurement:urgent-stock:3:1:2:8:0';
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:form:data`
? {
item_id: 8,
policy_id: '11',
version: 0,
reason: 'RESTORED-URGENT-STOCK-DRAFT',
operation_key: '117ed627-098c-49a8-a324-d75c4c989473',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('RESTORED-URGENT-STOCK-DRAFT');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render(8)).not.toContain('RESTORED-URGENT-STOCK-DRAFT');
expect(render(7, true, true)).not.toContain('RESTORED-URGENT-STOCK-DRAFT');
expect(post).not.toHaveBeenCalled();
});
test('approval readers see the evidence without being granted the preparation command', () => {
const html = render(7, false, true);
expect(html).toContain('SYNTHETIC-STOCK-PROOF');
expect(html).toContain('Indeterminado');
expect(html).not.toContain('>Conferir stock mínimo</button>');
expect(render(7, true, false, false)).not.toContain(
'>Conferir stock mínimo</button>',
);
});
test('comparison distinguishes the ordinary count from an applied urgent count and preserves independent evaluations', () => {
const html = renderToStaticMarkup(
<ComparisonPolicySummary
policy={{
...policy,
minimum_proposals: 1,
normal_minimum_proposals: 3,
}}
/>,
);
expect(html).toContain('mínimo de 1 propostas');
expect(html).toContain('mínimo normal é 3');
expect(html).toContain('2 avaliações');
});
test('frozen stock basis summary has no empty section and never represents unknown free stock as zero', () => {
expect(renderToStaticMarkup(<Summary />)).toBe('');
const html = renderToStaticMarkup(<Summary records={[proof]} />);
expect(html).toContain('SYNTHETIC-STOCK-PROOF');
expect(html).toContain('Indeterminado');
expect(html).toContain('Daily synthetic production');
});