fix: complete InvesteMoz validation and error corrections

This commit is contained in:
2026-10-29 21:47:33 +02:00
parent 63147312e2
commit daf8623441
718 changed files with 127308 additions and 20959 deletions
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace Tests\Support;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
trait AuthenticatesQaActors
{
protected function actingAsWithMfa(User $actor): static
{
$actor->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC-QA'), 'two_factor_confirmed_at' => now()])->save();
return $this->actingAs($actor)->withSession(['login.id' => null, 'portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time()]);
}
}
+34 -27
View File
@@ -15,35 +15,42 @@ final class OpportunitySearchFixture
{
public static function create(): array
{
if (! IsolatedQaDatabase::allowsSchemaChanges()) throw new \LogicException('Isolated QA only');
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
throw new \LogicException('Isolated QA only');
}
$province = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->where('name', 'Inhambane')->first();
if (! $province) throw new \LogicException('QA requires the existing public Inhambane reference');
if (! $province) {
throw new \LogicException('QA requires the existing public Inhambane reference');
}
$sector = Sector::where('slug', 'turismo')->firstOrFail();
$editor = User::factory()->create(); $reviewer = User::factory()->create();
$zone = InvestmentZone::query()->create(['id'=>(string)Str::uuid(), 'code'=>'SINT-QA-'.Str::random(8),
'name'=>'SINTÉTICO QA — Parque Industrial de Balama', 'category'=>'industrial_park', 'physical_category'=>'industrial_park',
'publication_status'=>'published','validation_status'=>'validated', 'editor_id'=>$editor->id,'reviewer_id'=>$reviewer->id,
'published_at'=>now(), 'source_evidence'=>[['source_type'=>'promoter','url'=>'https://example.invalid/synthetic-qa','supports'=>'SINTÉTICO QA: não constitui informação sobre o parque real.']]]);
$other = InvestmentZone::query()->create(['id'=>(string)Str::uuid(),'code'=>'SINT-QA-'.Str::random(8),'name'=>'SINTÉTICO QA — Outro parque',
'category'=>'industrial_park','physical_category'=>'industrial_park','publication_status'=>'published','validation_status'=>'validated','editor_id'=>$editor->id,'reviewer_id'=>$reviewer->id,
'published_at'=>now(),'source_evidence'=>[['source_type'=>'promoter','url'=>'https://example.invalid/synthetic-qa','supports'=>'SINTÉTICO QA: outra associação.']]]);
$prefix='SINTÉTICO QA turismo '.Str::upper(Str::random(8));
$create = function(string $name, string $purpose, string $currency, int $level, ?string $stage=null, ?string $target=null, bool $private=false) use ($sector,$province,$zone,$prefix) {
$row=['related_id'=>$target??$zone->id,'relation_type'=>'located_in','classification'=>['target_type'=>'park','purpose'=>$purpose,
'disclosure'=>'public','requested_state'=>'preliminary','source_reference'=>'SINTÉTICO QA — ensaio de pesquisa','citation'=>'Fixture local']];
return Opportunity::forceCreate(['reference'=>'SINT-QA-'.Str::random(10),'slug'=>'sintetico-qa-'.Str::uuid(),'title'=>$prefix.' '.$name,
'summary'=>'Dados sintéticos para ensaio exclusivo em QA.','sector_id'=>$sector->id,'province'=>'Inhambane','primary_territory_id'=>$province->id,
'maturity_level'=>$level,'maturity_label'=>$stage?OpportunityMaturity::STAGES[$stage]:OpportunityMaturity::LEGACY_LABELS[$level],
'estimated_investment_amount'=>'300000.00','estimated_investment_currency'=>$currency,'opportunity_category'=>'investment_project',
'status'=>$private?'draft':'published','published_at'=>$private?null:now(),
'workflow_context'=>['publication'=>['visibility'=>'public','classification'=>[$row],
'maturity'=>['catalogue_version'=>$stage?OpportunityMaturity::VERSION:OpportunityMaturity::LEGACY,'stage'=>$stage]]]]);
$editor = User::factory()->create();
$reviewer = User::factory()->create();
$zone = InvestmentZone::query()->create(['id' => (string) Str::uuid(), 'code' => 'SINT-QA-'.Str::random(8),
'name' => 'SINTÉTICO QA — Parque Industrial de Balama', 'category' => 'industrial_park', 'physical_category' => 'industrial_park',
'publication_status' => 'published', 'validation_status' => 'validated', 'editor_id' => $editor->id, 'reviewer_id' => $reviewer->id,
'published_at' => now(), 'source_evidence' => [['source_type' => 'promoter', 'url' => 'https://example.invalid/synthetic-qa', 'supports' => 'SINTÉTICO QA: não constitui informação sobre o parque real.']]]);
$other = InvestmentZone::query()->create(['id' => (string) Str::uuid(), 'code' => 'SINT-QA-'.Str::random(8), 'name' => 'SINTÉTICO QA — Outro parque',
'category' => 'industrial_park', 'physical_category' => 'industrial_park', 'publication_status' => 'published', 'validation_status' => 'validated', 'editor_id' => $editor->id, 'reviewer_id' => $reviewer->id,
'published_at' => now(), 'source_evidence' => [['source_type' => 'promoter', 'url' => 'https://example.invalid/synthetic-qa', 'supports' => 'SINTÉTICO QA: outra associação.']]]);
$prefix = 'SINTÉTICO QA turismo '.Str::upper(Str::random(8));
$create = function (string $name, string $purpose, string $currency, int $level, ?string $stage = null, ?string $target = null, bool $private = false) use ($sector, $province, $zone, $prefix) {
$row = ['related_id' => $target ?? $zone->id, 'relation_type' => 'located_in', 'classification' => ['target_type' => 'park', 'purpose' => $purpose,
'disclosure' => 'public', 'requested_state' => 'preliminary', 'source_reference' => 'SINTÉTICO QA — ensaio de pesquisa', 'citation' => 'Fixture local']];
return Opportunity::forceCreate(['reference' => 'SINT-QA-'.Str::random(10), 'slug' => 'sintetico-qa-'.Str::uuid(), 'title' => $prefix.' '.$name,
'summary' => 'Dados sintéticos para ensaio exclusivo em QA.', 'sector_id' => $sector->id, 'province' => 'Inhambane', 'primary_territory_id' => $province->id,
'maturity_level' => $level, 'maturity_label' => $stage ? OpportunityMaturity::STAGES[$stage] : OpportunityMaturity::LEGACY_LABELS[$level],
'estimated_investment_amount' => '300000.00', 'estimated_investment_currency' => $currency, 'opportunity_category' => 'investment_project',
'status' => $private ? 'draft' : 'published', 'published_at' => $private ? null : now(),
'workflow_context' => ['publication' => ['visibility' => 'public', 'classification' => [$row],
'maturity' => ['catalogue_version' => $stage ? OpportunityMaturity::VERSION : OpportunityMaturity::LEGACY, 'stage' => $stage]]]]);
};
return ['query'=>$prefix,'zone'=>$zone,'other_zone'=>$other,'province'=>$province,
'associated'=>$create('associada','park_operation','USD',2),
'nearby'=>$create('apenas próxima','proximity','USD',2,'concept'),
'same_territory'=>$create('mesmo território','administrative_boundary','MZN',4,'feasibility'),
'other_park'=>$create('outro parque','park_operation','USD',4,'feasibility',$other->id),
'private'=>$create('privada','park_operation','USD',2,null,null,true)];
return ['query' => $prefix, 'zone' => $zone, 'other_zone' => $other, 'province' => $province,
'associated' => $create('associada', 'park_operation', 'USD', 2),
'nearby' => $create('apenas próxima', 'proximity', 'USD', 2, 'concept'),
'same_territory' => $create('mesmo território', 'administrative_boundary', 'MZN', 4, 'feasibility'),
'other_park' => $create('outro parque', 'park_operation', 'USD', 4, 'feasibility', $other->id),
'private' => $create('privada', 'park_operation', 'USD', 2, null, null, true)];
}
}
+39 -23
View File
@@ -1,8 +1,10 @@
<?php
namespace Tests\Support;
use App\Models\User;
use App\Models\Sector;
use App\Models\User;
use App\Services\InvestmentGeography;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAdministration;
use Illuminate\Support\Facades\Crypt;
@@ -14,44 +16,58 @@ final class ProactiveInvestmentFixture
{
public static function guard(): void
{
$t=DB::selectOne('select current_database() as name,inet_server_port() as port');
throw_unless($t->name==='proactive_investment_20261027_test'&&(int)$t->port===55441,\RuntimeException::class,'Isolated proactive QA required');
$t = DB::selectOne('select current_database() as name,inet_server_port() as port');
throw_unless($t->name === 'proactive_investment_20261027_test' && (int) $t->port === 55441, \RuntimeException::class, 'Isolated proactive QA required');
}
public static function operator(): User
{
self::guard();
$actor=User::factory()->create(['name'=>'SYNTHETIC QA editorial operator','email'=>'proactive-'.Str::uuid().'@example.invalid','password'=>bcrypt('Synthetic-QA-only-2026!')]);
$actor->forceFill(['two_factor_secret'=>Crypt::encrypt('JBSWY3DPEHPK3PXP'),'two_factor_confirmed_at'=>now()])->save();
$org=(string)Str::uuid();
DB::table('organizations')->insert(['id'=>$org,'name'=>'SYNTHETIC QA proactivity operator','external_id'=>'SYNTHETIC-QA-'.$org,'organization_type'=>'private']);
DB::table('audit_events')->insert(['source_system'=>'portal-profiles-v1','entity_type'=>'authorization','action'=>'operator_organization_registered','data_classification'=>'restricted','after_data'=>json_encode(['organization_id'=>$org,'organization'=>['name'=>'SYNTHETIC QA proactivity operator','nuit'=>'SYNTHETIC-QA-'.$org],'source_reference'=>'SYNTHETIC QA designation, not a real appointment'])]);
app(PortalProfileAdministration::class)->insertGrant((string)Str::uuid(),User::factory()->create(),['user_id'=>$actor->id,'role'=>'promoter','organization_id'=>$org,'opportunity_types'=>OpportunityManagement::CATEGORIES,'responsibilities'=>[],'source'=>'internal-portal-designation']);
$actor = User::factory()->create(['name' => 'SYNTHETIC QA editorial operator', 'email' => 'proactive-'.Str::uuid().'@example.invalid', 'password' => bcrypt('Synthetic-QA-only-2026!')]);
$actor->forceFill(['two_factor_secret' => Crypt::encrypt('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()])->save();
$org = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC QA proactivity operator', 'external_id' => 'SYNTHETIC-QA-'.$org, 'organization_type' => 'private']);
DB::table('audit_events')->insert(['source_system' => 'portal-profiles-v1', 'entity_type' => 'authorization', 'action' => 'operator_organization_registered', 'data_classification' => 'restricted', 'after_data' => json_encode(['organization_id' => $org, 'organization' => ['name' => 'SYNTHETIC QA proactivity operator', 'nuit' => 'SYNTHETIC-QA-'.$org], 'source_reference' => 'SYNTHETIC QA designation, not a real appointment'])]);
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), ['user_id' => $actor->id, 'role' => 'promoter', 'organization_id' => $org, 'opportunity_types' => OpportunityManagement::CATEGORIES, 'responsibilities' => [], 'source' => 'internal-portal-designation']);
return $actor;
}
public static function analysis(string $pilot='Cahora Bassa'): array
public static function analysis(string $pilot = 'Cahora Bassa'): array
{
$id=(string)Str::uuid();$private=(string)Str::uuid();
return ['version'=>1,'kind'=>'ideas','evidence'=>[
['id'=>$id,'category'=>'infrastructure','purpose'=>'local','statement'=>'SYNTHETIC QA: capacidade fictícia em '.$pilot.'; não é diagnóstico económico real.','interpretation'=>'Hipótese sintética, sem contrato ou oferta comprovados.','source'=>'SYNTHETIC QA exemplar público fictício '.$pilot,'locator'=>'Fixture QA, linha1','period'=>'Exercício2026 — cenário sintético','scope'=>$pilot.' — contexto piloto','coverage'=>'Cobertura fictícia; informação real por confirmar','verified_on'=>'2026-10-27','access'=>'public','document_id'=>null],
['id'=>$private,'category'=>'supply','purpose'=>'local','statement'=>'PRIVATE-QA-UNIQUE-SUPPLY-'.Str::uuid(),'interpretation'=>'PRIVATE-QA-INTERPRETATION-'.Str::uuid(),'source'=>'PRIVATE-QA-COMPANY-LIST-'.Str::uuid(),'locator'=>'PRIVATE-QA-LOCATOR-'.Str::uuid(),'period'=>'2026','scope'=>'Análise interna','coverage'=>'Não divulgar','verified_on'=>'2026-10-27','access'=>'internal','document_id'=>null],
],'need'=>['state'=>'hypothesis','problem'=>'SYNTHETIC QA lacuna por verificar em '.$pilot,'observed_supply'=>'Oferta real desconhecida; não equivale a ausência.','observed_demand'=>'Procura real não comprovada; cenário sintético.','type'=>'support','clients'=>'Beneficiários hipotéticos, sem encomenda ou compromisso.','evidence_ids'=>[$id],'limitations'=>'Não demonstra mercado nem viabilidade.','missing'=>'Dados locais reais por confirmar.','confirmation'=>'Fundamento de hipótese sintética, não confirmação económica.'],
'idea'=>['solution'=>'SYNTHETIC QA: '.match($pilot){'Montepuez'=>'fornecimentos e manutenção mineira','Gurué'=>'serviços da cadeia do chá',default=>'serviços complementares de energia'},'activity'=>'Actividade hipotética de apoio','chain_id'=>null,'stage'=>'Serviços de apoio — por corresponder','coverage'=>$pilot,'mode'=>'create','resources'=>'Não demonstrados; por inventariar','assumptions'=>'Não há acesso garantido a energia, terra ou cliente.','conditions'=>'Confirmar dados e autorizações aplicáveis.','pending'=>'Evidência económica real','next_action'=>'Recolher dados locais e testar a hipótese.'],'relations'=>[]];
$id = (string) Str::uuid();
$private = (string) Str::uuid();
return ['version' => 1, 'kind' => 'ideas', 'evidence' => [
['id' => $id, 'category' => 'infrastructure', 'purpose' => 'local', 'statement' => 'SYNTHETIC QA: capacidade fictícia em '.$pilot.'; não é diagnóstico económico real.', 'interpretation' => 'Hipótese sintética, sem contrato ou oferta comprovados.', 'source' => 'SYNTHETIC QA exemplar público fictício '.$pilot, 'locator' => 'Fixture QA, linha1', 'period' => 'Exercício2026 — cenário sintético', 'scope' => $pilot.' — contexto piloto', 'coverage' => 'Cobertura fictícia; informação real por confirmar', 'verified_on' => '2026-10-27', 'access' => 'public', 'document_id' => null],
['id' => $private, 'category' => 'supply', 'purpose' => 'local', 'statement' => 'PRIVATE-QA-UNIQUE-SUPPLY-'.Str::uuid(), 'interpretation' => 'PRIVATE-QA-INTERPRETATION-'.Str::uuid(), 'source' => 'PRIVATE-QA-COMPANY-LIST-'.Str::uuid(), 'locator' => 'PRIVATE-QA-LOCATOR-'.Str::uuid(), 'period' => '2026', 'scope' => 'Análise interna', 'coverage' => 'Não divulgar', 'verified_on' => '2026-10-27', 'access' => 'internal', 'document_id' => null],
], 'need' => ['state' => 'hypothesis', 'problem' => 'SYNTHETIC QA lacuna por verificar em '.$pilot, 'observed_supply' => 'Oferta real desconhecida; não equivale a ausência.', 'observed_demand' => 'Procura real não comprovada; cenário sintético.', 'type' => 'support', 'clients' => 'Beneficiários hipotéticos, sem encomenda ou compromisso.', 'evidence_ids' => [$id], 'limitations' => 'Não demonstra mercado nem viabilidade.', 'missing' => 'Dados locais reais por confirmar.', 'confirmation' => 'Fundamento de hipótese sintética, não confirmação económica.'],
'idea' => ['solution' => 'SYNTHETIC QA: '.match ($pilot) {
'Montepuez' => 'fornecimentos e manutenção mineira','Gurué' => 'serviços da cadeia do chá',default => 'serviços complementares de energia'
}, 'activity' => 'Actividade hipotética de apoio', 'chain_id' => null, 'stage' => 'Serviços de apoio — por corresponder', 'coverage' => $pilot, 'mode' => 'create', 'resources' => 'Não demonstrados; por inventariar', 'assumptions' => 'Não há acesso garantido a energia, terra ou cliente.', 'conditions' => 'Confirmar dados e autorizações aplicáveis.', 'pending' => 'Evidência económica real', 'next_action' => 'Recolher dados locais e testar a hipótese.'], 'relations' => []];
}
public static function input(string $pilot='Cahora Bassa',bool $analysis=true): array
public static function input(string $pilot = 'Cahora Bassa', bool $analysis = true): array
{
self::guard();
$t=DB::table('geo_locations')->whereNull('deleted_at')->where('data_classification','public')->where('location_type','district')->where('name','ilike',$pilot==='Gurué'?'Guru%':($pilot==='Cahora Bassa'?'CAHORA-BASSA':$pilot))->first();
throw_unless($t,\RuntimeException::class,'Existing pilot territory required:'.$pilot);
$path=app(\App\Services\InvestmentGeography::class)->path($t->id,true);$geo=[];foreach($path as $n)if(in_array($n->location_type,['province','district','admin_post','locality']))$geo[$n->location_type.'_id']=$n->id;
$s=Sector::choices()->whereNotNull('published_at')->where('slug',match($pilot){'Cahora Bassa'=>'energia-especifica','Montepuez'=>'mineracao',default=>'agronegocio'})->firstOrFail();
return ['creation_key'=>(string)Str::uuid(),'reason'=>'SYNTHETIC QA creating an independent territorial analysis, no active publication','title'=>'SYNTHETIC QA — '.$pilot,'summary'=>'Piloto técnico sintético; conclusões económicas reais por confirmar.','description'=>'Preparação editorial sintética em QA.','sector_id'=>$s->id,'opportunity_category'=>'investment_project',...$geo,...($analysis?['proactive'=>self::analysis($pilot)]:[])];
$t = DB::table('geo_locations')->whereNull('deleted_at')->where('data_classification', 'public')->where('location_type', 'district')->where('name', 'ilike', $pilot === 'Gurué' ? 'Guru%' : ($pilot === 'Cahora Bassa' ? 'CAHORA-BASSA' : $pilot))->first();
throw_unless($t, \RuntimeException::class, 'Existing pilot territory required:'.$pilot);
$path = app(InvestmentGeography::class)->path($t->id, true);
$geo = [];
foreach ($path as $n) {
if (in_array($n->location_type, ['province', 'district', 'admin_post', 'locality'])) {
$geo[$n->location_type.'_id'] = $n->id;
}
}
$s = Sector::choices()->whereNotNull('published_at')->where('slug', match ($pilot) {
'Cahora Bassa' => 'energia-especifica','Montepuez' => 'mineracao',default => 'agronegocio'
})->firstOrFail();
return ['creation_key' => (string) Str::uuid(), 'reason' => 'SYNTHETIC QA creating an independent territorial analysis, no active publication', 'title' => 'SYNTHETIC QA — '.$pilot, 'summary' => 'Piloto técnico sintético; conclusões económicas reais por confirmar.', 'description' => 'Preparação editorial sintética em QA.', 'sector_id' => $s->id, 'opportunity_category' => 'investment_project', ...$geo, ...($analysis ? ['proactive' => self::analysis($pilot)] : [])];
}
public static function publication(array $analysis): array
{
return ['proactive_reviewed'=>true,'proactive_public'=>['group'=>$analysis['kind'],'state'=>'hypothesis','need'=>'SYNTHETIC QA necessidade por verificar.','proposal'=>'SYNTHETIC QA solução em preparação.','basis'=>'Fixture pública sintética; não é evidência de procura local.','limitations'=>'Sem validação económica, contrato, terra ou energia garantidos.','next_action'=>'Confirmar evidências reais antes de decidir.','evidence_ids'=>[$analysis['evidence'][0]['id']],'chain_id'=>null,'stage'=>'Apoio — correspondência real por confirmar']];
return ['proactive_reviewed' => true, 'proactive_public' => ['group' => $analysis['kind'], 'state' => 'hypothesis', 'need' => 'SYNTHETIC QA necessidade por verificar.', 'proposal' => 'SYNTHETIC QA solução em preparação.', 'basis' => 'Fixture pública sintética; não é evidência de procura local.', 'limitations' => 'Sem validação económica, contrato, terra ou energia garantidos.', 'next_action' => 'Confirmar evidências reais antes de decidir.', 'evidence_ids' => [$analysis['evidence'][0]['id']], 'chain_id' => null, 'stage' => 'Apoio — correspondência real por confirmar']];
}
}