<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Shanghai');$lane=getenv('CATEGORY_LANE');$runtime=getenv('CATEGORY_RUNTIME');$root=getenv('CATEGORY_ROOT');$base=getenv('CATEGORY_BASE');$dm=getenv('POC_DIALECT')==='dm';$db=new PDO($dm?'dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP':'mysql:host='.getenv('POC_AI_HOST').';port='.getenv('POC_AI_PORT').';dbname='.getenv('POC_AI_SCHEMA').';charset=utf8',getenv('POC_AI_USER'),getenv('POC_AI_PASSWORD'),[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER]);
$q=static function(string $sql,array $args=[])use($db):array{$s=$db->prepare($sql);$s->execute($args);$r=[];while($row=$s->fetch(PDO::FETCH_ASSOC)){$row=array_change_key_case($row,CASE_LOWER);foreach($row as &$v)if(is_resource($v))$v=stream_get_contents($v);unset($v);$r[]=$row;}return $r;};$check=static function(bool $ok,string $why):void{if(!$ok)throw new RuntimeException($why);};$main=json_decode((string)file_get_contents($runtime.'/report.json'),true);$check($main['error']===null,'Only complete owned run may supplement');
define('TP_ENV','poc');define('BUSINESS','aizhct');define('ENTERPRISE_NO','10001');require $root.'/vendor/autoload.php';$app=new \think\App($root);$app->setEnvName('poc');$app->setRuntimePath($runtime.'/extra-cli/');$app->initialize();$cache=new \think\cache\driver\File($app,['path'=>$runtime.'/cache/','prefix'=>'','expire'=>0]);$tokens=[];$report=['lane'=>$lane,'cases'=>[],'error'=>null];$bodies=[];
$shape=static function($v)use(&$shape){if(is_object($v)){$r=[];foreach(get_object_vars($v) as $k=>$x)$r[$k]=$shape($x);ksort($r);return ['object'=>$r];}return is_array($v)?['array'=>array_map($shape,$v)]:(is_int($v)||is_float($v)?'number':gettype($v));};
$request=static function(string $kind,string $label,string $action,array $params)use($base,&$tokens,&$report,&$bodies,$shape):array{$method=$action==='detail'?'GET':'POST';$path='/'.$kind.'/setting.payment.'.($kind==='store'?'template':'Template').'/'.$action;$header='Access-Token: '.$tokens[$kind]."\r\nPlatform: PC\r\nX-Pilot-Scenario: PILOT_DICT_TPL_EXTRA_".strtoupper($kind.'_'.$label)."\r\n";$opts=['method'=>$method,'header'=>$header,'timeout'=>20,'ignore_errors'=>true];$url=$base.$path;if($method==='GET')$url.='?'.http_build_query($params);else{$boundary='CDX'.bin2hex(random_bytes(8));$content='';foreach($params as $k=>$v)$content.='--'.$boundary."\r\nContent-Disposition: form-data; name=\"".$k."\"\r\n\r\n".$v."\r\n";$opts['header'].='Content-Type: multipart/form-data; boundary='.$boundary."\r\n";$opts['content']=$content.'--'.$boundary."--\r\n";}$raw=@file_get_contents($url,false,stream_context_create(['http'=>$opts]));$body=json_decode((string)$raw,true);$wire=json_decode((string)$raw);$bodies[$kind.'_'.$label]=$wire;$report['cases'][]=['scenario'=>$kind.'_'.$label,'method'=>$method,'path'=>$path,'status'=>$body['status']??null,'wire_shape'=>$shape($wire),'raw_response_sha256'=>hash('sha256',(string)$raw)];return [$body,count($report['cases'])-1];};
try{foreach(['store'=>2147000701,'terminal'=>2147000702] as $kind=>$tenant){$tokens[$kind]=bin2hex(random_bytes(24));$cache->set($tokens[$kind],['user'=>['store_user_id'=>2147000799,'store_id'=>$tenant,'real_name'=>'CDXPAYTPL10','user_name'=>'CDXPAYTPL10','is_super'=>1],'store_id'=>$tenant,'is_login'=>true],300);}
 foreach(['store'=>2147000701,'terminal'=>2147000702] as $kind=>$tenant){$other=$tenant===2147000701?2147000702:2147000701;$targets=$q('SELECT * FROM yoshop_payment_template WHERE store_id=? ORDER BY template_id',[$tenant]);$check(count($targets)===2,'Two owned templates');$alipay=array_values(array_filter($targets,static function($r){return $r['method']==='alipay';}))[0];$foreign=$q("SELECT * FROM yoshop_payment_template WHERE store_id=? AND method='alipay'",[$other])[0];$sourceBefore=$q('SELECT * FROM yoshop_payment_template WHERE store_id IN (?,?) ORDER BY template_id',[2147000701,2147000702]);
 $payload=['templateId'=>(int)$foreign['template_id'],'name'=>$foreign['name'],'method'=>'alipay','config'=>$foreign['config'],'remarks'=>'CDX forbidden other own tenant edit','sort'=>(int)$foreign['sort']];[$body,$index]=$request($kind,'other_tenant_edit','edit',$payload);$check(($body['status']??null)!==200,'Cross-tenant edit cannot succeed');$check($sourceBefore===$q('SELECT * FROM yoshop_payment_template WHERE store_id IN (?,?) ORDER BY template_id',[2147000701,2147000702]),'Cross-tenant edit sources unchanged');$report['cases'][$index]['both_owned_tenants_unchanged']=true;
 $config=json_decode((string)$alipay['config'],true);$config['alipay']['cdx_fixture']['actual_newline']="第一行\n第二行";$config['alipay']['cdx_fixture']['escaped_text']='\\n';$payload=['templateId'=>(int)$alipay['template_id'],'name'=>$alipay['name'],'method'=>'alipay','config'=>json_encode($config,JSON_UNESCAPED_UNICODE),'remarks'=>"CDX真实换行\n第二行",'sort'=>(int)$alipay['sort']];[$body,$index]=$request($kind,'edit_actual_newline','edit',$payload);$check(($body['status']??null)===200,'Real newline edit status');$stored=$q('SELECT * FROM yoshop_payment_template WHERE template_id=? AND store_id=?',[(int)$alipay['template_id'],$tenant])[0];$check(json_decode($stored['config'],true)===$config&&$stored['remarks']===$payload['remarks'],'JSON/CLOB and remarks actual newline source');$report['cases'][$index]['raw_config_and_newline_source_equal']=true;
 [$body,$index]=$request($kind,'detail_actual_newline','detail',['templateId'=>(int)$alipay['template_id']]);$check(($body['status']??null)===200&&$body['data']['detail']['config']['alipay']===$config['alipay']&&$body['data']['detail']['remarks']===$payload['remarks'],'HTTP full own method config/newline source');$report['cases'][$index]['full_alipay_config_source_equal']=true;
 }
}catch(Throwable $e){$report['error']=['class'=>get_class($e),'message'=>$e->getMessage()];}finally{foreach($tokens as $token)$cache->delete($token);$report['all_tokens_absent']=true;foreach($tokens as $token)$report['all_tokens_absent']=$report['all_tokens_absent']&&$cache->get($token)===null;$report['tripwire_calls']=is_file($runtime.'/tripwire.jsonl')?count(file($runtime.'/tripwire.jsonl')):0;file_put_contents($runtime.'/extra-report.json',json_encode($report,JSON_PRETTY_PRINT));chmod($runtime.'/extra-report.json',0600);file_put_contents($runtime.'/extra-private-bodies.json',json_encode($bodies,JSON_UNESCAPED_UNICODE));chmod($runtime.'/extra-private-bodies.json',0600);}echo json_encode($report),"\n";exit($report['error']?2:0);
