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

This commit is contained in:
2026-11-28 07:11:35 +02:00
parent d58b75c87a
commit eb32c74c56
202 changed files with 17463 additions and 1526 deletions
+77 -1
View File
@@ -7,6 +7,26 @@ use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
function auditMetadataRows(string $csv): array
{
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new LogicException('Synthetic CSV stream unavailable.');
}
try {
fwrite($stream, $csv);
rewind($stream);
$rows = [];
while (($row = fgetcsv($stream, 0, ';', '"', '')) !== false) {
$rows[] = $row;
}
return array_slice($rows, 2);
} finally {
fclose($stream);
}
}
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
@@ -35,7 +55,8 @@ test('audit metadata block exports the complete filtered scope independently of
$query = '?action=people.selected&actor_id='.$this->f['receiver']->id.'&from=2026-11-01&to=2026-11-01';
$this->get('/auditoria/eventos'.$query)->assertOk()->assertInertia(fn (Assert $p) => $p->where('events.total', 10));
$csv = $this->get('/auditoria/eventos.csv'.$query.'&page=2')->assertOk()->streamedContent();
expect(substr_count($csv, 'people.selected'))->toBe(10)->and($csv)->not->toContain('receipt.confirmed', 'PRIVATE-BEFORE', 'PRIVATE-AFTER');
expect(array_count_values(array_column(auditMetadataRows($csv), 2))['people.selected'])->toBe(10)
->and($csv)->not->toContain('receipt.confirmed', 'PRIVATE-BEFORE', 'PRIVATE-AFTER');
$this->get('/auditoria/eventos?to=2026-11-01')->assertOk();
$this->getJson('/auditoria/eventos?from=2026-11-02&to=2026-11-01')->assertUnprocessable();
DB::table('audit_logs')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id, 'action' => '=1+1', 'created_at' => now(), 'after' => '{}']);
@@ -76,3 +97,58 @@ test('audit metadata block isolates companies and adds no grants or audit events
}
expect(array_key_exists('audit_metadata_read', OrganizationAccess::PERMISSIONS))->toBeTrue();
});
test('auditor investigates one exact request across pages exports the full same scope and opens only an independently visible process', function () {
$own = $this->f;
$source = $own['r'];
$source->update(['number' => 'QA%_AUDIT-REQUEST']);
foreach (range(1, 131) as $index) {
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $source->id, 'user_id' => $own['receiver']->id,
'action' => 'requisition.synthetic_checked', 'created_at' => '2026-11-01 12:00:00',
'before' => json_encode(['private' => 'PRIVATE-BEFORE']), 'after' => json_encode(['private' => 'PRIVATE-AFTER'])]);
}
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $source->id, 'user_id' => $own['receiver']->id,
'action' => 'requisition.synthetic_checked', 'created_at' => '2026-10-31 12:00:00', 'after' => '{}']);
$foreign = receiptFixture();
$foreign['r']->update(['number' => 'FOREIGN-AUDIT-ONLY']);
// Deliberately malformed synthetic linkage must not expose another company's request through an own-tenant event.
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $foreign['r']->id, 'user_id' => $own['receiver']->id,
'action' => 'malformed.foreign_link', 'created_at' => '2026-11-01 12:00:00', 'after' => '{}']);
$this->actingAs($own['receiver']);
$query = '?request_reference='.urlencode($source->number).'&action=requisition.synthetic_checked&actor_id='.$own['receiver']->id.'&from=2026-11-01&to=2026-11-01';
$before = [];
foreach (['audit_logs', 'requisitions', 'users', 'organization_profiles', 'organization_memberships', 'budget_entries', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/auditoria/eventos'.$query)->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->where('events.total', 131)->has('events.data', 25)
->where('requestContext', null)->missing('events.data.0.before')->missing('events.data.0.after'));
$this->get('/auditoria/eventos'.$query.'&page=2')->assertInertia(fn (Assert $page) => $page->where('events.current_page', 2)->has('events.data', 25));
$csv = $this->get('/auditoria/eventos.csv'.$query.'&page=6')->assertOk()->streamedContent();
expect(auditMetadataRows($csv))->toHaveCount(131)
->and(array_unique(array_column(auditMetadataRows($csv), 2)))->toBe(['requisition.synthetic_checked'])
->and($csv)->toContain('QA%_AUDIT-REQUEST', '2026-11-01')->not->toContain('PRIVATE-BEFORE', 'PRIVATE-AFTER');
$this->get('/requisicoes/'.$source->id)->assertNotFound();
foreach (['FOREIGN-AUDIT-ONLY', 'QA', '0'] as $unknown) {
$this->get('/auditoria/eventos?request_reference='.urlencode($unknown))->assertInertia(fn (Assert $page) => $page
->where('events.total', 0)->where('requestContext', null));
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$auditProfile = DB::table('organization_memberships')->where('user_id', $own['receiver']->id)->value('profile_id');
supplyGrant($own['receiver'], ['finance']);
$this->get('/auditoria/eventos'.$query)->assertInertia(fn (Assert $page) => $page
->where('requestContext.number', $source->number)->where('requestContext.href', '/requisicoes/'.$source->id.'#requisition-history'));
$this->get('/requisicoes/'.$source->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canReadAuditMetadata', true));
DB::table('organization_memberships')->where('user_id', $own['receiver']->id)->where('profile_id', $auditProfile)->update(['expires_at' => now()->subSecond()]);
$this->get('/requisicoes/'.$source->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canReadAuditMetadata', false));
$this->get('/auditoria/eventos'.$query)->assertForbidden();
});
test('literal zero action remains an exact audit filter and malformed references are refused', function () {
DB::table('audit_logs')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id, 'action' => '0', 'created_at' => now(), 'after' => '{}']);
$this->get('/auditoria/eventos?action=0')->assertInertia(fn (Assert $page) => $page->where('events.total', 1)->where('events.data.0.action', '0'));
$this->getJson('/auditoria/eventos?request_reference='.str_repeat('x', 101))->assertUnprocessable();
$this->getJson('/auditoria/eventos?request_reference[]=QA')->assertUnprocessable();
});
+19
View File
@@ -70,6 +70,25 @@ test('asset references reuse a physical equipment identity and reject duplicate
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => ['invalid']]))->toThrow(ValidationException::class);
});
test('equipment backlink revalidates current register access without exposing a reference after revocation', function () {
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(),
'code' => 'LINK-QA', 'name' => 'Ensaio de ligação', 'criteria' => 'Dados sintéticos', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id,
'code' => 'EQ-LINK-QA', 'description' => 'Identidade sintética de equipamento', 'area' => 'Ensaio', 'status' => 'active',
'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
$service = app(CapitalRegister::class);
$source = $service->save($this->f['issuer'], [...$this->input, 'type' => 'asset', 'code' => 'ASSET-LINK-QA', 'equipment_id' => $equipment->id]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment)['record_key'])->toBe($source->record_key);
supplyGrant($this->f['issuer'], ['admin']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => true]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => false]);
DB::table('organization_profiles')->where('tenant_id', $this->f['tenant']->id)->update(['permissions' => json_encode(['requester'])]);
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
auth()->logout();
expect($service->referenceForEquipment($this->f['issuer'], $equipment))->toBeNull();
});
test('native register page is encrypted private paginated and gated off outside QA', function () {
app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$this->get('/projectos-imobilizado')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
+14
View File
@@ -77,6 +77,20 @@ test('corrections append history preserve the original assertion and reject stal
$this->get('/conflitos/'.$original->id)->assertInertia(fn (Assert $page) => $page->has('history', 3));
});
test('personal conflict consultation protects browser history and cache without changing declarations or audit', function () {
$this->post('/conflitos', personalConflict($this->supplier->id))->assertSessionHasNoErrors();
$declaration = ConflictDeclaration::query()->firstOrFail();
$before = ConflictDeclaration::query()->get()->toArray();
$audit = AuditLog::query()->get()->toArray();
foreach (['/conflitos', '/conflitos/'.$declaration->id] as $url) {
$response = $this->get($url)->assertOk();
$response->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
}
expect(ConflictDeclaration::query()->get()->toArray())->toBe($before)
->and(AuditLog::query()->get()->toArray())->toBe($audit);
});
test('corrections cannot remove conflicts change scope author or company', function (string $field, mixed $value) {
$this->post('/conflitos', personalConflict($this->supplier->id));
$declaration = ConflictDeclaration::query()->firstOrFail();
+12
View File
@@ -205,6 +205,18 @@ test('catalogue requires explicit minimum and supports optimistic audited update
$this->postJson('/equipamentos/pecas', $payload)->assertUnprocessable()->assertJsonValidationErrors('version');
});
test('equipment preparation consultation protects browser history without catalogue or stock writes', function () {
$before = [];
foreach (['equipment', 'spare_parts', 'equipment_spare_parts', 'stock_operations', 'stock_movements', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->map(fn (object $row) => (array) $row)->all();
}
$response = $this->get('/equipamentos')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->map(fn (object $row) => (array) $row)->all())->toBe($rows);
}
});
test('warehouse stock drives minimum alert without duplicate inventory balances', function () {
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->get('/equipamentos')->assertInertia(fn (Assert $p) => $p->component('equipment/index')->where('parts.0.balance_milli', 1000)->where('parts.0.below_minimum', true));
+50
View File
@@ -12,6 +12,8 @@ use App\Services\ImportLandedCosts;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\ImportTariffCodes;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionSubmissionPreview;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Database\Eloquent\ModelNotFoundException;
@@ -22,6 +24,7 @@ use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -153,6 +156,11 @@ test('native submission approves the full estimate reserves goods and extras onc
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000];
$estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
$workflow = app(RequisitionWorkflow::class);
$preview = app(RequisitionSubmissionPreview::class)->for($this->f['issuer'], $this->draft->fresh());
expect($preview['state'])->toBe('planned')->and($preview['total_minor'])->toBe('10000')
->and($preview['approval_amount_minor'])->toBe('11000')->and($preview['import_basis'])->toBeTrue()
->and(array_column($preview['steps'], 'role'))->toBe(['department_head', 'procurement', 'finance'])
->and(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0);
$workflow->submit($this->f['issuer'], $this->draft);
$submitted = $this->draft->fresh();
expect($submitted->status)->toBe('pending')->and($submitted->total_minor)->toBe(10000)
@@ -171,6 +179,48 @@ test('native submission approves the full estimate reserves goods and extras onc
->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0);
});
test('expired import cycle preserves its actual landed estimate routing amount in historical consultation', function () {
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
$this->markTestSkipped('Authorised cycle composition required.');
}
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
config(['requisition-expiry.qa_enabled' => true]);
$this->f['tenant']->update(['first_limit_minor' => 10500, 'second_limit_minor' => 10800]);
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($admin);
$expiry = app(RequisitionExpiry::class);
$expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []]],
'reason' => 'Synthetic explicit deadline for historical import estimate consultation']);
$this->actingAs($this->f['issuer']);
$input = $this->input;
foreach ($input['components'] as &$component) {
$component['status'] = 'not_applicable';
}
unset($component);
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000];
app(ImportEstimates::class)->save($this->f['issuer'], $this->draft->fresh(), $input);
$workflow = app(RequisitionWorkflow::class);
$request = $this->draft->fresh();
$workflow->submit($this->f['issuer'], $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->travel(31)->minutes();
$deadline = $expiry->deadline($request);
$workflow->expire($this->f['issuer'], $request, $deadline['basis_hash'], (string) Str::uuid(), $request->process_version);
$before = [];
foreach (['budget_entries', 'budget_landed_entries', 'budget_requisition_cycles', 'supply_records', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page
->where('requisition.approval_cycle', 2)->where('history.data.0.request.total_minor', 10000)
->where('history.data.0.approval_amount_minor', 11000)->where('history.data.0.approval_uses_separate_basis', true)
->where('history.data.0.rules.first_limit_minor', 10500)->has('history.data.0.steps', 3));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('unknown or stale estimate prevents native submission without partial reservations or approval steps', function () {
app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $this->input);
try {
+25 -4
View File
@@ -24,14 +24,27 @@ use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
beforeEach(function () {
if (! class_exists(BudgetLandedCostPlan::class)) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
$source = requisitionLedgerQaSource();
if ($source === null) {
throw new LogicException('Integrated import costs require the dedicated actual-ledger QA runner.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
expect($composition['verified_tables'])->toHaveCount(12);
}
config(['import-landed-costs.qa_enabled' => true]);
Storage::fake('local');
$this->f = receiptFixture();
@@ -94,7 +107,9 @@ test('technical inspection detects private import evidence loss alteration and o
});
test('cost to item references are frozen in reviewed preparations without stock valuation or financial effects', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$selection = [...importCostSelection($this, $document), 'item_references' => [
@@ -299,7 +314,9 @@ test('a documentary correction preserves both original bytes and values and inva
});
test('the native independently reviewed cost plan reserves commits and consumes the additional origin once', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
@@ -344,7 +361,9 @@ function approvedImportCostPreparation(object $test): array
}
test('logistics progression does not revoke a reviewed cost preparation or require another financial approval', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
[, $approved] = approvedImportCostPreparation($this);
$service = app(ImportLandedCosts::class);
$service->financial($this->finance, $this->import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0,
@@ -362,7 +381,9 @@ test('logistics progression does not revoke a reviewed cost preparation or requi
});
test('a failed native financial receipt rolls back the common journal and its audit together', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
}
[, $approved] = approvedImportCostPreparation($this);
if (DB::getDriverName() === 'pgsql') {
DB::unprepared("CREATE FUNCTION reject_synthetic_import_cost_receipt() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.kind = 'import_cost_event' THEN RAISE EXCEPTION 'Synthetic receipt failure'; END IF; RETURN NEW; END $$;
+12
View File
@@ -1,5 +1,6 @@
<?php
use App\Models\Requisition;
use App\Models\StockMovement;
use App\Models\StockOperation;
use App\Models\SupplyRecord;
@@ -10,6 +11,7 @@ use App\Services\InventoryDispositions;
use App\Services\InventoryLots;
use App\Services\InventoryReversals;
use App\Services\InvoiceWorkflow;
use App\Services\ProcurementDeliveryInsights;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\StockWorkflow;
@@ -17,6 +19,7 @@ use App\Services\SupplyCoordination;
use App\Services\SupplyHistory;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -128,7 +131,14 @@ test('a reversal outside a closed history period invalidates its signature and c
});
test('receipt reversal restores authorised quantities without deleting acceptance and a new correction receipt is not a duplicate', function () {
supplyGrant($this->f['issuer'], ['procurement']);
$delivery = fn () => app(ProcurementDeliveryInsights::class)->build($this->f['issuer'], Requisition::query()->whereKey($this->f['r']->id),
CarbonImmutable::now(), null, 'all');
$this->actingAs($this->f['issuer']);
expect($delivery()['unverified_receipt_lines'])->toBe(0);
$executed = executeReversal($this, approvedReversal($this, ['source_kind' => 'receipt', 'receipt_item_id' => $this->receiptItem->id]));
$this->actingAs($this->f['issuer']);
expect($delivery()['unverified_receipt_lines'])->toBe(0);
expect(app(ReceiptWorkflow::class)->recordedQuantity($this->f['line']->id, 'received_milli'))->toBe(0)
->and(app(ReceiptWorkflow::class)->recordedQuantity($this->f['line']->id, 'accepted_milli'))->toBe(0)
->and($this->receiptItem->fresh()->accepted_milli)->toBe(10000)
@@ -140,6 +150,8 @@ test('receipt reversal restores authorised quantities without deleting acceptanc
expect(app(ReceiptWorkflow::class)->recordedQuantity($this->f['line']->id, 'accepted_milli'))->toBe(10000)
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(10000)
->and($executed->snapshot['source']['receipt']['accepted_milli'])->toBe(10000);
$this->actingAs($this->f['issuer']);
expect($delivery()['unverified_receipt_lines'])->toBe(0);
});
test('receipt line reversal removes the full documentary quantities but only the accepted physical entry', function () {
+12
View File
@@ -48,6 +48,18 @@ test('policy author cannot approve own proposal', function () {
$this->post('/regras-investimento/'.$policy->id.'/decidir', ['decision' => 'approved', 'reason' => 'Teste'])->assertForbidden();
});
test('investment preparation consultation keeps policy and reviews private without publishing or changing them', function () {
$policy = proposeInvestmentTest($this);
$before = InvestmentPolicy::query()->get()->toArray();
$reviews = InvestmentPolicyReview::query()->get()->toArray();
$response = $this->get('/regras-investimento')->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true && $page['props']['canManage'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
$this->actingAs($this->f['issuer'])->get('/regras-investimento')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['canManage'] === false);
expect(InvestmentPolicy::query()->get()->toArray())->toBe($before)
->and(InvestmentPolicyReview::query()->get()->toArray())->toBe($reviews)
->and($policy->fresh()->status)->toBe('pending');
});
test('policy parameters and decisions cannot be rewritten', function () {
$policy = proposeInvestmentTest($this);
expect(fn () => $policy->update(['ceiling_minor' => 1]))->toThrow(LogicException::class);
@@ -49,6 +49,27 @@ afterEach(function () {
}
});
test('company preparation and bootstrap protect history without configuration or access writes', function () {
DB::table('organization_access')->where('tenant_id', $this->f['tenant']->id)->update(['active' => false]);
$legacyAdmin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['r']->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$starter = User::factory()->create(['tenant_id' => null, 'department_id' => null, 'purchasing_role' => PurchasingRole::Requester]);
$tables = ['tenants', 'departments', 'cost_centers', 'users', 'organization_profiles', 'organization_memberships', 'organization_access', 'audit_logs'];
$snapshot = static function () use ($tables): array {
$frames = [];
foreach ($tables as $table) {
$frames[$table] = DB::table($table)->get()->map(fn (object $row) => json_encode((array) $row, JSON_THROW_ON_ERROR))->sort()->values()->all();
}
return $frames;
};
$before = $snapshot();
foreach ([[$legacyAdmin, '/empresa', 'company/index'], [$starter, '/empresa/iniciar', 'company/setup']] as [$actor, $url, $component]) {
$response = $this->actingAs($actor)->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === $component && $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
}
expect($snapshot())->toBe($before);
});
test('intelligence settings are independently configurable audited and scoped without rewriting processes', function () {
if (DB::getDriverName() === 'pgsql') {
// The real report opens its own read-only snapshot, outside the test wrapper.
+2 -1
View File
@@ -52,7 +52,8 @@ test('contract report preserves unknown legacy associations without writes and e
$this->withoutVite();
$before = [DB::table('purchase_orders')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page->where('contractInsights.coverage.unknown', 1)
->where('contractInsights.coverage.without_contract', 0)->where('contractInsights.currencies.0.amount_minor', '10000'));
->where('contractInsights.coverage.without_contract', 0)->where('contractInsights.currencies.0.amount_minor', '10000')
->where('deliveryInsights.coverage.unknown', 1)->where('deliveryInsights.records.data.0.late_days', null));
$csv = $this->get('/relatorios/contratos.csv')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain('"Associação por determinar";MZN;1;10000')->toContain('não pagamentos')
->and([DB::table('purchase_orders')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
+77
View File
@@ -8,11 +8,13 @@ use App\Models\GoodsReceipt;
use App\Models\Invoice;
use App\Models\Supplier;
use App\Models\User;
use App\Services\SupplyPlanning;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
// The new page is built privately; HTTP scope tests must not require publishing it to the pilot.
@@ -21,6 +23,81 @@ beforeEach(function () {
$this->actingAs($this->f['issuer']);
});
test('global supply search returns only current native agreement and contract references with no private payload or writes', function () {
config(['procurement_search.supply_metadata_enabled' => true, 'agreement_order_limits.qa_enabled' => true]);
supplyGrant($this->f['issuer'], ['supply_prepare']);
$planning = app(SupplyPlanning::class);
$agreement = $planning->save($this->f['issuer'], 'agreement', supplyInput([
'stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
'supplier_id' => $this->f['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(),
'valid_until' => today()->addYear()->toDateString(), 'origin' => 'local', 'currency' => 'MZN',
'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'SEARCH-AGREEMENT-OLD']));
$current = $planning->save($this->f['issuer'], 'agreement', supplyInput([...$agreement->data,
'reference' => 'SEARCH-AGREEMENT-NEW'], 'save', $agreement));
$contract = $planning->save($this->f['issuer'], 'contract', supplyInput([
'supplier_id' => $this->f['order']->supplier_id, 'reference' => 'SEARCH-CONTRACT', 'currency' => 'MZN',
'valid_from' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString(),
'periodicity_days' => 30, 'order_limit_amount' => '100.00', 'lead_days' => 3]));
$supplierName = $contract->snapshot['supplier']['name'];
Supplier::query()->findOrFail($this->f['order']->supplier_id)->update(['name' => 'Later supplier name, outside original reference']);
$before = [];
foreach (['supply_records', 'audit_logs', 'requisitions', 'purchase_orders', 'invoices', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/compras/pesquisa?q=SEARCH-')->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)->assertInertia(fn (Assert $page) => $page
->where('supplySearchAvailable', true)->has('groups', 3)
->where('groups.1.records.total', 1)->where('groups.1.records.data.0.id', $current->id)
->where('groups.1.records.data.0.title', 'SEARCH-AGREEMENT-NEW · v2')
->where('groups.1.records.data.0.href', '/compras/fornecimento?view=agreements&record_id='.$current->id.'#supply-record-'.$current->id)
->where('groups.2.records.data.0.id', $contract->id)->missing('groups.2.records.data.0.data')
->missing('groups.2.records.data.0.price_minor')->missing('groups.2.records.data.0.snapshot'));
$this->get('/compras/pesquisa?q=SEARCH-AGREEMENT-OLD')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 0));
$this->get('/compras/pesquisa?q='.urlencode($supplierName))->assertInertia(fn (Assert $page) => $page
->where('groups.1.records.total', 1)->where('groups.2.records.total', 1));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->get('/compras/fornecimento?view=agreements&record_id='.$current->id)->assertOk();
$this->get('/compras/fornecimento?view=contracts&record_id='.$contract->id)->assertOk();
config(['procurement_search.supply_metadata_enabled' => false]);
$this->get('/compras/pesquisa?q=SEARCH-')->assertInertia(fn (Assert $page) => $page->where('supplySearchAvailable', false)->has('groups', 1));
});
test('supply search preserves native isolation literal matching pagination and current access', function () {
config(['procurement_search.supply_metadata_enabled' => true]);
$own = $this->f;
supplyGrant($own['issuer'], ['supply_read', 'supply_prepare']);
$planning = app(SupplyPlanning::class);
$input = ['stock_item_id' => $own['stock']->id, 'warehouse_id' => $own['warehouse']->id,
'supplier_id' => $own['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(),
'valid_until' => today()->addYear()->toDateString(), 'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4];
foreach (range(1, 17) as $index) {
$planning->save($own['issuer'], 'agreement', supplyInput([...$input, 'reference' => 'SUPPLY-PAGE-'.$index]));
}
$literal = $planning->save($own['issuer'], 'agreement', supplyInput([...$input, 'reference' => 'LITERAL%_SUPPLY']));
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['supply_prepare']);
$this->actingAs($foreign['issuer']);
$planning->save($foreign['issuer'], 'agreement', supplyInput([...$input,
'stock_item_id' => $foreign['stock']->id, 'warehouse_id' => $foreign['warehouse']->id,
'supplier_id' => $foreign['order']->supplier_id, 'reference' => 'SUPPLY-PAGE-FOREIGN']));
$this->actingAs($own['issuer'])->get('/compras/pesquisa?q=SUPPLY-PAGE&agreements_page=2')->assertOk()
->assertInertia(fn (Assert $page) => $page->has('groups', 2)->where('groups.1.records.total', 17)
->where('groups.1.records.current_page', 2)->has('groups.1.records.data', 2));
$this->get('/compras/pesquisa?q='.urlencode('%_'))->assertInertia(fn (Assert $page) => $page
->where('groups.1.records.total', 1)->where('groups.1.records.data.0.id', $literal->id));
$this->get('/compras/pesquisa?q=SUPPLY-PAGE&agreements_page=0')->assertSessionHasErrors('agreements_page');
$this->get('/compras/pesquisa?q=SUPPLY-PAGE&contracts_page=0')->assertSessionHasErrors('contracts_page');
$requester = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id,
'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($requester, ['requester']);
$this->actingAs($requester)->get('/compras/pesquisa?q=SUPPLY-PAGE')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('supplySearchAvailable', false)->has('groups', 1));
$this->actingAs($own['issuer']);
DB::table('organization_memberships')->where('user_id', $own['issuer']->id)->update(['expires_at' => now()->subSecond()]);
$this->get('/compras/pesquisa?q=SUPPLY-PAGE')->assertForbidden();
});
test('process search combines native modules without exposing financial or contact data or writing records', function () {
$this->f['r']->update(['number' => 'QA-NEED-001', 'justification' => 'Necessidade sintética de ensaio global.']);
$supplier = Supplier::query()->findOrFail($this->f['order']->supplier_id);
+220 -23
View File
@@ -47,6 +47,7 @@ use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementContractInsights;
use App\Services\ProcurementDeliveryInsights;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
@@ -56,12 +57,14 @@ use App\Services\PurchaseRevisionWorkflow;
use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -69,16 +72,17 @@ use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
function nativeCapitalAssignment(object $test): array
function nativeCapitalAssignment(object $test, string $type = 'project'): array
{
config(['capital-register.qa_enabled' => true]);
$test->actingAs($test->buyer);
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => $type,
'code' => 'PRJ-NATIVE-QA', 'name' => 'Projecto sintético da ordem', 'department_id' => $test->department->id,
'equipment_id' => null, 'reference' => 'Documento sintético de investimento', 'state' => 'active', 'reason' => 'Cadastro estritamente sintético da ligação à ordem'];
$source = app(CapitalRegister::class)->save($test->buyer, $input);
@@ -121,6 +125,45 @@ test('native order preserves the capital destination and print after the indepen
expect(DB::table('stock_movements')->get()->toJson())->toBe($before);
});
test('native frozen asset origin connects later equipment registration to its actual order and receipt', function () {
[$source, $assignment, $input] = nativeCapitalAssignment($this, 'asset');
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
expect($order->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'ASSET-QA', 'name' => 'Armazém sintético']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'ASSET-QA', 'name' => 'Artigo sintético', 'unit' => 'un']);
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'ASSET-LATE-LINK-QA',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
$this->actingAs($this->buyer);
$level = CriticalityLevel::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'created_at' => now(),
'code' => 'ASSET-QA', 'name' => 'Criticidade de ensaio', 'criteria' => 'Registo exclusivamente sintético', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'department_id' => $this->department->id,
'code' => 'EQ-LATE-QA', 'description' => 'Equipamento registado após recepção sintética', 'area' => 'Área de ensaio', 'status' => 'active', 'criticality_level_id' => $level->id]);
app(CapitalRegister::class)->save($this->buyer, [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $source->record_key,
'version' => 1, 'equipment_id' => $equipment->id, 'name' => 'Referência actual do activo', 'state' => 'archived']);
$before = [];
foreach (['purchase_orders', 'purchase_order_items', 'goods_receipts', 'goods_receipt_items', 'budget_entries', 'stock_movements', 'audit_logs', 'supply_records'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->withoutVite();
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->where('capitalReference.record_key', $source->record_key)->where('capitalReference.version', 2)
->where('capitalReference.state', 'archived')->missing('capitalReference.reason')->missing('capitalReference.snapshot'));
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('trace.orders.data.0.order_number', $order->number)->where('trace.receipts.data.0.receipt_id', $receipt->id));
expect($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['version'])->toBe(1)
->and($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
config(['capital-register.qa_enabled' => false]);
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('capitalReference', null));
$other = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outra área QA'])->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($other)->get('/equipamentos/'.$equipment->id)->assertNotFound();
});
test('native partial order freezes the same explicit capital origin without changing its financial allocation', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
@@ -815,6 +858,18 @@ function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bo
}
beforeEach(function () {
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
$source = requisitionLedgerQaSource();
if ($source === null) {
throw new LogicException('Integrated orders require the dedicated actual-ledger QA runner.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
expect($composition['verified_tables'])->toHaveCount(12);
}
$this->tenant = Tenant::query()->create(['name' => 'Empresa das ordens']);
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Produção']);
$center = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'PROD', 'name' => 'Produção']);
@@ -880,6 +935,89 @@ test('discount evidence and net prices survive award order and printable report'
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('20.00%');
});
test('native order preserves common ledger account references without creating a journal or changing the chart', function () {
$source = getenv('RQ01_LEDGER_QA_SOURCE');
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
$this->markTestSkipped('Dedicated real common-ledger QA schema required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
config(['requisition-accounts.qa_enabled' => true]);
$id = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->tenant->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-NATIVE-ACCOUNT', 'label' => 'Conta fictícia da necessidade', 'currency' => 'MZN', 'is_movement' => true]);
$this->r->update(['status' => 'draft']);
$this->actingAs($this->owner);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->owner, $this->r);
$record = $service->save($this->owner, $this->r, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Referência contabilística da necessidade sintética',
'allocations' => [['account_id' => $id, 'source_hash' => $space['accounts']['data'][0]['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]]);
$this->r->update(['status' => 'approved']);
$before = DB::table('gl_accounts')->get()->toJson();
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['account_assignments'][$this->item->id]['id'])->toBe($record->id)
->and($order->snapshot['account_assignments'][$this->item->id]['data']['allocations'][0]['account']['code'])->toBe('QA-NATIVE-ACCOUNT')
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_accounts')->get()->toJson())->toBe($before);
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()
->assertSee('QA-NATIVE-ACCOUNT')->assertSee('Parcelas originais');
});
test('native order preserves common ledger across partial and consolidated origins', function (string $mode) {
$source = getenv('RQ01_LEDGER_QA_SOURCE');
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Dedicated common ledger and authorised order-parts QA composition required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
config(['requisition-accounts.qa_enabled' => true]);
DB::table('gl_accounts')->insert(['tenant_id' => $this->tenant->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-ORIGINS-ACCOUNT', 'label' => 'Conta fictícia das origens', 'currency' => 'MZN', 'is_movement' => true]);
$firstAward = nativeOrderPartsAward($this);
$requests = [$this->r];
$secondAward = null;
if ($mode === 'consolidated') {
[$second, $quotes] = secondNativeOrderPartsOrigin($this);
$secondAward = nativeOrderPartsAward($this, $second, $quotes[0]);
$requests[] = $second;
}
$records = [];
foreach ($requests as $request) {
$request->refresh()->update(['status' => 'draft']);
$this->actingAs($this->owner);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->owner, $request);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
$records[$line['id']] = $service->save($this->owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação original explícita no ensaio das origens',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
'subtotal' => (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2), 'total' => (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2)]]]);
$request->update(['status' => 'approved']);
}
$this->actingAs($this->buyer);
$flow = app(OrderPartsWorkflow::class);
if ($secondAward === null) {
$orders = [$flow->issue($this->buyer, nativeOrderPartsInput($this, $firstAward, '0.400', 0)),
$flow->issue($this->buyer, nativeOrderPartsInput($this, $firstAward, '0.600', 1))];
} else {
$a = nativeOrderPartsInput($this, $firstAward, '1.000', 0);
$b = nativeOrderPartsInput($this, $secondAward, '1.000', 0);
$input = [...$a, 'sources' => [...$a['sources'], ...$b['sources']], 'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]];
$input['fingerprint'] = app(OrderPartsPreparation::class)->prepare($this->buyer, $input)['fingerprint'];
$orders = [$flow->issue($this->buyer, $input)];
}
foreach ($orders as $order) {
expect($order->snapshot['account_assignments'])->toHaveCount(count($records));
foreach ($records as $line => $record) {
expect($order->snapshot['account_assignments'][$line]['id'])->toBe($record->id)
->and($order->snapshot['account_assignments'][$line]['data']['allocations'])->toBe($record->data['allocations']);
}
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('QA-ORIGINS-ACCOUNT')->assertSee('Parcelas originais');
}
expect(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_accounts')->count())->toBe(1);
})->with(['partial', 'consolidated']);
test('comparison rule is printed with the order and policy tampering invalidates an approved award', function () {
$policy = [...ComparisonPolicy::DEFAULTS, 'revision' => 1, 'configured' => true];
$this->r->update(['comparison_policy' => $policy]);
@@ -964,12 +1102,25 @@ test('invalid source policy approval or unsupported purchase type cannot be pres
$this->r->update(['approval_snapshot' => null]);
} elseif ($change === 'approval') {
$this->r->steps()->update(['decision' => 'pending']);
} elseif (in_array($change, ['additional', 'routing'], true)) {
// Deliberately inconsistent synthetic history: a frozen level without its decision.
$this->r->update(['approval_snapshot' => [...$this->r->approval_snapshot,
'additional_levels' => ['configured_1' => ['name' => 'Synthetic missing level', 'profile_ids' => [1], 'scope' => 'company']]]]);
if ($change === 'routing') {
$this->r->steps()->create(['tenant_id' => $this->tenant->id, 'position' => $this->r->steps()->count() + 1,
'role' => 'configured_1', 'decision' => 'approved', 'approver_id' => $this->finance->id, 'decided_at' => now(),
'routing' => ['name' => 'Mismatched synthetic routing', 'profile_ids' => [2], 'scope' => 'company']]);
}
} elseif ($change === 'approval_basis') {
// A frozen landed-cost basis cannot be replaced by the lower goods-only amount.
$this->r->update(['approval_snapshot' => [...$this->r->approval_snapshot,
'approval_basis' => ['subtotal_minor' => 1000000000, 'total_minor' => 1000000000]]]);
} else {
$this->item->update(['purchase_type' => $change]);
}
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors($error);
expect(PurchaseAward::query()->count())->toBe(0);
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['additional', 'approvals'], ['routing', 'approvals'], ['approval_basis', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
test('award approvals enforce role order department distinct people and no self approval', function () {
awardPrices($this, 15000001);
@@ -1630,6 +1781,48 @@ function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quant
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('budget consultations use the common balance and protect private history without source writes', function () {
$this->withoutVite();
$centre = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id,
'code' => 'BUD-PRIV-QA', 'name' => 'Synthetic private budget view']);
$this->actingAs($this->finance);
$budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Explicit synthetic budget for private native read regression']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($budget);
$tables = ['budgets', 'budget_entries', 'budget_consumptions', 'audit_logs'];
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
$before = $snapshot();
$response = $this->actingAs($this->finance)->get('/orcamentos')->assertOk()
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('budgets/index')->where('budgets.0.id', $budget)->where('budgets.0.available_minor', 100000));
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store');
$this->actingAs($this->owner)->getJson('/orcamentos')->assertForbidden();
expect($snapshot())->toBe($before);
});
test('purchase control preparations retain native scope encrypted history and private headers without source writes', function () {
$this->withoutVite();
$this->actingAs($this->admin);
app(PurchaseControlPolicyWorkflow::class)->propose($this->admin, ['previous_id' => 0, 'mode' => 'unissued_award',
'enabled' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
'reason' => 'Pending disabled synthetic proposal exists before comparing operational and requester visibility']);
$tables = ['requisitions', 'purchase_awards', 'purchase_control_policies', 'purchase_control_reviews', 'award_cancellations',
'purchase_revisions', 'audit_logs', 'budget_entries', 'stock_movements'];
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
$before = $snapshot();
$response = $this->actingAs($this->admin)->get('/revisao-compras')->assertOk()
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('purchase-controls/index')->where('actorId', $this->admin->id)
->has('policies', 1)->where('policies.0.status', 'pending')->where('policies.0.enabled', false));
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store');
$response = $this->actingAs($this->owner)->get('/revisao-compras')->assertOk()
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->where('actorId', $this->owner->id)->has('policies', 0)->has('awards', 0)->has('cancellations', 0));
expect($response->headers->get('Cache-Control'))->toContain('private', 'no-store')
->and($snapshot())->toBe($before);
});
test('native partial-order foreign receipts and invoices preserve origin rates and cumulative remainders', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
@@ -1813,10 +2006,12 @@ test('native partial-order issuance commits only forty then sixty and preserves
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
$this->markTestSkipped('Explicit cycle-capable common QA source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
config(['requisition-expiry.qa_enabled' => true]);
$engine = app(CommonBudget::class)->for($this->buyer, [$this->r->id => 1]);
$engine->beginRequisitionCycle($this->r->id, 1, (string) Str::uuid());
@@ -1935,13 +2130,13 @@ function commitNativeReviewReportFixture(object $test): void
$test->committedConsolidatedReportFixture = true;
}
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function () {
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function (bool $afterDue) {
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
$service = app(\App\Services\ProcurementDeliveryInsights::class);
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), \Carbon\CarbonImmutable::now(), null, 'all');
$service = app(ProcurementDeliveryInsights::class);
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), CarbonImmutable::now(), null, 'all');
expect($read()['coverage']['pending'])->toBe(1);
$due = \Carbon\CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
$due = CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
$this->travelTo($due);
expect($read()['coverage']['pending'])->toBe(1);
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
@@ -1952,27 +2147,29 @@ test('native delivery analysis follows the frozen promise partial receipts and a
'received_quantity' => $quantity, 'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.400'));
$this->travel(1)->days();
$this->travel($afterDue ? 1 : 0)->days();
$this->actingAs($this->buyer);
$late = $read();
expect($late['coverage']['pending_late'])->toBe(1)->and($late['records']['data'][0]['late_days'])->toBe(1)
->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
expect($late['coverage'][$afterDue ? 'pending_late' : 'pending'])->toBe(1);
if ($afterDue) {
expect($late['records']['data'][0]['late_days'])->toBe(1)->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
}
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.600'));
$this->actingAs($this->buyer);
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$complete = $read();
expect($complete['coverage']['completed_late'])->toBe(1)->and($complete['pending_lines'])->toBe(0)
->and($complete['records']['data'][0]['late_lines'][0]['completed_on'])->toBe(today()->toDateString())
$completedState = $afterDue ? 'completed_late' : 'completed_on_time';
expect($complete['coverage'][$completedState])->toBe(1)->and($complete['pending_lines'])->toBe(0)
->and([DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
commitNativeReviewReportFixture($this);
$this->withoutVite();
$this->get('/relatorios?delivery_state=completed_late')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('deliveryInsights.coverage.completed_late', 1)->where('deliveryInsights.records.data.0.number', $order->number));
$csv = $this->get('/relatorios/entregas.csv?delivery_state=completed_late')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain($order->number)->toContain('Recepção integral depois da data acordada')->toContain('0.000');
$this->get('/relatorios?delivery_state='.$completedState)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('deliveryInsights.coverage.'.$completedState, 1)->where('deliveryInsights.records.data.0.number', $order->number));
$csv = $this->get('/relatorios/entregas.csv?delivery_state='.$completedState)->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain($order->number)->toContain(ProcurementDeliveryInsights::LABELS[$completedState]);
$this->travelBack();
});
})->with([false, true]);
function secondNativeOrderPartsOrigin(object $test): array
{
@@ -2035,8 +2232,8 @@ test('native consolidated order retains both origins and consumes a single invoi
expect($order->total_minor)->toBe(30000)->and($order->items()->count())->toBe(2)
->and(DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->count())->toBe(2)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->whereKey($order->id)->exists())->toBeTrue();
$delivery = app(\App\Services\ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
\Carbon\CarbonImmutable::now()->addDays(8), null, 'all');
$delivery = app(ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
CarbonImmutable::now()->addDays(8), null, 'all');
expect($delivery['coverage']['pending_late'])->toBe(1)->and($delivery['unknown_lines'])->toBe(0)
->and($delivery['records']['data'][0]['late_lines'])->toHaveCount(1)
->and($delivery['records']['data'][0]['late_lines'][0]['id'])->toBe($order->items()->where('requisition_item_id', $this->item->id)->value('id'));
+6
View File
@@ -22,6 +22,12 @@ beforeEach(function () {
$this->payload = receiptPayload($this->f);
});
test('receipt preparation uses encrypted history without registering a receipt or stock movement', function () {
$this->get($this->url)->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('receipts/order')->where('canConfirm', true));
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
});
test('partial then total receipts preserve pending quantities and credit only accepted stock', function () {
$this->postJson($this->url, receiptPayload($this->f, '0.400'))->assertCreated()->assertJsonPath('status', 'partial');
$first = GoodsReceipt::query()->firstOrFail();
@@ -2,9 +2,14 @@
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\CostCenter;
use App\Models\Department;
use App\Models\Requisition;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\EquipmentWorkflow;
use App\Services\RequisitionApprovalLevels;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowNotices;
@@ -111,6 +116,65 @@ function configuredDecision($test, User $actor, Requisition $record, string $dec
$test->actingAs($actor)->postJson('/requisicoes/'.$record->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $record->fresh()->process_version, 'decision' => $decision, 'comment' => 'Fundamento sintético da decisão.'])->assertRedirect();
}
test('classified machinery follows an explicitly designated direction level at any value through the existing contract', function () {
config(['capital-register.qa_enabled' => true]);
$tenant = $this->f['tenant']->id;
$this->f['tenant']->update(['first_limit_minor' => 100000000, 'second_limit_minor' => 200000000]);
$direction = approvalLevelProfile($tenant, 'Direcção de maquinaria QA', ['requisition_approve']);
approvalLevelMember($this->approvers[0], $direction);
$this->plan['levels'] = [[...$this->plan['levels'][0], 'name' => 'Direcção para maquinaria', 'profile_ids' => [$direction],
'procurement_categories' => ['capital_equipment']]];
$this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect();
$body = $this->body;
$centre = CostCenter::query()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id,
'code' => 'CAP-DIR-QA', 'name' => 'Centro sintético de investimento']);
$this->actingAs($this->financier);
$budget = app(CommonBudget::class)->for($this->financier)->create(['cost_center_id' => $centre->id,
'year' => (int) now()->year, 'kind' => 'investment', 'amount_minor' => 1000000, 'includes_tax' => true,
'reason' => 'Dotação exclusivamente sintética para circuito de capital']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($budget);
$body['cost_center_id'] = $centre->id;
$body['items'][0] = [...$body['items'][0], 'purchase_type' => 'equipment', 'production_area' => 'Produção QA',
'procurement_category' => 'capital_equipment', 'category_reason' => 'Investimento exclusivamente sintético para aprovação multinível'];
$this->postJson('/requisicoes', $body)->assertRedirect();
$request = Requisition::query()->latest('id')->firstOrFail();
$project = app(CapitalRegister::class)->save($this->admin, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'type' => 'project', 'code' => 'PRJ-DIR-QA', 'name' => 'Projecto sintético de maquinaria', 'department_id' => $request->department_id,
'reference' => 'Referência de ensaio sem projecto real', 'state' => 'active', 'reason' => 'Cadastro próprio para ensaio do circuito']);
app(CapitalAssignments::class)->save($this->admin, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $request->items()->sole()->id, 'capital_id' => $project->id, 'reason' => 'Destino expresso de investimento sintético']);
expect(DB::table('budget_entries')->count())->toBe(0);
$this->actingAs($this->head);
$technical = app(EquipmentWorkflow::class);
$technical->review($this->head, $request, $technical->basis($request), 'approved', 'Conferência técnica independente de maquinaria QA');
$this->actingAs($this->admin);
foreach ([0, 1000000000000] as $amount) {
expect(app(RequisitionApprovalLevels::class)->policy($request, $amount)['additional_levels']['configured_1']['profile_ids'])->toBe([$direction]);
}
$this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])->assertRedirect();
$request->refresh();
expect($request->total_minor)->toBe(11600)->and($request->steps()->orderBy('position')->pluck('role')->all())
->toBe(['department_head', 'finance', 'configured_1'])
->and($request->approval_snapshot['additional_levels']['configured_1']['procurement_categories'])->toBe(['capital_equipment']);
configuredDecision($this, $this->head, $request);
configuredDecision($this, $this->financier, $request);
$this->actingAs($this->admin)->postJson('/administracao/parametrizacao/approval_levels', [
'version' => 2, 'enabled' => false, 'levels' => [], 'reason' => 'Alteração sintética só para pedidos futuros'])->assertRedirect();
approvalLevelMember($this->admin, $direction);
foreach ([$this->admin, $this->approvers[1]] as $ineligible) {
$this->actingAs($ineligible)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Tentativa sintética sem elegibilidade'])->assertForbidden();
}
DB::table('organization_memberships')->where('user_id', $this->approvers[0]->id)->where('profile_id', $direction)->update(['expires_at' => now()->subSecond()]);
expect($request->fresh()->canDecide($this->approvers[0]))->toBeFalse();
DB::table('organization_memberships')->where('user_id', $this->approvers[0]->id)->where('profile_id', $direction)->update(['expires_at' => null]);
configuredDecision($this, $this->approvers[0], $request);
expect($request->fresh()->status)->toBe('approved')->and($request->steps()->where('role', 'configured_1')->sole()->approver_id)->toBe($this->approvers[0]->id)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(11600)
->and(DB::table('stock_movements')->count())->toBe(0);
});
test('native three controls and five configured levels progress sequentially with one eligible person per level', function () {
$r = submitConfiguredRequest($this);
expect($r->steps()->count())->toBe(8)->and($r->approval_snapshot['routing_quorum'])->toBe('one_eligible');
+262 -3
View File
@@ -11,19 +11,36 @@ use App\Services\ProcurementOperationalInsights;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\UrgentRequisitionReviews;
use App\Services\WorkflowNotices;
use App\Services\WorkflowTaskInbox;
use Carbon\CarbonImmutable;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Purchasing\Internal\InternalRequisitions;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
afterEach(function () {
if ($this->committedUrgentReviewFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Urgent review cleanup requires its disposable committed QA fixture.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
@@ -35,9 +52,21 @@ beforeEach(function () {
$this->budget = Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true,
'reason' => 'Dotação aprovada estritamente sintética para ciclos', 'created_by' => $this->f['issuer']->id, 'approved_by' => $this->reviewer->id]);
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
$source = requisitionLedgerQaSource();
if ($source === null) {
throw new LogicException('Integrated cycles require the dedicated actual-ledger QA runner.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
expect($composition['verified_tables'])->toHaveCount(12);
} else {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
config(['requisition-expiry.qa_enabled' => true]);
});
@@ -161,6 +190,217 @@ test('import assumptions release in the old cycle before a separately identified
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
});
test('urgent deadlines are explicitly configured frozen per submission and expire only the selected request', function () {
$owner = $this->f['issuer'];
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Destinatário sintético configurável',
'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
$this->actingAs($admin);
$expiry = app(RequisitionExpiry::class);
$policy = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'reason' => 'Prazos sintéticos explícitos para conferir urgências',
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => 20, 'profile_ids' => [$profile],
'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => 2]]];
$first = $expiry->savePolicy($admin, $policy);
expect($expiry->savePolicy($admin, $policy)->id)->toBe($first->id);
$this->actingAs($owner);
$workflow = app(RequisitionWorkflow::class);
$make = function (string $priority) use ($owner, $workflow) {
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id,
'priority' => $priority, 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade sintética com prioridade expressamente indicada',
'items' => [['description' => 'Material sintético', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000',
'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
return $request->fresh();
};
$normal = $make('normal');
$urgent = $make('urgent');
$normalDeadline = $expiry->deadline($normal);
$urgentDeadline = $expiry->deadline($urgent);
expect($normalDeadline['timing'])->toBe('standard')->and($urgentDeadline['timing'])->toBe('urgent_override')
->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['expires_at'])))->toEqual(300)
->and(CarbonImmutable::parse($normalDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($normalDeadline['expires_at'])))->toEqual(1800)
->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['reminder_at'])))->toEqual(60)
->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['escalation_at'])))->toEqual(120);
$policy['operation_key'] = (string) Str::uuid();
$policy['version'] = 1;
$policy['levels'][0]['urgent_expire_minutes'] = 4;
$this->actingAs($admin);
$expiry->savePolicy($admin, $policy);
$this->actingAs($owner);
expect($expiry->deadline($urgent)['expires_at'])->toBe($urgentDeadline['expires_at']);
$later = $make('urgent');
$laterDeadline = $expiry->deadline($later);
expect(CarbonImmutable::parse($laterDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($laterDeadline['expires_at'])))->toEqual(240);
$this->travel(2)->minutes();
$check = $expiry->check($owner, $urgent, ['operation_key' => (string) Str::uuid(), 'process_version' => $urgent->process_version]);
expect($check['notices_created'])->toBe(1)->and($check['escalation_eligible'])->toBe(0);
$this->travel(3)->minutes();
$deadline = $expiry->deadline($urgent);
expect($deadline['state'])->toBe('expired')->and($expiry->deadline($normal)['state'])->toBe('running');
$this->postJson('/requisicoes/'.$urgent->id.'/expiracao', ['operation_key' => (string) Str::uuid(), 'process_version' => $urgent->process_version,
'basis_hash' => $deadline['basis_hash']])->assertRedirect();
expect($urgent->fresh()->status)->toBe('draft')->and($normal->fresh()->status)->toBe('pending')
->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(20000);
$this->travelBack();
});
test('urgent configuration rejects missing slower or unordered deadlines and preserves legacy replay inputs', function () {
$owner = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($owner);
$expiry = app(RequisitionExpiry::class);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'reason' => 'Política sintética sem alteração dos pedidos antigos',
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]]];
$record = $expiry->savePolicy($owner, $input);
expect($record->data['levels'][0])->not->toHaveKey('urgent_expire_minutes')
->and($expiry->savePolicy($owner, $input)->id)->toBe($record->id);
foreach ([['urgent_expire_minutes' => 30, 'urgent_reminder_minutes' => 1], ['urgent_expire_minutes' => 5],
['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 5], ['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => 2],
['urgent_reminder_minutes' => 1]] as $changes) {
$bad = $input;
$bad['operation_key'] = (string) Str::uuid();
$bad['version'] = 1;
$bad['levels'][0] = [...$bad['levels'][0], ...$changes];
expect(fn () => $expiry->savePolicy($owner, $bad))->toThrow(ValidationException::class);
}
expect(SupplyRecord::query()->where('kind', 'req_expiry_policy')->count())->toBe(1);
});
test('posterior urgent review follows final decisions and preserves each concluded cycle without changing financial sources', function (string $outcome) {
config(['urgent-reviews.qa_enabled' => true]);
$owner = $this->f['issuer'];
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$reviewer = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Procurement]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Direcção de Compras sintética',
'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $owner->tenant_id, 'profile_id' => $profile, 'user_id' => $reviewer->id, 'maintenance' => false]);
$service = app(UrgentRequisitionReviews::class);
$this->actingAs($admin);
$policyInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'profile_ids' => [$profile], 'reason' => 'Designação expressa para a revisão posterior sintética'];
$policy = $service->savePolicy($admin, $policyInput);
expect($service->savePolicy($admin, $policyInput)->id)->toBe($policy->id);
app(RequisitionExpiry::class)->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => [],
'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => null, 'urgent_escalation_minutes' => null]], 'reason' => 'Prazo sintético explícito para conferir expiração e revisão']);
$this->actingAs($owner);
$workflow = app(RequisitionWorkflow::class);
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'urgent',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Urgência sintética que exige revisão posterior do ciclo concluído',
'items' => [['description' => 'Material urgente original', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000',
'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]];
$request = $workflow->save($owner, $input);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->actingAs($reviewer);
expect($service->queue($reviewer)['records']['total'])->toBe(0)
->and(fn () => $service->workspace($reviewer, $request->id, 1))->toThrow(HttpException::class);
if ($outcome === 'expired') {
$this->travel(6)->minutes();
$this->actingAs($owner);
$proof = app(RequisitionExpiry::class)->deadline($request);
$workflow->expire($owner, $request, $proof['basis_hash'], (string) Str::uuid(), $request->process_version);
$request->refresh();
$input['operation_key'] = (string) Str::uuid();
$input['process_version'] = $request->process_version;
$input['priority'] = 'normal';
$input['items'][0]['description'] = 'Nova preparação deliberadamente diferente';
$input['items'][0]['unit_price'] = '120.00';
$request = $workflow->save($owner, $input, $request);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
expect($request->status)->toBe('pending')->and($request->approval_cycle)->toBe(2)
->and((int) DB::table('budget_entries')->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000);
} else {
$this->actingAs($head);
$workflow->decide($head, $request, $outcome, 'Decisão final sintética independente', (string) Str::uuid(), $request->process_version);
}
$this->actingAs($reviewer);
$space = $service->workspace($reviewer, $request->id, 1);
expect($space['source']['outcome'])->toBe($outcome)->and($space['source']['request']['total_minor'])->toBe('10000')
->and($space['source']['items'][0]['description'])->toBe('Material urgente original')->and($space['canReview'])->toBeTrue()
->and($service->queue($reviewer)['coverage']['pending'])->toBe(1);
$this->withoutVite();
$path = '/requisicoes/'.$request->id.'/ciclos/1/revisao-urgencia';
if ($outcome === 'approved' && DB::getDriverName() === 'pgsql') {
if (DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Urgent review native task snapshot requires the guarded QA transaction.');
}
DB::commit();
$this->committedUrgentReviewFixture = true;
$this->get('/requisicoes/tarefas?module=purchases')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('urgentReviewsReady', true)->where('tasks.data', fn ($rows) => collect($rows)->contains('task', 'urgent_requisition_review')));
}
$this->get($path)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page
->component('requisitions/urgent-review')->where('source.outcome', $outcome)->where('canReview', true));
$tasks = app(WorkflowTaskInbox::class)->build($reviewer, 'procurement');
expect(array_column($tasks, 'task'))->toContain('urgent_requisition_review');
$before = [];
foreach (['requisitions', 'requisition_items', 'approval_steps', 'budget_entries', 'stock_movements', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$body = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'source_hash' => $space['source']['fingerprint'], 'notes' => 'Conferência posterior sintética, sem alterar a decisão ou os movimentos'];
$this->postJson($path, $body)->assertRedirect();
$this->postJson($path, $body)->assertRedirect();
expect($service->queue($reviewer)['coverage']['reviewed'])->toBe(1)
->and(SupplyRecord::query()->where('kind', 'urgent_review')->count())->toBe(1)
->and(array_column(app(WorkflowTaskInbox::class)->build($reviewer, 'procurement'), 'task'))->not->toContain('urgent_requisition_review');
$firstReview = SupplyRecord::query()->where('kind', 'urgent_review')->sole();
$this->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'source_hash' => str_repeat('0', 64)])->assertConflict();
$correction = [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'notes' => 'Correcção expressa da revisão, com a primeira versão preservada'];
$this->postJson($path, $correction)->assertRedirect();
$this->postJson($path, $correction)->assertRedirect();
$this->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1])->assertConflict();
expect(SupplyRecord::query()->where('kind', 'urgent_review')->count())->toBe(2)
->and($firstReview->fresh()->data['notes'])->toBe($body['notes'])
->and(DB::table('audit_logs')->where('action', 'urgent.review_recorded')->count())->toBe(2);
if ($outcome === 'expired') {
$latestAudit = DB::table('audit_logs')->where('action', 'urgent.review_recorded')->latest('id')->value('id');
DB::table('audit_logs')->where('id', $latestAudit)->delete();
expect($service->workspace($reviewer, $request->id, 1)['currentVerified'])->toBeFalse()
->and($service->queue($reviewer, null, 'all')['coverage']['indeterminate'])->toBe(1)
->and($service->queue($reviewer, null, 'all')['coverage']['reviewed'])->toBe(0);
$expiration = SupplyRecord::query()->where('kind', 'req_expiration')->sole();
expect(fn () => DB::transaction(fn () => DB::table('supply_records')->where('id', $expiration->id)
->update(['snapshot' => json_encode([...$expiration->snapshot, 'items' => []], JSON_THROW_ON_ERROR)])))->toThrow(QueryException::class)
->and($firstReview->fresh()->snapshot['items'][0]['description'])->toBe('Material urgente original');
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->actingAs($owner)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden();
$this->actingAs($admin)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden();
DB::table('organization_memberships')->where('user_id', $reviewer->id)->update(['expires_at' => now()->subSecond()]);
$this->actingAs($reviewer)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden();
$this->travelBack();
})->with(['approved', 'rejected', 'expired']);
test('urgent review keeps indeterminate coverage and rejects a foreign profile without changing an accepted outcome', function () {
config(['urgent-reviews.qa_enabled' => true]);
$request = $this->f['r'];
$request->update(['priority' => 'urgent']);
$owner = $this->f['issuer'];
$service = app(UrgentRequisitionReviews::class);
$this->actingAs($owner);
$queue = $service->queue($owner, null, 'all');
expect($queue['coverage'])->toBe(['pending' => 0, 'reviewed' => 0, 'indeterminate' => 1])
->and($queue['records']['data'][0]['href'])->toBe('/requisicoes/'.$request->id)
->and(fn () => $service->workspace($owner, $request->id, 1))->toThrow(HttpException::class)
->and($request->fresh()->status)->toBe('approved');
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$foreign = receiptFixture();
$foreignProfile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $foreign['tenant']->id, 'name' => 'Perfil de outra empresa sintética',
'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
$this->actingAs($admin);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'profile_ids' => [$foreignProfile], 'reason' => 'Tentativa sintética de designação fora da empresa'];
expect(fn () => $service->savePolicy($admin, $input))->toThrow(HttpException::class);
$this->withoutVite();
$this->get('/administracao/revisao-urgencias')->assertOk()->assertInertia(fn (Assert $page) => $page->component('organization/urgent-review-policy')->has('profiles', 0));
$this->actingAs($foreign['issuer'])->getJson('/requisicoes/'.$request->id.'/ciclos/1/revisao-urgencia')->assertNotFound();
expect(SupplyRecord::query()->where('kind', 'urgent_review_policy')->count())->toBe(0);
});
test('configured escalation alerts respect current membership and never delegate the pending approval', function () {
$owner = $this->f['issuer'];
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Configured]);
@@ -243,6 +483,10 @@ test('native expiry returns the same request and preserves the approved stage be
->and($request->allSteps()->where('decision', 'expired')->count())->toBe(1)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1);
$this->actingAs($head)->get('/requisicoes?view=decided')->assertInertia(fn (Assert $page) => $page
->where('requisitions.total', 1)->where('requisitions.data.0.id', $request->id)
->has('requisitions.data.0.steps', 0));
$this->actingAs($owner);
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('requisitions/expiry')->where('requisition.approval_cycle', 2)->where('canEdit', true)->has('history.data', 1));
@@ -256,6 +500,21 @@ test('native expiry returns the same request and preserves the approved stage be
->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->sole()->snapshot['request']['total_minor'])->toBe(10000);
$this->f['tenant']->update(['first_limit_minor' => 9000]);
$beforeHistoryRead = [];
foreach (['requisitions', 'approval_steps', 'supply_records', 'audit_logs', 'budget_entries', 'budget_requisition_cycles', 'stock_movements'] as $table) {
$beforeHistoryRead[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('history.data.0.request.total_minor', 10000)->where('history.data.0.request.priority', 'normal')
->where('history.data.0.items.0.description', 'Bem de ensaio')->where('history.data.0.items.0.total_minor', 10000)
->where('history.data.0.rules.first_limit_minor', 5000)->where('history.data.0.rules.approval_includes_tax', true)
->where('history.data.0.approval_amount_minor', 10000)->where('history.data.0.approval_uses_separate_basis', false)
->where('history.data.0.steps.0.approver_id', $head->id)->where('history.data.0.steps.0.comment', 'Conferência sintética do primeiro nível')
->missing('history.data.0.rules.timing')->missing('history.data.0.items.0.category_context'));
foreach ($beforeHistoryRead as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$notices = app(WorkflowNotices::class)->visible($owner);
expect(array_column($notices, 'outcome'))->toContain('expired')
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
@@ -0,0 +1,76 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionDuplicateHints;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function duplicateHintCopy(Requisition $source, array $changes = []): Requisition
{
$copy = $source->replicate();
$copy->fill(['number' => 'REQ-HINT-'.Str::random(12), 'status' => 'draft', ...$changes])->save();
foreach ($source->items as $line) {
$copy->items()->save($line->replicate());
}
return $copy->fresh();
}
test('duplicate advisory is a private native read with no financial or workflow effects', function () {
$f = receiptFixture();
$draft = duplicateHintCopy($f['r']);
$this->actingAs($f['issuer']);
$before = [Requisition::query()->count(), DB::table('audit_logs')->count(), DB::table('budget_entries')->count()];
$this->get('/requisicoes/'.$draft->id)->assertOk()->assertInertia(fn (Assert $page) => $page
->has('duplicateHints.matches', 1)->where('duplicateHints.matches.0.id', $f['r']->id)
->where('duplicateHints.matches.0.status', 'approved')->where('duplicateHints.complete', true)
->missing('duplicateHints.matches.0.items')->missing('duplicateHints.matches.0.justification'));
expect([Requisition::query()->count(), DB::table('audit_logs')->count(), DB::table('budget_entries')->count()])->toBe($before)
->and($draft->fresh()->status)->toBe('draft');
});
test('duplicate advisory excludes different contents dates centres authors and inactive outcomes', function () {
$f = receiptFixture();
$draft = duplicateHintCopy($f['r']);
$this->actingAs($f['issuer']);
$hints = app(RequisitionDuplicateHints::class);
foreach (['cancelled', 'rejected'] as $status) {
$f['r']->update(['status' => $status]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
}
$f['r']->update(['status' => 'pending', 'needed_by' => today()->addDays(20)]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
$f['r']->update(['needed_by' => $draft->needed_by]);
$f['r']->items()->firstOrFail()->update(['description' => 'Outra necessidade sintética']);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
$other = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
$f['r']->items()->firstOrFail()->update(['description' => $draft->items->first()->description]);
$f['r']->update(['requester_id' => $other->id]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
$f['r']->update(['requester_id' => $f['issuer']->id]);
$centre = $draft->costCenter->replicate();
$centre->code = 'OTHER-QA';
$centre->save();
$f['r']->update(['cost_center_id' => $centre->id]);
expect($hints->for($f['issuer'], $draft)['matches'])->toBe([]);
duplicateHintCopy($draft, ['requester_id' => $other->id]);
expect($hints->for($other, $draft))->toBeNull();
$draft->update(['total_minor' => null]);
expect($hints->for($f['issuer'], $draft))->toBeNull();
});
test('bounded duplicate comparison reports incomplete coverage without pretending absence', function () {
$f = receiptFixture();
$draft = duplicateHintCopy($f['r']);
for ($i = 0; $i < 100; $i++) {
duplicateHintCopy($f['r']);
}
$this->actingAs($f['issuer']);
$result = app(RequisitionDuplicateHints::class)->for($f['issuer'], $draft);
expect($result['complete'])->toBeFalse()->and($result['matches'])->toHaveCount(100);
});
@@ -0,0 +1,508 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CriticalityLevel;
use App\Models\Equipment;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrder;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\StockItem;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\EquipmentWorkflow;
use App\Services\ExpenseAllocations;
use App\Services\ExternalPaymentWorkflow;
use App\Services\InvoiceWorkflow;
use App\Services\ProcurementPaymentInsights;
use App\Services\ProposalComparison;
use App\Services\PurchaseLineAmounts;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\RequisitionWorkflow;
use App\Services\SupplierBankWorkflow;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
beforeEach(function () {
$source = requisitionLedgerQaSource();
if ($source === null) {
$this->markTestSkipped('Use the dedicated ledger QA runner with the real common schema and isolated non-elevated role.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::install(DB::connection());
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$this->schemaComposition = integratedPurchasingQaSchema();
}
$this->f = receiptFixture();
$this->item = $this->f['r']->items()->firstOrFail();
$this->actingAs($this->f['issuer']);
$this->withoutVite();
config(['requisition-accounts.qa_enabled' => true]);
$this->account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-ONLY-100', 'label' => 'Conta fictícia de movimentos', 'currency' => 'MZN', 'is_movement' => true]);
});
test('pinned private runtime refuses source fallback and mismatched composition without effects', function () {
if (config('common-finance-bundle.manifest_sha256') !== '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df') {
$this->markTestSkipped('This regression requires the exact frozen private composition.');
}
$tables = ['gl_accounts', 'gl_journals', 'requisitions', 'budget_entries', 'supply_records', 'audit_logs'];
$snapshot = fn () => array_map(fn ($table) => DB::table($table)->orderBy('id')->get()->toJson(), $tables);
$before = $snapshot();
$source = getenv('RQ01_LEDGER_QA_SOURCE');
$settings = ['common-finance-bundle.manifest_sha256' => config('common-finance-bundle.manifest_sha256'),
'common-finance-bundle.root' => config('common-finance-bundle.root'), 'general-ledger.path' => config('general-ledger.path')];
try {
foreach (['C:/laragon/www/sgf-tempo/packages/general-ledger', base_path('storage/framework/testing/unapproved-ledger-source')] as $wrong) {
putenv('RQ01_LEDGER_QA_SOURCE='.$wrong);
expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class);
}
putenv('RQ01_LEDGER_QA_SOURCE='.$source);
foreach (['common-finance-bundle.manifest_sha256' => str_repeat('0', 64),
'common-finance-bundle.root' => base_path('storage/framework/testing/unapproved-ledger-source'),
'general-ledger.path' => 'C:/laragon/www/sgf-tempo/packages/general-ledger'] as $key => $wrong) {
config([$key => $wrong]);
expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class);
config($settings);
}
} finally {
putenv('RQ01_LEDGER_QA_SOURCE='.$source);
config($settings);
}
expect($snapshot())->toBe($before);
});
test('minimal purchasing catalogue reads the actual common chart without journals or a second chart', function () {
$service = app(RequisitionLedgerAccounts::class);
$before = [DB::table('gl_accounts')->get()->toJson(), DB::table('gl_journals')->count(), DB::table('audit_logs')->count()];
$page = $service->options($this->f['issuer']);
expect($service->ready())->toBeTrue()->and($page['total'])->toBe(1)
->and(array_keys($page['data'][0]))->toBe(['id', 'code', 'label', 'currency', 'source_hash'])
->and($service->resolve($this->f['issuer'], $this->account, $page['data'][0]['source_hash']))->toBe($page['data'][0])
->and([DB::table('gl_accounts')->get()->toJson(), DB::table('gl_journals')->count(), DB::table('audit_logs')->count()])->toBe($before);
expect($service->options($this->f['issuer'], '%')['total'])->toBe(0);
expect($service->options($this->f['issuer'], 'fictícia')['total'])->toBe(1);
});
test('chart references reject foreign scope summary accounts and stale hashes', function () {
$service = app(RequisitionLedgerAccounts::class);
$hash = $service->options($this->f['issuer'])['data'][0]['source_hash'];
foreach (['company_id' => 8, 'unit_id' => 9, 'tenant_id' => $this->f['tenant']->id + 100, 'is_movement' => false] as $column => $value) {
$other = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-EXCLUDED-'.$column, 'label' => 'Referência sintética fora do catálogo', 'currency' => 'MZN', 'is_movement' => true, $column => $value]);
expect($service->options($this->f['issuer'])['total'])->toBe(1)
->and(fn () => $service->resolve($this->f['issuer'], $other, $hash))->toThrow(HttpException::class);
}
expect(fn () => $service->resolve($this->f['issuer'], $this->account, str_repeat('0', 64)))->toThrow(HttpException::class);
// Common accounts are append-only: corrections cannot silently rename an accepted source.
expect(fn () => DB::transaction(fn () => DB::table('gl_accounts')->where('id', $this->account)->update(['label' => 'Alteração proibida'])))->toThrow(QueryException::class);
config(['requisition-accounts.qa_enabled' => false]);
expect($service->ready())->toBeFalse()->and(fn () => $service->options($this->f['issuer']))->toThrow(HttpException::class);
});
test('native line account assignment conserves exact parcels versions and originals without ledger effects', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft']);
$service = app(RequisitionAccountAssignments::class);
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
$space = $service->workspace($this->f['issuer'], $request);
$account = $space['accounts']['data'][0];
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id,
'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Imputação expressa no ensaio sintético',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]];
$before = [DB::table('gl_journals')->count(), DB::table('gl_lines')->count(), DB::table('budget_entries')->count(), DB::table('stock_movements')->count()];
$path = '/requisicoes/'.$request->id.'/contas';
$this->postJson($path, $input)->assertRedirect();
$this->postJson($path, $input)->assertRedirect();
$this->get($path)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page
->component('requisitions/accounts')->where('current.0.version', 1)->where('items.0.total_minor', '10000')->where('canWrite', true));
$first = SupplyRecord::query()->where('kind', 'req_account')->sole();
expect($first->data['allocations'][0]['total_minor'])->toBe('10000')
->and($service->freezeForItems($this->f['issuer'], [$this->item->id])[$this->item->id]['id'])->toBe($first->id);
$input['operation_key'] = (string) Str::uuid();
$input['version'] = 1;
$input['reason'] = 'Nova conferência documental sintética';
$this->postJson($path, $input)->assertRedirect();
expect(SupplyRecord::query()->where('kind', 'req_account')->count())->toBe(2)
->and($first->fresh()->reason)->toBe('Imputação expressa no ensaio sintético')
->and([DB::table('gl_journals')->count(), DB::table('gl_lines')->count(), DB::table('budget_entries')->count(), DB::table('stock_movements')->count()])->toBe($before);
$input['operation_key'] = (string) Str::uuid();
$this->postJson($path, $input)->assertConflict();
$input['version'] = 2;
$input['allocations'][0]['total'] = '99.99';
$this->postJson($path, $input)->assertUnprocessable();
$request->items()->whereKey($this->item->id)->update(['description' => 'Linha alterada de forma explícita']);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$this->item->id]))->toThrow(HttpException::class);
});
test('classified line requires explicit exact account parcels and rejects another operator', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft']);
$this->item->setAttribute('category_context', ['version' => 1, 'category' => 'other', 'reason' => 'Necessidade sintética sem catálogo']);
$this->item->save();
$service = app(RequisitionAccountAssignments::class);
expect(fn () => $service->assertSubmission($this->f['issuer'], $request))->toThrow(ValidationException::class);
$space = $service->workspace($this->f['issuer'], $request);
$account = $space['accounts']['data'][0];
$secondId = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-ONLY-200', 'label' => 'Segunda conta fictícia', 'currency' => 'MZN', 'is_movement' => true]);
$second = app(RequisitionLedgerAccounts::class)->options($this->f['issuer'])['data'][1];
expect($second['id'])->toBe($secondId);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'],
'reason' => 'Duas parcelas explícitas, sem rateio automático', 'allocations' => [
['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '0.33', 'total' => '0.33'],
['account_id' => $second['id'], 'source_hash' => $second['source_hash'], 'subtotal' => '99.67', 'total' => '99.67']]];
$path = '/requisicoes/'.$request->id.'/contas';
$bad = $input;
$bad['allocations'][1]['subtotal'] = '99.66';
$this->postJson($path, $bad)->assertUnprocessable();
$bad = $input;
$bad['allocations'][1]['account_id'] = $account['id'];
$this->postJson($path, $bad)->assertUnprocessable();
$this->actingAs($this->f['receiver'])->postJson($path, $input)->assertNotFound();
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->postJson($path, $input)->assertForbidden();
$this->actingAs($this->f['issuer'])->postJson($path, $input)->assertRedirect();
$service->assertSubmission($this->f['issuer'], $request);
$source = SupplyRecord::query()->where('kind', 'req_account')->sole();
expect(array_column($source->data['allocations'], 'total_minor'))->toBe(['33', '9967'])
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0);
DB::table('audit_logs')->where('action', 'requisition.accounts_assigned')->delete();
expect(fn () => $service->freezeForItems($this->f['issuer'], [$this->item->id]))->toThrow(HttpException::class);
});
test('zero monetary line retains its explicit account without invented compensation', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft', 'subtotal_minor' => 0, 'total_minor' => 0]);
$amounts = PurchaseLineAmounts::portion(1, '0', 0, 1);
$this->item->update(['quantity' => '0.001', 'unit_price_minor' => 1, ...$amounts]);
expect($amounts['total_minor'])->toBe(0);
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->f['issuer'], $request);
$account = $space['accounts']['data'][0];
$record = $service->save($this->f['issuer'], $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $this->item->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Conta preservada para linha arredondada a zero',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '0.00', 'total' => '0.00']]]);
expect($record->data['allocations'][0]['total_minor'])->toBe('0')
->and($record->data['allocations'][0]['account']['code'])->toBe('QA-ONLY-100')
->and(DB::table('gl_journals')->count())->toBe(0);
$request->update(['total_minor' => null]);
expect($service->workspace($this->f['issuer'], $request)['canWrite'])->toBeFalse();
});
test('native office purchase reconciles declared accounts through receipt invoice and confirmed payment', function (bool $machinery, bool $withExpiry, bool $higherLimit = false) {
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
expect($this->schemaComposition['migrations'])->toHaveCount(5)
->and($this->schemaComposition['verified_tables'])->toHaveCount(12)
->and(config('requisition-expiry.qa_enabled'))->toBeTrue();
}
$tenant = $this->f['tenant']->id;
$department = $this->f['department']->id;
$staff = fn ($role) => User::factory()->create(['tenant_id' => $tenant, 'department_id' => $department, 'purchasing_role' => $role]);
if ($higherLimit) {
$this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
}
$owner = $staff(PurchasingRole::Requester);
$buyer = $staff(PurchasingRole::Procurement);
$independentBuyer = $staff(PurchasingRole::Procurement);
$head = $staff(PurchasingRole::DepartmentHead);
$finance = $staff(PurchasingRole::Finance);
$reviewer = $staff(PurchasingRole::Finance);
$category = $machinery ? 'Maquinaria QA' : 'Escritório QA';
$description = $machinery ? 'Maquinaria exclusivamente sintética' : 'Material de escritório de ensaio';
$direction = null;
if ($machinery) {
config(['capital-register.qa_enabled' => true, 'requisition_approval.qa_enabled' => true]);
require_once __DIR__.'/../Support/InvestmentFixture.php';
publishInvestmentFixture($tenant, '100.00');
$admin = $staff(PurchasingRole::Admin);
foreach (User::query()->where('tenant_id', $tenant)->get() as $person) {
$nativeProfile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => 'QA function '.$person->id,
'permissions' => json_encode([$person->purchasing_role->value]), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $tenant, 'user_id' => $person->id, 'profile_id' => $nativeProfile, 'maintenance' => false]);
}
$direction = $staff(PurchasingRole::Configured);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => 'QA direction',
'permissions' => json_encode(['requisition_approve']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $tenant, 'user_id' => $direction->id, 'profile_id' => $profile, 'maintenance' => false]);
DB::table('organization_access')->insert(['tenant_id' => $tenant, 'active' => true, 'version' => 1]);
$this->actingAs($admin)->postJson('/administracao/parametrizacao/approval_levels', ['version' => 1, 'enabled' => true,
'reason' => 'Explicit synthetic direction designation for integrated machinery QA', 'levels' => [[
'name' => 'QA direction', 'profile_ids' => [$profile], 'scope' => 'company', 'min_amount' => null,
'categories' => [], 'procurement_categories' => ['capital_equipment'], 'cost_center_ids' => []]]])->assertRedirect();
}
if ($withExpiry) {
$policyAuthor = $machinery ? $admin : $staff(PurchasingRole::Admin);
$this->actingAs($policyAuthor);
app(RequisitionExpiry::class)->savePolicy($policyAuthor, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => null,
'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement', 'finance', 'configured_1']),
'reason' => 'Explicitly synthetic expiry policy for the fully integrated purchase lifecycle']);
}
$this->actingAs($finance);
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $this->f['r']->cost_center_id,
'year' => (int) now()->year, 'kind' => $machinery ? 'investment' : 'operating', 'includes_tax' => true, 'amount_minor' => 100000,
'reason' => 'Dotação sintética de ensaio: '.$category]);
$this->actingAs($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
$this->actingAs($owner)->postJson('/requisicoes', ['operation_key' => (string) Str::uuid(),
'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'justification' => 'Compra exclusivamente sintética: '.$category.', taxa ilustrativa zero sem regra fiscal real',
'items' => [['description' => $description, 'category' => $category, 'purchase_type' => $machinery ? 'equipment' : 'consumable',
'production_area' => $machinery ? 'Synthetic production line' : null,
'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00',
'procurement_category' => $machinery ? 'capital_equipment' : 'office_equipment', 'category_reason' => 'Justificação exclusivamente sintética de aquisição: '.$category]]])->assertRedirect();
$request = Requisition::query()->where('requester_id', $owner->id)->sole();
$line = $request->items()->sole();
if ($machinery) {
$this->actingAs($buyer);
$asset = app(CapitalRegister::class)->save($buyer, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'type' => 'asset', 'code' => 'MACHINERY-FLOW-QA', 'name' => 'Synthetic machinery destination', 'department_id' => $department,
'reference' => 'Synthetic acquisition only', 'state' => 'active', 'reason' => 'Explicit asset destination before synthetic acquisition']);
$this->actingAs($owner);
app(CapitalAssignments::class)->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $line->id, 'capital_id' => $asset->id, 'reason' => 'Explicit synthetic machinery destination']);
$this->actingAs($head);
$technical = app(EquipmentWorkflow::class);
$technical->review($head, $request, $technical->basis($request), 'approved', 'Independent technical check of synthetic machinery');
$this->actingAs($owner);
}
$space = app(RequisitionAccountAssignments::class)->workspace($owner, $request);
$account = $space['accounts']['data'][0];
$this->postJson('/requisicoes/'.$request->id.'/contas', ['operation_key' => (string) Str::uuid(), 'version' => 0,
'item_id' => $line->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Conta do plano próprio escolhida antes da submissão',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]])->assertRedirect();
$submit = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson('/requisicoes/'.$request->id.'/submeter', $submit)->assertRedirect();
$this->postJson('/requisicoes/'.$request->id.'/submeter', $submit)->assertRedirect();
expect(array_key_exists('approval_expiry', $request->fresh()->approval_snapshot))->toBe($withExpiry);
$this->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Tentativa própria sem competência'])->assertForbidden();
$this->actingAs($head)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Necessidade sintética conferida pela chefia distinta'])->assertRedirect();
if ($higherLimit) {
expect($request->fresh()->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'procurement']);
$this->actingAs($independentBuyer)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Independent procurement check of the synthetic request'])->assertRedirect();
}
if ($machinery) {
expect($request->fresh()->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'finance', 'configured_1']);
foreach ([$finance, $direction] as $actor) {
$this->actingAs($actor)->postJson('/requisicoes/'.$request->id.'/decidir', ['operation_key' => (string) Str::uuid(),
'process_version' => $request->fresh()->process_version, 'decision' => 'approved', 'comment' => 'Independent synthetic machinery approval'])->assertRedirect();
}
$this->actingAs($admin)->postJson('/administracao/parametrizacao/approval_levels', ['version' => 2, 'enabled' => false,
'levels' => [], 'reason' => 'Synthetic future policy change preserves already approved machinery route'])->assertRedirect();
}
expect($request->fresh()->status)->toBe('approved');
$quotes = [];
foreach ([100, 110, 120] as $index => $price) {
$this->actingAs($buyer)->postJson('/fornecedores', ['name' => 'Fornecedor de escritório QA '.($index + 1), 'nuit' => (string) (200000001 + $index),
'contact' => 'Contacto sintético', 'email' => 'office-'.$index.'@example.invalid', 'phone' => '123456789', 'address' => 'Morada sintética',
'category' => $category, 'beneficiaries' => 'Beneficiário sintético', 'document_references' => 'Referências exclusivamente sintéticas',
'diligence_notes' => 'Diligência preparada no ensaio, sem fornecedor real', 'blocked' => false, 'next_review' => today()->addYear()->toDateString()])->assertRedirect();
$supplier = Supplier::query()->where('nuit', (string) (200000001 + $index))->sole();
$this->actingAs($finance)->postJson('/fornecedores/'.$supplier->id.'/validar', ['version' => $supplier->version, 'status' => 'active',
'comment' => 'Conferência financeira independente dos dados sintéticos'])->assertRedirect();
$this->actingAs($buyer)->postJson('/requisicoes/'.$request->id.'/cotacoes', ['currency' => 'MZN', 'supplier_id' => $supplier->id,
'reference' => 'OFFICE-QA-'.($index + 1), 'delivery_days' => 5, 'valid_until' => today()->addMonth()->toDateString(),
'payment_terms' => 'Condições sintéticas de trinta dias', 'no_conflict' => true,
'items' => [['requisition_item_id' => $line->id, 'unit_price' => $price.'.00', 'discount_type' => 'none', 'discount_value' => '0.00']]])->assertRedirect();
$quote = Quotation::query()->where('requisition_id', $request->id)->where('supplier_id', $supplier->id)->sole();
foreach ([$head, $reviewer] as $evaluator) {
$this->actingAs($evaluator)->postJson('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '5', 'history' => '5', 'payment' => '5',
'comment' => 'Avaliação independente e exclusivamente sintética', 'no_conflict' => true])->assertRedirect();
}
$quotes[] = $quote;
}
$comparison = app(ProposalComparison::class)->inspect($request->fresh());
expect($comparison['ready'])->toBeTrue()->and($comparison['top_ids'])->toBe([$quotes[0]->id]);
$this->actingAs($buyer)->postJson('/requisicoes/'.$request->id.'/adjudicacao', ['quotation_id' => $quotes[0]->id,
'justification' => 'Escolha sintética da proposta com maior pontuação pelo circuito vigente',
'delivery_date' => today()->addWeek()->toDateString(), 'delivery_location' => 'Armazém de ensaio'])->assertRedirect();
$award = PurchaseAward::query()->where('requisition_id', $request->id)->sole();
$approvers = ['department_head' => $head, 'procurement' => $independentBuyer, 'finance' => $reviewer];
foreach ($award->approvals()->orderBy('position')->get() as $step) {
if ($step->role === 'procurement') {
$this->actingAs($buyer)->postJson('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved',
'comment' => 'Selector must not approve their own award, even with procurement authority'])->assertForbidden();
expect($award->fresh()->status)->toBe('pending');
}
$this->actingAs($approvers[$step->role])->postJson('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved', 'comment' => 'Conferência sintética do valor final'])->assertRedirect();
}
$this->actingAs($buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
$this->postJson('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
$order = PurchaseOrder::query()->where('purchase_award_id', $award->id)->sole();
expect($order->total_minor)->toBe(10000)->and($order->snapshot['account_assignments'][$line->id]['data']['allocations'][0]['account']['id'])->toBe($account['id']);
$receiver = $this->f['receiver'];
$this->actingAs($receiver);
$stock = StockItem::query()->create(['tenant_id' => $tenant, 'created_by' => $receiver->id, 'code' => 'OFFICE-FLOW-QA',
'name' => $description, 'unit' => 'un']);
$orderLine = $order->items()->sole();
$receiptInput = ['idempotency_key' => (string) Str::uuid(),
'delivery_note' => 'OFFICE-DELIVERY-QA', 'received_on' => today()->toDateString(), 'warehouse_id' => $this->f['warehouse']->id,
'items' => [['purchase_order_item_id' => $orderLine->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000',
'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptInput);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptInput)->id)->toBe($receipt->id);
if ($machinery) {
$this->actingAs($admin)->postJson('/equipamentos/categorias', ['code' => 'FLOW-QA', 'name' => 'Synthetic criticality',
'criteria' => 'Synthetic machinery registration only', 'is_critical' => false])->assertRedirect();
$criticality = CriticalityLevel::query()->where('code', 'FLOW-QA')->sole();
$this->actingAs($buyer)->postJson('/equipamentos/activos', ['code' => 'MACHINERY-FLOW-QA', 'description' => 'Synthetic received machinery',
'area' => 'Synthetic production line', 'serial_number' => 'SYNTHETIC-ONLY', 'status' => 'active', 'department_id' => $department,
'stock_item_id' => $stock->id, 'criticality_level_id' => $criticality->id])->assertRedirect();
$equipment = Equipment::query()->where('code', 'MACHINERY-FLOW-QA')->sole();
$updatedAsset = app(CapitalRegister::class)->save($buyer, [...$asset->data, 'operation_key' => (string) Str::uuid(),
'record_key' => $asset->record_key, 'version' => 1, 'state' => 'active', 'equipment_id' => $equipment->id,
'reason' => 'Link the actual synthetic received machinery without changing original acquisition']);
expect($updatedAsset->version)->toBe(2)
->and($order->fresh()->snapshot['capital_assignments'][$line->id]['snapshot']['source']['version'])->toBe(1)
->and($order->fresh()->snapshot['capital_assignments'][$line->id]['snapshot']['source']['data']['equipment_id'])->toBeNull();
$this->get('/equipamentos/'.$equipment->id)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('capitalReference.record_key', $asset->record_key)->where('capitalReference.version', 2));
$this->get('/projectos-imobilizado?history='.$asset->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page
->where('trace.orders.data.0.order_number', $order->number)->where('trace.receipts.data.0.receipt_id', $receipt->id));
}
$this->actingAs($finance);
$invoice = app(InvoiceWorkflow::class)->register($finance, $order, ['number' => 'OFFICE-INVOICE-QA', 'issued_on' => today()->toDateString(),
'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00', 'items' => [['purchase_order_item_id' => $orderLine->id,
'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$this->postJson('/facturas/'.$invoice->id.'/validar')->assertForbidden();
expect($invoice->fresh()->status)->toBe('pending');
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
$supplier = $quotes[0]->supplier;
$this->actingAs($buyer);
$bank = app(SupplierBankWorkflow::class)->propose($buyer, $supplier, ['account_key' => (string) Str::uuid(), 'previous_id' => 0,
'bank_name' => 'Banco estritamente sintético', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Titular sintético',
'account_identifier' => 'OFFICE-ACCOUNT-QA', 'evidence_reference' => 'Evidência bancária apenas para teste', 'reason' => 'Registo de conta fictícia para o ensaio']);
foreach ([$finance, $reviewer] as $bankReviewer) {
$this->actingAs($bankReviewer);
app(SupplierBankWorkflow::class)->review($bankReviewer, $bank, 'approved', 'Conferência independente de evidência fictícia');
}
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'office-process-qa', 'expense-allocations.qa_enabled' => true]);
foreach ([$finance, $reviewer] as $reader) {
DB::table('pa_access')->insert(['tenant_id' => $tenant, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $reader->id,
'person' => 'office-qa-'.$reader->id, 'action' => 'view']);
}
$this->actingAs($finance);
$payments = app(ExternalPaymentWorkflow::class);
$paymentInput = ['supplier_bank_detail_id' => $bank->id, 'amount' => '40.00', 'paid_on' => today()->toDateString(),
'external_reference' => 'OFFICE-PAYMENT-QA', 'evidence_reference' => 'Evidência exclusivamente sintética de pagamento parcial'];
$payment = $payments->register($finance, $invoice, $paymentInput);
expect($payments->register($finance, $invoice, $paymentInput)->id)->toBe($payment->id);
$this->postJson('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'independently_verified' => true,
'reason' => 'Tentativa própria de conferência no ensaio'])->assertForbidden();
expect($payment->fresh()->status)->toBe('pending');
$this->actingAs($reviewer);
$allocations = app(ExpenseAllocations::class);
expect(fn () => $allocations->source($reviewer, $payment->id))->toThrow(HttpException::class);
$payments->review($reviewer, $payment, 'confirmed', 'Confirmação independente de pagamento externo fictício');
$this->actingAs($finance);
expect(fn () => $payments->register($finance, $invoice, [...$paymentInput, 'external_reference' => 'OFFICE-OVERPAY-QA', 'amount' => '60.01']))
->toThrow(ValidationException::class);
$this->actingAs($reviewer);
$source = $allocations->source($reviewer, $payment->id);
$financialRows = [];
foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'budget_consumptions', 'stock_movements', 'gl_journals', 'gl_lines', 'pa_commands'] as $table) {
$financialRows[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$allocation = $allocations->save($reviewer, $payment->id, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'fingerprint' => $source['fingerprint'], 'reason' => 'Imputação expressa do pagamento pela função de Finanças',
'allocations' => [['category' => $category, 'amount' => '40.00']]]);
$insights = app(ProcurementPaymentInsights::class)->build($reviewer, Requisition::query()->whereKey($request->id), null, null);
$balance = app(CommonBudget::class)->for($reviewer)->balance($budget);
expect($balance['reserved_minor'])->toBe(0)->and($balance['committed_minor'])->toBe(0)
->and($balance['consumed_minor'])->toBe(10000)->and($balance['available_minor'])->toBe(90000);
expect($receipt->items()->sole()->accepted_milli)->toBe(1000)->and($invoice->fresh()->status)->toBe('validated')
->and($payment->fresh()->status)->toBe('confirmed')->and($payments->outstanding($invoice))->toBe(6000)
->and($allocation->data['allocations'])->toBe([['category' => $category, 'amount_minor' => '4000']])
->and($insights['currencies'][0]['amount_minor'])->toBe('4000')->and($insights['category_attribution']['groups']['data'][0]['amount_minor'])->toBe('4000')
->and((int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000)
->and(DB::table('gl_journals')->count())->toBe(0);
foreach ($financialRows as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->actingAs($finance);
$finalPayment = $payments->register($finance, $invoice, [...$paymentInput, 'external_reference' => 'OFFICE-FINAL-PAYMENT-QA', 'amount' => '60.00']);
$this->actingAs($reviewer);
$payments->review($reviewer, $finalPayment, 'confirmed', 'Confirmação independente do saldo externo estritamente sintético');
$finalSource = $allocations->source($reviewer, $finalPayment->id);
$allocations->save($reviewer, $finalPayment->id, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'fingerprint' => $finalSource['fingerprint'], 'reason' => 'Imputação explícita do pagamento final por Finanças',
'allocations' => [['category' => $category, 'amount' => '60.00']]]);
$settled = app(ProcurementPaymentInsights::class)->build($reviewer, Requisition::query()->whereKey($request->id), null, null);
$settledBudget = app(CommonBudget::class)->for($reviewer)->balance($budget);
expect($payments->outstanding($invoice))->toBe(0)->and($settled['currencies'][0]['amount_minor'])->toBe('10000')
->and($settled['coverage']['confirmed_payments'])->toBe(2)->and($settled['category_attribution']['coverage']['allocated'])->toBe(2)
->and($settled['category_attribution']['groups']['data'][0]['amount_minor'])->toBe('10000')
->and($settledBudget)->toBe($balance)->and($allocation->fresh()->data['allocations'])->toBe([['category' => $category, 'amount_minor' => '4000']])
->and((int) DB::table('stock_movements')->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
$this->actingAs($owner)->get('/requisicoes/'.$request->id.'/processo')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('stages.7.state', 'restricted')->where('stages.8.state', 'restricted')
->missing('invoices')->missing('payments')->missing('bank_snapshot'));
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
expect(DB::table('budget_requisition_cycles')->where('requisition_id', $request->id)->count())->toBe($withExpiry ? 1 : 0)
->and(DB::table('budget_order_commands')->count())->toBe(0)
->and(DB::table('budget_landed_entries')->count())->toBe(0)
->and(DB::table('budget_distribution_entries')->count())->toBe(0);
}
})->with(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1'
? ['office_without_expiry_policy' => [false, false], 'office_with_explicit_expiry_policy' => [false, true],
'machinery_without_expiry_policy' => [true, false], 'machinery_with_explicit_expiry_policy' => [true, true],
'office_with_independent_procurement' => [false, true, true]]
: ['office' => [false, false], 'machinery' => [true, false]]);
test('native submission requires account reference before reserve and approval', function () {
$owner = $this->f['issuer'];
$finance = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Finance]);
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($finance);
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $this->f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação exclusivamente sintética para submissão']);
$this->actingAs($admin);
app(CommonBudget::class)->for($admin)->approve($budget);
$this->actingAs($owner);
$request = app(RequisitionWorkflow::class)->save($owner, ['operation_key' => (string) Str::uuid(),
'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'justification' => 'Pedido sintético de conferência da conta antes da reserva', 'items' => [['description' => 'Material sintético novo', 'category' => 'Material',
'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00',
'procurement_category' => 'other', 'category_reason' => 'Necessidade de texto livre fundamentada no ensaio']]]);
$path = '/requisicoes/'.$request->id;
$submit = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson($path.'/submeter', $submit)->assertUnprocessable()->assertJsonValidationErrors('account_assignment');
expect($request->fresh()->status)->toBe('draft')->and($request->steps()->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0);
$space = app(RequisitionAccountAssignments::class)->workspace($owner, $request);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
$this->postJson($path.'/contas', ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'],
'basis_hash' => $line['basis_hash'], 'reason' => 'Imputação explícita anterior à submissão',
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]])->assertRedirect();
$this->postJson($path.'/submeter', $submit)->assertRedirect();
$this->postJson($path.'/submeter', $submit)->assertRedirect();
expect($request->fresh()->status)->toBe('pending')->and($request->steps()->count())->toBe(1)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(10000)
->and(DB::table('gl_journals')->count())->toBe(0);
$this->actingAs($head)->postJson($path.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $request->fresh()->process_version,
'decision' => 'approved', 'comment' => 'Decisão sintética pelo aprovador distinto'])->assertRedirect();
expect($request->fresh()->status)->toBe('approved');
});
@@ -0,0 +1,99 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionSubmissionPreview;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
afterEach(function () {
if ($this->committedSubmissionPreviewFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Preview cleanup requires its disposable committed QA fixture.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
function submissionPreviewDraft(array $fixture): Requisition
{
$draft = $fixture['r']->replicate();
$draft->fill(['number' => 'REQ-PREVIEW-'.Str::random(12), 'status' => 'draft'])->save();
foreach ($fixture['r']->items as $line) {
$draft->items()->save($line->replicate());
}
return $draft->fresh();
}
test('submission preview is a private read without reservation approval receipt or audit changes', function () {
$f = receiptFixture();
$draft = submissionPreviewDraft($f);
$this->actingAs($f['issuer']);
$f['tenant']->update(['first_limit_minor' => 10000, 'second_limit_minor' => 20000]);
$tables = ['requisitions', 'requisition_items', 'approval_steps', 'audit_logs', 'budget_entries', 'supply_records'];
$before = collect($tables)->mapWithKeys(fn ($table) => [$table => DB::table($table)->orderBy('id')->get()->toJson()])->all();
if (DB::getDriverName() === 'pgsql') {
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Native read-only preview requires the guarded QA fixture.');
}
DB::commit();
$this->committedSubmissionPreviewFixture = true;
}
$this->get('/requisicoes/'.$draft->id)->assertOk()->assertHeader('cache-control', 'no-cache, private')
->assertInertia(fn (Assert $page) => $page->where('submissionPreview.state', 'planned')
->where('submissionPreview.total_minor', '10000')->where('submissionPreview.approval_amount_minor', '10000')
->has('submissionPreview.steps', 1)->where('submissionPreview.steps.0.role', 'department_head')
->missing('submissionPreview.first_limit_minor')->missing('submissionPreview.additional_levels'));
expect(collect($tables)->mapWithKeys(fn ($table) => [$table => DB::table($table)->orderBy('id')->get()->toJson()])->all())->toBe($before);
});
test('submission preview follows current threshold tax equipment and configured routing without freezing a plan', function () {
$f = receiptFixture();
$draft = submissionPreviewDraft($f);
$this->actingAs($f['issuer']);
$f['tenant']->update(['first_limit_minor' => 9000, 'second_limit_minor' => 9500]);
$service = app(RequisitionSubmissionPreview::class);
expect(array_column($service->for($f['issuer'], $draft)['steps'], 'role'))->toBe(['department_head', 'procurement', 'finance']);
$f['tenant']->update(['first_limit_minor' => 10000, 'second_limit_minor' => 20000, 'approval_includes_tax' => false]);
$draft->update(['subtotal_minor' => 9000, 'tax_minor' => 1000]);
expect($service->for($f['issuer'], $draft)['approval_amount_minor'])->toBe('9000');
$draft->items()->update(['purchase_type' => 'equipment']);
$draft->unsetRelation('items');
expect(array_column($service->for($f['issuer'], $draft)['steps'], 'role'))->toBe(['department_head', 'finance']);
config(['requisition_approval.qa_enabled' => true]);
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $f['tenant']->id, 'name' => 'Direcção sintética',
'permissions' => json_encode(['requisition_approve']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
$f['tenant']->forceFill(['requisition_approval_policy' => ['enabled' => true, 'revision' => 3, 'levels' => [
['name' => 'Direcção sintética', 'profile_ids' => [$profile], 'scope' => 'company', 'min_minor' => null,
'categories' => [], 'procurement_categories' => [], 'cost_center_ids' => []],
]]])->save();
$preview = $service->for($f['issuer'], $draft);
expect($preview['steps'][2])->toBe(['role' => 'configured_1', 'label' => 'Direcção sintética'])
->and($draft->fresh()->approval_snapshot)->toBe($draft->approval_snapshot);
config(['requisition_approval.qa_enabled' => false]);
expect($service->for($f['issuer'], $draft)['state'])->toBe('unavailable');
});
test('submission preview preserves incomplete unknown and unauthorized states', function () {
$f = receiptFixture();
$draft = submissionPreviewDraft($f);
$this->actingAs($f['issuer']);
$service = app(RequisitionSubmissionPreview::class);
$draft->setAttribute('draft_input', ['incomplete' => true]);
expect($service->for($f['issuer'], $draft)['state'])->toBe('incomplete');
$draft->setAttribute('draft_input', null);
$other = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
expect($service->for($other, $draft))->toBeNull();
$draft->status = 'pending';
expect($service->for($f['issuer'], $draft))->toBeNull();
$foreign = User::factory()->create();
expect($service->for($foreign, $draft))->toBeNull();
});
+15
View File
@@ -3,6 +3,7 @@
use App\Enums\PurchasingRole;
use App\Models\StockMovement;
use App\Models\StockOperation;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
@@ -30,6 +31,20 @@ test('issues are exact, idempotent and cannot make stock negative', function ()
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(400)->and(StockOperation::query()->count())->toBe(1);
});
test('stock preparation consultations keep native visibility private history and source quantities intact', function () {
$before = StockMovement::query()->get()->toArray();
$operations = StockOperation::query()->get()->toArray();
foreach (['/stock', '/stock/operacoes'] as $url) {
$response = $this->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
expect($response->headers->get('Cache-Control'))->toContain('private')->toContain('no-store');
}
$requester = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($requester)->get('/stock')->assertForbidden();
$this->get('/stock/operacoes')->assertForbidden();
expect(StockMovement::query()->get()->toArray())->toBe($before)
->and(StockOperation::query()->get()->toArray())->toBe($operations);
});
test('transfer creates exactly two opposite ledger entries and rejects repeated references', function () {
$this->p['kind'] = 'transfer';
$this->p['destination_warehouse_id'] = $this->dest->id;
+41 -3
View File
@@ -24,6 +24,28 @@ function maintenanceSupplierData(): array
return ['name' => 'Fornecedor existente', 'nuit' => '123456789', 'contact' => 'Contacto comercial', 'email' => 'fornecedor@example.test', 'phone' => '123456789', 'address' => 'Maputo', 'category' => 'Material', 'beneficiaries' => 'Beneficiário de teste', 'document_references' => 'Documentos verificados no processo de teste.', 'diligence_notes' => 'Documentação conferida para testes de manutenção.', 'blocked' => false, 'next_review' => now()->addYear()->format('Y-m-d')];
}
/** Real synthetic PDF bytes: fake()->create reports a virtual size over an empty file. */
function maintenanceSupplierDocument(string $name): UploadedFile
{
$objects = ['<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Count 1 /Kids [3 0 R] >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R >>', "<< /Length 0 >>\nstream\n\nendstream"];
// The uploader requires at least 1 KB of actual content, rather than a virtual size.
$bytes = "%PDF-1.4\n% ".str_repeat('Synthetic QA evidence only; not an official certificate. ', 24)."\n";
$offsets = [];
foreach ($objects as $index => $object) {
$offsets[] = strlen($bytes);
$bytes .= ($index + 1)." 0 obj\n".$object."\nendobj\n";
}
$xref = strlen($bytes);
$bytes .= "xref\n0 5\n0000000000 65535 f \n";
foreach ($offsets as $offset) {
$bytes .= sprintf("%010d 00000 n \n", $offset);
}
$bytes .= "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n".$xref."\n%%EOF\n";
return UploadedFile::fake()->createWithContent($name, $bytes);
}
beforeEach(function () {
Storage::fake('supplier_documents');
$this->tenant = Tenant::query()->create(['name' => 'Manutenção A']);
@@ -46,6 +68,14 @@ test('procurement can edit and renew a supplier but cannot forge validation or o
expect($audit->before['name'])->toBe('Fornecedor existente')->and($audit->after['name'])->toBe('Nome actualizado');
});
test('supplier edit preparation is encrypted and never renews diligence or changes validation by reading', function () {
$before = $this->supplier->fresh()->getAttributes();
$audits = AuditLog::query()->count();
$this->get($this->url.'/editar')->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('suppliers/edit')->where('supplier.version', 1));
expect($this->supplier->fresh()->getAttributes())->toBe($before)->and(AuditLog::query()->count())->toBe($audits);
});
test('unchanged edits preserve validation and do not create audit noise', function () {
$this->put($this->url, [...maintenanceSupplierData(), 'version' => 1])->assertSessionHasNoErrors();
expect($this->supplier->refresh()->status)->toBe('active')->and($this->supplier->version)->toBe(1);
@@ -73,11 +103,16 @@ test('non procurement roles cannot change suppliers or upload documents', functi
})->with([PurchasingRole::Finance, PurchasingRole::Admin, PurchasingRole::Requester, PurchasingRole::DepartmentHead, PurchasingRole::Warehouse]);
test('private upload saves metadata invalidates validation and audits without leaking storage paths', function () {
$this->post($this->url.'/documentos', ['document_type' => 'license', 'file' => UploadedFile::fake()->create('alvara.pdf', 10, 'application/pdf')])->assertSessionHasNoErrors()->assertRedirect();
$file = maintenanceSupplierDocument('alvara.pdf');
$bytes = file_get_contents($file->getPathname());
expect(strlen($bytes))->toBeGreaterThanOrEqual(1024)->toBeLessThanOrEqual(2097152);
$this->post($this->url.'/documentos', ['document_type' => 'license', 'file' => $file])->assertSessionHasNoErrors()->assertRedirect();
$document = SupplierDocument::query()->firstOrFail();
Storage::disk('supplier_documents')->assertExists($document->path);
expect($document->path)->toStartWith($this->tenant->id.'/'.$this->supplier->id.'/');
expect($document->original_name)->toBe('alvara.pdf')->and(strlen($document->sha256))->toBe(64);
expect((int) $document->size)->toBe(strlen($bytes))->and($document->sha256)->toBe(hash('sha256', $bytes))
->and(Storage::disk('supplier_documents')->get($document->path))->toBe($bytes);
expect($document->toArray())->not->toHaveKey('path');
expect($this->supplier->refresh()->status)->toBe('pending')->and($this->supplier->version)->toBe(2);
expect(AuditLog::query()->where('action', 'supplier.document_uploaded')->firstOrFail()->after['document'])->not->toHaveKey('path');
@@ -86,10 +121,13 @@ test('private upload saves metadata invalidates validation and audits without le
});
test('authorised downloads are attachments and recorded in audit', function (PurchasingRole $role) {
$this->post($this->url.'/documentos', ['document_type' => 'tax', 'file' => UploadedFile::fake()->create('certidao.pdf', 10, 'application/pdf')]);
$file = maintenanceSupplierDocument('certidao.pdf');
$bytes = file_get_contents($file->getPathname());
$this->post($this->url.'/documentos', ['document_type' => 'tax', 'file' => $file])->assertSessionHasNoErrors();
$document = SupplierDocument::query()->firstOrFail();
$user = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => $role]);
$this->actingAs($user)->get($this->url.'/documentos/'.$document->id)->assertOk()->assertDownload('certidao.pdf')->assertHeader('X-Content-Type-Options', 'nosniff')->assertHeader('Content-Type', 'application/octet-stream');
$response = $this->actingAs($user)->get($this->url.'/documentos/'.$document->id)->assertOk()->assertDownload('certidao.pdf')->assertHeader('X-Content-Type-Options', 'nosniff')->assertHeader('Content-Type', 'application/octet-stream');
expect($response->streamedContent())->toBe($bytes);
expect(AuditLog::query()->where('action', 'supplier.document_downloaded')->count())->toBe(1);
})->with([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]);
+91
View File
@@ -1,9 +1,14 @@
<?php
use App\Models\CostCenter;
use App\Models\CriticalityLevel;
use App\Models\Department;
use App\Models\Equipment;
use App\Models\User;
use App\Models\WarehouseRequest;
use App\Services\RequisitionWorkflow;
use App\Services\WarehouseFulfilment;
use App\Services\WarehouseWorkdesk;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
@@ -20,6 +25,92 @@ beforeEach(function () {
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '2.500', 'use' => 'internal', 'equipment_id' => null]]];
});
test('warehouse list and detail agree when an owner no longer has preparation or department review authority', function () {
$this->withoutVite();
$this->postJson('/stock/requisicoes', $this->data)->assertRedirect();
$record = WarehouseRequest::query()->sole();
$actor = $this->f['issuer'];
$desk = app(WarehouseWorkdesk::class);
expect($desk->canView($actor, $record))->toBeTrue();
DB::table('organization_memberships')->where('user_id', $actor->id)->update(['expires_at' => now()->subSecond()]);
supplyGrant($actor, ['warehouse_request_deliver']);
expect($desk->canView($actor, $record))->toBeFalse();
$this->get('/stock/requisicoes/'.$record->id)->assertForbidden();
expect($desk->visible($actor)->whereKey($record->id)->exists())->toBeFalse();
$this->get('/stock/requisicoes')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
supplyGrant($actor, ['warehouse_request_read']);
expect($desk->canView($actor, $record))->toBeTrue();
$this->get('/stock/requisicoes')->assertOk()->assertInertia(fn (Assert $page) => $page->where('records.total', 1));
});
test('global warehouse search uses native references event state literal terms and pagination without effects', function () {
$this->withoutVite();
config(['procurement_search.warehouse_requests_metadata_enabled' => true]);
$this->postJson('/stock/requisicoes', [...$this->data, 'destination' => 'GLOBAL-WAREHOUSE%_QA'])->assertRedirect();
$record = WarehouseRequest::query()->sole();
$this->postJson('/stock/requisicoes/'.$record->id.'/eventos', ['operation_key' => (string) Str::uuid(),
'version' => app(WarehouseFulfilment::class)->progress($record)['version'], 'action' => 'submit',
'reason' => 'Submissão sintética para conferir a projecção de pesquisa'])->assertRedirect();
foreach (range(1, 16) as $index) {
$this->postJson('/stock/requisicoes', [...$this->data, 'operation_key' => (string) Str::uuid(),
'destination' => 'PAGE-WAREHOUSE-'.$index])->assertRedirect();
}
$name = $record->snapshot['requester']['name'];
$this->f['issuer']->update(['name' => 'Current name changed after request']);
$before = [];
foreach (['warehouse_requests', 'warehouse_request_events', 'audit_logs', 'stock_movements', 'requisitions', 'budget_entries'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/compras/pesquisa?q=RA-'.$record->id)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)->assertInertia(fn (Assert $page) => $page
->where('warehouseRequestSearchAvailable', true)->where('groups.1.key', 'warehouse_requests')->where('groups.1.records.total', 1)
->where('groups.1.records.data.0.title', 'RA-'.$record->id)->where('groups.1.records.data.0.detail', 'submitted')
->where('groups.1.records.data.0.href', '/stock/requisicoes/'.$record->id)
->missing('groups.1.records.data.0.snapshot')->missing('groups.1.records.data.0.destination'));
$this->get('/compras/pesquisa?q='.urlencode('%_'))->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
$this->get('/compras/pesquisa?q='.urlencode($name))->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 17));
$this->get('/compras/pesquisa?q=PAGE-WAREHOUSE&warehouse_requests_page=2')->assertInertia(fn (Assert $page) => $page
->where('groups.1.records.total', 16)->where('groups.1.records.current_page', 2)->has('groups.1.records.data', 1));
$this->get('/compras/pesquisa?q=PAGE-WAREHOUSE&warehouse_requests_page=0')->assertSessionHasErrors('warehouse_requests_page');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$this->get('/stock/requisicoes/'.$record->id)->assertOk();
config(['procurement_search.warehouse_requests_metadata_enabled' => false]);
$this->get('/compras/pesquisa?q=RA-'.$record->id)->assertInertia(fn (Assert $page) => $page
->where('warehouseRequestSearchAvailable', false)->has('groups', 1));
});
test('global warehouse search and native read predicate agree across departments companies and withdrawn authority', function () {
$this->withoutVite();
config(['procurement_search.warehouse_requests_metadata_enabled' => true]);
$own = $this->f;
$this->postJson('/stock/requisicoes', [...$this->data, 'destination' => 'GLOBAL-SCOPE-OWN'])->assertRedirect();
$record = WarehouseRequest::query()->sole();
$department = Department::query()->create(['tenant_id' => $own['tenant']->id, 'name' => 'Other synthetic department']);
$centre = CostCenter::query()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $department->id, 'code' => 'SCOPE-QA', 'name' => 'Other synthetic centre']);
$otherOwner = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $department->id]);
supplyGrant($otherOwner, ['warehouse_request_prepare']);
$this->actingAs($otherOwner)->postJson('/stock/requisicoes', [...$this->data, 'operation_key' => (string) Str::uuid(),
'cost_center_id' => $centre->id, 'destination' => 'GLOBAL-SCOPE-OTHER-DEPARTMENT'])->assertRedirect();
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['warehouse_request_prepare']);
$this->actingAs($foreign['issuer'])->postJson('/stock/requisicoes', [...$this->data, 'operation_key' => (string) Str::uuid(),
'warehouse_id' => $foreign['warehouse']->id, 'cost_center_id' => $foreign['r']->cost_center_id, 'destination' => 'GLOBAL-SCOPE-OTHER-COMPANY',
'lines' => [['stock_item_id' => $foreign['stock']->id, 'quantity' => '1.000', 'use' => 'internal', 'equipment_id' => null]]])->assertRedirect();
$this->actingAs($own['issuer'])->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
$reviewer = User::factory()->create(['tenant_id' => $own['tenant']->id, 'department_id' => $own['department']->id]);
supplyGrant($reviewer, ['warehouse_request_review']);
$this->actingAs($reviewer)->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 1));
supplyGrant($reviewer, ['warehouse_request_read']);
$this->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 2));
$this->actingAs($own['issuer']);
DB::table('organization_memberships')->where('user_id', $own['issuer']->id)->update(['expires_at' => now()->subSecond()]);
supplyGrant($own['issuer'], ['warehouse_request_deliver']);
$this->get('/compras/pesquisa?q=GLOBAL-SCOPE')->assertInertia(fn (Assert $page) => $page->where('groups.1.records.total', 0));
expect(app(WarehouseWorkdesk::class)->canView($own['issuer'], $record))->toBeFalse();
});
test('warehouse draft freezes catalogue and destination once without stock budget or purchase effects', function () {
$moves = DB::table('stock_movements')->count();
$purchases = DB::table('requisitions')->count();