commit de armazens
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-04 09:40:26 +02:00
parent e753f7a0a4
commit 63d20b10fc
245 changed files with 10847 additions and 230 deletions
@@ -0,0 +1,74 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Department;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AdministrativeGeography;
use Inertia\Testing\AssertableInertia as Assert;
beforeEach(function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$tenant = Tenant::query()->create(['name' => 'Revisão cartográfica sintética']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Administração']);
$this->admin = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($this->admin);
});
test('administrative geography review paginates all unresolved source records in stable order', function () {
$response = $this->get('/administracao/divisao-administrativa');
$response->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page->component('company/geography-review')->where('total', 10729)->has('records', 50)->where('manifest.records', 20407));
$first = $response->inertiaProps('records');
$second = $this->get('/administracao/divisao-administrativa?page=2')->assertOk()->inertiaProps('records');
expect(array_intersect(array_column($first, 'id'), array_column($second, 'id')))->toBeEmpty();
$this->get('/administracao/divisao-administrativa?issue=blank_designation')->assertInertia(fn (Assert $page) => $page->where('total', 9)->has('records', 9));
});
test('administrative geography review applies the same filters to complete CSV export', function () {
$expected = app(AdministrativeGeography::class)->inconsistencies(['issue' => 'duplicate_code_path']);
$response = $this->get('/administracao/divisao-administrativa.csv?issue=duplicate_code_path&page=2');
$response->assertOk()->assertDownload('sgc-cartografia-pendencias.csv');
$stream = fopen('php://temp', 'r+');
fwrite($stream, $response->streamedContent());
rewind($stream);
$header = fgetcsv($stream, escape: '');
$rows = [];
while (($row = fgetcsv($stream, escape: '')) !== false) {
$rows[] = $row;
}
fclose($stream);
expect($header)->toHaveCount(10)->and($rows)->toHaveCount(96)->and(array_column($rows, 1))->toBe(array_column($expected, 'id'));
expect($rows[0][2])->toBe($expected[0]['raw']['Provincia'])->and($rows[0][8])->toBe($expected[0]['raw']['Designacao']);
$id = $expected[0]['id'];
$this->get('/administracao/divisao-administrativa?search='.$id.'&issue=duplicate_code_path')->assertInertia(fn (Assert $page) => $page->where('total', 1)->where('records.0.id', $id));
});
test('administrative geography review rejects non administrators and revoked roles', function () {
$this->admin->forceFill(['purchasing_role' => PurchasingRole::Procurement])->save();
$this->get('/administracao/divisao-administrativa')->assertForbidden();
$this->get('/administracao/divisao-administrativa.csv')->assertForbidden();
});
test('administrative geography review validates filters and honours the feature switch', function () {
$this->getJson('/administracao/divisao-administrativa?issue=invented')->assertUnprocessable();
$this->getJson('/administracao/divisao-administrativa?page=0')->assertUnprocessable();
config(['geography.enabled' => false]);
$this->get('/administracao/divisao-administrativa')->assertServiceUnavailable();
$this->get('/administracao/divisao-administrativa.csv')->assertServiceUnavailable();
});
test('administrative geography review CSV neutralizes formulas without modifying catalogue values', function () {
$original = app(AdministrativeGeography::class)->record('2');
$malicious = $original;
$malicious['raw']['Designacao'] = "\t=1+1";
$this->partialMock(AdministrativeGeography::class)->shouldReceive('inconsistencies')->once()->andReturn([$malicious]);
$response = $this->get('/administracao/divisao-administrativa.csv')->assertOk();
$stream = fopen('php://temp', 'r+');
fwrite($stream, $response->streamedContent());
rewind($stream);
fgetcsv($stream, escape: '');
$row = fgetcsv($stream, escape: '');
fclose($stream);
expect($row[8])->toBe("'\t=1+1")->and($original['raw']['Designacao'])->toBe('Niassa');
});
@@ -0,0 +1,153 @@
<?php
use App\Enums\PurchasingRole;
use App\Http\Middleware\EnsureWorkContext;
use App\Models\AuditLog;
use App\Models\Department;
use App\Models\Supplier;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AdministrativeGeography;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
beforeEach(function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$this->company = Tenant::query()->create(['name' => 'Geografia sintética']);
$department = Department::query()->create(['tenant_id' => $this->company->id, 'name' => 'Operações']);
$this->buyer = User::factory()->create(['tenant_id' => $this->company->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Procurement]);
$this->admin = User::factory()->create(['tenant_id' => $this->company->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($this->buyer);
$this->reference = ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => '2'];
$this->data = ['name' => 'Fornecedor geográfico', 'nuit' => '123456789', 'contact' => 'Contacto', 'email' => 'geo@example.test', 'phone' => '123456789', 'address' => 'Morada original estrangeira ou nacional', 'category' => 'Material', 'beneficiaries' => 'Beneficiário sintético', 'document_references' => 'Referências sintéticas', 'diligence_notes' => 'Diligência sintética sem dados reais', 'blocked' => false, 'next_review' => now()->addYear()->format('Y-m-d')];
});
test('catalogue preserves all source records and quarantines ambiguity without inventing nodes', function () {
$catalogue = app(AdministrativeGeography::class)->catalogue();
expect($catalogue['manifest']['records'])->toBe(20407)->and($catalogue['manifest']['selectable'])->toBe(9678)->and($catalogue['manifest']['duplicate_code_groups'])->toBe(48)->and($catalogue['manifest']['edition'])->toBeNull();
expect(count($catalogue['records']))->toBe(20407);
$ids = [];
$preserved = true;
$quarantined = true;
$parentsValid = true;
foreach ($catalogue['records'] as $record) {
$ids[$record['id']] = $record;
$preserved = $preserved && $record['name'] === $record['raw']['Designacao'];
if ($record['issues']) {
$quarantined = $quarantined && ! $record['selectable'];
}
}
foreach ($ids as $record) {
if ($record['parent_id'] !== null && $record['selectable']) {
$parentsValid = $parentsValid && $ids[$record['parent_id']]['selectable'];
}
}
expect($preserved)->toBeTrue()->and($quarantined)->toBeTrue()->and($parentsValid)->toBeTrue();
});
test('only authenticated company users can browse confirmed paginated locations', function () {
$this->getJson('/api/divisao-administrativa')->assertOk()->assertJsonCount(11, 'data')->assertJsonPath('data.0.level', 1);
$this->getJson('/api/divisao-administrativa?parent=2')->assertOk()->assertJsonPath('data.0.parent_id', '2');
$this->getJson('/api/divisao-administrativa?page=0')->assertUnprocessable();
$this->getJson('/api/divisao-administrativa?parent=999999')->assertUnprocessable();
auth()->logout();
$this->getJson('/api/divisao-administrativa')->assertUnauthorized();
});
test('inconsistent locations and stale catalogue versions cannot be selected', function () {
$service = app(AdministrativeGeography::class);
foreach (['duplicate_code_path', 'missing_parent', 'blank_designation', 'ambiguous_parent', 'ancestor_requires_review'] as $issue) {
$record = collect($service->catalogue()['records'])->first(fn ($record) => in_array($issue, $record['issues'], true));
expect(fn () => $service->canonical([...$this->reference, 'record_id' => $record['id']]))->toThrow(ValidationException::class);
}
expect(fn () => $service->canonical([...$this->reference, 'catalogue' => str_repeat('0', 64)]))->toThrow(ValidationException::class);
});
test('supplier registration reuses geographic reference and preserves address and independent review', function () {
$this->post('/fornecedores', [...$this->data, 'geography_reference' => $this->reference])->assertSessionHasNoErrors();
$supplier = Supplier::query()->sole();
expect($supplier->geography_reference)->toBe($this->reference)->and($supplier->address)->toBe($this->data['address'])->and($supplier->status)->toBe('pending');
$this->get('/fornecedores/'.$supplier->id)->assertOk();
expect(AuditLog::query()->where('action', 'supplier.created')->sole()->after['geography_reference'])->toBe($this->reference);
});
test('supplier geography changes follow the native version and revalidation circuit', function () {
$supplier = Supplier::query()->create([...$this->data, 'tenant_id' => $this->company->id, 'created_by' => $this->buyer->id, 'status' => 'active']);
$url = '/fornecedores/'.$supplier->id;
$this->put($url, [...$this->data, 'version' => 1, 'geography_reference' => $this->reference])->assertSessionHasNoErrors();
expect($supplier->refresh()->status)->toBe('pending')->and($supplier->version)->toBe(2)->and($supplier->address)->toBe($this->data['address']);
$this->put($url, [...$this->data, 'version' => 1, 'geography_reference' => null])->assertSessionHasErrors('version');
$this->put($url, [...$this->data, 'version' => 2, 'geography_reference' => $this->reference])->assertSessionHasNoErrors();
expect($supplier->refresh()->version)->toBe(2);
$this->put($url, [...$this->data, 'version' => 2])->assertSessionHasNoErrors();
expect($supplier->refresh()->geography_reference)->toBe($this->reference);
$this->put($url, [...$this->data, 'version' => 2, 'geography_reference' => null])->assertSessionHasNoErrors();
expect($supplier->refresh()->geography_reference)->toBeNull()->and($supplier->address)->toBe($this->data['address']);
});
test('unclassified and foreign supplier addresses remain supported without guessing country', function () {
$this->post('/fornecedores', $this->data)->assertSessionHasNoErrors();
expect(Supplier::query()->sole()->geography_reference)->toBeNull();
$this->post('/fornecedores', [...$this->data, 'nuit' => '987654321', 'geography_reference' => [...$this->reference, 'record_id' => '999999']])->assertSessionHasErrors('geography_reference');
expect(Supplier::query()->count())->toBe(1);
});
test('geographic filter includes descendant locations and remains tenant scoped', function () {
$service = app(AdministrativeGeography::class);
$child = collect($service->catalogue()['records'])->first(fn ($record) => $record['selectable'] && $record['level'] > 1 && $record['codes'][0] === '01');
$supplier = Supplier::query()->create([...$this->data, 'geography_reference' => [...$this->reference, 'record_id' => $child['id']], 'tenant_id' => $this->company->id, 'created_by' => $this->buyer->id]);
$other = Tenant::query()->create(['name' => 'Outra empresa']);
Supplier::query()->create([...$this->data, 'tenant_id' => $other->id, 'created_by' => $this->buyer->id, 'geography_reference' => $this->reference]);
$this->get('/fornecedores?location=2')->assertInertia(fn ($page) => $page->has('suppliers.data', 1)->where('suppliers.data.0.id', $supplier->id));
$this->get('/fornecedores?location=999999')->assertSessionHasErrors('geography_reference');
});
test('only current administrators can change company location without changing approval rules', function () {
$payload = ['geography_reference' => $this->reference, 'expected_reference' => null];
$this->post('/empresa/localizacao', $payload)->assertForbidden();
$before = $this->company->refresh()->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax']);
$this->actingAs($this->admin)->post('/empresa/localizacao', $payload)->assertSessionHasNoErrors();
expect($this->company->refresh()->geography_reference)->toBe($this->reference)->and($this->company->only(array_keys($before)))->toBe($before);
$this->post('/empresa/localizacao', ['geography_reference' => null, 'expected_reference' => null])->assertSessionHasErrors('geography_reference');
$this->post('/empresa/localizacao', ['geography_reference' => $this->reference, 'expected_reference' => $this->reference])->assertSessionHasNoErrors();
expect(AuditLog::query()->where('action', 'company.geography_updated')->count())->toBe(1);
$this->admin->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
expect($this->admin->fresh()->purchasing_role)->toBe(PurchasingRole::Finance);
$this->withoutMiddleware(EnsureWorkContext::class);
$this->post('/empresa/localizacao', ['geography_reference' => null, 'expected_reference' => $this->reference])->assertForbidden();
});
test('disabled feature and missing schema do not accept geographic changes', function () {
config(['geography.enabled' => false]);
$this->getJson('/api/divisao-administrativa')->assertServiceUnavailable();
$this->post('/fornecedores', [...$this->data, 'geography_reference' => $this->reference])->assertSessionHasErrors('geography_reference');
$this->post('/fornecedores', $this->data)->assertSessionHasNoErrors();
config(['geography.enabled' => true]);
Schema::table('suppliers', fn ($table) => $table->dropColumn('geography_reference'));
$this->getJson('/api/divisao-administrativa')->assertServiceUnavailable();
});
test('catalogue integrity mismatch fails closed', function () {
config(['geography.catalogue_sha256' => str_repeat('0', 64)]);
$this->getJson('/api/divisao-administrativa')->assertServiceUnavailable();
});
test('geographic choices remain paginated without losing older locations', function () {
$service = app(AdministrativeGeography::class);
$group = collect($service->catalogue()['records'])->filter(fn ($record) => $record['selectable'] && $record['parent_id'] !== null)->groupBy('parent_id')->first(fn ($records) => $records->count() > 50);
$parent = $group->first()['parent_id'];
$first = $service->children($parent);
$second = $service->children($parent, 2);
expect($first['data'])->toHaveCount(50)->and($first['has_more'])->toBeTrue()->and($second['data'])->not->toBeEmpty();
expect(array_intersect(array_column($first['data'], 'id'), array_column($second['data'], 'id')))->toBeEmpty();
});
test('audit failure rolls back supplier geography and its validation state together', function () {
$supplier = Supplier::query()->create([...$this->data, 'tenant_id' => $this->company->id, 'created_by' => $this->buyer->id, 'status' => 'active']);
$this->partialMock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->put('/fornecedores/'.$supplier->id, [...$this->data, 'version' => 1, 'geography_reference' => $this->reference]))->toThrow(RuntimeException::class, 'Synthetic audit failure');
expect($supplier->refresh()->geography_reference)->toBeNull()->and($supplier->status)->toBe('active')->and($supplier->version)->toBe(1);
});
+78
View File
@@ -0,0 +1,78 @@
<?php
use App\Services\OrganizationAccess;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['receiver'], ['audit_metadata_read']);
$this->actingAs($this->f['receiver']);
$this->ids = [];
foreach (range(1, 30) as $index) {
$this->ids[] = DB::table('audit_logs')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id,
'action' => $index % 3 === 0 ? 'people.selected' : 'receipt.confirmed', 'created_at' => '2026-11-01 12:00:00',
'before' => json_encode(['bank' => 'PRIVATE-BEFORE']), 'after' => json_encode(['secret' => 'PRIVATE-AFTER'])]);
}
});
test('audit metadata block paginates oldest events and exposes only the four allowed metadata fields', function () {
$before = DB::table('audit_logs')->orderBy('id')->get()->toArray();
$this->get('/auditoria/eventos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertDontSee('PRIVATE-BEFORE')->assertDontSee('PRIVATE-AFTER')
->assertInertia(fn (Assert $p) => $p->component('audit/metadata')->where('events.total', 30)->has('events.data', 25)
->where('events.data.0.id', $this->ids[0])->where('events.data.24.id', $this->ids[24])
->missing('events.data.0.before')->missing('events.data.0.after')->missing('events.data.0.tenant_id'));
$this->get('/auditoria/eventos?page=2')->assertOk()->assertInertia(fn (Assert $p) => $p->has('events.data', 5)->where('events.data.0.id', $this->ids[25]));
expect(DB::table('audit_logs')->orderBy('id')->get()->toArray())->toEqual($before);
});
test('audit metadata block exports the complete filtered scope independently of the screen page and protects spreadsheet cells', function () {
$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');
$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' => '{}']);
$formula = $this->get('/auditoria/eventos.csv?action='.urlencode('=1+1'))->assertOk()->streamedContent();
expect($formula)->toContain("'=1+1");
$all = $this->get('/auditoria/eventos.csv')->assertOk()->streamedContent();
expect(substr_count($all, 'receipt.confirmed'))->toBe(20)->and(substr_count($all, 'people.selected'))->toBe(10);
});
test('audit metadata block requires an explicit current nonmaintenance grant even for administrators', function (string $mode) {
if ($mode === 'administrator') {
supplyGrant($this->f['issuer'], ['admin']);
$this->actingAs($this->f['issuer']);
} elseif ($mode === 'expired') {
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['expires_at' => now()->subMinute()]);
} elseif ($mode === 'maintenance') {
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => true]);
} else {
DB::table('organization_profiles')->where('tenant_id', $this->f['tenant']->id)->update(['permissions' => '[]']);
}
$this->get('/auditoria/eventos')->assertForbidden();
$this->get('/auditoria/eventos.csv')->assertForbidden();
})->with(['administrator', 'expired', 'maintenance', 'revoked']);
test('audit metadata block isolates companies and adds no grants or audit events during consultation', function () {
$foreign = receiptFixture();
supplyGrant($foreign['receiver'], ['audit_metadata_read']);
DB::table('audit_logs')->insert(['tenant_id' => $foreign['tenant']->id, 'user_id' => $foreign['receiver']->id, 'action' => 'FOREIGN-ONLY', 'created_at' => now(), 'after' => '{}']);
$before = [];
foreach (['audit_logs', 'users', 'organization_profiles', 'organization_memberships', 'approval_steps', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->actingAs($this->f['receiver'])->get('/auditoria/eventos')->assertOk()->assertDontSee('FOREIGN-ONLY');
$this->actingAs($foreign['receiver'])->get('/auditoria/eventos')->assertOk()->assertInertia(fn (Assert $p) => $p->where('events.total', 1)->where('events.data.0.action', 'FOREIGN-ONLY'));
expect($this->get('/auditoria/eventos.csv')->assertOk()->streamedContent())->toContain('FOREIGN-ONLY')->not->toContain('people.selected');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
expect(array_key_exists('audit_metadata_read', OrganizationAccess::PERMISSIONS))->toBeTrue();
});
@@ -0,0 +1,72 @@
<?php
use App\Http\Middleware\EnterLocalEvaluation;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Inertia\Testing\AssertableInertia as Assert;
use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
use PragmaRX\Google2FA\Google2FA;
require_once __DIR__.'/../../Support/FortifyMfa.php';
beforeEach(function () {
foundationMfaRoutes();
app()->instance('env', 'payable-testing');
config(['public_navigation.enabled' => true]);
$this->withSession(['_token' => 'mfa-boundary-csrf']);
});
test('mfa evaluation boundary blocks password free entries before their handlers or data changes', function (string $method, string $path) {
$reached = false;
Route::middleware('web')->match([$method], $path, function () use (&$reached) {
$reached = true;
return response('unsafe demo handler');
});
$before = DB::table('users')->count();
$this->call($method, 'http://127.0.0.1:8005/'.$path, ['role' => 'admin', '_token' => 'mfa-boundary-csrf'])->assertRedirect('/login');
expect($reached)->toBeFalse()->and(DB::table('users')->count())->toBe($before)->and(DB::table('audit_logs')->count())->toBe(0);
$this->assertGuest();
})->with([
['GET', 'avaliar'], ['POST', 'avaliar/entrar'], ['GET', 'demo'], ['POST', 'demo/entrar'], ['POST', 'demo/sair'],
]);
test('mfa evaluation boundary requires normal credentials instead of automatic owner entry or public development navigation', function () {
$this->get('http://127.0.0.1:8005/dashboard')->assertRedirect('/login');
$this->assertGuest();
$this->get('http://127.0.0.1:8005/login')->assertOk()->assertInertia(fn (Assert $p) => $p->component('auth/login'));
expect(DB::table('users')->count())->toBe(0)->and(DB::table('audit_logs')->count())->toBe(0);
});
test('mfa evaluation boundary preserves the native password and authenticator challenge', function () {
$user = User::factory()->create();
app(EnableTwoFactorAuthentication::class)($user);
$user->forceFill(['two_factor_confirmed_at' => now()])->save();
$this->post('http://127.0.0.1:8005/login', ['email' => $user->email, 'password' => 'password', '_token' => 'mfa-boundary-csrf'])->assertRedirect('/two-factor-challenge');
$this->assertGuest();
$this->get('http://127.0.0.1:8005/dashboard')->assertRedirect('/login');
$this->assertGuest();
$code = (new Google2FA)->getCurrentOtp(decrypt($user->two_factor_secret));
$this->post('http://127.0.0.1:8005/two-factor-challenge', ['code' => $code, '_token' => session()->token()])->assertRedirect();
$this->assertAuthenticatedAs($user);
});
test('mfa evaluation boundary never switches an authenticated account through a demo shortcut', function () {
$user = User::factory()->create();
$this->actingAs($user);
$reached = false;
$next = function () use (&$reached) {
$reached = true;
return response('unsafe demo handler');
};
$before = $user->fresh()->getAttributes();
$request = Request::create('http://127.0.0.1:8005/demo/entrar', 'POST', ['role' => 'validacao']);
$request->setUserResolver(fn () => $user);
$response = app(EnterLocalEvaluation::class)->handle($request, $next);
expect($response->getStatusCode())->toBe(302)->and($response->headers->get('Location'))->toBe(url('/login'));
$this->assertAuthenticatedAs($user);
expect($reached)->toBeFalse()->and($user->fresh()->getAttributes())->toBe($before)->and(DB::table('users')->count())->toBe(1);
});
+179
View File
@@ -0,0 +1,179 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CandidateAccount;
use App\Models\User;
use App\Services\AdministrativeGeography;
use App\Services\CandidateProfiles;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function additionalGeographyReference(int $index = 0): array
{
$record = collect(app(AdministrativeGeography::class)->catalogue()['records'])->filter(fn ($record) => $record['level'] === 4 && $record['selectable'] && $record['id'] !== '5')->values()->get($index);
return ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => $record['id']];
}
beforeEach(function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$this->f = receiptFixture();
$this->admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($this->admin);
app(CandidateProfiles::class)->configure($this->admin, ['version' => 0, 'registration_open' => true, 'notice' => 'Aviso sintético de testes, sem dados ou contas reais.', 'reason' => 'Configuração de teste da geografia.']);
$this->base = '/candidaturas/'.$this->f['tenant']->id;
$this->post($this->base.'/registar', ['email' => 'geo-candidate@example.test', 'password' => 'Synthetic-Geo-123!', 'password_confirmation' => 'Synthetic-Geo-123!', 'notice_acknowledged' => true, 'portal_version' => 1])->assertRedirect();
$this->account = CandidateAccount::query()->sole();
$this->reference = ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => '5'];
$this->profileData = ['version' => 0, 'name' => 'Pessoa sintética', 'phone' => '', 'summary' => 'Perfil de competências de teste.', 'availability' => ['province' => 'Texto original', 'district' => 'Distrito original', 'locality' => 'Localidade original'], 'reason' => 'Registo sintético de disponibilidade.'];
});
test('candidate geography catalog is scoped to a current candidate session without staff grants', function () {
Auth::guard('web')->logout();
$this->getJson($this->base.'/divisao-administrativa')->assertOk()->assertJsonCount(11, 'data')->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$this->getJson($this->base.'/divisao-administrativa?parent=2')->assertOk();
$this->getJson('/api/divisao-administrativa')->assertUnauthorized();
$this->getJson('/candidaturas/999999/divisao-administrativa')->assertUnauthorized();
$this->account->increment('session_version');
$this->getJson($this->base.'/divisao-administrativa')->assertUnauthorized();
});
test('candidate geography endpoint rejects guests and staff identities without candidate authentication', function () {
Auth::guard('candidate')->logout();
$this->getJson($this->base.'/divisao-administrativa')->assertUnauthorized();
Auth::guard('web')->logout();
$this->getJson($this->base.'/divisao-administrativa')->assertUnauthorized();
});
test('candidate geography derives official availability from the reference and preserves earlier manual versions', function () {
$this->post($this->base.'/perfil', $this->profileData)->assertSessionHasNoErrors();
$first = DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->first()->data;
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1, 'availability_reference' => $this->reference])->assertSessionHasNoErrors();
$profile = app(CandidateProfiles::class)->profile($this->account);
expect($profile['data']['availability_reference'])->toBe($this->reference)->and($profile['data']['availability'])->toBe(['province' => 'Niassa', 'district' => 'CIDADE DE LICHINGA', 'locality' => 'Urbana nº 1']);
expect(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->orderBy('version')->first()->data)->toBe($first);
$this->get($this->base.'/perfil')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', true)->where('availabilityGeography.reference.record_id', '5')->where('auth.user', null));
});
test('candidate geography legacy updates preserve known references only while availability text is unchanged', function () {
$this->post($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $this->reference])->assertSessionHasNoErrors();
$current = app(CandidateProfiles::class)->profile($this->account);
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1, 'availability' => array_reverse($current['data']['availability'], true)])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data']['availability_reference'])->toBe($this->reference);
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 2])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data'])->not->toHaveKey('availability_reference');
});
test('candidate geography rejects ambiguous incomplete and obsolete references without creating profile versions', function () {
$bad = collect(app(AdministrativeGeography::class)->catalogue()['records'])->first(fn ($record) => in_array('duplicate_code_path', $record['issues'], true));
foreach ([['record_id' => '999999'], ['record_id' => $bad['id']], ['record_id' => '2'], ['catalogue' => str_repeat('0', 64)]] as $change) {
$this->postJson($this->base.'/perfil', [...$this->profileData, 'availability_reference' => [...$this->reference, ...$change]])->assertUnprocessable();
}
expect(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->count())->toBe(0);
});
test('candidate geography keeps native profile version and duplicate availability rules', function () {
$this->post($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $this->reference])->assertSessionHasNoErrors();
$this->postJson($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $this->reference])->assertUnprocessable()->assertJsonValidationErrors('version');
$location = app(CandidateProfiles::class)->profile($this->account)['data']['availability'];
$this->postJson($this->base.'/perfil', [...$this->profileData, 'version' => 1, 'availability_reference' => $this->reference, 'additional_availability' => [$location]])->assertUnprocessable()->assertJsonValidationErrors('additional_availability');
expect(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->count())->toBe(1);
});
test('candidate geography can be cleared explicitly while foreign and unresolved locations stay manual', function () {
$this->post($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $this->reference])->assertSessionHasNoErrors();
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1, 'availability_reference' => null])->assertSessionHasNoErrors();
$profile = app(CandidateProfiles::class)->profile($this->account);
expect($profile['data']['availability_reference'])->toBeNull()->and($profile['data']['availability'])->toBe($this->profileData['availability']);
});
test('candidate geography disabled keeps manual profiles and historical references usable', function () {
$this->post($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $this->reference])->assertSessionHasNoErrors();
$location = app(CandidateProfiles::class)->profile($this->account)['data']['availability'];
config(['geography.enabled' => false]);
$this->getJson($this->base.'/divisao-administrativa')->assertServiceUnavailable();
$this->get($this->base.'/perfil')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false));
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1, 'availability' => $location])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data']['availability_reference'])->toBe($this->reference);
});
test('candidate geography event failure rolls back profile and resolved reference together', function () {
$this->partialMock(CandidateProfiles::class)->shouldReceive('event')->andThrow(new RuntimeException('Synthetic candidate event failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->post($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $this->reference]))->toThrow(RuntimeException::class, 'Synthetic candidate event failure');
expect(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->count())->toBe(0);
});
test('candidate additional geography resolves each selected locality and preserves manual entries', function () {
$reference = additionalGeographyReference();
$manual = $this->profileData['availability'];
$manual['locality'] = 'Outro local manual';
$this->post($this->base.'/perfil', [...$this->profileData, 'additional_availability' => [$manual, []], 'additional_availability_references' => [null, $reference]])->assertSessionHasNoErrors();
$data = app(CandidateProfiles::class)->profile($this->account)['data'];
expect($data['additional_availability_references'])->toBe([null, $reference])->and($data['additional_availability'][0])->toBe($manual);
$path = app(AdministrativeGeography::class)->describe($reference)['path'];
$names = array_column($path, 'name', 'level');
expect($data['additional_availability'][1])->toBe(['province' => $names[1], 'district' => $names[2], 'locality' => $names[4]]);
});
test('candidate additional geography validates alignment list shape limits and invalid references', function () {
$entry = $this->profileData['availability'];
foreach ([
['additional_availability' => [$entry], 'additional_availability_references' => []],
['additional_availability' => [$entry], 'additional_availability_references' => [1 => additionalGeographyReference()]],
['additional_availability' => [$entry], 'additional_availability_references' => [[...$this->reference, 'record_id' => '999999']]],
['additional_availability' => array_fill(0, 21, $entry), 'additional_availability_references' => array_fill(0, 21, null)],
['additional_availability_references' => []],
] as $case) {
$this->postJson($this->base.'/perfil', [...$this->profileData, ...$case])->assertUnprocessable();
}
expect(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->count())->toBe(0);
});
test('candidate additional geography legacy reorder removal and edits retain only known unchanged associations', function () {
$references = [additionalGeographyReference(), additionalGeographyReference(1)];
$this->post($this->base.'/perfil', [...$this->profileData, 'additional_availability' => [[], []], 'additional_availability_references' => $references])->assertSessionHasNoErrors();
$first = app(CandidateProfiles::class)->profile($this->account)['data'];
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1, 'additional_availability' => array_reverse($first['additional_availability'])])->assertSessionHasNoErrors();
$second = app(CandidateProfiles::class)->profile($this->account)['data'];
expect($second['additional_availability_references'])->toBe(array_reverse($references));
$edited = $second['additional_availability'];
$edited[0]['locality'] = 'Modificação manual sem associação';
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 2, 'additional_availability' => $edited])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data']['additional_availability_references'])->toBe([null, $references[0]]);
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 3, 'additional_availability' => []])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data']['additional_availability_references'])->toBe([]);
$old = json_decode(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->orderBy('version')->first()->data, true);
expect($old['additional_availability_references'])->toBe($references);
});
test('candidate additional geography omitted data stays intact while explicit null associations become manual', function () {
$reference = additionalGeographyReference();
$this->post($this->base.'/perfil', [...$this->profileData, 'additional_availability' => [[]], 'additional_availability_references' => [$reference]])->assertSessionHasNoErrors();
$first = app(CandidateProfiles::class)->profile($this->account)['data'];
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1])->assertSessionHasNoErrors();
$second = app(CandidateProfiles::class)->profile($this->account)['data'];
expect($second['additional_availability'])->toBe($first['additional_availability'])->and($second['additional_availability_references'])->toBe([$reference]);
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 2, 'additional_availability' => $second['additional_availability'], 'additional_availability_references' => [null]])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data']['additional_availability_references'])->toBe([null]);
});
test('candidate additional geography keeps duplicate and obsolete catalogue checks across all locations', function () {
$reference = additionalGeographyReference();
$this->postJson($this->base.'/perfil', [...$this->profileData, 'availability_reference' => $reference, 'additional_availability' => [[]], 'additional_availability_references' => [$reference]])->assertUnprocessable()->assertJsonValidationErrors('additional_availability');
$this->postJson($this->base.'/perfil', [...$this->profileData, 'additional_availability' => [[], []], 'additional_availability_references' => [$reference, $reference]])->assertUnprocessable()->assertJsonValidationErrors('additional_availability');
$this->postJson($this->base.'/perfil', [...$this->profileData, 'additional_availability' => [[]], 'additional_availability_references' => [[...$reference, 'catalogue' => str_repeat('0', 64)]]])->assertUnprocessable()->assertJsonValidationErrors('additional_availability_references.0');
expect(DB::table('candidate_profile_versions')->where('candidate_account_id', $this->account->id)->count())->toBe(0);
});
test('candidate additional geography suspended catalogue preserves existing associations through legacy requests', function () {
$reference = additionalGeographyReference();
$this->post($this->base.'/perfil', [...$this->profileData, 'additional_availability' => [[]], 'additional_availability_references' => [$reference]])->assertSessionHasNoErrors();
config(['geography.enabled' => false]);
$this->post($this->base.'/perfil', [...$this->profileData, 'version' => 1])->assertSessionHasNoErrors();
expect(app(CandidateProfiles::class)->profile($this->account)['data']['additional_availability_references'])->toBe([$reference]);
});
+267
View File
@@ -4,11 +4,13 @@ use App\Enums\PurchasingRole;
use App\Models\CandidateAccount;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AdministrativeGeography;
use App\Services\CandidateProfiles;
use App\Services\CandidateSubmissions;
use App\Services\CandidateTriage;
use App\Services\PeopleAccess;
use App\Services\PeopleHiring;
use App\Services\ReceivedCandidateAvailability;
use App\Services\RequisitionWorkflow;
use App\Services\SubmissionForms;
use Illuminate\Database\QueryException;
@@ -46,6 +48,271 @@ beforeEach(function () {
'answers' => ['full_name' => 'Pessoa fictícia', 'availability_location' => $this->profile['availability']]];
});
function territoryReceived(object $test, array $changes = []): int
{
$account = app(CandidateProfiles::class)->register($test->tenant->id, [...$test->credentials, 'email' => Str::uuid().'@territory.example.test']);
$account->setAttribute('email_verified_at', now())->save();
app(CandidateProfiles::class)->save($account, [...$test->profile, ...$changes]);
$location = app(CandidateProfiles::class)->profile($account)['data']['availability'];
return app(CandidateSubmissions::class)->submit($account, $test->process->id, [...$test->body, 'operation_key' => (string) Str::uuid(), 'answers' => [...$test->body['answers'], 'availability_location' => $location]]);
}
function territoryReference(bool $otherProvince = false): array
{
$record = collect(app(AdministrativeGeography::class)->catalogue()['records'])->first(fn ($record) => $record['selectable'] && $record['level'] === 4 && ($otherProvince ? $record['codes'][0] !== '01' : $record['codes'][0] === '01'));
return ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => $record['id']];
}
function receivedAvailabilityApplication(object $test, array $profileChanges = []): int
{
config(['geography.enabled' => true]);
$submission = territoryReceived($test, ['availability_reference' => territoryReference(), ...$profileChanges]);
$test->postJson('/pessoas/'.$test->process->id.'/recebidas/'.$submission.'/triagem', electronicTriagePayload($test))->assertRedirect();
return $submission;
}
test('received availability projection reuses main additional and manual submitted data on page and dossier', function () {
$this->withoutVite();
$reference = territoryReference(true);
$submission = receivedAvailabilityApplication($this, ['additional_availability' => [$this->profile['availability'], []], 'additional_availability_references' => [null, $reference]]);
$received = json_decode(DB::table('candidate_submissions')->where('id', $submission)->value('snapshot'), true);
$current = CandidateAccount::query()->findOrFail(DB::table('candidate_submissions')->where('id', $submission)->value('candidate_account_id'));
app(CandidateProfiles::class)->save($current, [...$this->profile, 'version' => 1, 'additional_availability' => [], 'additional_availability_references' => [], 'availability_reference' => territoryReference(true)]);
$before = [];
foreach (['people_processes', 'people_applications', 'people_reviews', 'candidate_submissions', 'candidate_triage', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$page = $this->get('/pessoas/'.$this->process->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('candidates.0.received_availability.submission_id', $submission)->where('candidates.0.received_availability.profile_version', 1));
$availability = $page->inertiaProps('candidates.0.received_availability');
expect($availability['availability'])->toBe($received['profile']['data']['availability'])->and($availability['additional_availability'])->toBe($received['profile']['data']['additional_availability'])->and($availability['additional_availability_references'])->toBe([null, $reference]);
expect($availability)->not->toHaveKeys(['email', 'phone', 'documents', 'answers', 'candidate_account_id']);
$this->getJson('/pessoas/'.$this->process->id.'/dossier.json')->assertOk()->assertJsonPath('candidates.0.received_availability', $availability);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
});
test('received availability projection hides the data from view-only and review-only scopes', function () {
$this->withoutVite();
receivedAvailabilityApplication($this);
$url = '/pessoas/'.$this->process->id;
$this->actingAs($this->reviewer)->get($url)->assertOk()->assertInertia(fn (Assert $page) => $page->missing('candidates.0.received_availability'));
$this->getJson($url.'/dossier.json')->assertOk()->assertJsonMissingPath('candidates.0.received_availability');
$this->actingAs($this->admin);
app(PeopleAccess::class)->assign($this->admin, $this->process->id, ['version' => DB::table('people_access_states')->where('people_process_id', $this->process->id)->value('version'), 'user_id' => $this->reviewer->id, 'scopes' => ['review', 'interviews'], 'reason' => 'Consultar fontes do perfil recebido para conferência.']);
$this->actingAs($this->reviewer)->get($url)->assertInertia(fn (Assert $page) => $page->has('candidates.0.received_availability'));
DB::table('people_process_access')->where('people_process_id', $this->process->id)->where('user_id', $this->reviewer->id)->update(['scopes' => json_encode(['view', 'review'])]);
$this->getJson($url.'/dossier.json')->assertOk()->assertJsonMissingPath('candidates.0.received_availability');
});
test('received availability projection is not added to selection matrices or their frozen decision basis', function () {
$this->withoutVite();
receivedAvailabilityApplication($this);
$this->travel(8)->days();
$record = $this->process->fresh();
app(PeopleHiring::class)->execute($this->admin, $record->id, 'close', ['version' => $record->version, 'reason' => 'Fechar recepção sintética para avaliar.']);
$application = DB::table('people_applications')->sole();
$this->actingAs($this->reviewer);
app(PeopleHiring::class)->execute($this->reviewer, $record->id, 'evaluate', ['version' => $record->fresh()->version, 'reason' => 'Avaliação sintética pelas competências.', 'no_conflict' => true, 'application_id' => $application->id, 'answers' => [['score' => '8', 'evidence' => 'Competências verificadas nesta avaliação sintética.']]]);
$this->actingAs($this->admin);
app(PeopleHiring::class)->execute($this->admin, $record->id, 'select', ['version' => $record->fresh()->version, 'reason' => 'Proposta sintética com base nas avaliações.', 'no_conflict' => true, 'application_id' => $application->id]);
$before = $record->fresh()->selection;
expect($before['rows'][0])->not->toHaveKey('received_availability');
$this->get('/pessoas/'.$record->id)->assertOk()->assertInertia(fn (Assert $page) => $page->has('candidates.0.received_availability')->missing('process.selection.rows.0.received_availability'));
$this->getJson('/pessoas/'.$record->id.'/dossier.json')->assertOk()->assertJsonMissingPath('process.selection.rows.0.received_availability');
expect($record->fresh()->selection)->toBe($before)->and(app(PeopleHiring::class)->matrix($record->fresh())[0])->not->toHaveKey('received_availability');
});
test('received availability projection does not invent geography for manual internal applications or refused submissions', function () {
$this->withoutVite();
$id = territoryReceived($this);
$this->postJson('/pessoas/'.$this->process->id.'/recebidas/'.$id.'/triagem', electronicTriagePayload($this, 'not_accepted'))->assertRedirect();
DB::table('people_applications')->insert(['tenant_id' => $this->tenant->id, 'people_process_id' => $this->process->id, 'created_by' => $this->admin->id, 'operation_key' => (string) Str::uuid(), 'reference' => 'MANUAL-SEM-GEO', 'name' => 'Pessoa manual sintética', 'summary' => 'Resumo sem origem electrónica associada.', 'received_on' => today(), 'created_at' => now(), 'updated_at' => now()]);
$this->get('/pessoas/'.$this->process->id)->assertInertia(fn (Assert $page) => $page->has('candidates', 1)->missing('candidates.0.received_availability'));
});
test('received availability projection keeps historical locality names when the catalogue is disabled', function () {
$this->withoutVite();
receivedAvailabilityApplication($this);
config(['geography.enabled' => false]);
$this->getJson('/pessoas/'.$this->process->id.'/dossier.json')->assertOk()->assertJsonPath('candidates.0.received_availability.availability.province', 'Niassa');
});
test('received availability projection preserves manual submitted text without assigning catalogue references', function () {
$this->withoutVite();
receivedAvailabilityApplication($this, ['availability_reference' => null]);
$this->getJson('/pessoas/'.$this->process->id.'/dossier.json')->assertOk()
->assertJsonPath('candidates.0.received_availability.availability', $this->profile['availability'])
->assertJsonPath('candidates.0.received_availability.availability_reference', null)
->assertJsonPath('candidates.0.received_availability.additional_availability_references', []);
});
test('received availability projection revalidates current actor authority and cannot cross processes', function () {
receivedAvailabilityApplication($this);
$record = $this->process->fresh();
$rows = app(PeopleHiring::class)->matrix($record);
$stale = $this->admin->fresh();
DB::table('users')->where('id', $this->admin->id)->update(['purchasing_role' => PurchasingRole::Requester->value]);
expect(app(ReceivedCandidateAvailability::class)->attach($stale, $record, $rows)[0])->not->toHaveKey('received_availability');
DB::table('users')->where('id', $this->admin->id)->update(['purchasing_role' => PurchasingRole::Admin->value]);
$other = app(PeopleHiring::class)->execute($this->admin, null, 'create', ['operation_key' => (string) Str::uuid(), 'kind' => 'service', 'title' => 'Outro processo da projecção', 'purpose' => 'Processo sintético distinto para verificar o âmbito.', 'closes_on' => today()->addWeek()->toDateString(), 'minimum_reviews' => 1, 'criteria' => [['label' => 'Competências', 'weight' => 100]]]);
expect(app(ReceivedCandidateAvailability::class)->attach($this->admin, $other, $rows)[0])->not->toHaveKey('received_availability');
});
test('candidate territory filters main and additional frozen references without classifying matching manual names', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$reference = territoryReference();
$main = territoryReceived($this, ['availability_reference' => $reference]);
$extra = territoryReceived($this, ['availability_reference' => territoryReference(true), 'additional_availability' => [$this->profile['availability'], []], 'additional_availability_references' => [null, $reference]]);
$snapshot = json_decode(DB::table('candidate_submissions')->where('id', $main)->value('snapshot'), true);
territoryReceived($this, ['availability' => $snapshot['profile']['data']['availability']]);
territoryReceived($this, ['availability_reference' => territoryReference(true)]);
$url = '/pessoas/'.$this->process->id.'/recebidas';
$this->get($url.'?location=2')->assertInertia(fn (Assert $page) => $page->where('submissions.total', 2)->where('submissions.data.0.id', $main)->where('submissions.data.1.id', $extra)->where('geographyFilter.path.0.name', 'Niassa'));
$this->get($url)->assertInertia(fn (Assert $page) => $page->where('submissions.total', 4));
expect(DB::table('candidate_triage')->count())->toBe(0)->and(DB::table('people_reviews')->count())->toBe(0);
expect(app(CandidateTriage::class)->pending($this->process->fresh()))->toBe(4);
});
test('candidate territory never replaces the received location with the current profile location', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$id = territoryReceived($this, ['availability_reference' => territoryReference()]);
$row = DB::table('candidate_submissions')->where('id', $id)->first();
$account = CandidateAccount::query()->findOrFail($row->candidate_account_id);
app(CandidateProfiles::class)->save($account, [...$this->profile, 'version' => 1, 'availability_reference' => territoryReference(true)]);
$this->get('/pessoas/'.$this->process->id.'/recebidas?location=2')->assertInertia(fn (Assert $page) => $page->where('submissions.total', 1)->where('submissions.data.0.id', $id));
expect(DB::table('candidate_submissions')->where('id', $id)->value('snapshot'))->toBe($row->snapshot);
});
test('candidate territory paginates oldest matching submissions and keeps focus and filter together', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$ids = [];
for ($index = 0; $index < 21; $index++) {
$ids[] = territoryReceived($this, ['availability_reference' => territoryReference()]);
}
$url = '/pessoas/'.$this->process->id.'/recebidas';
$this->get($url.'?location=2')->assertInertia(fn (Assert $page) => $page->where('submissions.total', 21)->has('submissions.data', 20)->where('submissions.data.0.id', $ids[0]));
$response = $this->get($url.'?location=2&page=2')->assertInertia(fn (Assert $page) => $page->has('submissions.data', 1)->where('submissions.data.0.id', $ids[20]));
expect($response->inertiaProps('submissions.prev_page_url'))->toContain('location=2');
$this->get($url.'?location=2&submission='.$ids[0])->assertInertia(fn (Assert $page) => $page->where('submissions.total', 1)->where('submissions.data.0.id', $ids[0]));
});
test('candidate territory keeps the OR branches inside the process and tenant boundaries', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$id = territoryReceived($this, ['additional_availability' => [[]], 'additional_availability_references' => [territoryReference()]]);
$copy = (array) DB::table('candidate_submissions')->where('id', $id)->first();
unset($copy['id']);
$other = $this->process->replicate();
$other->operation_key = (string) Str::uuid();
$other->title = 'Outro processo sintético';
$other->save();
DB::table('candidate_submissions')->insert([...$copy, 'people_process_id' => $other->id, 'operation_key' => (string) Str::uuid(), 'reference' => (string) Str::uuid()]);
$foreign = Tenant::query()->create(['name' => 'Outra empresa territorial']);
$foreignAdmin = User::factory()->create(['tenant_id' => $foreign->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($foreignAdmin);
app(CandidateProfiles::class)->configure($foreignAdmin, ['version' => 0, 'registration_open' => true, 'notice' => 'Aviso sintético da outra empresa para teste de isolamento.', 'reason' => 'Preparar origem sintética de outra empresa.']);
$foreignAccount = app(CandidateProfiles::class)->register($foreign->id, [...$this->credentials, 'email' => Str::uuid().'@foreign.example.test']);
$this->actingAs($this->admin);
$foreignProcess = $this->process->replicate();
$foreignProcess->operation_key = (string) Str::uuid();
$foreignProcess->tenant_id = $foreign->id;
$foreignProcess->created_by = $foreignAdmin->id;
$foreignProcess->save();
DB::table('candidate_submissions')->insert([...$copy, 'candidate_account_id' => $foreignAccount->id, 'tenant_id' => $foreign->id, 'people_process_id' => $foreignProcess->id, 'operation_key' => (string) Str::uuid(), 'reference' => (string) Str::uuid()]);
$this->get('/pessoas/'.$this->process->id.'/recebidas?location=2')->assertInertia(fn (Assert $page) => $page->where('submissions.total', 1)->where('submissions.data.0.id', $id));
$this->getJson('/pessoas/'.$foreignProcess->id.'/divisao-administrativa')->assertNotFound();
});
test('candidate territory respects revoked scoped access and candidate identities on both routes', function () {
config(['geography.enabled' => true]);
$base = '/pessoas/'.$this->process->id;
$this->actingAs($this->reviewer)->getJson($base.'/divisao-administrativa')->assertForbidden();
$this->actingAs($this->admin);
DB::table('people_process_access')->where('people_process_id', $this->process->id)->where('user_id', $this->admin->id)->update(['expires_at' => now()->subMinute()]);
$this->getJson($base.'/divisao-administrativa')->assertForbidden();
$this->getJson($base.'/recebidas?location=2')->assertForbidden();
Auth::guard('web')->logout();
$this->getJson($base.'/divisao-administrativa')->assertUnauthorized();
});
test('candidate territory has a people-scoped catalogue without opening the procurement context', function () {
config(['geography.enabled' => true, 'work_context.entitlements.'.$this->tenant->id => ['people.internal']]);
$this->tenant->update(['work_context_policy' => ['revision' => 1, 'enabled' => ['people.internal']]]);
$this->post('/contexto', ['area' => 'people', 'option' => 'people.internal'])->assertRedirect();
$this->getJson('/pessoas/'.$this->process->id.'/divisao-administrativa')->assertOk()->assertJsonCount(11, 'data')->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$this->getJson('/api/divisao-administrativa')->assertForbidden();
});
test('candidate territory rejects invalid locations and can be disabled without losing the unfiltered inbox', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$url = '/pessoas/'.$this->process->id;
$this->getJson($url.'/recebidas?location=999999')->assertUnprocessable();
$this->getJson($url.'/recebidas?location[]=2')->assertUnprocessable();
$this->getJson($url.'/recebidas?page=0')->assertUnprocessable();
config(['geography.enabled' => false]);
$this->getJson($url.'/divisao-administrativa')->assertServiceUnavailable();
$this->getJson($url.'/recebidas?location=2')->assertServiceUnavailable();
$this->get($url.'/recebidas')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false));
});
test('candidate territory excludes references from other editions and handles missing additional lists', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$id = territoryReceived($this, ['availability_reference' => territoryReference()]);
$snapshot = json_decode(DB::table('candidate_submissions')->where('id', $id)->value('snapshot'), true);
$snapshot['profile']['data']['availability_reference']['catalogue'] = str_repeat('0', 64);
$snapshot['profile']['data']['additional_availability_references'] = ['not_a_list' => territoryReference()];
$copy = (array) DB::table('candidate_submissions')->where('id', $id)->first();
unset($copy['id']);
$account = CandidateAccount::query()->findOrFail($copy['candidate_account_id'])->replicate();
$account->email = Str::uuid().'@historical.example.test';
$account->save();
$stale = DB::table('candidate_submissions')->insertGetId([...$copy, 'candidate_account_id' => $account->id, 'operation_key' => (string) Str::uuid(), 'reference' => (string) Str::uuid(), 'snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR)]);
territoryReceived($this);
$url = '/pessoas/'.$this->process->id.'/recebidas?location=2';
$this->get($url)->assertInertia(fn (Assert $page) => $page->where('submissions.total', 1)->where('submissions.data.0.id', $id));
$this->get($url.'&submission='.$stale)->assertInertia(fn (Assert $page) => $page->where('submissions.total', 0));
});
test('candidate geography submission freezes canonical location and does not change when profile is edited later', function () {
config(['geography.enabled' => true]);
$reference = ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => '5'];
$this->post($this->base.'/perfil', [...$this->profile, 'version' => 1, 'availability_reference' => $reference])->assertSessionHasNoErrors();
$location = app(CandidateProfiles::class)->profile($this->account)['data']['availability'];
$body = [...$this->body, 'profile_version' => 2, 'answers' => [...$this->body['answers'], 'availability_location' => $location]];
$this->post($this->base.'/oportunidades/'.$this->process->id, $body)->assertRedirect();
$submission = DB::table('candidate_submissions')->sole();
$snapshot = json_decode($submission->snapshot, true);
expect($snapshot['profile']['data']['availability_reference'])->toBe($reference)->and($snapshot['profile']['data']['availability'])->toBe($location);
$this->post($this->base.'/perfil', [...$this->profile, 'version' => 2, 'availability_reference' => null])->assertSessionHasNoErrors();
$this->post($this->base.'/oportunidades/'.$this->process->id, $body)->assertRedirect();
expect(DB::table('candidate_submissions')->count())->toBe(1)->and(DB::table('candidate_submissions')->sole()->snapshot)->toBe($submission->snapshot);
});
test('candidate additional geography submission reuses a selected additional location and freezes references', function () {
config(['geography.enabled' => true]);
$record = collect(app(AdministrativeGeography::class)->catalogue()['records'])->first(fn ($record) => $record['selectable'] && $record['level'] === 4);
$reference = ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => $record['id']];
$this->post($this->base.'/perfil', [...$this->profile, 'version' => 1, 'additional_availability' => [[]], 'additional_availability_references' => [$reference]])->assertSessionHasNoErrors();
$location = app(CandidateProfiles::class)->profile($this->account)['data']['additional_availability'][0];
$body = [...$this->body, 'profile_version' => 2, 'answers' => [...$this->body['answers'], 'availability_location' => $location]];
$this->post($this->base.'/oportunidades/'.$this->process->id, $body)->assertRedirect();
$submission = DB::table('candidate_submissions')->sole();
$snapshot = json_decode($submission->snapshot, true);
expect($snapshot['profile']['data']['additional_availability_references'])->toBe([$reference])->and($snapshot['answers']['availability_location'])->toBe($location);
$this->post($this->base.'/perfil', [...$this->profile, 'version' => 2, 'additional_availability' => [], 'additional_availability_references' => []])->assertSessionHasNoErrors();
$this->post($this->base.'/oportunidades/'.$this->process->id, $body)->assertRedirect();
expect(DB::table('candidate_submissions')->count())->toBe(1)->and(DB::table('candidate_submissions')->sole()->snapshot)->toBe($submission->snapshot)->and(DB::table('candidate_triage')->count())->toBe(0);
});
test('guests see only explicitly published public opportunity fields while submission remains authenticated', function () {
Auth::guard('candidate')->logout();
Auth::guard('web')->logout();
+140
View File
@@ -11,15 +11,155 @@ use App\Models\StockMovement;
use App\Models\StockOperation;
use App\Models\TechnicalReview;
use App\Models\User;
use App\Models\WarehouseRequest;
use App\Services\EquipmentWorkflow;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\StockWorkflow;
use App\Services\WarehouseFulfilment;
use App\Services\WarehouseRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
function equipmentWarehouseDraft(array $f, bool $mixed = false): WarehouseRequest
{
return app(WarehouseRequests::class)->draft($f['receiver'], ['operation_key' => (string) Str::uuid(), 'warehouse_id' => $f['warehouse']->id,
'cost_center_id' => $f['r']->cost_center_id, 'destination' => 'Destino do equipamento', 'reason' => 'Manutenção interna com material já registado.', 'priority' => 'normal',
'lines' => [['stock_item_id' => $f['stock']->id, 'quantity' => '0.100', 'use' => 'equipment', 'equipment_id' => $f['asset']->id],
...($mixed ? [['stock_item_id' => $f['stock']->id, 'quantity' => '9.000', 'use' => 'internal', 'equipment_id' => null]] : [])]]);
}
test('equipment warehouse requests use native scope and expose only matching lines without mutations', function () {
$this->withoutVite();
supplyGrant($this->f['receiver'], ['warehouse', 'warehouse_request_prepare']);
$record = equipmentWarehouseDraft($this->f, true);
$before = [];
foreach (['warehouse_requests', 'warehouse_request_events', 'warehouse_reservations', 'stock_operations', 'stock_movements', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertInertia(fn (Assert $p) => $p
->where('warehouseRequests.total', 1)->where('warehouseRequests.data.0.id', $record->id)->where('warehouseRequests.data.0.state', 'draft')
->has('warehouseRequests.data.0.lines', 1)->where('warehouseRequests.data.0.lines.0.requested_milli', 100)
->where('warehouseRequests.data.0.lines.0.delivered_milli', 0)->where('warehouseRequests.data.0.lines.0.remaining_milli', 100)
->missing('warehouseRequests.data.0.snapshot')->missing('warehouseRequests.data.0.events'));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
supplyGrant($this->f['finance'], ['finance']);
$this->actingAs($this->f['finance'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()
->assertInertia(fn (Assert $p) => $p->where('warehouseRequests', null));
supplyGrant($this->f['issuer'], ['procurement', 'warehouse_request_prepare']);
$this->actingAs($this->f['issuer'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()
->assertInertia(fn (Assert $p) => $p->where('warehouseRequests.total', 0));
});
test('equipment warehouse requests paginate old pending documents independently', function () {
$this->withoutVite();
supplyGrant($this->f['receiver'], ['warehouse', 'warehouse_request_prepare']);
foreach (range(1, 16) as $index) {
$last = equipmentWarehouseDraft($this->f);
}
$url = '/equipamentos/'.$this->f['asset']->id.'?requests_page=2&purchases_page=1&movements_page=1';
$response = $this->get($url)->assertOk()->assertInertia(fn (Assert $p) => $p->where('warehouseRequests.total', 16)
->has('warehouseRequests.data', 1)->where('warehouseRequests.data.0.id', $last->id)->where('purchases.current_page', 1)->where('movements.current_page', 1));
expect($response->inertiaProps('warehouseRequests.prev_page_url'))->toContain('purchases_page=1', 'movements_page=1');
$this->getJson('/equipamentos/'.$this->f['asset']->id.'?requests_page=0')->assertUnprocessable();
});
test('equipment warehouse requests retain department and tenant equipment boundaries', function () {
$this->withoutVite();
supplyGrant($this->f['receiver'], ['warehouse', 'warehouse_request_prepare']);
equipmentWarehouseDraft($this->f);
supplyGrant($this->f['head'], ['department_head', 'warehouse_request_review']);
$this->actingAs($this->f['head'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()
->assertInertia(fn (Assert $p) => $p->where('warehouseRequests.total', 1));
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
$this->f['asset']->update(['department_id' => $department->id]);
$this->get('/equipamentos/'.$this->f['asset']->id)->assertNotFound();
$foreign = receiptFixture();
$this->actingAs($foreign['receiver'])->get('/equipamentos/'.$this->f['asset']->id)->assertNotFound();
});
test('equipment integration block reuses the stock operation produced by an authorized internal warehouse delivery', function () {
$this->withoutVite();
supplyGrant($this->f['issuer'], ['warehouse_request_prepare']);
supplyGrant($this->f['head'], ['warehouse_request_review', 'warehouse_request_read']);
supplyGrant($this->f['receiver'], ['warehouse', 'warehouse_request_deliver']);
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
$this->actingAs($this->f['issuer']);
$request = app(WarehouseRequests::class)->draft($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id,
'cost_center_id' => $this->f['r']->cost_center_id, 'destination' => 'Linha do equipamento', 'reason' => 'Peça para manutenção interna do equipamento.', 'priority' => 'normal',
'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '0.100', 'use' => 'equipment', 'equipment_id' => $this->f['asset']->id]]]);
$flow = app(WarehouseFulfilment::class);
foreach ([[$this->f['issuer'], 'submit'], [$this->f['head'], 'authorize'], [$this->f['receiver'], 'deliver']] as [$actor, $action]) {
$this->actingAs($actor);
$flow->command($actor, $request->id, ['operation_key' => (string) Str::uuid(), 'version' => $flow->progress($request)['version'], 'action' => $action,
'reason' => 'Intervenção nativa do percurso interno de teste.', ...($action === 'deliver' ? ['lines' => [['index' => 0, 'quantity' => '0.100']]] : [])]);
}
$operation = StockOperation::query()->where('equipment_id', $this->f['asset']->id)->sole();
$before = DB::table('stock_movements')->count();
$this->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('movements.total', 1)
->where('movements.data.0.id', $operation->id)->where('movements.data.0.quantity_milli', 100)
->where('warehouseRequests.total', 1)->where('warehouseRequests.data.0.state', 'delivered')
->where('warehouseRequests.data.0.lines.0.delivered_milli', 100)->where('warehouseRequests.data.0.lines.0.remaining_milli', 0));
expect(DB::table('stock_movements')->count())->toBe($before)->and($flow->progress($request)['state'])->toBe('delivered');
});
test('equipment integration block separates native purchase requests from actual equipment stock issues without mutations', function () {
$this->withoutVite();
$request = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f, 'spare_part'));
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
$operation = app(StockWorkflow::class)->record($this->f['receiver'], ['kind' => 'issue', 'reference' => 'EQ-ISSUE', 'idempotency_key' => (string) Str::uuid(),
'responsible_id' => $this->f['receiver']->id, 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'equipment_id' => $this->f['asset']->id,
'quantity' => '0.100', 'destination' => 'Equipamento de teste', 'reason' => 'Saída física nativa para o equipamento.']);
$before = [];
foreach (['audit_logs', 'requisitions', 'requisition_items', 'approval_steps', 'stock_movements', 'stock_operations', 'equipment'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $p) => $p->component('equipment/show')->where('equipment.code', 'EQ-TEST')->where('purchases.total', 1)
->where('purchases.data.0.id', $request->id)->where('purchases.data.0.items.0.quantity', '1.000')->missing('purchases.data.0.items.0.unit_price_minor')
->where('movements.total', 1)->where('movements.data.0.id', $operation->id)->where('movements.data.0.quantity_milli', 100)->missing('movements.data.0.snapshot'));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
});
test('equipment integration block preserves department and native requisition visibility with tenant isolation', function () {
$this->withoutVite();
$request = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
$this->actingAs($this->f['finance'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('purchases.total', 1));
$otherDepartment = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
$request->update(['department_id' => $otherDepartment->id]);
$this->actingAs($this->f['head'])->get('/equipamentos/'.$this->f['asset']->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('purchases.total', 0));
$this->f['asset']->update(['department_id' => $otherDepartment->id]);
$this->get('/equipamentos/'.$this->f['asset']->id)->assertNotFound();
$foreign = receiptFixture();
$this->actingAs($foreign['receiver'])->get('/equipamentos/'.$this->f['asset']->id)->assertNotFound();
$user = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($user)->get('/equipamentos/'.$this->f['asset']->id)->assertForbidden();
});
test('equipment integration block keeps old purchase and movement pages independently accessible', function () {
$this->withoutVite();
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
foreach (range(1, 16) as $index) {
app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
app(StockWorkflow::class)->record($this->f['receiver'], ['kind' => 'issue', 'reference' => 'EQ-PAGE-'.$index, 'idempotency_key' => (string) Str::uuid(),
'responsible_id' => $this->f['receiver']->id, 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'equipment_id' => $this->f['asset']->id,
'quantity' => '0.001', 'reason' => 'Saída física nativa para paginação.']);
}
$this->get('/equipamentos/'.$this->f['asset']->id.'?purchases_page=2&movements_page=1')->assertOk()
->assertInertia(fn (Assert $p) => $p->where('purchases.total', 16)->has('purchases.data', 1)->where('purchases.current_page', 2)->has('movements.data', 15)->where('movements.current_page', 1));
$this->get('/equipamentos/'.$this->f['asset']->id.'?purchases_page=1&movements_page=2')->assertOk()
->assertInertia(fn (Assert $p) => $p->has('purchases.data', 15)->has('movements.data', 1)->where('movements.data.0.reference', 'EQ-PAGE-16'));
});
function equipmentRequestData(array $f, string $type = 'equipment'): array
{
@@ -0,0 +1,185 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\OrderCancellation;
use App\Models\PurchaseOrder;
use App\Models\User;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowTaskInbox;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/IssuedOrderCancellationFixture.php';
beforeEach(function () {
$this->withoutVite();
issuedOrderCancellationFixture($this);
});
function issuedCancellation(object $test): OrderCancellation
{
$test->actingAs($test->buyer);
return app(OrderCancellationWorkflow::class)->request($test->buyer, $test->f['order'], $test->data);
}
test('issued cancellation approves once with independent finance and preserves order approvals and original commitment', function () {
$order = $this->f['order']->fresh()->getAttributes();
$original = DB::table('budget_entries')->orderBy('id')->get()->toArray();
$approvals = DB::table('approval_steps')->get()->toArray();
$record = issuedCancellation($this);
expect(app(OrderCancellationWorkflow::class)->state($this->f['order']))->toBe('cancellation_pending');
expect(PurchaseOrder::query()->operational()->whereKey($this->f['order']->id)->exists())->toBeFalse();
$this->actingAs($this->finance);
expect(collect(app(WorkflowTaskInbox::class)->build($this->finance, 'procurement'))->pluck('task')->all())->toContain('order_cancellation_review');
app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'approved', 'Decisão financeira independente no ensaio fictício.');
app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'approved', 'Decisão financeira independente no ensaio fictício.');
expect((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(0)->and(DB::table('budget_entries')->count())->toBe(4)
->and($this->f['order']->fresh()->getAttributes())->toBe($order)->and($this->f['r']->fresh()->status)->toBe('cancelled')
->and(DB::table('budget_entries')->orderBy('id')->limit(3)->get()->toArray())->toEqual($original)
->and(DB::table('approval_steps')->get()->toArray())->toEqual($approvals)
->and(app(OrderCancellationWorkflow::class)->state($this->f['order']))->toBe('cancelled');
expect(issuedCancellation($this)->id)->toBe($record->id);
$this->actingAs($this->f['issuer']);
expect(collect(app(WorkflowTaskInbox::class)->build($this->f['issuer'], 'procurement'))->pluck('task')->all())->toContain('order_cancellation_revision');
$draft = app(OrderCancellationWorkflow::class)->revise($this->f['issuer'], $record, today()->addWeek()->toDateString(), 'Nova necessidade fictícia para revisão após cancelamento.');
expect($draft->status)->toBe('draft')->and($draft->steps()->count())->toBe(0)->and($draft->items()->count())->toBe(1)
->and(DB::table('budget_entries')->where('requisition_id', $draft->id)->count())->toBe(0);
expect(app(OrderCancellationWorkflow::class)->revise($this->f['issuer'], $record, today()->addWeek()->toDateString(), 'Nova necessidade fictícia para revisão após cancelamento.')->id)->toBe($draft->id);
expect(collect(app(WorkflowTaskInbox::class)->build($this->f['issuer'], 'procurement'))->pluck('task')->all())->not->toContain('order_cancellation_revision');
});
test('issued cancellation pending hold blocks receipt invoice and reissue while rejection preserves commitment', function () {
$record = issuedCancellation($this);
$this->actingAs($this->f['receiver']);
expect(fn () => app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f)))->toThrow(ValidationException::class);
config(['order_cancellation.enabled' => false]);
expect(fn () => app(OrderCancellationWorkflow::class)->assertOperational($this->f['order']))->toThrow(ValidationException::class);
config(['order_cancellation.enabled' => true]);
$this->actingAs($this->finance);
expect(fn () => app(InvoiceWorkflow::class)->register($this->finance, $this->f['order'], []))->toThrow(ValidationException::class);
app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'rejected', 'Rejeição fundamentada para conservar a ordem original.');
expect((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000)->and(app(OrderCancellationWorkflow::class)->state($this->f['order']))->toBe('issued');
expect(PurchaseOrder::query()->operational()->whereKey($this->f['order']->id)->exists())->toBeTrue();
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
expect(DB::table('goods_receipts')->count())->toBe(1);
});
test('issued cancellation refuses any existing receipt or invoice without creating a request', function (string $source) {
if ($source === 'receipt') {
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
} else {
Invoice::query()->create(['tenant_id' => $this->f['tenant']->id, 'purchase_order_id' => $this->f['order']->id, 'supplier_id' => $this->f['order']->supplier_id,
'created_by' => $this->finance->id, 'number' => 'INV-TEST', 'issued_on' => today()->toDateString(), 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'snapshot' => []]);
}
expect(fn () => issuedCancellation($this))->toThrow(ValidationException::class);
expect(OrderCancellation::query()->count())->toBe(0)->and((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000);
})->with(['receipt', 'invoice']);
test('issued cancellation rolls back reversal decision and request state when the final audit fails', function () {
$record = issuedCancellation($this);
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Injected final audit failure'));
$this->actingAs($this->finance);
expect(fn () => app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'approved', 'Decisão financeira fictícia para ensaio de falha.'))->toThrow(RuntimeException::class);
expect(OrderCancellation::query()->findOrFail($record->id)->status)->toBe('pending')->and(DB::table('budget_entries')->count())->toBe(3)
->and((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000)->and($this->f['r']->fresh()->status)->toBe('approved');
});
test('issued cancellation rejects involved or revoked finance foreign tenant and altered replay', function () {
$record = issuedCancellation($this);
$this->actingAs($this->buyer);
$this->buyer->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
expect(fn () => app(OrderCancellationWorkflow::class)->decide($this->buyer->fresh(), $record, 'approved', 'Tentativa do autor do pedido com função alterada.'))->toThrow(HttpException::class);
$this->actingAs($this->finance);
$this->finance->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
expect(fn () => app(OrderCancellationWorkflow::class)->decide($this->finance->fresh(), $record, 'approved', 'Tentativa com função financeira retirada.'))->toThrow(HttpException::class);
$this->buyer->forceFill(['purchasing_role' => PurchasingRole::Procurement])->save();
$this->actingAs($this->buyer->fresh());
expect(fn () => app(OrderCancellationWorkflow::class)->request($this->buyer->fresh(), $this->f['order'], [...$this->data, 'reason' => 'Outro conteúdo na mesma chave de operação.']))->toThrow(HttpException::class);
$foreign = receiptFixture();
$this->actingAs($foreign['issuer']);
expect(fn () => app(OrderCancellationWorkflow::class)->request($foreign['issuer'], $this->f['order'], $this->data))->toThrow(ModelNotFoundException::class);
});
test('issued cancellation stays disabled and unapproved policies cannot authorize execution', function () {
config(['order_cancellation.enabled' => false]);
expect(fn () => issuedCancellation($this))->toThrow(HttpException::class);
$this->get('/ordens/cancelamentos')->assertStatus(503);
config(['order_cancellation.enabled' => true]);
$this->actingAs($this->admins[0]);
app(OrderCancellationPolicyWorkflow::class)->propose($this->admins[0], ['previous_id' => $this->policy->id, 'mode' => 'issued_order', 'enabled' => false,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Nova proposta ainda não publicada no ensaio.']);
// A pending proposal does not silently replace the previously published policy.
expect(app(OrderCancellationPolicyWorkflow::class)->requireCurrent()->id)->toBe($this->policy->id);
});
test('issued cancellation HTTP connects preparation independent decision and preserved order consultation', function () {
$this->post('/ordens/'.$this->f['order']->id.'/cancelamento', $this->data)->assertRedirect('/ordens/cancelamentos');
$record = OrderCancellation::query()->sole();
$this->actingAs($this->finance)->get('/ordens/cancelamentos')->assertOk()->assertInertia(fn (AssertableInertia $p) => $p
->component('purchase-controls/orders')->where('records.data.0.canDecide', true));
$this->get('/ordens/cancelamentos?cancellation_id='.$record->id)->assertOk()->assertInertia(fn (AssertableInertia $p) => $p->where('records.data.0.id', $record->id));
$this->post('/ordens/cancelamentos/'.$record->id.'/decidir', ['decision' => 'approved', 'reason' => 'Conferência financeira independente através do controlador.'])->assertRedirect();
$this->get('/ordens/'.$this->f['order']->id)->assertOk()->assertInertia(fn (AssertableInertia $p) => $p->where('orderCancellation.state', 'cancelled')->where('order.status', 'issued'));
});
test('issued cancellation expired policy can be rejected but cannot release a commitment', function () {
$record = issuedCancellation($this);
$this->travel(8)->days();
try {
$this->actingAs($this->finance);
expect(fn () => app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'approved', 'Tentativa após expiração da política fictícia.'))->toThrow(HttpException::class);
app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'rejected', 'Rejeitar pedido sem política vigente para retomar a execução.');
expect((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000);
} finally {
$this->travelBack();
}
});
test('issued cancellation refuses changed financial basis and unavailable reversal artifact without partial effects', function () {
$record = issuedCancellation($this);
$this->actingAs($this->finance);
config(['order_cancellation.reversal_sha256' => 'unavailable']);
expect(fn () => app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'approved', 'Ensaio de capacidade de reversão não disponível.'))->toThrow(HttpException::class);
expect(OrderCancellation::query()->sole()->status)->toBe('pending')->and(DB::table('budget_entries')->count())->toBe(3);
DB::table('budget_entries')->insert(['tenant_id' => $this->f['tenant']->id, 'budget_id' => $this->budget->id, 'requisition_id' => $this->f['r']->id,
'created_by' => $this->finance->id, 'kind' => 'test-changed-basis', 'reserved_minor' => 0, 'committed_minor' => -1, 'created_at' => now()]);
expect(fn () => app(OrderCancellationWorkflow::class)->decide($this->finance, $record, 'approved', 'Ensaio de base financeira diferente da proposta.'))->toThrow(HttpException::class);
expect(OrderCancellation::query()->sole()->status)->toBe('pending');
});
test('issued cancellation policy preserves publication separation and rejects a revoked proposer', function () {
$this->actingAs($this->admins[0]);
$flow = app(OrderCancellationPolicyWorkflow::class);
$policy = $flow->propose($this->admins[0], ['previous_id' => $this->policy->id, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Outra proposta de política para testar a segregação.']);
expect(fn () => $flow->review($this->admins[0], $policy, 'approved', 'O proponente não pode conferir a sua própria proposta.'))->toThrow(HttpException::class);
$this->actingAs($this->admins[1]);
expect($flow->canReview($this->admins[1], $policy))->toBeTrue();
expect(collect(app(WorkflowTaskInbox::class)->build($this->admins[1], 'procurement'))->pluck('task')->all())->toContain('order_cancellation_policy_review');
$flow->review($this->admins[1], $policy, 'approved', 'Primeira conferência administrativa independente.');
expect($flow->canReview($this->admins[1], $policy))->toBeFalse();
$this->admins[0]->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
$this->actingAs($this->admins[2]);
expect(fn () => $flow->review($this->admins[2], $policy, 'approved', 'Tentativa de publicação após retirada da função do proponente.'))->toThrow(ValidationException::class);
expect($policy->fresh()->status)->toBe('pending');
});
test('issued cancellation requires a published policy in the same company before accepting a request', function () {
$foreign = receiptFixture();
$buyer = User::factory()->create(['tenant_id' => $foreign['tenant']->id, 'department_id' => $foreign['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
$this->actingAs($buyer);
expect(fn () => app(OrderCancellationWorkflow::class)->request($buyer, $foreign['order'], $this->data))->toThrow(HttpException::class);
expect(DB::table('order_cancellations')->where('tenant_id', $foreign['tenant']->id)->count())->toBe(0);
});
+185
View File
@@ -0,0 +1,185 @@
<?php
use App\Enums\PurchasingRole;
use App\Http\Middleware\EnsureOrganizationAccess;
use App\Models\AuditLog;
use App\Models\CriticalityLevel;
use App\Models\Department;
use App\Models\Equipment;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\AdministrativeGeography;
use App\Services\ConflictGuard;
use App\Services\OrganizationAccess;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function operationalAssetData(Equipment $asset): array
{
return $asset->refresh()->only(['id', 'version', 'code', 'description', 'area', 'serial_number', 'status', 'department_id', 'stock_item_id', 'criticality_level_id']);
}
beforeEach(function () {
$this->withoutVite();
config(['geography.enabled' => true, 'geography.operational_enabled' => true]);
$this->f = receiptFixture();
$this->actingAs($this->f['receiver']);
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['receiver']->id, 'code' => 'CRIT', 'name' => 'Categoria sintética', 'criteria' => 'Critério sintético de teste', 'is_critical' => false, 'created_at' => now()]);
$this->asset = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['receiver']->id, 'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id, 'code' => 'EQ-GEO', 'description' => 'Equipamento sintético', 'area' => 'Área textual original', 'status' => 'active']);
$this->reference = ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => '2'];
$this->warehouseUrl = '/stock/armazens/'.$this->f['warehouse']->id.'/localizacao';
});
test('operational geography creates warehouse and equipment without movements or implicit locations', function () {
$this->post('/stock/armazens', ['code' => 'GEO', 'name' => 'Armazém geográfico', 'geography_reference' => $this->reference])->assertSessionHasNoErrors();
$warehouse = Warehouse::query()->where('code', 'GEO')->sole();
expect($warehouse->geography_reference)->toBe($this->reference);
$data = operationalAssetData($this->asset);
unset($data['id'], $data['version']);
$this->post('/equipamentos/activos', [...$data, 'code' => 'EQ-NOVO', 'geography_reference' => $this->reference])->assertSessionHasNoErrors();
expect(Equipment::query()->where('code', 'EQ-NOVO')->sole()->geography_reference)->toBe($this->reference);
$this->post('/stock/armazens', ['code' => 'SEM-GEO', 'name' => 'Sem classificação'])->assertSessionHasNoErrors();
expect(Warehouse::query()->where('code', 'SEM-GEO')->sole()->geography_reference)->toBeNull();
expect(DB::table('stock_movements')->count())->toBe(0)->and(DB::table('purchase_orders')->count())->toBe(1);
});
test('operational geography warehouse update is isolated audited and rejects stale overwrite', function () {
$before = $this->f['warehouse']->refresh()->only(['code', 'name', 'created_by']);
$payload = ['geography_reference' => $this->reference, 'expected_reference' => null, 'name' => 'Não aplicar', 'tenant_id' => 999];
$this->post($this->warehouseUrl, $payload)->assertSessionHasNoErrors();
expect($this->f['warehouse']->refresh()->only(array_keys($before)))->toBe($before)->and($this->f['warehouse']->geography_reference)->toBe($this->reference);
$this->post($this->warehouseUrl, ['geography_reference' => null, 'expected_reference' => null])->assertSessionHasErrors('geography_reference');
$this->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => $this->reference])->assertSessionHasNoErrors();
expect(AuditLog::query()->where('action', 'stock.warehouse_geography_updated')->count())->toBe(1);
$this->post($this->warehouseUrl, ['geography_reference' => null, 'expected_reference' => $this->reference])->assertSessionHasNoErrors();
expect($this->f['warehouse']->refresh()->geography_reference)->toBeNull();
});
test('operational geography warehouse changes require native role and company ownership', function () {
$this->actingAs($this->f['issuer'])->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => null])->assertForbidden();
$this->actingAs($this->f['receiver']);
$foreign = Tenant::query()->create(['name' => 'Outra empresa']);
$warehouse = Warehouse::query()->create(['tenant_id' => $foreign->id, 'created_by' => $this->f['receiver']->id, 'code' => 'OUTRO', 'name' => 'Não visível']);
$this->post('/stock/armazens/'.$warehouse->id.'/localizacao', ['geography_reference' => $this->reference, 'expected_reference' => null])->assertNotFound();
});
test('operational geography revalidates current warehouse authority after company locking', function () {
$actor = $this->f['receiver'];
$this->partialMock(ConflictGuard::class)->shouldReceive('lockCompany')->once()->andReturnUsing(function () use ($actor) {
DB::table('users')->where('id', $actor->id)->update(['purchasing_role' => PurchasingRole::Finance->value]);
});
$this->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => null])->assertForbidden();
expect($this->f['warehouse']->refresh()->geography_reference)->toBeNull();
});
test('operational geography warehouse audit failure rolls back the reference', function () {
$this->partialMock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => null]))->toThrow(RuntimeException::class, 'Synthetic audit failure');
expect($this->f['warehouse']->refresh()->geography_reference)->toBeNull();
});
test('operational geography invalid ambiguous or stale references never change the operational registries', function () {
$service = app(AdministrativeGeography::class);
$bad = collect($service->catalogue()['records'])->first(fn ($record) => in_array('duplicate_code_path', $record['issues'], true));
foreach ([['record_id' => '999999'], ['record_id' => $bad['id']], ['catalogue' => str_repeat('0', 64)]] as $change) {
$reference = [...$this->reference, ...$change];
$this->post($this->warehouseUrl, ['geography_reference' => $reference, 'expected_reference' => null])->assertSessionHasErrors('geography_reference');
$this->post('/equipamentos/activos', [...operationalAssetData($this->asset), 'geography_reference' => $reference])->assertSessionHasErrors('geography_reference');
}
expect($this->asset->refresh()->geography_reference)->toBeNull()->and($this->f['warehouse']->refresh()->geography_reference)->toBeNull();
});
test('operational geography equipment updates retain native version checks area and approved documents', function () {
$before = [];
foreach (['requisitions', 'requisition_items', 'approval_steps', 'purchase_orders', 'purchase_order_items'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$payload = operationalAssetData($this->asset);
$this->post('/equipamentos/activos', [...$payload, 'geography_reference' => $this->reference])->assertSessionHasNoErrors();
expect($this->asset->refresh()->geography_reference)->toBe($this->reference)->and($this->asset->area)->toBe('Área textual original')->and($this->asset->version)->toBe(2);
$this->post('/equipamentos/activos', [...$payload, 'geography_reference' => null])->assertSessionHasErrors('version');
$this->post('/equipamentos/activos', operationalAssetData($this->asset))->assertSessionHasNoErrors();
expect($this->asset->refresh()->geography_reference)->toBe($this->reference);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
$this->get('/equipamentos/'.$this->asset->id)->assertInertia(fn (Assert $page) => $page->where('geography.path.0.name', 'Niassa'));
$this->post('/equipamentos/activos', [...operationalAssetData($this->asset), 'geography_reference' => null])->assertSessionHasNoErrors();
expect($this->asset->refresh()->geography_reference)->toBeNull();
});
test('operational geography warehouse filter includes descendants and does not rewrite receipt snapshots', function () {
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
$before = DB::table('stock_movements')->orderBy('id')->get()->toArray();
$child = collect(app(AdministrativeGeography::class)->catalogue()['records'])->first(fn ($record) => $record['selectable'] && $record['level'] > 1 && $record['codes'][0] === '01');
$this->post($this->warehouseUrl, ['geography_reference' => [...$this->reference, 'record_id' => $child['id']], 'expected_reference' => null])->assertSessionHasNoErrors();
$this->get('/stock?location=2')->assertInertia(fn (Assert $page) => $page->has('warehouses', 1)->has('movements.data', 1)->has('balances', 1));
$this->get('/stock?location=999999')->assertSessionHasErrors('geography_reference');
expect(DB::table('stock_movements')->orderBy('id')->get()->toArray())->toEqual($before);
});
test('operational geography equipment filter retains tenant and department scope', function () {
$this->asset->update(['geography_reference' => $this->reference]);
$otherDepartment = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
$data = $this->asset->only(['tenant_id', 'created_by', 'description', 'area', 'status', 'criticality_level_id']);
Equipment::query()->create([...$data, 'department_id' => $otherDepartment->id, 'code' => 'FORA-AREA', 'geography_reference' => $this->reference]);
$otherTenant = Tenant::query()->create(['name' => 'Outra empresa']);
Equipment::query()->create([...$data, 'tenant_id' => $otherTenant->id, 'department_id' => $otherDepartment->id, 'code' => 'FORA-EMPRESA', 'geography_reference' => $this->reference]);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($head)->get('/equipamentos?location=2')->assertInertia(fn (Assert $page) => $page->has('equipment', 1)->where('equipment.0.id', $this->asset->id));
});
test('operational geography missing columns hide only the new controls and preserve legacy creation', function () {
foreach (['warehouses', 'equipment'] as $table) {
Schema::table($table, fn ($schema) => $schema->dropColumn('geography_reference'));
}
$this->get('/stock')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false));
$this->get('/equipamentos')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false));
$this->actingAs($this->f['issuer'])->get('/fornecedores')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', true));
$this->actingAs($this->f['receiver']);
$this->post('/stock/armazens', ['code' => 'LEGACY', 'name' => 'Cadastro sem nova coluna'])->assertSessionHasNoErrors();
$this->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => null])->assertServiceUnavailable();
$this->post('/equipamentos/activos', [...operationalAssetData($this->asset), 'geography_reference' => $this->reference])->assertSessionHasErrors('geography_reference');
});
test('operational geography maintenance access cannot mutate either registry even without route middleware', function () {
$this->withoutMiddleware(EnsureOrganizationAccess::class);
$this->partialMock(OrganizationAccess::class)->shouldReceive('maintenanceOnly')->andReturn(true);
$this->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => null])->assertForbidden();
$this->post('/equipamentos/activos', [...operationalAssetData($this->asset), 'geography_reference' => $this->reference])->assertForbidden();
expect($this->f['warehouse']->refresh()->geography_reference)->toBeNull()->and($this->asset->refresh()->geography_reference)->toBeNull();
});
test('operational geography equipment audit failure rolls back version and location together', function () {
$before = operationalAssetData($this->asset);
$this->partialMock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic equipment audit failure'));
$this->withoutExceptionHandling();
expect(fn () => $this->post('/equipamentos/activos', [...$before, 'geography_reference' => $this->reference]))->toThrow(RuntimeException::class, 'Synthetic equipment audit failure');
expect($this->asset->refresh()->geography_reference)->toBeNull()->and($this->asset->version)->toBe($before['version']);
});
test('operational geography revalidates current equipment authority before saving', function () {
$actor = $this->f['receiver'];
$this->partialMock(ConflictGuard::class)->shouldReceive('lockCompany')->once()->andReturnUsing(function () use ($actor) {
DB::table('users')->where('id', $actor->id)->update(['purchasing_role' => PurchasingRole::Finance->value]);
});
$this->post('/equipamentos/activos', [...operationalAssetData($this->asset), 'geography_reference' => $this->reference])->assertForbidden();
expect($this->asset->refresh()->geography_reference)->toBeNull();
});
test('operational geography can be suspended without disabling company supplier or catalogue selection', function () {
config(['geography.operational_enabled' => false]);
expect(app(AdministrativeGeography::class)->enabled())->toBeTrue();
$this->getJson('/api/divisao-administrativa')->assertOk()->assertJsonCount(11, 'data');
$this->get('/stock')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false));
$this->get('/equipamentos')->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false));
$this->post($this->warehouseUrl, ['geography_reference' => $this->reference, 'expected_reference' => null])->assertServiceUnavailable();
$this->post('/equipamentos/activos', [...operationalAssetData($this->asset), 'geography_reference' => $this->reference])->assertSessionHasErrors('geography_reference');
});
+88
View File
@@ -0,0 +1,88 @@
<?php
use App\Services\OperationalHealth;
use App\Services\ReceiptDocumentHealth;
use App\Services\ReplenishmentHeartbeat;
use App\Services\ReplenishmentQueue;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
$this->f = receiptFixture();
auth()->logout();
$this->originalStorage = app()->storagePath();
$this->temporaryStorage = $this->originalStorage.'/framework/testing/operations-'.Str::uuid();
File::ensureDirectoryExists($this->temporaryStorage.'/framework');
File::ensureDirectoryExists($this->temporaryStorage.'/documents');
app()->useStoragePath($this->temporaryStorage);
Storage::set('receipt_documents', Storage::build(['driver' => 'local', 'root' => $this->temporaryStorage.'/documents', 'throw' => true]));
app(ReplenishmentHeartbeat::class)->record(now()->toIso8601String(), 0);
});
afterEach(function () {
app()->useStoragePath($this->originalStorage);
File::deleteDirectory($this->temporaryStorage);
});
test('operational health integrates native inspections without changing facts or heartbeat', function () {
$before = [];
foreach (['requisitions', 'stock_movements', 'audit_logs', 'replenishment_work', 'receipt_documents', 'approval_steps'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$heartbeat = File::get(storage_path('framework/replenishment-command-status.json'));
expect(Artisan::call('sgc:operations-check', ['--json' => true]))->toBe(0);
$output = Artisan::output();
$result = json_decode($output, true, 32, JSON_THROW_ON_ERROR);
expect($result['schema_version'])->toBe(1)->and($result['ok'])->toBeTrue()->and($result['complete'])->toBeTrue()
->and($result['checks']['replenishment']['result']['work']['total'])->toBe(0)
->and($result['checks']['receipt_documents']['result']['documents_checked'])->toBe(0);
expect($output)->not->toContain($this->temporaryStorage, 'tenant_id', 'password');
expect(File::get(storage_path('framework/replenishment-command-status.json')))->toBe($heartbeat);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
});
test('operational health continues the other inspection after a private failure', function () {
$this->mock(ReplenishmentQueue::class)->shouldReceive('health')->once()->andThrow(new RuntimeException('PRIVATE database password and path'));
expect(Artisan::call('sgc:operations-check', ['--json' => true]))->toBe(1);
$output = Artisan::output();
$result = json_decode($output, true, 32, JSON_THROW_ON_ERROR);
expect($result['ok'])->toBeFalse()->and($result['complete'])->toBeFalse()
->and($result['checks']['replenishment']['status'])->toBe('unavailable')
->and($result['checks']['receipt_documents']['status'])->toBe('passed');
expect($output)->not->toContain('PRIVATE', 'password', $this->temporaryStorage);
});
test('operational health reports incomplete document coverage and preserves files', function () {
Storage::disk('receipt_documents')->put('one.bin', 'one');
Storage::disk('receipt_documents')->put('two.bin', 'two');
expect(Artisan::call('sgc:operations-check', ['--json' => true, '--document-limit' => '1']))->toBe(1);
$result = json_decode(Artisan::output(), true, 32, JSON_THROW_ON_ERROR);
expect($result['complete'])->toBeFalse()->and($result['checks']['receipt_documents']['status'])->toBe('incomplete')
->and($result['checks']['receipt_documents']['result']['reasons'])->toContain('limit_reached');
expect(Storage::disk('receipt_documents')->allFiles())->toHaveCount(2);
});
test('operational health distinguishes complete attention from successful operation', function () {
File::delete(storage_path('framework/replenishment-command-status.json'));
$result = app(OperationalHealth::class)->inspect();
expect($result['ok'])->toBeFalse()->and($result['complete'])->toBeTrue()
->and($result['checks']['replenishment']['status'])->toBe('attention')
->and($result['checks']['receipt_documents']['status'])->toBe('passed');
$this->artisan('sgc:operations-check')->expectsOutput('Operação: verificações requerem atenção.')->assertExitCode(1);
});
test('operational health rejects invalid limits and interactive identities before inspection', function () {
$this->mock(ReceiptDocumentHealth::class)->shouldNotReceive('inspect');
expect(Artisan::call('sgc:operations-check', ['--document-limit' => '10001']))->toBe(2);
expect(fn () => app(OperationalHealth::class)->inspect(0))->toThrow(LogicException::class);
$this->actingAs($this->f['receiver']);
expect(fn () => app(OperationalHealth::class)->inspect())->toThrow(HttpException::class);
});
+45
View File
@@ -8,6 +8,7 @@ use App\Models\User;
use App\Services\AiPreparationPlan;
use App\Services\PeopleAccess;
use App\Services\PeopleClarifications;
use App\Services\PeopleContractHandoff;
use App\Services\PeopleEvidenceBrief;
use App\Services\PeopleHiring;
use App\Services\PeopleOperationalInsights;
@@ -18,9 +19,53 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Testing\TestResponse;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/AiPlanFixture.php';
test('people dossier block reuses approved selection and draft without changing decisions or contract status', function (string $kind) {
$record = hiringAssessment($this, $kind);
$application = DB::table('people_applications')->sole();
hiringCommand($this, $this->reviewer, $record, 'evaluate', ['application_id' => $application->id, 'answers' => [
['score' => 8, 'evidence' => 'Competências fictícias verificadas.'], ['score' => 8, 'evidence' => 'Experiência fictícia verificada.']]])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'select', ['application_id' => $application->id])->assertRedirect();
hiringCommand($this, $this->approver, $record, 'confirm', ['outcome' => 'approved'])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'contract', ['reference' => 'MINUTA-DOSSIER', 'starts_on' => today()->addWeek()->toDateString(), 'terms' => 'Minuta fictícia para preparação, sem assinatura.'])->assertRedirect();
$before = [];
foreach (['people_processes', 'people_applications', 'people_reviews', 'people_process_access', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->actingAs($this->preparer)->getJson('/pessoas/'.$record->id.'/dossier.json')->assertOk()
->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertHeader('X-Content-Type-Options', 'nosniff')
->assertJsonPath('schema', 'sgc.people.process-dossier.v1')->assertJsonPath('effect', 'preparation_only')
->assertJsonPath('process.status', 'contract_draft')->assertJsonPath('process.contract.status', 'draft')
->assertJsonPath('process.contract.reference', 'MINUTA-DOSSIER')->assertJsonPath('process.selected_application_id', $application->id)
->assertJsonMissingPath('process.creation_hash')->assertJsonMissingPath('process.tenant_id');
$this->getJson('/pessoas/'.$record->id.'/dossier.json')->assertOk();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
expect(fn () => app(PeopleContractHandoff::class)->envelope($record->fresh()))->toThrow(HttpException::class);
})->with(['service', 'staff']);
test('people dossier block shares page redactions and rejects expired or foreign access', function () {
$this->body['annex'] = ['fields' => ['financial' => 'DOSSIER-FINANCIAL-SECRET'], 'requirements' => []];
$record = hiringAssessment($this);
$application = DB::table('people_applications')->sole();
hiringCommand($this, $this->reviewer, $record, 'evaluate', ['application_id' => $application->id, 'answers' => [
['score' => 8, 'evidence' => 'DOSSIER-INTERVIEW-SECRET', 'evidence_type' => 'verified'], ['score' => 8, 'evidence' => 'Experiência fictícia documentada.', 'evidence_type' => 'verified']]])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'select', ['application_id' => $application->id])->assertRedirect();
$this->actingAs($this->approver)->getJson('/pessoas/'.$record->id.'/dossier.json')->assertOk()
->assertDontSee('DOSSIER-FINANCIAL-SECRET')->assertDontSee('DOSSIER-INTERVIEW-SECRET')
->assertJsonMissingPath('process.rules.annex.fields.financial')->assertJsonMissingPath('process.selection.rules.annex.fields.financial')
->assertJsonCount(0, 'candidates.0.reviews')->assertJsonCount(0, 'process.selection.rows.0.reviews')->assertJsonPath('process.contract', null);
DB::table('people_process_access')->where('user_id', $this->approver->id)->update(['expires_at' => now()->subMinute()]);
$this->getJson('/pessoas/'.$record->id.'/dossier.json')->assertForbidden();
$foreign = Tenant::query()->create(['name' => 'Outra empresa fictícia']);
$user = User::factory()->create(['tenant_id' => $foreign->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($user)->getJson('/pessoas/'.$record->id.'/dossier.json')->assertNotFound();
});
beforeEach(function () {
$this->tenant = Tenant::query()->create(['name' => 'Empresa de contratação fictícia']);
foreach (['preparer', 'reviewer', 'approver'] as $key) {
@@ -0,0 +1,96 @@
<?php
use App\Models\ReceiptDocument;
use App\Services\ReceiptDocumentHealth;
use App\Services\ReceiptDocuments;
use App\Services\ReceiptWorkflow;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
$this->directory = storage_path('framework/testing/receipt-health-'.Str::uuid());
File::ensureDirectoryExists($this->directory);
Storage::set('receipt_documents', Storage::build(['driver' => 'local', 'root' => $this->directory, 'throw' => true]));
$this->f = receiptFixture();
$this->actingAs($this->f['receiver']);
$this->receipt = app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f));
$this->bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
$this->document = app(ReceiptDocuments::class)->add($this->f['receiver'], $this->receipt, ['operation_key' => (string) Str::uuid(), 'document_type' => 'delivery_note'], UploadedFile::fake()->createWithContent('private-name.png', $this->bytes));
auth()->logout();
});
afterEach(function () {
File::deleteDirectory($this->directory);
});
test('receipt document health checks native evidence without mutations or disclosing private identifiers', function () {
$other = receiptFixture();
$this->actingAs($other['receiver']);
$receipt = app(ReceiptWorkflow::class)->confirm($other['receiver'], $other['order'], receiptPayload($other));
app(ReceiptDocuments::class)->add($other['receiver'], $receipt, ['operation_key' => (string) Str::uuid(), 'document_type' => 'quality'], UploadedFile::fake()->createWithContent('other-private.png', $this->bytes));
auth()->logout();
$before = [];
foreach (['receipt_documents', 'audit_logs', 'goods_receipts', 'stock_movements', 'approval_steps'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
expect(Artisan::call('sgc:receipt-documents-check', ['--json' => true]))->toBe(0);
$output = Artisan::output();
$result = json_decode($output, true, 32, JSON_THROW_ON_ERROR);
expect($result['ok'])->toBeTrue()->and($result['complete'])->toBeTrue()->and($result['documents_checked'])->toBe(2)->and($result['files_checked'])->toBe(2);
expect($output)->not->toContain($this->directory, $this->document->path, 'private-name.png');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
expect(Storage::disk('receipt_documents')->get($this->document->path))->toBe($this->bytes);
});
test('receipt document health detects missing altered and unreferenced files without removing any', function () {
$disk = Storage::disk('receipt_documents');
$disk->delete($this->document->path);
expect(app(ReceiptDocumentHealth::class)->inspect()['missing'])->toBe(1);
$changed = $this->bytes;
$changed[10] = 'x';
$disk->put($this->document->path, $changed);
$disk->put('recent.bin', 'recent');
$disk->put('older.bin', 'older');
touch($disk->path('older.bin'), now()->subHours(2)->timestamp);
$result = app(ReceiptDocumentHealth::class)->inspect();
expect($result['ok'])->toBeFalse()->and($result['altered'])->toBe(1)->and($result['unreferenced_recent'])->toBe(1)->and($result['unreferenced_older'])->toBe(1);
expect($disk->allFiles())->toHaveCount(3)->and($disk->get($this->document->path))->toBe($changed);
expect(ReceiptDocument::withoutGlobalScopes()->count())->toBe(1);
});
test('receipt document health rejects invalid paths and reports a bounded incomplete scan', function () {
DB::table('receipt_documents')->insert([...$this->document->getRawOriginal(), 'id' => $this->document->id + 1, 'document_type' => 'other', 'path' => '../outside-secret.txt']);
expect(app(ReceiptDocumentHealth::class)->inspect()['invalid_reference'])->toBe(1);
$result = app(ReceiptDocumentHealth::class)->inspect(1);
expect($result['ok'])->toBeFalse()->and($result['complete'])->toBeFalse()->and($result['reasons'])->toContain('limit_reached');
expect(Artisan::call('sgc:receipt-documents-check', ['--limit' => '10001']))->toBe(2);
});
test('receipt document health distinguishes unavailable installation and hides technical errors', function () {
Schema::drop('receipt_documents');
expect(app(ReceiptDocumentHealth::class)->inspect()['reasons'])->toBe(['not_installed']);
$this->mock(ReceiptDocumentHealth::class)->shouldReceive('inspect')->andThrow(new RuntimeException('private secret path/password'));
expect(Artisan::call('sgc:receipt-documents-check', ['--json' => true]))->toBe(1);
expect(Artisan::output())->toContain('unavailable')->not->toContain('password', 'secret');
});
test('receipt document health refuses an interactive identity instead of exposing a global tenant scan', function () {
$this->actingAs($this->f['receiver']);
expect(fn () => app(ReceiptDocumentHealth::class)->inspect())->toThrow(HttpException::class);
});
test('receipt document health does not certify an unavailable storage root', function () {
File::deleteDirectory($this->directory);
$result = app(ReceiptDocumentHealth::class)->inspect();
expect($result['ok'])->toBeFalse()->and($result['complete'])->toBeFalse()->and($result['reasons'])->toBe(['storage_unavailable']);
});
+50
View File
@@ -0,0 +1,50 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\ReceiptDocument;
use App\Models\User;
use App\Services\ReceiptWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('receipt print block reproduces preserved facts escapes evidence and leaves business data untouched', function () {
$f = receiptFixture();
$this->actingAs($f['receiver']);
$payload = receiptPayload($f);
$payload['items'][0]['notes'] = '<script>alert(1)</script>';
$receipt = app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], $payload);
ReceiptDocument::query()->create(['tenant_id' => $f['tenant']->id, 'goods_receipt_id' => $receipt->id, 'uploaded_by' => $f['receiver']->id,
'document_type' => 'quality', 'original_name' => 'quality.png', 'path' => 'private-secret-path', 'mime_type' => 'image/png', 'size' => 40, 'sha256' => str_repeat('a', 64), 'created_at' => now()]);
$before = [];
foreach (['goods_receipts', 'goods_receipt_items', 'stock_movements', 'audit_logs', 'receipt_documents', 'approval_steps', 'budget_entries'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->get('/recepcoes/'.$receipt->id.'/imprimir')->assertOk()
->assertHeader('Cache-Control', 'no-store, private')
->assertSee($receipt->number)->assertSee($f['order']->number)->assertSee('0,600')->assertSee('Conforme')
->assertSee('&lt;script&gt;alert(1)&lt;/script&gt;', false)->assertDontSee('<script>alert(1)</script>', false)
->assertSee('quality.png')->assertSee(str_repeat('a', 64))->assertDontSee('private-secret-path');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
$this->actingAs($f['issuer'])->get('/recepcoes/'.$receipt->id.'/imprimir')->assertOk();
});
test('receipt print block preserves tenant isolation and native visibility', function () {
$f = receiptFixture();
$receipt = app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f));
$foreign = receiptFixture();
$this->actingAs($foreign['receiver'])->get('/recepcoes/'.$receipt->id.'/imprimir')->assertNotFound();
$requester = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Requester]);
$this->actingAs($requester);
$this->get('/recepcoes/'.$receipt->id.'/imprimir')->assertForbidden();
});
test('receipt print block remains available without the optional document table', function () {
$f = receiptFixture();
$receipt = app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f));
Schema::drop('receipt_documents');
$this->actingAs($f['receiver'])->get('/recepcoes/'.$receipt->id.'/imprimir')->assertOk()->assertSee('Sem referências documentais');
});
+109 -16
View File
@@ -4,28 +4,14 @@ use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\Department;
use App\Models\Supplier;
use App\Models\SupplierEvaluation;
use App\Models\SupplierImprovement;
use App\Models\User;
use App\Services\AdministrativeGeography;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function reportEvaluation(array $fixture, ?int $department = null, int $revision = 1, ?int $previous = null): SupplierEvaluation
{
return SupplierEvaluation::query()->create(['tenant_id' => $fixture['tenant']->id, 'supplier_id' => $fixture['order']->supplier_id, 'department_id' => $department ?? $fixture['r']->department_id,
'created_by' => $fixture['issuer']->id, 'operation_key' => (string) Str::uuid(), 'creation_hash' => str_repeat('b', 64), 'status' => 'approved', 'contributors' => [$fixture['issuer']->id],
'revision' => $revision, 'previous_id' => $previous, 'supplier_snapshot' => ['id' => $fixture['order']->supplier_id, 'name' => 'Fornecedor preservado QA', 'nuit' => '123456789'],
'payload' => ['title' => 'Avaliação QA', 'order_ids' => [], 'criteria' => [], 'period_start' => null, 'period_end' => null]]);
}
function reportMeasure(SupplierEvaluation $evaluation, User $responsible, array $extra = []): SupplierImprovement
{
return SupplierImprovement::query()->create([...['tenant_id' => $evaluation->tenant_id, 'supplier_evaluation_id' => $evaluation->id, 'created_by' => $responsible->id, 'responsible_id' => $responsible->id,
'operation_key' => (string) Str::uuid(), 'creation_hash' => str_repeat('c', 64), 'title' => 'Medida QA', 'description' => 'Objectivo fictício para o relatório.', 'due_on' => '2026-10-29', 'contributors' => [$responsible->id]], ...$extra]);
}
require_once __DIR__.'/../Support/SupplierImprovementFixture.php';
beforeEach(function () {
$this->f = receiptFixture();
@@ -35,6 +21,113 @@ beforeEach(function () {
$this->travelTo(now()->setDate(2026, 10, 30)->startOfDay());
});
function supplierReportReference(bool $otherProvince = false): array
{
$record = collect(app(AdministrativeGeography::class)->catalogue()['records'])->first(fn ($record) => $record['selectable'] && $record['level'] === 4 && ($otherProvince ? $record['codes'][0] !== '01' : $record['codes'][0] === '01'));
return ['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => $record['id']];
}
test('supplier territory report shares directory classification and preserves approved evaluation snapshots', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$supplier = Supplier::query()->findOrFail($this->evaluation->supplier_id);
$supplier->update(['geography_reference' => supplierReportReference()]);
$measure = reportMeasure($this->evaluation, $this->f['issuer']);
$before = [];
foreach (['suppliers', 'supplier_evaluations', 'supplier_improvements', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->get($this->base.'?location=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 1)->where('records.data.0.id', $measure->id)->where('records.data.0.supplier', 'Fornecedor preservado QA')->where('counts.open', 1)->where('overdue', 1)->where('geographyFilter.path.0.name', 'Niassa'));
$this->get('/fornecedores?location=2')->assertInertia(fn (Assert $page) => $page->has('suppliers.data', 1)->where('suppliers.data.0.id', $supplier->id));
expect($this->get($this->base.'.csv?location=2')->assertOk()->streamedContent())->toContain('Niassa', 'localizacao_actual_da_ficha', 'Fornecedor preservado QA');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
});
test('supplier territory report uses current registration without rewriting the evaluation when geography changes', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$supplier = Supplier::query()->findOrFail($this->evaluation->supplier_id);
$supplier->update(['geography_reference' => supplierReportReference()]);
reportMeasure($this->evaluation, $this->f['issuer']);
$original = $this->evaluation->fresh()->getAttributes();
$this->get($this->base.'?location=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 1));
$supplier->update(['geography_reference' => supplierReportReference(true)]);
$this->get($this->base.'?location=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('records.total', 1));
expect($this->evaluation->refresh()->getAttributes())->toBe($original);
});
test('supplier territory report keeps historical revisions suspended suppliers and complete CSV across pages', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
Supplier::query()->findOrFail($this->evaluation->supplier_id)->update(['geography_reference' => supplierReportReference(), 'status' => 'suspended']);
$revision = reportEvaluation($this->f, null, 2, $this->evaluation->id);
foreach (range(1, 26) as $index) {
reportMeasure($index === 26 ? $revision : $this->evaluation, $this->f['issuer'], ['title' => 'Território '.$index, 'status' => $index === 1 ? 'closed' : 'open']);
}
$this->get($this->base.'?location=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 26)->has('records.data', 25)->where('counts.open', 25)->where('counts.closed', 1)->where('overdue', 25));
$response = $this->get($this->base.'?location=2&page=2')->assertInertia(fn (Assert $page) => $page->has('records.data', 1)->where('records.data.0.revision', 2));
expect($response->inertiaProps('records.prev_page_url'))->toContain('location=2');
$csv = $this->get($this->base.'.csv?location=2&page=2')->assertOk()->streamedContent();
$rows = array_map(fn ($line) => str_getcsv($line, ';', '"', ''), explode("\n", trim($csv)));
expect($rows)->toHaveCount(29)->and($rows[2])->toHaveCount(17)->and($rows[3][4])->toBe('Território 1')->and($rows[28][4])->toBe('Território 26');
});
test('supplier territory report does not infer location from address or obsolete and foreign country references', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
$supplier = Supplier::query()->findOrFail($this->evaluation->supplier_id);
$supplier->update(['address' => 'Niassa / CIDADE DE LICHINGA / Urbana nº 1']);
reportMeasure($this->evaluation, $this->f['issuer']);
foreach ([null, [...supplierReportReference(), 'catalogue' => str_repeat('0', 64)], [...supplierReportReference(), 'country' => 'ZA']] as $reference) {
$supplier->update(['geography_reference' => $reference]);
$this->get($this->base.'?location=2')->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
$this->get('/fornecedores?location=2')->assertInertia(fn (Assert $page) => $page->has('suppliers.data', 0));
}
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('records.total', 1));
});
test('supplier territory report combines native filters and retains department and tenant boundaries', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
Supplier::query()->findOrFail($this->evaluation->supplier_id)->update(['geography_reference' => supplierReportReference()]);
reportMeasure($this->evaluation, $this->f['issuer'], ['title' => 'Visível territorial', 'status' => 'returned']);
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
reportMeasure(reportEvaluation($this->f, $department->id), $this->f['issuer'], ['title' => 'OCULTA-AREA']);
$foreign = receiptFixture();
Supplier::query()->findOrFail($foreign['order']->supplier_id)->update(['geography_reference' => supplierReportReference()]);
reportMeasure(reportEvaluation($foreign), $foreign['issuer'], ['title' => 'OCULTA-EMPRESA']);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($head);
$query = '?location=2&status=returned&supplier_id='.$this->evaluation->supplier_id.'&responsible_id='.$this->f['issuer']->id.'&search=territorial&overdue=1';
$this->get($this->base.$query)->assertInertia(fn (Assert $page) => $page->where('records.total', 1)->where('counts.returned', 1));
$csv = $this->get($this->base.'.csv'.$query)->assertOk()->streamedContent();
expect($csv)->toContain('Visível territorial')->not->toContain('OCULTA-AREA', 'OCULTA-EMPRESA');
});
test('supplier territory report validates territory before export and preserves legacy reports when disabled', function () {
$this->withoutVite();
config(['geography.enabled' => true]);
reportMeasure($this->evaluation, $this->f['issuer']);
$this->getJson($this->base.'?location=999999')->assertUnprocessable();
$this->getJson($this->base.'.csv?location=999999')->assertUnprocessable();
$this->getJson($this->base.'?location[]=2')->assertUnprocessable();
config(['geography.enabled' => false]);
$this->getJson($this->base.'?location=2')->assertServiceUnavailable();
$this->getJson($this->base.'.csv?location=2')->assertServiceUnavailable();
$this->get($this->base)->assertInertia(fn (Assert $page) => $page->where('geographyEnabled', false)->where('records.total', 1));
});
test('supplier territory report revalidates a revoked role before reading geographic results', function () {
config(['geography.enabled' => true]);
$this->f['issuer']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
$this->getJson($this->base.'?location=2')->assertForbidden();
$this->getJson($this->base.'.csv?location=2')->assertForbidden();
});
test('report paginates all authorized revisions with counts over the entire filtered set', function () {
$next = reportEvaluation($this->f, null, 2, $this->evaluation->id);
foreach (range(1, 27) as $i) {
+126
View File
@@ -23,6 +23,132 @@ use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
test('warehouse request export shares filters and preserves facts while protecting spreadsheet cells', function () {
$this->r = app(WarehouseRequests::class)->draft($this->f['issuer'], [...$this->draftData, 'operation_key' => (string) Str::uuid(), 'reason' => '=SUM(100;200)']);
warehouseCommand($this, $this->f['issuer'], 'submit', ['partial_allowed' => true]);
warehouseCommand($this, $this->reviewer, 'authorize', ['partial_allowed' => true]);
warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '1.500']]]);
$before = [];
foreach (['warehouse_requests', 'warehouse_request_events', 'warehouse_reservations', 'stock_operations', 'stock_movements', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->actingAs($this->reviewer);
$url = '/stock/requisicoes.csv?view=reserve&state=partial&search=RA-'.$this->r->id.'&warehouse_id='.$this->f['warehouse']->id.'&page=2';
$csv = $this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->streamedContent();
$rows = array_map(fn ($line) => str_getcsv($line, ';', '"', ''), explode("\n", trim($csv)));
expect($rows)->toHaveCount(4)->and($rows[2])->toHaveCount(21)->and($rows[3][0])->toBe('RA-'.$this->r->id)
->and($rows[3][7])->toBe("'=SUM(100;200)")->and(array_slice($rows[3], 14, 5))->toBe(['4.000', '2.500', '1.500', '2.500', '0.000']);
expect($this->get('/stock/requisicoes.csv?state=draft')->streamedContent())->not->toContain('RA-'.$this->r->id);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
});
test('warehouse request export includes old pending requests beyond pagination', function () {
foreach (range(1, 16) as $index) {
app(WarehouseRequests::class)->draft($this->f['issuer'], [...$this->draftData, 'operation_key' => (string) Str::uuid(), 'reason' => 'Pendência antiga '.$index]);
}
$csv = $this->get('/stock/requisicoes.csv?state=draft&page=2')->assertOk()->streamedContent();
expect(explode("\n", trim($csv)))->toHaveCount(20);
expect($csv)->toContain('RA-'.$this->r->id, 'Pendência antiga 16');
});
test('warehouse request export enforces roles tenant scope and validates filters', function () {
$this->getJson('/stock/requisicoes.csv?state=invalid')->assertUnprocessable();
$other = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id]);
$this->actingAs($other)->get('/stock/requisicoes.csv')->assertForbidden();
supplyGrant($other, ['warehouse_request_prepare']);
expect($this->actingAs($other)->get('/stock/requisicoes.csv')->assertOk()->streamedContent())->not->toContain('RA-'.$this->r->id);
$foreign = receiptFixture();
supplyGrant($foreign['receiver'], ['warehouse_request_read']);
expect($this->actingAs($foreign['receiver'])->get('/stock/requisicoes.csv')->assertOk()->streamedContent())->not->toContain('RA-'.$this->r->id);
$this->getJson('/stock/requisicoes.csv?warehouse_id='.$this->f['warehouse']->id)->assertUnprocessable();
});
test('warehouse request print reproduces reservations partial deliveries and confirmations without writes', function () {
warehouseCommand($this, $this->f['issuer'], 'submit', ['partial_allowed' => true]);
warehouseCommand($this, $this->reviewer, 'authorize', ['partial_allowed' => true]);
warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '1.500']], 'reason' => '<script>unsafe()</script>']);
$delivery = WarehouseRequestEvent::query()->where('action', 'deliver')->sole();
$url = '/stock/requisicoes/'.$this->r->id.'/imprimir';
$tables = ['warehouse_requests', 'warehouse_request_events', 'warehouse_reservations', 'stock_movements', 'stock_operations', 'audit_logs', 'budget_entries'];
$before = [];
foreach ($tables as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertSee('Entrega parcial')->assertSee('4,000')->assertSee('1,500')->assertSee('2,500')->assertSee('Sem factura')
->assertSee($this->reviewer->name)->assertSee('Oficina interna')->assertSee('Recepção por confirmar')
->assertSee('/entregas/'.$delivery->id.'/imprimir', false)->assertDontSee('<script>unsafe()', false)->assertSee('&lt;script&gt;', false);
$this->get($url)->assertOk();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
warehouseCommand($this, $this->f['issuer'], 'receive', ['delivery_event_id' => $delivery->id]);
$this->get($url)->assertOk()->assertSee('Recepção confirmada');
});
test('warehouse request print distinguishes draft and cancellation without pretending a stock exit', function () {
$url = '/stock/requisicoes/'.$this->r->id.'/imprimir';
$this->get($url)->assertOk()->assertSee('Rascunho')->assertSee('Sem intervenções registadas')->assertSee('4,000');
warehouseCommand($this, $this->f['issuer'], 'submit', ['partial_allowed' => true]);
warehouseCommand($this, $this->reviewer, 'authorize', ['partial_allowed' => true]);
warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '1.500']]]);
warehouseCommand($this, $this->reviewer, 'cancel');
$this->get($url)->assertOk()->assertSee('Cancelada')->assertSee('2,500')->assertSee('1,500')->assertSee('0,000');
});
test('warehouse request print respects existing viewer and tenant isolation', function () {
$url = '/stock/requisicoes/'.$this->r->id.'/imprimir';
$this->actingAs($this->reviewer)->get($url)->assertOk();
$other = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id]);
$this->actingAs($other)->get($url)->assertForbidden();
$foreign = receiptFixture();
$this->actingAs($foreign['receiver'])->get($url)->assertNotFound();
$this->actingAs($this->f['issuer'])->get('/stock/requisicoes/999999/imprimir')->assertNotFound();
});
test('warehouse delivery print block isolates a partial delivery and reflects native receipt without mutating business facts', function () {
warehouseCommand($this, $this->f['issuer'], 'submit', ['partial_allowed' => true]);
warehouseCommand($this, $this->reviewer, 'authorize', ['partial_allowed' => true]);
warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '1.500']], 'reason' => '<script>alert("test")</script>']);
$first = WarehouseRequestEvent::query()->where('action', 'deliver')->sole();
warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '2.500']]]);
$url = '/stock/requisicoes/'.$this->r->id.'/entregas/'.$first->id.'/imprimir';
$tables = ['warehouse_requests', 'warehouse_request_events', 'stock_movements', 'stock_operations', 'warehouse_reservations', 'audit_logs', 'invoices', 'budget_entries'];
$before = [];
foreach ($tables as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertSee('RA-'.$this->r->id)->assertSee('Sem factura')->assertSee('1,500')->assertDontSee('2,500')
->assertSee('Oficina interna')->assertSee($this->reviewer->name)->assertSee('Recepção por confirmar')->assertDontSee('<script>alert(', false)
->assertSee('&lt;script&gt;', false);
$this->get($url)->assertOk();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
warehouseCommand($this, $this->f['issuer'], 'receive', ['delivery_event_id' => $first->id]);
$this->get($url)->assertOk()->assertSee('Recepção confirmada por')->assertSee($this->f['issuer']->name);
$this->actingAs($this->reviewer)->get($url)->assertOk();
});
test('warehouse delivery print block rejects foreign tenants unrelated events and viewers without native access', function () {
warehouseCommand($this, $this->f['issuer'], 'submit');
$submit = WarehouseRequestEvent::query()->where('action', 'submit')->sole();
$base = '/stock/requisicoes/'.$this->r->id.'/entregas/';
$this->get($base.$submit->id.'/imprimir')->assertNotFound();
warehouseCommand($this, $this->reviewer, 'authorize');
warehouseCommand($this, $this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '4.000']]]);
$delivery = WarehouseRequestEvent::query()->where('action', 'deliver')->sole();
$url = $base.$delivery->id.'/imprimir';
$other = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id]);
$this->actingAs($other)->get($url)->assertForbidden();
$foreign = receiptFixture();
$this->actingAs($foreign['receiver'])->get($url)->assertNotFound();
$this->actingAs($this->f['receiver'])->get('/stock/requisicoes/999999/entregas/'.$delivery->id.'/imprimir')->assertNotFound();
});
beforeEach(function () {
$this->f = receiptFixture('100.000');
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['issuer']->department_id]);
@@ -0,0 +1,43 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function issuedOrderCancellationFixture(object $test): void
{
config(['order_cancellation.enabled' => true]);
$test->f = receiptFixture();
$base = ['tenant_id' => $test->f['tenant']->id, 'department_id' => $test->f['department']->id];
$test->buyer = User::factory()->create([...$base, 'purchasing_role' => PurchasingRole::Procurement]);
$test->finance = User::factory()->create([...$base, 'purchasing_role' => PurchasingRole::Finance]);
$test->admins = [];
foreach (range(1, 3) as $index) {
$test->admins[] = User::factory()->create([...$base, 'purchasing_role' => PurchasingRole::Admin]);
}
$test->actingAs($test->admins[0]);
$flow = app(OrderCancellationPolicyWorkflow::class);
$test->policy = $flow->propose($test->admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Política exclusivamente fictícia para o circuito de testes.']);
foreach ([$test->admins[1], $test->admins[2]] as $admin) {
$test->actingAs($admin);
$flow->review($admin, $test->policy, 'approved', 'Conferência independente da política fictícia.');
}
$test->actingAs($test->finance);
$test->budget = Budget::query()->create(['tenant_id' => $test->f['tenant']->id, 'cost_center_id' => $test->f['r']->cost_center_id, 'year' => now()->year,
'amount_minor' => 20000, 'includes_tax' => true, 'reason' => 'Dotação fictícia para ensaio da reversão.', 'created_by' => $test->finance->id,
'approved_by' => $test->admins[0]->id, 'approved_at' => now()]);
DB::transaction(function () use ($test) {
foreach (['reserve', 'award', 'commit'] as $kind) {
app(BudgetWorkflow::class)->record($test->finance, $test->f['r'], $kind, 10000, 10000);
}
});
$test->data = ['operation_key' => (string) Str::uuid(), 'reason' => 'Cancelamento integral fictício antes de qualquer execução.', 'evidence' => 'Referência documental fictícia do fundamento do cancelamento.'];
$test->actingAs($test->buyer);
}
@@ -0,0 +1,20 @@
<?php
use App\Models\SupplierEvaluation;
use App\Models\SupplierImprovement;
use App\Models\User;
use Illuminate\Support\Str;
function reportEvaluation(array $fixture, ?int $department = null, int $revision = 1, ?int $previous = null): SupplierEvaluation
{
return SupplierEvaluation::query()->create(['tenant_id' => $fixture['tenant']->id, 'supplier_id' => $fixture['order']->supplier_id, 'department_id' => $department ?? $fixture['r']->department_id,
'created_by' => $fixture['issuer']->id, 'operation_key' => (string) Str::uuid(), 'creation_hash' => str_repeat('b', 64), 'status' => 'approved', 'contributors' => [$fixture['issuer']->id],
'revision' => $revision, 'previous_id' => $previous, 'supplier_snapshot' => ['id' => $fixture['order']->supplier_id, 'name' => 'Fornecedor preservado QA', 'nuit' => '123456789'],
'payload' => ['title' => 'Avaliação QA', 'order_ids' => [], 'criteria' => [], 'period_start' => null, 'period_end' => null]]);
}
function reportMeasure(SupplierEvaluation $evaluation, User $responsible, array $extra = []): SupplierImprovement
{
return SupplierImprovement::query()->create([...['tenant_id' => $evaluation->tenant_id, 'supplier_evaluation_id' => $evaluation->id, 'created_by' => $responsible->id, 'responsible_id' => $responsible->id,
'operation_key' => (string) Str::uuid(), 'creation_hash' => str_repeat('c', 64), 'title' => 'Medida QA', 'description' => 'Objectivo fictício para o relatório.', 'due_on' => '2026-10-29', 'contributors' => [$responsible->id]], ...$extra]);
}
@@ -0,0 +1,76 @@
<?php
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
function orderCancellationRaces(array $environment, array $config, string $database): array
{
config(['database.connections.cancel_race_read' => [...$config, 'database' => $database, 'url' => null]]);
$reader = DB::connection('cancel_race_read');
$results = [];
foreach (['request_receipt', 'receipt_request', 'double_approval'] as $scenario) {
$worker = fn (array $args) => new Process([PHP_BINARY, 'tests/Support/order-cancellation-worker.php', ...$args], base_path(), $environment, timeout: 40);
$seed = $worker(['seed']);
$seed->mustRun();
$data = json_decode($seed->getOutput(), true, 64, JSON_THROW_ON_ERROR);
$data['barrier'] = storage_path('framework/testing/cancellation-race-'.bin2hex(random_bytes(8)));
if (! is_dir(dirname($data['barrier'])) && ! mkdir(dirname($data['barrier']), 0700, true)) {
throw new RuntimeException('Testing barrier directory unavailable.');
}
if ($scenario === 'double_approval') {
$worker(['run', json_encode($data, JSON_THROW_ON_ERROR), 'request'])->mustRun();
}
$first = $worker(['hold', json_encode($data, JSON_THROW_ON_ERROR), $scenario === 'receipt_request' ? 'receipt' : ($scenario === 'double_approval' ? 'approve' : 'request')]);
$second = $worker(['run', json_encode($data, JSON_THROW_ON_ERROR), $scenario === 'receipt_request' ? 'request' : ($scenario === 'double_approval' ? 'approve' : 'receipt')]);
try {
$first->start();
$deadline = microtime(true) + 15;
while ($first->isRunning() && ! str_contains($first->getOutput(), 'LOCKED') && microtime(true) < $deadline) {
usleep(20000);
}
if (! str_contains($first->getOutput(), 'LOCKED')) {
throw new RuntimeException('Company lock not acquired by first worker.');
}
$second->start();
$waited = false;
$deadline = microtime(true) + 15;
while ($second->isRunning() && microtime(true) < $deadline) {
$waited = $reader->selectOne("select count(*) as total from pg_stat_activity where datname = ? and application_name = 'cancel-race-run' and wait_event_type = 'Lock'", [$database])->total > 0;
if ($waited) {
break;
} usleep(20000);
}
if (! $waited) {
throw new RuntimeException('Company row lock wait not observed.');
}
file_put_contents($data['barrier'], 'release');
$first->wait();
$second->wait();
if (! $first->isSuccessful() || ! $second->isSuccessful() || ! str_contains($first->getOutput(), 'OK')
|| ! str_contains($second->getOutput(), $scenario === 'double_approval' ? 'OK' : 'BLOCKED')) {
throw new RuntimeException('Concurrent outcome not expected.');
}
$receipts = $reader->table('goods_receipts')->where('purchase_order_id', $data['order'])->count();
$cancellations = $reader->table('order_cancellations')->where('purchase_order_id', $data['order'])->get();
$reversals = $reader->table('budget_entries')->where('kind', 'order-cancel-'.$data['order'])->count();
if ($receipts !== ($scenario === 'receipt_request' ? 1 : 0) || $cancellations->count() !== ($scenario === 'receipt_request' ? 0 : 1)
|| $reversals !== ($scenario === 'double_approval' ? 1 : 0)
|| ($scenario === 'double_approval' && $cancellations->first()->status !== 'approved')) {
throw new RuntimeException('Concurrent effects not unique.');
}
$results[] = ['scenario' => $scenario, 'company_lock_wait_observed' => true, 'receipts' => $receipts, 'cancellations' => $cancellations->count(), 'reversal_entries' => $reversals, 'result' => 'passed'];
} finally {
if ($first->isRunning()) {
$first->stop();
} if ($second->isRunning()) {
$second->stop();
}
if (is_file($data['barrier'])) {
unlink($data['barrier']);
}
}
}
DB::purge('cancel_race_read');
return $results;
}
@@ -0,0 +1,73 @@
<?php
use App\Models\OrderCancellation;
use App\Models\PurchaseOrder;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\OrderCancellationWorkflow;
use App\Services\ReceiptWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())) {
throw new LogicException('Disposable test database required.');
}
config(['order_cancellation.enabled' => true]);
require_once __DIR__.'/IssuedOrderCancellationFixture.php';
$mode = $argv[1];
if ($mode === 'seed') {
$fixture = new class extends stdClass
{
public function withoutVite(): void {}
public function actingAs(User $user): self
{
auth()->guard('web')->setUser($user);
return $this;
}
};
issuedOrderCancellationFixture($fixture);
echo json_encode(['order' => $fixture->f['order']->id, 'buyer' => $fixture->buyer->id, 'finance' => $fixture->finance->id, 'receiver' => $fixture->f['receiver']->id,
'warehouse' => $fixture->f['warehouse']->id, 'stock' => $fixture->f['stock']->id, 'line' => $fixture->f['line']->id, 'input' => $fixture->data], JSON_THROW_ON_ERROR);
exit;
}
$data = json_decode($argv[2], true, 32, JSON_THROW_ON_ERROR);
$action = $argv[3];
DB::select("select set_config('application_name', ?, false)", ['cancel-race-'.$mode]);
$actor = User::query()->findOrFail($data[$action === 'request' ? 'buyer' : ($action === 'receipt' ? 'receiver' : 'finance')]);
auth()->guard('web')->setUser($actor);
try {
DB::transaction(function () use ($data, $actor, $action, $mode) {
if ($mode === 'hold') {
app(ConflictGuard::class)->lockCompany($actor);
echo "LOCKED\n";
flush();
$deadline = microtime(true) + 20;
while (! is_file($data['barrier']) && microtime(true) < $deadline) {
usleep(20000);
}
if (! is_file($data['barrier'])) {
throw new RuntimeException('Barrier not released.');
}
}
$order = PurchaseOrder::query()->findOrFail($data['order']);
if ($action === 'request') {
app(OrderCancellationWorkflow::class)->request($actor, $order, $data['input']);
} elseif ($action === 'receipt') {
app(ReceiptWorkflow::class)->confirm($actor, $order, ['idempotency_key' => $data['input']['operation_key'], 'delivery_note' => 'RACE-GUIDE', 'received_on' => today()->toDateString(), 'warehouse_id' => $data['warehouse'],
'items' => [['purchase_order_item_id' => $data['line'], 'received_quantity' => '0.100', 'accepted_quantity' => '0.100', 'quality_status' => 'compliant', 'stock_item_id' => $data['stock'], 'notes' => null]]]);
} else {
$record = OrderCancellation::query()->where('purchase_order_id', $order->id)->where('status', 'pending')->first()
?? OrderCancellation::query()->where('purchase_order_id', $order->id)->where('status', 'approved')->firstOrFail();
app(OrderCancellationWorkflow::class)->decide($actor, $record, 'approved', 'Decisão financeira independente concorrente fictícia.');
}
});
echo "OK\n";
} catch (ValidationException $error) {
echo "BLOCKED\n";
}