commit compras3 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 18:56:24 +02:00
parent 930064269e
commit 9cf9764710
87 changed files with 2856 additions and 195 deletions
@@ -6,6 +6,8 @@ use App\Models\Requisition;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\ImportBankSupport;
use App\Services\ImportCostDocumentHealth;
@@ -45,7 +47,8 @@ require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
$legalAmounts = ($argv[2] ?? '') === 'import-legal-amount';
$capitalRestore = ($argv[2] ?? '') === 'capital';
$legalAmounts = $capitalRestore || ($argv[2] ?? '') === 'import-legal-amount';
$legalRules = $legalAmounts || ($argv[2] ?? '') === 'import-legal';
$bankSupport = $legalRules || ($argv[2] ?? '') === 'import-bank-support';
$importEstimates = $bankSupport || ($argv[2] ?? '') === 'import-estimates';
@@ -231,6 +234,10 @@ if ($landedCosts) {
config(['import-estimates.qa_enabled' => true]);
$legalPlanRequest = $f['r']->replicate();
$legalPlanRequest->fill(['number' => 'LEGAL-RECOVERY-'.Str::random(10), 'status' => 'draft']);
if ($capitalRestore) {
$legalPlanRequest->requester_id = $partyBuyer->id;
supplyGrant($partyBuyer, ['requester']);
}
$legalPlanRequest->save();
$legalPlanItem = $f['r']->items()->sole()->replicate();
$legalPlanItem->requisition_id = $legalPlanRequest->id;
@@ -246,6 +253,18 @@ if ($landedCosts) {
'subtotal_minor' => $kind === 'duty' ? 750 : null, 'tax_minor' => $kind === 'duty' ? 0 : null,
'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)];
$legalNativePlan = app(ImportEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalNativeInput);
if ($capitalRestore) {
config(['capital-register.qa_enabled' => true]);
$capitalInput = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'type' => 'project', 'code' => 'RECOVERY-QA', 'name' => 'Projecto sintético antes da revisão', 'department_id' => $f['department']->id,
'equipment_id' => null, 'reference' => 'Documento sintético para recuperação', 'state' => 'active', 'reason' => 'Cadastro próprio de Compras no ensaio de recuperação'];
$capitalFirst = app(CapitalRegister::class)->save($partyBuyer, $capitalInput);
$capitalAssignmentInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $legalPlanItem->id,
'capital_id' => $capitalFirst->id, 'reason' => 'Destino sintético preservado na recuperação do cadastro'];
$capitalAssignment = app(CapitalAssignments::class)->save($partyBuyer, $legalPlanRequest, $capitalAssignmentInput);
$capitalArchive = app(CapitalRegister::class)->save($partyBuyer, [...$capitalInput, 'operation_key' => (string) Str::uuid(),
'record_key' => $capitalFirst->record_key, 'version' => 1, 'state' => 'archived', 'name' => 'Designação sintética posterior']);
}
}
}
$evidenceManifest = [];
@@ -391,6 +410,20 @@ try {
echo json_encode(['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true,
'native_legal_plan_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
if ($capitalRestore) {
$capitalService = app(CapitalRegister::class);
$capitalReplay = $capitalService->save($restoredBuyer, $capitalInput);
$assignmentReplay = app(CapitalAssignments::class)->save($restoredBuyer, $restoredRequest, $capitalAssignmentInput);
$capitalFrozen = app(CapitalAssignments::class)->freezeForItems($restoredBuyer, [$legalPlanItem->id]);
$capitalHead = app(SupplyPlanning::class)->latest('capital_register')->where('record_key', $capitalFirst->record_key)->firstOrFail();
if ($capitalReplay->id !== $capitalFirst->id || $assignmentReplay->id !== $capitalAssignment->id
|| $capitalHead->id !== $capitalArchive->id || $capitalHead->state !== 'archived'
|| $capitalFrozen[$legalPlanItem->id]['snapshot']['source']['id'] !== $capitalFirst->id) {
throw new RuntimeException('Capital identity versions, archival, frozen assignment or operation replay differs after recovery.');
}
echo json_encode(['capital_register_versions_restored' => 2, 'capital_assignment_source_version_restored' => 1,
'capital_archived_head_preserved' => true, 'capital_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
}
}
$readFingerprint = $fingerprint($restored, $afterColumns);
+32
View File
@@ -13,6 +13,7 @@ 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 () {
config(['capital-register.qa_enabled' => true]);
@@ -133,3 +134,34 @@ test('submitted requisitions reject new line destinations and stale versions do
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
});
test('revoked requester retains only native historical visibility without new catalogue choices or commands', function () {
supplyGrant($this->f['issuer'], ['procurement', 'requester']);
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$this->f['r']->update(['status' => 'draft']);
$item = $this->f['r']->items()->sole();
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
'reason' => 'Escolha sintética antes da revogação dos acessos'];
$service = app(CapitalAssignments::class);
$service->save($this->f['issuer'], $this->f['r'], $input);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['canWrite'])->toBeFalse()->and($workspace['choices']->total())->toBe(0)->and($workspace['current'])->toHaveCount(1);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(HttpException::class);
});
test('classified machinery cannot submit without a capital destination or create approvals and reservations', function () {
$this->f['r']->update(['status' => 'draft']);
$item = $this->f['r']->items()->sole();
$item->update(['purchase_type' => 'equipment', 'production_area' => 'Área sintética',
'category_context' => ['version' => 1, 'category' => 'capital_equipment', 'reason' => 'Justificação sintética de investimento']]);
$this->postJson('/requisicoes/'.$this->f['r']->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $this->f['r']->process_version])
->assertUnprocessable()->assertJsonValidationErrors('capital_assignment');
expect($this->f['r']->fresh()->status)->toBe('draft')->and(DB::table('budget_entries')->count())->toBe(0)
->and($this->f['r']->steps()->count())->toBe(0);
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
app(CapitalAssignments::class)->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $item->id, 'capital_id' => $source->id, 'reason' => 'Destino sintético para maquinaria classificada']);
app(CapitalAssignments::class)->assertSubmission($this->f['issuer'], $this->f['r']);
expect(DB::table('budget_entries')->count())->toBe(0)->and($this->f['r']->steps()->count())->toBe(0);
});
+8
View File
@@ -1969,6 +1969,14 @@ test('native consolidated order retains both origins and consumes a single invoi
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
$request->forceFill(['requester_id' => $this->head->id])->save();
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
// The search must respect every consolidated origin after a current department change,
// while keeping the native company-wide warehouse reader's receipt access.
$otherDepartment = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outro departamento sintético']);
$request->forceFill(['department_id' => $otherDepartment->id])->save();
$this->actingAs($this->head)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 0));
$this->actingAs($receiver)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 1));
});
test('native partial-order cancellation uses independent Finance and preserves the unissued reservation and requisition', function () {
@@ -0,0 +1,220 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Invoice;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowNotices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
use Tempo\Purchasing\Internal\InternalRequisitions;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
$this->markTestSkipped('The optional cycle contract uses the explicitly authorised common QA source, never the installed kernel.');
}
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->budget = Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true,
'reason' => 'Dotação aprovada estritamente sintética para ciclos', 'created_by' => $this->f['issuer']->id, 'approved_by' => $this->reviewer->id]);
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
config(['requisition-expiry.qa_enabled' => true]);
});
test('ordinary budget cycles release and reserve a revised amount without replaying or rewriting the original cycle', function () {
$origin = $this->f['r']->id;
$service = app(CommonBudget::class);
$first = $service->for($this->f['issuer'], [$origin => 1]);
$open = (string) Str::uuid();
$first->beginRequisitionCycle($origin, 1, $open);
$first->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
$first->record($origin, $this->f['r']->cost_center_id, 'operating', 'release');
$close = (string) Str::uuid();
$first->closeRequisitionCycle($origin, 1, $close);
$old = DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson();
expect($first->closeRequisitionCycle($origin, 1, $close)['replayed'])->toBeTrue();
$second = $service->for($this->f['issuer'], [$origin => 2]);
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000);
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000);
expect(DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson())->toBe($old)
->and(DB::table('budget_entries')->where('requisition_cycle', 2)->count())->toBe(1)
->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(12000);
$this->actingAs($this->reviewer);
expect($service->for($this->reviewer)->balance($this->budget->id)['available_minor'])->toBe(88000);
$this->actingAs($this->f['issuer']);
expect(fn () => $service->for($this->f['issuer'])->record($origin, $this->f['r']->cost_center_id, 'operating', 'release'))->toThrow(BudgetFailure::class);
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'release');
expect((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(0);
});
test('a current committed cycle cannot expire or open another cycle and malformed operations cannot establish identity', function () {
$origin = $this->f['r']->id;
$engine = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]);
expect(fn () => $engine->beginRequisitionCycle($origin, 1, str_repeat('-', 36)))->toThrow(BudgetFailure::class);
$engine->beginRequisitionCycle($origin, 1, (string) Str::uuid());
$engine->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
$engine->record($origin, $this->f['r']->cost_center_id, 'operating', 'commit', 10000, 10000);
expect(fn () => $engine->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2])->beginRequisitionCycle($origin, 2, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_requisition_cycles')->count())->toBe(1)
->and((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000);
$invoice = Invoice::query()->create(['tenant_id' => $this->f['tenant']->id, 'purchase_order_id' => $this->f['order']->id,
'supplier_id' => $this->f['order']->supplier_id, 'created_by' => $this->f['issuer']->id, 'number' => 'CYCLE-CONSUMPTION-QA',
'issued_on' => today(), 'status' => 'validated', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000, 'snapshot' => ['synthetic' => true]]);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer, [$origin => 1])->consume($origin, $invoice->id, 10000, 10000);
$this->actingAs($this->f['issuer']);
expect((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(0);
expect(fn () => $engine->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
});
test('current approval relations select the new cycle during eager loading and keep all original decisions addressable', function () {
$request = $this->f['r']->fresh();
$old = $request->allSteps()->create(['tenant_id' => $request->tenant_id, 'approval_cycle' => 1, 'position' => 1,
'role' => 'department_head', 'decision' => 'approved', 'approver_id' => $this->reviewer->id, 'decided_at' => now()]);
$request->setAttribute('approval_cycle', 2);
$request->setAttribute('status', 'pending');
$request->save();
expect((int) DB::table('requisitions')->where('id', $request->id)->value('approval_cycle'))->toBe(2);
$current = $request->allSteps()->create(['tenant_id' => $request->tenant_id, 'approval_cycle' => 2, 'position' => 1,
'role' => 'department_head', 'decision' => 'pending']);
$loaded = Requisition::query()->with('steps')->whereKey($request->id)->firstOrFail();
expect($loaded->steps->pluck('id')->all())->toBe([$current->id])
->and($loaded->allSteps()->count())->toBe(2)->and($old->fresh()->decision)->toBe('approved')
->and(InternalRequisitions::nextStep($loaded->toArray(), $this->reviewer->id)['id'])->toBe($current->id);
});
test('distributed reservations use a fresh cycle header and preserve the released original allocations', function () {
$origin = $this->f['r']->id;
$line = $this->f['r']->items()->sole();
$allocations = [['allocation_key' => 'A', 'line_id' => $line->id, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$revision = hash('sha256', 'synthetic cycle-one native source');
$first = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]);
$first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
$first->recordDistribution($origin, 'reserve', $allocations, $lines, $revision, (string) Str::uuid());
$first->recordDistribution($origin, 'release', $allocations, $lines, $revision, (string) Str::uuid());
$first->closeRequisitionCycle($origin, 1, (string) Str::uuid());
$old = DB::table('budget_distributions')->where('requisition_cycle', 1)->sole();
$this->f['r']->setAttribute('approval_cycle', 2);
$this->f['r']->save();
$line->update(['unit_price_minor' => 12000, 'subtotal_minor' => 12000, 'total_minor' => 12000]);
$this->f['r']->update(['subtotal_minor' => 12000, 'total_minor' => 12000]);
$allocations[0]['subtotal_minor'] = $allocations[0]['total_minor'] = 12000;
$lines[$line->id]['subtotal_minor'] = $lines[$line->id]['total_minor'] = 12000;
$second = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2]);
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
$second->recordDistribution($origin, 'reserve', $allocations, $lines, hash('sha256', 'synthetic cycle-two native source'), (string) Str::uuid());
expect(DB::table('budget_distributions')->where('id', $old->id)->sole())->toEqual($old)
->and(DB::table('budget_distributions')->where('requisition_id', $origin)->count())->toBe(2)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(12000)
->and(app(RequisitionBudgetDistributions::class)->source($this->f['r'])->requisition_cycle)->toBe(2);
});
test('import assumptions release in the old cycle before a separately identified new plan can reserve', function () {
$origin = $this->f['r']->id;
$first = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]);
$first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
$goods = ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000];
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
'basis' => 'Explicit synthetic assumption; not a real import or exemption', 'subtotal_minor' => $kind === 'duty' ? 1000 : null,
'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 1000 : null], BudgetImportEstimate::KINDS);
$plan = (string) Str::uuid();
$first->reserveImportEstimate($plan, 1, $this->budget->id, $origin, $goods, $components, (string) Str::uuid());
expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
$hash = BudgetImportEstimate::reconcile($goods, $components, true)['fingerprint'];
$first->releaseImportEstimate($plan, 1, $hash, (string) Str::uuid());
$first->closeRequisitionCycle($origin, 1, (string) Str::uuid());
$old = DB::table('budget_landed_entries')->orderBy('id')->get()->toJson();
$second = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2]);
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
foreach ($components as &$component) {
if ($component['kind'] === 'duty') {
$component['subtotal_minor'] = $component['total_minor'] = 1500;
}
}
unset($component);
$second->reserveImportEstimate((string) Str::uuid(), 1, $this->budget->id, $origin, $goods, $components, (string) Str::uuid());
expect((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(1500)
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
});
test('native expiry returns the same request and preserves the approved stage before a fresh revised submission and reservation', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$buyer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
$this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
$expiry = app(RequisitionExpiry::class);
$this->actingAs($admin);
$expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement']),
'reason' => 'Prazos corridos expressamente sintéticos deste teste de expiração']);
$owner = $this->f['issuer'];
$this->actingAs($owner);
$workflow = app(RequisitionWorkflow::class);
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Requisição sintética para duas submissões independentes',
'items' => [['description' => 'Bem de ensaio', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]];
$request = $workflow->save($owner, $input);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->actingAs($head);
$workflow->decide($head, $request, 'approved', 'Conferência sintética do primeiro nível', (string) Str::uuid(), $request->process_version);
$request->refresh();
$approved = $request->steps()->where('decision', 'approved')->sole()->toArray();
$this->travel(31)->minutes();
$deadline = $expiry->deadline($request);
expect($deadline['state'])->toBe('expired');
$this->actingAs($buyer);
expect(fn () => $workflow->decide($buyer, $request, 'approved', 'Aprovação fora do prazo', (string) Str::uuid(), $request->process_version))->toThrow(HttpException::class);
$this->actingAs($owner);
$operation = (string) Str::uuid();
$version = $request->process_version;
$this->withoutVite();
$body = ['basis_hash' => $deadline['basis_hash'], 'operation_key' => $operation, 'process_version' => $version];
$this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect();
$this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect();
$request->refresh();
expect($request->status)->toBe('draft')->and($request->approval_cycle)->toBe(2)->and($request->steps()->count())->toBe(0)
->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved)
->and($request->allSteps()->where('decision', 'expired')->count())->toBe(1)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1);
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('requisitions/expiry')->where('requisition.approval_cycle', 2)->where('canEdit', true)->has('history.data', 1));
$input['operation_key'] = (string) Str::uuid();
$input['process_version'] = $request->process_version;
$input['items'][0]['unit_price'] = '120.00';
$request = $workflow->save($owner, $input, $request);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
expect($request->status)->toBe('pending')->and($request->steps()->count())->toBe(2)
->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->sole()->snapshot['request']['total_minor'])->toBe(10000);
$notices = app(WorkflowNotices::class)->visible($owner);
expect(array_column($notices, 'outcome'))->toContain('expired')
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
$this->travelBack();
});
+8
View File
@@ -24,6 +24,14 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return false;
};
$mode = ($command[1] ?? '') === 'vendor/bin/pest' ? 'pest' : ($command[3] ?? '');
if ($mode === 'capital') {
if (! $contains(fn ($row) => ($row['capital_register_versions_restored'] ?? null) === 2
&& ($row['capital_assignment_source_version_restored'] ?? null) === 1 && ($row['capital_archived_head_preserved'] ?? false) === true
&& ($row['capital_replay_without_effects'] ?? false) === true)) {
return false;
}
$mode = 'import-legal-amount';
}
if ($mode === 'migrate') {
return $contains(fn ($row) => ($row['isolated_schema_prepared'] ?? false) === true);
}
+8
View File
@@ -195,4 +195,12 @@ test('legal amount receipts require both contention cases and recovery of the ex
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
$rows[1]['native_legal_plan_total_minor'] = 10751;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$command[3] = 'capital';
$rows[1]['native_legal_plan_total_minor'] = 10750;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$rows[] = ['capital_register_versions_restored' => 2, 'capital_assignment_source_version_restored' => 1,
'capital_archived_head_preserved' => true, 'capital_replay_without_effects' => true];
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
$rows[2]['capital_assignment_source_version_restored'] = 2;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
});
+43
View File
@@ -87,3 +87,46 @@ test('approved requisitions display the preserved source independently of availa
expect(frozen).toContain('&lt;script&gt;QA&lt;/script&gt;');
expect(renderToStaticMarkup(<CapitalAssignmentSummary />)).toBe('');
});
test('capital lineage distinguishes the original receipt from current returns and reversal', () => {
const html = render(CapitalRegister, {
records: page([source]),
history: page([source]),
departments: [],
equipment: [],
canManage: false,
actorId: 1,
tenantId: 1,
trace: {
orders: page([
{
id: 7,
description: 'Synthetic item',
quantity: '2.000',
unit: 'un',
order_id: 8,
order_number: 'OC-QA',
},
]),
receipts: page([
{
id: 9,
description: 'Synthetic item',
unit: 'un',
receipt_id: 10,
order_id: 8,
received_on: '2026-11-27',
quality_status: 'compliant',
accepted_quantity: '2.000',
reversed: true,
returned_quantity: '1.000',
},
]),
},
});
expect(html).toContain('Aceite no original: 2.000');
expect(html).toContain('Devolução ao fornecedor: 1.000');
expect(html).toContain('Recepção estornada');
expect(html).toContain('/ordens/8');
expect(html).not.toContain('<form');
});
+249
View File
@@ -0,0 +1,249 @@
import fs from 'node:fs';
import path from 'node:path';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
ActionBar,
FormErrors,
PageTitle,
Panel,
TableViewport,
} from '@/components/procurement';
import RequisitionForm from '@/pages/requisitions/form';
import SupplierEdit from '@/pages/suppliers/edit';
import ProcurementReports from '@/pages/reports/procurement';
import type { Supplier } from '@/types/procurement';
function render(
component: Parameters<typeof App>[0]['initialComponent'],
props: object,
) {
const html = renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/qa',
version: 'presentation',
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
if (process.env.SGC_PRESENTATION_PREVIEW) {
const root = path.resolve(process.env.SGC_PRESENTATION_PREVIEW);
const allowed = path.resolve('storage/framework/testing') + path.sep;
if (!root.startsWith(allowed))
throw Error('Private preview path required');
fs.mkdirSync(root, { recursive: true });
const name =
component === RequisitionForm
? 'requisition'
: component === SupplierEdit
? 'supplier'
: 'report';
fs.writeFileSync(
path.join(root, name + '.html'),
'<!doctype html><html lang="pt-MZ"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SGC - ' +
name +
' - dados sinteticos</title><link rel="stylesheet" href="/preview.css"><body><aside style="padding:12px;background:#fef3c7">Pre-visualizacao estatica isolada com dados sinteticos; sem gravacao.</aside>' +
html +
'</body></html>',
);
}
return html;
}
test('shared panels have distinct accessible titles and preserve their own content', () => {
const html = renderToStaticMarkup(
<>
<Panel title="Dados gerais">
<input name="reference" defaultValue="SINTETICO" />
</Panel>
<Panel title="Historico">
<p>Versao original</p>
</Panel>
</>,
);
const headings = [...html.matchAll(/<h2 id="([^"]+)"/g)].map(
(match) => match[1],
);
expect(new Set(headings).size).toBe(2);
for (const id of headings)
expect(html).toContain(`aria-labelledby="${id}"`);
expect(html).toContain('name="reference"');
expect(html).toContain('Versao original');
});
test('shared actions preserve submission and disabled semantics without adding commands', () => {
const html = renderToStaticMarkup(
<form>
<ActionBar align="end">
<a href="/requisicoes">Cancelar</a>
<button type="submit" disabled>
Guardar rascunho
</button>
</ActionBar>
</form>,
);
expect(html).toContain('role="group"');
expect(html).toContain('href="/requisicoes"');
expect(html).toContain('type="submit" disabled');
expect(html.match(/<button/g)).toHaveLength(1);
});
test('wide result viewport preserves table headers, cells and escaped user text', () => {
const html = renderToStaticMarkup(
<TableViewport label="Resultados autorizados">
<table>
<thead>
<tr>
<th>Referencia</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
<td>{'<script>synthetic</script>'}</td>
<td>100,00 MZN</td>
</tr>
</tbody>
</table>
</TableViewport>,
);
expect(html).toContain('tabindex="0"');
expect(html).toContain('aria-label="Resultados autorizados"');
expect(html).toContain('&lt;script&gt;synthetic&lt;/script&gt;');
expect(html).toContain('<td>100,00 MZN</td>');
expect(html.match(/<th>/g)).toHaveLength(2);
});
test('title keeps the single page heading without inserting an empty action area', () => {
const html = renderToStaticMarkup(
<PageTitle
eyebrow="Compras"
title="Nova requisicao"
description="Preparacao sintetica"
/>,
);
expect(html.match(/<h1 /g)).toHaveLength(1);
expect(html).not.toContain('sgc-page-actions');
});
test('shared validation keeps every error and the existing help action', () => {
const html = renderToStaticMarkup(
<FormErrors
errors={{
'items.0.quantity': 'Quantidade invalida',
currency: 'Moeda por indicar',
}}
/>,
);
expect(html).toContain('role="alert"');
expect(html).toContain('Quantidade invalida');
expect(html).toContain('Moeda por indicar');
expect(html).toContain('type="button"');
});
test.each([false, true])(
'requisition preserves existing save guard with incomplete drafts %s',
(incompleteDraftsAvailable) => {
const html = render(RequisitionForm, {
costCenters: [],
requisition: null,
incompleteDraftsAvailable,
});
expect(html).toContain('Guardar rascunho');
expect(html).toContain('sgc-action-bar');
const save = html.slice(
html.lastIndexOf('<button'),
html.lastIndexOf('</button>'),
);
expect(
/\sdisabled(?:=|[ >])/.test(save.slice(0, save.indexOf('>') + 1)),
).toBe(!incompleteDraftsAvailable);
},
);
test('supplier editing keeps the financial revalidation warning and cancellation destination', () => {
const supplier = {
id: 7,
name: 'Fornecedor SINTETICO',
nuit: '',
contact: '',
email: '',
phone: '',
address: '',
category: '',
beneficiaries: '',
document_references: '',
diligence_notes: '',
next_review: '2026-12-01',
blocked: false,
version: 3,
} as Supplier;
const html = render(SupplierEdit, { supplier });
expect(html).toContain('/fornecedores/7');
expect(html).toContain('Guardar alterações');
expect(html).toContain('retiram a validação actual');
expect(html).toContain('sgc-action-bar');
});
test('procurement report retains applied export filters, result scope and both pagination destinations', () => {
const html = render(ProcurementReports, {
records: {
data: [],
total: 0,
current_page: 2,
last_page: 3,
prev_page_url: '/relatorios?status=approved&page=1',
next_page_url: '/relatorios?status=approved&page=3',
},
filters: { status: 'approved', department_id: 9 },
departments: [{ id: 9, name: 'Departamento SINTETICO' }],
counts: {},
generatedAt: '2026-11-27T12:00:00Z',
});
expect(html).toContain(
'/relatorios/compras.csv?status=approved&amp;department_id=9',
);
expect(html).toContain('/relatorios?status=approved&amp;page=1');
expect(html).toContain('/relatorios?status=approved&amp;page=3');
expect(html).toContain('âmbito autorizado');
expect(html).toContain('sgc-table-viewport');
});
test('populated report keeps every authorised row and its process/report actions', () => {
const records = {
data: Array.from({ length: 25 }, (_, i) => ({
id: 100 + i,
number: `REQ-SINTETICA-${i + 1}`,
status: 'approved',
created_at: '2026-11-27T12:00:00Z',
needed_by: '2026-12-01',
department: 'Departamento sintetico de aprovisionamento',
requester: 'Utilizador sintetico',
total_minor: '10000',
quotations_count: 3,
order_number: null,
})),
total: 75,
current_page: 2,
last_page: 3,
prev_page_url: '/relatorios?page=1',
next_page_url: '/relatorios?page=3',
};
const html = render(ProcurementReports, {
records,
filters: {},
departments: [],
counts: {},
generatedAt: '2026-11-27T12:00:00Z',
});
expect(html.match(/Acompanhar processo/g)).toHaveLength(25);
expect(html.match(/Gerar relatório de conferência/g)).toHaveLength(25);
expect(html).toContain('REQ-SINTETICA-25');
expect(html).toContain('/requisicoes/124/relatorio');
});
+251
View File
@@ -0,0 +1,251 @@
import fs from 'node:fs';
import path from 'node:path';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ReviewReport from '@/pages/purchases/review-report';
import Improvements from '@/pages/reports/supplier-improvements';
import PeopleReports from '@/pages/people/reports';
import WarehouseRequests from '@/pages/stock/requests';
import BankSupport from '@/pages/supply/import-bank-support';
const stamp = '2026-11-27T12:00:00Z';
const page = <T,>(data: T[]) => ({
data,
from: data.length ? 1 : null,
to: data.length || null,
total: data.length,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
});
function render(
component: Parameters<typeof App>[0]['initialComponent'],
props: object,
name: string,
) {
const html = renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/qa',
version: 'screen-review',
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
const folder = process.env.SGC_REVIEW_PREVIEW;
if (folder) {
const root = path.resolve(folder);
if (
!root.startsWith(
path.resolve('storage/framework/testing') + path.sep,
)
)
throw Error('Private preview required');
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(
path.join(root, name + '.html'),
'<!doctype html><html lang="pt-MZ"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SGC QA ' +
name +
'</title><link rel="stylesheet" href="/preview.css"><body><aside class="print:hidden" style="padding:12px;background:#fef3c7">Pre-visualizacao isolada; dados sinteticos; sem gravacao.</aside>' +
html +
'</body></html>',
);
}
return html;
}
const policy = {
revision: 1,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: { price: 40, quality: 20, delivery: 20, history: 10, payment: 10 },
};
test('long review report preserves all proposals, original amounts and finance visibility restriction', () => {
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
reference: 'QA-PROPOSTA-' + String(i + 1).padStart(3, '0'),
supplier: 'Fornecedor SINTETICO ' + (i + 1),
currency: 'MZN',
subtotal_minor: 10000,
tax_minor: 1600,
total_minor: 11600,
delivery_days: 15,
valid_until: '2026-12-31',
evaluation_count: 2,
score_minor: null,
eligible: false,
ineligibility_reasons: [
'Condicao sintetica por completar; nenhuma adjudicacao automatica.',
],
is_top: false,
weights: policy.weights,
}));
const report = {
generated_at: stamp,
generated_by: 'Operador SINTETICO',
company: 'Empresa SINTETICA',
requisition: {
id: 42,
number: 'REQ-SINTETICA-42',
status: 'approved',
justification:
'Necessidade sintetica para ensaio de impressao; sem operacao.',
department: 'Departamento SINTETICO',
requester: 'Requisitante SINTETICO',
},
comparison: { ready: false, top_count: 0, rows, policy },
recommendation: null,
admission: null,
qualification: null,
opening: null,
award: null,
order: null,
fulfilment: {
receipts: [],
finance_visible: false,
invoices: null,
payments: null,
},
};
const html = render(ReviewReport, { report }, 'review');
for (const row of rows) expect(html).toContain(row.reference);
expect(html).toContain('report-fulfilment');
expect(html).not.toContain('QA-FACTURA-PRIVADA');
});
test('improvement report preserves details on every visible row without changing their disclosure state', () => {
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
evaluation_id: 50 + i,
revision: 1,
supplier: 'Fornecedor SINTETICO ' + (i + 1),
responsible: 'Responsavel SINTETICO',
title: 'QA-MEDIDA-' + String(i + 1).padStart(3, '0'),
description:
'Descricao sintetica da medida de melhoria e acompanhamento da entrega com verificacao independente.',
due_on: '2026-12-01',
status: 'open',
version: 1,
overdue: false,
result: 'QA-RESULTADO-' + String(i + 1).padStart(3, '0'),
evidence: 'QA-EVIDENCIA-' + String(i + 1).padStart(3, '0'),
review_reason: 'Conferencia sintetica preservada.',
}));
const html = render(
Improvements,
{
records: page(rows),
filters: {},
counts: { open: 30 },
overdue: 0,
suppliers: [],
responsibles: [],
today: '2026-11-27',
generatedAt: stamp,
},
'improvements',
);
for (const row of rows) {
expect(html).toContain(row.title);
expect(html).toContain(row.evidence);
}
expect(html).not.toContain('<details open');
});
test('people deadline report retains all tasks and preserves visibility of unknown deadlines', () => {
const items = Array.from({ length: 35 }, (_, i) => ({
id: 'task-' + i,
reference: 'QA-PESSOAS-' + String(i + 1).padStart(3, '0'),
title: 'Processo SINTETICO ' + (i + 1),
category: 'task',
label: 'Conferencia sintetica',
responsibility: 'Responsavel SINTETICO',
due_on: null,
days_overdue: null,
href: '/pessoas/' + (i + 1),
}));
const html = render(
PeopleReports,
{
deadlineReport: {
as_of: '2026-11-27',
window: 'all',
total_items: 35,
matching_processes: 35,
processes_considered: 35,
tasks: 35,
approvals: 0,
alerts: 0,
without_deadline: 35,
overdue_items: 0,
items,
pagination: page([]),
},
selectionMetrics: {},
applicationMetrics: {},
filters: { view: 'deadlines' },
kinds: ['staff', 'service'],
generatedAt: stamp,
summary: [],
processes: page([]),
},
'people',
);
for (const item of items) expect(html).toContain(item.reference);
expect(html).toContain('Sem prazo');
});
test.each([true, false])(
'warehouse preparation remains conditional on its existing permission (%s)',
(canPrepare) => {
const html = render(
WarehouseRequests,
{
filters: {
view: 'all',
state: '',
search: '',
warehouse_id: null,
},
views: [],
states: {},
checkedAt: stamp,
ready: true,
canPrepare,
items: [],
warehouses: [],
costCenters: [],
equipment: [],
records: page([]),
},
canPrepare ? 'warehouse' : 'warehouse-read',
);
expect(html.includes('Preparar rascunho')).toBe(canPrepare);
},
);
test.each([true, false])(
'bank documentary editing remains conditional on its existing permission (%s)',
(canWrite) => {
const html = render(
BankSupport,
{
importRecord: { id: 5, record_key: 'synthetic', version: 1 },
order: { id: 2, number: 'OC-SINTETICA' },
current: page([]),
history: page([]),
documents: page([]),
types: { commitment: 'Termo sintetico' },
canWrite,
actorId: 1,
tenantId: 1,
today: '2026-11-27',
},
canWrite ? 'bank' : 'bank-read',
);
expect(html).toContain('Suporte documental bancário');
expect(html.includes('<form')).toBe(canWrite);
},
);