Files
Investidor-V2/outputs/investmoz-fintech-investimento-QA-20261015/prove-delta-QA.php
T
nala 6a76aac80f
tests / ci (push) Canceled after 0s
versao compilada 1
2026-10-16 09:17:28 +02:00

64 lines
15 KiB
PHP

<?php
ini_set('zend.exception_ignore_args','1');set_exception_handler(function(Throwable $e){fwrite(STDERR,$e::class.': '.$e->getMessage().' line '.$e->getLine().' file '.basename($e->getFile()).PHP_EOL);exit(1);});
require __DIR__.'/boot-QA.php';
set_exception_handler(function(Throwable $e){echo json_encode(['error'=>$e::class,'message'=>$e->getMessage(),'status'=>method_exists($e,'getStatusCode')?$e->getStatusCode():null,'trace'=>array_map(fn($t)=>['file'=>basename($t['file']??''),'line'=>$t['line']??0,'function'=>$t['function']??''],array_slice($e->getTrace(),0,8))]);exit(1);});
use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Str;use Illuminate\Http\Request;
$report=__DIR__.'/PROVA-DELTA-QA.json';if(is_file($report))throw new RuntimeException('Preserve completed proof');
$checks=[];$check=function($n,$v)use(&$checks){if(!$v)throw new RuntimeException('Failed: '.$n);$checks[$n]=true;};
$reject=function($n,$fn,$status)use($check){try{$fn();$check($n,false);}catch(Illuminate\Validation\ValidationException$e){$check($n,$status===422);}catch(Symfony\Component\HttpKernel\Exception\HttpException$e){$check($n,$e->getStatusCode()===$status);}};
$desk=app(App\Services\VirtualDesk::class);$path=app(App\Services\InvestorPath::class);$fin=app(App\Services\FintechInvestment::class);$sectors=app(App\Services\SectorInvestment::class);$manager=App\Models\User::findOrFail(2);
config(['portal.managers'=>[strtolower($manager->email)]]);
$oldOpportunities=DB::table('opportunities')->orderBy('id')->get()->toJson();$oldSectors=DB::table('sectors')->orderBy('id')->get()->toJson();$oldResources=DB::table('portal_resources')->orderBy('id')->get()->toJson();
$seven=['mineracao','energia-especifica','agronegocio','turismo','infraestruturas','tecnologias-de-informacao','mercado-financeiro'];$sectorProof=[];
foreach($seven as$slug){$s=$sectors->sector($slug);$v=$sectors->publicView($s);$check('sector_actions_'.$slug,$v['start_href']==='/investimentos/a-partir-do-setor/'.$slug&&$v['register_href']==='/minhas-oportunidades/create?sector_id='.$s->id);$sectorProof[]=['slug'=>$slug,'id'=>$s->id,'articles'=>count($v['articles']),'relations'=>count($v['relations']),'locations'=>count($v['locations']),'actions'=>$v['start_href'],'register'=>$v['register_href']];if($slug==='mercado-financeiro')$check('empty_financial_article_does_not_block_sector',$v['content_notice']!==null&&count($v['articles'])===1);}
$password=Str::random(40);$users=[];foreach(['A','B','other']as$label)$users[$label]=App\Models\User::forceCreate(['name'=>'QA Fintech '.$label,'email'=>'qa-fintech-'.strtolower($label).'-'.Str::lower(Str::random(8)).'@example.invalid','password'=>Hash::make($password),'email_verified_at'=>now()]);
$scenarios=[];$credentials=[];
foreach(['A','B']as$label){
$owner=$users[$label];$create=['title'=>'QA Fintech '.$label.' — preparação sintética','client_key'=>(string)Str::uuid(),'reuse_consent'=>true];$id=$path->create($owner,$create);$ver=fn()=>(int)$desk->case($owner,$id)->version;
$check($label.'_same_19_steps_five_phases',count($path->view($owner,$id)['steps'])===19&&count($path->view($owner,$id)['phases'])===5);
$sector=$label==='A'?'tecnologias-de-informacao':'mercado-financeiro';$sectors->attach($owner,$id,['version'=>$ver(),'sector_slug'=>$sector]);$v=$ver();$sectors->attach($owner,$id,['version'=>$v,'sector_slug'=>$sector]);$check($label.'_sector_replay_no_write',$ver()===$v);
app(App\Services\LegacyContent::class)->attach($owner,$id,['version'=>$ver(),'resource_id'=>27]);
$check($label.'_incomplete_profile_allowed',true);$fin->save($owner,$id,['version'=>$ver(),'profile'=>['model'=>'undetermined']]);$v=$path->view($owner,$id);$check($label.'_empty_model_unknown_not_zero',count(array_filter($v['fintech']['requirements'],fn($q)=>$q['state']==='undetermined'))===7&&count($v['results'])===0);
$profile=['model'=>$label==='A'?'technology_provider':'financial_operator','fields'=>['problem'=>'Simplificar reconciliação sintética '.$label,'clients'=>'Clientes nacionais e estrangeiros de teste','value'=>'Serviço tecnológico sintético','revenues'=>'Assinatura de teste','services'=>$label==='A'?'Software sem execução financeira':'Pagamentos declarados, por enquadrar','location'=>'Maputo — instalação declarada, sem parcela fictícia','technology'=>'API sintética '.$label,'security'=>'Controlo de acesso e revisão de teste','continuity'=>'Recuperação de teste','partners'=>'Parceiro ainda não contratado','maturity'=>'Ideia em preparação','schedule'=>'Preparar antes de operar'],'operation_countries'=>['MZ','ZA'],'activities'=>array_fill_keys(array_keys(App\Services\FintechInvestment::ACTIVITIES),'no'),'activity_basis'=>'Cenário sintético: apenas as atividades explicitamente assinaladas são previstas.','documents'=>[]];
if($label==='B')$profile['activities']['payments']='yes';
$fin->save($owner,$id,['version'=>$ver(),'profile'=>$profile]);$v=$path->view($owner,$id);$current=$ver();$events=DB::table('desk_events')->where('case_id',$id)->count();$fin->save($owner,$id,['version'=>$current,'profile'=>$profile]);$check($label.'_profile_replay_idempotent',$ver()===$current&&DB::table('desk_events')->where('case_id',$id)->count()===$events);
$check($label.'_countries_and_location_recovered',$v['fintech']['record']['profile']['operation_countries']===['MZ','ZA']&&$v['fintech']['record']['profile']['fields']['location']===$profile['fields']['location']);
$check($label.'_legal_rules_explicitly_undetermined',count(array_filter($v['fintech']['requirements'],fn($q)=>$q['legal_license_state']==='undetermined'&&$q['source']['provision']===null))===7);
$check($label.'_activity_conditional',count(array_filter($v['fintech']['requirements'],fn($q)=>$q['state']==='applicable'))===($label==='A'?0:1));
$check($label.'_existing_guidance_engine',$v['fintech']['guidance_version']===App\Services\Ai\InvestorGuidanceRules::VERSION&&count($v['fintech']['guidance'])===7);
$reject($label.'_foreign_user_denied',fn()=>$fin->save($users['other'],$id,['version'=>$ver(),'profile'=>$profile]),403);
$reject($label.'_independent_manager_cannot_overwrite_profile',fn()=>$fin->save($manager,$id,['version'=>$ver(),'profile'=>$profile]),403);
$bad=$profile;$bad['operation_countries']=['XX'];$reject($label.'_invalid_country_rejected',fn()=>$fin->save($owner,$id,['version'=>$ver(),'profile'=>$bad]),422);
$bad=$profile;$bad['fields']['problem']='changed';$reject($label.'_stale_version_rejected',fn()=>$fin->save($owner,$id,['version'=>1,'profile'=>$bad]),409);
$bad=$profile;$bad['documents']['external']=(string)Str::uuid();$reject($label.'_unlinked_document_denied',fn()=>$fin->save($owner,$id,['version'=>$ver(),'profile'=>$bad]),422);
$path->facts($owner,$id,['version'=>$ver(),'land_needed'=>'unknown','external_funding'=>$label==='A'?'no':'yes','viability'=>'unknown','reason'=>'Preparação sintética; sem decisão externa nem terreno declarado.']);
// Existing private upload and real scanner, not a marked-clean fixture.
$tmp=tempnam(sys_get_temp_dir(),'fintech-qa-');file_put_contents($tmp,'Documento sintético QA '.$label.'; preparação e arquitetura, não é uma licença.');
$request=Request::create('/balcao-virtual/dossiers/'.$id.'/documentos','POST',['version'=>$ver(),'category'=>'Preparação Fintech','source_reference'=>'Autoria sintética QA; sem ato externo','consent'=>true],[],['file'=>new Illuminate\Http\UploadedFile($tmp,'fintech-'.$label.'.txt','text/plain',null,true)]);$request->headers->set('Accept','application/json');$request->setUserResolver(fn()=>$owner);app(App\Http\Controllers\VirtualDeskController::class)->attach($request,$id,$desk);if(is_file($tmp))unlink($tmp);
$doc=DB::table('desk_documents as l')->join('documents as d','d.id','=','l.document_id')->where('l.case_id',$id)->first(['l.id as link_id','d.*']);$check($label.'_private_document_real_scan',$doc&&$doc->data_classification==='confidential'&&$doc->status==='active'&&$doc->malware_scan_status==='clean'&&trim($doc->sha256)===$doc->malware_scanned_sha256);
$profile['documents']['architecture']=$doc->id;$fin->save($owner,$id,['version'=>$ver(),'profile'=>$profile]);$check($label.'_document_reference_without_duplicate',DB::table('desk_documents')->where('case_id',$id)->count()===1);
$download=Request::create('/');$download->setUserResolver(fn()=>$users['other']);$reject($label.'_private_download_other_user_denied',fn()=>app(App\Http\Controllers\VirtualDeskController::class)->download($download,$id,$doc->link_id,$desk),403);
// Actual tool snapshot and frozen return in this context.
$snapshot=['version'=>1,'data'=>['budgetPeriod'=>'Mensal','loan'=>['principal'=>'100000','rate'=>'0','months'=>'24','rateType'=>'nominal','periodMonths'=>'1','gracePeriods'=>'0','upfrontFee'=>'0','recurringFee'=>'0'],'breakEven'=>['fixed'=>'1000','price'=>'100','variable'=>'50'],'funding'=>['total'=>'100000','secured'=>$label==='A'?'100000':'30000'],'incomes'=>[['label'=>'Receita sintética QA','amount'=>'100']],'expenses'=>[['label'=>'Custo sintético QA','amount'=>'50']]]];
$req=Request::create('/simulador-fiscal','POST',['context'=>$id]);$req->setUserResolver(fn()=>$owner);$draft=app(App\Services\SimulationFormDrafts::class)->create(['personal_snapshot'=>[],'economic_snapshot'=>['purpose'=>'simulate_only','project_title'=>$create['title'],'project_summary'=>'Resumo sintético '.$label,'currency'=>'MZN','financial_tools_snapshot'=>json_encode($snapshot)]],$req,(string)Str::uuid())['draft'];
$result=$path->returnTool($req,$id,['version'=>$ver(),'draft_id'=>$draft->id,'draft_version'=>$draft->version_no]);$check($label.'_financial_result_only_same_context',$result['draft_id']===$draft->id&&count($path->view($owner,$id)['results'])===1&&count($path->view($manager,$id)['results'])===0);
$service=DB::table('desk_service_versions')->where('code','project-preparation')->where('status','published')->orderByDesc('version')->first();$support=$desk->createRequest($owner,$id,$service->id,(string)Str::uuid());$check($label.'_support_draft_current_local_service',$support->status==='draft'&&$support->service_version_id===$service->id&&$desk->decode($support->payload)['description']==='Resumo sintético '.$label);
$task=$path->task($owner,$id,['version'=>$ver(),'code'=>'S19','title'=>'Acompanhar preparação sintética '.$label,'due_at'=>now()->addDays(3)->toIso8601String(),'consent'=>true]);$check($label.'_internal_task_without_external_crm',DB::table('tasks')->where('id',$task)->where('desk_case_id',$id)->where('external_sync_status','pending_authorization')->exists());
foreach(['S02','S08','S17','S04']as$code)$path->stage($manager,$id,$code,['version'=>$ver(),'state'=>'reviewing','action'=>'review','reason'=>'Conferência interna sintética; não é aprovação externa.']);
$before=DB::table('journey_steps')->where('journey_id',$desk->case($owner,$id)->journey_id)->orderBy('step_code')->get()->toJson();
$profile['fields']['technology'].=' — alteração material';$fin->save($owner,$id,['version'=>$ver(),'profile'=>$profile]);$view=$path->view($owner,$id);$check($label.'_only_technical_scope_reopened',$view['fintech']['affected_reviews']===['S17']);$check($label.'_prior_opinions_rows_preserved',$before===DB::table('journey_steps')->where('journey_id',$desk->case($owner,$id)->journey_id)->orderBy('step_code')->get()->toJson());
$profile['activities']['payments']=$profile['activities']['payments']==='yes'?'unknown':'yes';$fin->save($owner,$id,['version'=>$ver(),'profile'=>$profile]);$check($label.'_legal_and_technical_only_reopened',$path->view($owner,$id)['fintech']['affected_reviews']===['S08','S17']);
$reject($label.'_owner_cannot_claim_external_approval',fn()=>$path->stage($owner,$id,'S08',['version'=>$ver(),'state'=>'approved','action'=>'record_external','reason'=>'Não há ato externo.']),403);
$reject($label.'_manager_cannot_claim_external_without_document',fn()=>$path->stage($manager,$id,'S17',['version'=>$ver(),'state'=>'approved','action'=>'record_external','reason'=>'Não há ato externo.']),422);
$path->stage($owner,$id,'S16',['version'=>$ver(),'state'=>'preparing','action'=>'prepare','reason'=>'Tecnologia e testes podem preparar-se sem licença presumida.']);$path->stage($owner,$id,'S18',['version'=>$ver(),'state'=>'preparing','action'=>'prepare','reason'=>'Preparar a operação sem declarar início autorizado.']);
$v=$path->view($owner,$id);$check($label.'_preparation_parallel_no_fictitious_authorization',collect($v['steps'])->firstWhere('code','S18')['state']==='preparing'&&count(array_filter($v['steps'],fn($s)=>$s['state']==='approved'))===0);
$raw=DB::table('desk_cases')->where('id',$id)->value('payload');$check($label.'_payload_encrypted',!str_contains($raw,'Simplificar')&&!str_contains($raw,'fintech-preparation'));
$scenarios[]=['scenario'=>$label,'id'=>$id,'user_id'=>$owner->id,'email'=>$owner->email,'sector'=>$sector,'version'=>$ver(),'document_id'=>$doc->id,'document_link_id'=>$doc->link_id,'document_sha256'=>trim($doc->sha256),'draft_id'=>$draft->id,'recovered_financial_result'=>$result,'support_id'=>$support->id,'service_code'=>$service->code,'service_version'=>$service->version,'task_id'=>$task,'profile_sha256'=>$v['fintech']['record']['sha256'],'profile'=>$v['fintech']['record']['profile']];
$credentials[]=['scenario'=>$label,'email'=>$owner->email,'password'=>$password];
}
$check('distinct_dossiers_results_support',$scenarios[0]['id']!==$scenarios[1]['id']&&$scenarios[0]['draft_id']!==$scenarios[1]['draft_id']&&$scenarios[0]['support_id']!==$scenarios[1]['support_id']);
$foreignReq=Request::create('/','GET',['context'=>$scenarios[0]['id']]);$foreignReq->setUserResolver(fn()=>$users['A']);$reject('cross_context_financial_return_denied',fn()=>$path->returnTool($foreignReq,$scenarios[0]['id'],['version'=>$desk->case($users['A'],$scenarios[0]['id'])->version,'draft_id'=>$scenarios[1]['draft_id'],'draft_version'=>1]),403);
$check('no_opportunity_created_or_reclassified',$oldOpportunities===DB::table('opportunities')->orderBy('id')->get()->toJson());$check('sector_masters_unchanged',$oldSectors===DB::table('sectors')->orderBy('id')->get()->toJson());$check('library_publication_unchanged',$oldResources===DB::table('portal_resources')->orderBy('id')->get()->toJson());
file_put_contents(dirname($source).'/qa-login-private.json',json_encode($credentials,JSON_THROW_ON_ERROR));
file_put_contents($report,json_encode(['at'=>gmdate('c'),'target'=>$target,'result'=>'passed','checks'=>$checks,'sectors'=>$sectorProof,'scenarios'=>$scenarios,'scope'=>'Directed QA services/controllers, real isolated database/files/scans; no claim of browser acceptance','active_changes'=>0],JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));echo json_encode(['result'=>'passed','checks'=>count($checks),'scenarios'=>2,'sectors'=>7,'active_changes'=>0]);