true]); $u=User::findOrFail($f['actors']['read']);auth()->setUser($u);app(CompanyContext::class)->selectFor($u->id,$scope['tenant_id'],$scope['company_id'],$scope['unit_id']); $service=app(SupplierPayables::class); if($phase==='payable-report-http'){ auth()->forgetGuards();app(CompanyContext::class)->clear(); Illuminate\Support\Facades\Route::middleware('web')->get('/qa/report-enter',function(Illuminate\Http\Request $r)use($f){ $u=User::findOrFail($f['actors']['read']);auth()->login($u);$r->session()->regenerate();$token=bin2hex(random_bytes(24)); $r->session()->put('auth_version',$u->auth_version);$r->session()->put('company_context',$f['scope']+['token'=>$token,'module_id'=>'purchasing']);return response()->json(['context'=>$token])->header('Cache-Control','no-store'); }); $state=[];$locks=0;DB::listen(function($event)use(&$state,&$locks){if(str_contains(strtolower($event->sql),'for update'))$locks++;if(!$state&&str_contains($event->sql,'"pa_imported_sources"')){$pdo=$event->connection->getPdo();$state=['isolation'=>$pdo->query('SHOW transaction_isolation')->fetchColumn(),'read_only'=>$pdo->query('SHOW transaction_read_only')->fetchColumn()];}}); $app->handleRequest(Illuminate\Http\Request::capture()); if(($_SERVER['HTTP_X_QA_REPORT_PROOF']??'')==='capture')file_put_contents($s['root'].'/report-http-mode.json',json_encode(['transaction'=>$state,'writer_locks'=>$locks],JSON_PRETTY_PRINT));exit; } $fingerprint=function()use($scope):string{ $tables=['pa_imported_sources','pa_source_histories','pa_sources','pa_proposals','pa_obligations','pa_history_imports','pa_imported_payments','pa_events','pa_commands','pa_access']; $settlements=DB::getSchemaBuilder()->hasTable('ps_payments');if($settlements)$tables=[...$tables,...Tempo\Finance\Payables\SettlementSchema::TABLES,...Tempo\Finance\Payables\ReversalSchema::TABLES]; $hash=hash_init('sha256');foreach($tables as $table){hash_update($hash,$table."\n");$q=DB::table($table);if(!$settlements)$q->where($scope);foreach($q->orderBy($table==='ps_outbox'?'event_id':'id')->cursor() as $r)hash_update($hash,Payables::canonical((array)$r)."\n");}return hash_final($hash); }; if($phase==='payable-report-settlements'){ if(is_file($s['root'].'/report-settlements.json'))throw new LogicException('Completed settlement report proof preserved'); $before=$fingerprint();$r=$service->report($u);$baseline=json_decode(file_get_contents($s['root'].'/settlement-volume.json'),true,64,JSON_THROW_ON_ERROR); if($r['totals']['count']!==61||$r['totals']['principal_minor']!==366000||$r['known_positions']['net_allocated_minor']!==392||$r['known_positions']['historical_confirmed_minor']!==0||$r['totals']['balance_minor']!==365608||$fingerprint()!==$before||$before!==$baseline['baseline_fingerprint'])throw new LogicException('Settlement report is not reconciled with its original book'); file_put_contents($s['root'].'/report-settlements.json',json_encode(['passed'=>true,'report'=>$r,'baseline_fingerprint_equal'=>true,'net_allocations_include_reversal'=>true],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo "Settlement report reconciles 61 obligations and 392 minor units of net allocations; all original financial rows preserved.\n";exit; } if($phase==='payable-report-post'){ if(is_file($s['root'].'/report-post.json'))throw new LogicException('Completed report post proof preserved'); DB::beginTransaction();DB::statement('SET TRANSACTION READ ONLY');try{ $baseline=is_file($s['root'].'/settlement-volume.json')?json_decode(file_get_contents($s['root'].'/settlement-volume.json'),true)['baseline_fingerprint']:json_decode(file_get_contents($s['root'].'/page-post.json'),true)['scoped_business_fingerprint']; if($fingerprint()!==$baseline)throw new LogicException('Report changed preserved financial rows'); file_put_contents($s['root'].'/report-post.json',json_encode(['passed'=>true,'read_only'=>true,'business_fingerprint_equal'=>true,'business_fingerprint'=>$baseline],JSON_PRETTY_PRINT)); }finally{DB::rollBack();}echo "Report post-check: original financial fingerprint unchanged.\n";exit; } if(in_array($phase,['payable-report-volume','payable-report-volume-batch'],true)){ $output=$s['root'].($phase==='payable-report-volume'?'/report-volume.json':'/report-volume-batch.json'); if(is_file($output))throw new LogicException('Completed report volume proof preserved'); $queries=0;$locks=0;$mode=[];$capture=true;DB::listen(function($event)use(&$queries,&$locks,&$mode,&$capture){if(!$capture)return;$queries++;if(str_contains(strtolower($event->sql),'for update'))$locks++;if(!$mode&&str_contains($event->sql,'"pa_imported_sources"')){$pdo=$event->connection->getPdo();$mode=['isolation'=>$pdo->query('SHOW transaction_isolation')->fetchColumn(),'read_only'=>$pdo->query('SHOW transaction_read_only')->fetchColumn()];}}); gc_collect_cycles();memory_reset_peak_usage();$memory=memory_get_usage(true);$start=hrtime(true);$report=$service->report($u);$ms=(hrtime(true)-$start)/1e6;$peak=memory_get_peak_usage(true);$capture=false; $prior=json_decode(file_get_contents($s['root'].'/page-post.json'),true,64,JSON_THROW_ON_ERROR);$count=$prior['counts']['pa_obligations']; if($count!==10000||$report['totals']['count']!==$count||$report['totals']['principal_minor']!==6000*$count||$report['totals']['balance_minor']!==3000*$count||$report['known_positions']['historical_confirmed_minor']!==3000*$count||$report['windows']!==100||$report['window_size']!==100||$locks!==0||$mode!==['isolation'=>'repeatable read','read_only'=>'on']||$fingerprint()!==$prior['scoped_business_fingerprint'])throw new LogicException('Report volume or original history differs'); if($phase==='payable-report-volume-batch'){$old=json_decode(file_get_contents($s['root'].'/report-volume.json'),true,128,JSON_THROW_ON_ERROR);foreach(['totals','known_positions','positions_sha256','windows'] as $key)if($old['report'][$key]!==$report[$key])throw new LogicException('Optimised report differs from original complete report');} file_put_contents($output,json_encode(['passed'=>true,'report'=>$report,'time_ms'=>round($ms,3),'queries'=>$queries,'heap_baseline_bytes'=>$memory,'heap_peak_bytes'=>$peak,'writer_lock_queries'=>$locks,'transaction'=>$mode,'prior_business_fingerprint_equal'=>true,'not_deployment_capacity'=>true],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR)); echo json_encode(['passed'=>true,'positions'=>$count,'windows'=>100,'time_ms'=>round($ms,3),'queries'=>$queries,'heap_peak_bytes'=>$peak])."\n";exit; } if(in_array($phase,['payable-report-cases','payable-report-cases-batch'],true)){ $output=$s['root'].($phase==='payable-report-cases'?'/report-cases.json':'/report-cases-batch.json'); if(is_file($output))throw new LogicException('Completed report cases preserved'); $before=$fingerprint();$checks=0;$cases=[]; $assert=function(bool $ok,string $why)use(&$checks):void{$checks++;if(!$ok)throw new RuntimeException($why);}; $case=function(string $name,callable $test)use(&$checks,&$cases):void{$n=$checks;DB::beginTransaction();DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');try{$test();$cases[]=['name'=>$name,'assertions'=>$checks-$n,'passed'=>true];}finally{while(DB::transactionLevel()>0)DB::rollBack();}echo 'Passed report case: '.$name."\n";}; $case('filters-reproducible-positions-and-unknown-due-date',function()use($service,$u,$f,$assert):void{ $a=$service->report($u,['source'=>$f['source_id']]);$b=$service->report($u,['source'=>(string)$f['source_id']]); $assert($a['totals']['count']===1&&$a['totals']['balance_minor']===3000,'Original recognised position'); $assert($a['positions_sha256']===$b['positions_sha256'],'Equivalent ID types produce same content fingerprint'); $assert($a['totals']['unknown_due_count']===1,'Unknown due date preserved'); foreach(['%','_','NO-SUCH-NUMBER'] as $q){$r=$service->report($u,['q'=>$q]);$assert($r['totals']['count']===0&&$r['totals']['principal_minor']===0&&$r['totals']['balance_minor']===0,'Empty supported filter is an explicit empty universe');} }); $case('mixed-divergent-history-never-becomes-a-global-zero',function()use($service,$u,$scope,$assert):void{ $query=DB::table('pa_imported_sources')->where($scope)->whereRaw("payload->>'number' LIKE 'BENCH-0000%'"); $count=(clone $query)->count();if($count<2||$count>20)throw new LogicException('Use a small retained benchmark subset'); $row=$query->orderBy('id')->first();$doc=json_decode($row->payload,true,64,JSON_THROW_ON_ERROR);$doc['supplier_name']='QA_CHANGED_AFTER_HISTORY';$payload=Payables::canonical($doc); DB::table('pa_imported_sources')->where('id',$row->id)->update(['payload'=>$payload,'receipt_hash'=>hash('sha256',$payload)]); $r=$service->report($u,['q'=>'BENCH-0000']); $assert($r['totals']['count']===$count&&$r['totals']['principal_minor']===6000*$count,'Original principal stays recognised'); $assert($r['totals']['unknown_balance_count']===1&&$r['totals']['balance_minor']===null,'Global balance indeterminate'); $assert($r['known_positions']['count']===$count-1&&$r['known_positions']['balance_minor']===3000*($count-1),'Known component is explicitly partial'); $html=view('purchasing.payable-report',['report'=>$r])->render();$assert(str_contains($html,'saldo global permanece indeterminado')&&str_contains($html,'Saldo conhecido — parcial'),'Partial warning rendered'); DB::table('pa_imported_sources')->where('id',$row->id)->update(['receipt_hash'=>str_repeat('0',64)]); $blocked=false;try{$service->report($u,['source'=>(int)$row->id]);}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$blocked=$e->getStatusCode()===409;}$assert($blocked,'Invalid raw receipt integrity stops the report'); }); $case('isolation-and-fresh-authority',function()use($service,$u,$scope,$f,$assert):void{ $row=(array)DB::table('pa_imported_sources')->where('id',$f['source_id'])->first();unset($row['id']); foreach(['tenant_id','company_id','unit_id'] as $key){$id=DB::table('pa_imported_sources')->insertGetId(array_replace($row,[$key=>$scope[$key]+10000]));$status=null;try{$service->report($u,['source'=>$id]);}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$status=$e->getStatusCode();}$assert($status===403,'Foreign source scope refused: '.$key);} DB::table('pa_access')->where($scope)->where(['user_id'=>$u->id,'action'=>'view'])->delete(); $denied=false;try{$service->report($u,['source'=>$f['source_id']]);}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$denied=$e->getStatusCode()===403;}$assert($denied,'Report retains explicit financial view authority'); }); DB::beginTransaction();try{$blocked=false;try{$service->report($u);}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$blocked=$e->getStatusCode()===409;}$assert($blocked,'Incoherent nested transaction refused');}finally{DB::rollBack();} $assert($before===$fingerprint(),'Test frames changed original financial rows'); file_put_contents($output,json_encode(['passed'=>true,'cases'=>$cases,'assertions'=>$checks,'business_fingerprint_equal'=>true,'test_writes_rolled_back'=>true],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode(['cases'=>count($cases),'assertions'=>$checks,'passed'=>true])."\n";exit; } throw new LogicException('Unknown report QA phase');