seed_water_agent_customers_demo.php 6.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /** Seed clearly labelled customer archives under existing agents; --apply writes once. */
  3. declare(strict_types=1);
  4. require dirname(__DIR__).'/vendor/autoload.php';
  5. \Dotenv\Dotenv::createUnsafeMutable(dirname(__DIR__))->load();
  6. \support\App::loadAllConfig(['route']);
  7. date_default_timezone_set('Asia/Shanghai');
  8. use plugin\saiadmin\app\model\water\{WaterModel,WaterAgent,WaterEnterprise,WaterOperator,WaterLedger,WaterAccount,WaterOrder,WaterDelivery,WaterSku,WaterDevice};
  9. use plugin\saiadmin\app\service\{WaterBusiness,WaterEnterpriseDashboard};
  10. const CUSTOMER_DEMO_BATCH = 'TEST-WATER-AGENT-CUSTOMERS-20260916';
  11. const CUSTOMER_DEMO_TAG = '【代理测试0916】';
  12. function ensure(bool $ok,string $message): void { if (!$ok) throw new RuntimeException($message); }
  13. function protectedData(): array {
  14. $hashes=[];
  15. foreach ([WaterAgent::class,WaterAccount::class,WaterOrder::class,WaterDelivery::class,WaterSku::class,WaterDevice::class] as $model) {
  16. $hashes[$model]=hash('sha256',serialize($model::query()->orderBy('id')->get()->toArray()));
  17. }
  18. return $hashes;
  19. }
  20. $samples=['星澜科技','青禾创意','云帆商贸','沐光设计','森屿办公','远航服务'];
  21. $agents=WaterAgent::query()->where('status',1)->orderBy('id')->limit(3)->get(['id','name','region'])->toArray();
  22. $result=['applied'=>false,'agents'=>$agents,'planned_customers'=>count($samples),'tag'=>CUSTOMER_DEMO_TAG];
  23. if (in_array('--apply',$argv,true)) {
  24. $result=WaterModel::transaction(function () use ($samples,$agents): array {
  25. ensure((bool)WaterOperator::query()->where('id',1)->lockForUpdate()->first(),'缺少操作账号');
  26. if (WaterLedger::query()->where(['kind'=>'demo_seed','reference'=>CUSTOMER_DEMO_BATCH])->exists()) return ['applied'=>true,'replayed'=>true];
  27. ensure(count($agents)>0,'没有启用代理,无法创建代理客户');
  28. ensure(!WaterEnterprise::query()->where('name','like',CUSTOMER_DEMO_TAG.'%')->exists(),'存在同名批次,请先核对,禁止覆盖');
  29. $before=protectedData();
  30. $old=WaterEnterprise::query()->orderBy('id')->get()->toArray();
  31. $oldIds=array_column($old,'id');
  32. $business=new WaterBusiness(); $dashboard=new WaterEnterpriseDashboard(); $ids=[]; $byAgent=[];
  33. foreach ($samples as $index=>$name) {
  34. $agent=$agents[intdiv($index,2)%count($agents)];
  35. $id=$business->save('enterprise',[
  36. 'name'=>CUSTOMER_DEMO_TAG.$name,'contact'=>'测试联系人'.($index+1),'phone'=>'TEST-0916-'.str_pad((string)($index+1),2,'0',STR_PAD_LEFT),
  37. 'agent_id'=>(int)$agent['id'],'region'=>$agent['region'] ?: '测试区域',
  38. 'address'=>'【虚构测试地址,请勿实际配送】代理客户测试园区'.($index+1).'号',
  39. 'longitude'=>null,'latitude'=>null,'status'=>$index===5?2:1,
  40. ],1)['id'];
  41. $ids[]=$id; $byAgent[(int)$agent['id']][]=$id;
  42. $detail=$dashboard->detail($id);
  43. ensure($detail['enterprise']['agent_id']===(int)$agent['id'] && $detail['enterprise']['agent_name']===$agent['name'],'详情代理关联不正确');
  44. ensure($detail['accounts']===[] && $detail['orders']===[],'档案测试不应生成账户或订单');
  45. }
  46. $page=$dashboard->dashboard(['keyword'=>CUSTOMER_DEMO_TAG,'limit'=>6]);
  47. ensure($page['list']['total']===6 && count($page['list']['data'])===6,'客户搜索或列表验证失败');
  48. foreach ($byAgent as $agentId=>$agentIds) {
  49. $filtered=$dashboard->dashboard(['keyword'=>CUSTOMER_DEMO_TAG,'agent_id'=>$agentId]);
  50. ensure($filtered['list']['total']===count($agentIds),'代理筛选验证失败');
  51. }
  52. ensure($dashboard->dashboard(['keyword'=>CUSTOMER_DEMO_TAG,'status'=>'1'])['list']['total']===5,'启用筛选验证失败');
  53. ensure($dashboard->dashboard(['keyword'=>CUSTOMER_DEMO_TAG,'status'=>'2'])['list']['total']===1,'停用筛选验证失败');
  54. ensure($dashboard->dashboard(['keyword'=>CUSTOMER_DEMO_TAG,'agent_id'=>0])['list']['total']===0,'测试客户不应混入直营');
  55. ensure($before===protectedData(),'非目标业务数据发生变化');
  56. ensure($old===WaterEnterprise::query()->whereIn('id',$oldIds)->orderBy('id')->get()->toArray(),'已有客户被修改');
  57. WaterLedger::query()->create(['kind'=>'demo_seed','reference'=>CUSTOMER_DEMO_BATCH,'created_by'=>1,'enterprise_id'=>0,'sku_id'=>0,'quantity'=>0,
  58. 'note'=>'代理客户档案测试,IDs='.implode(',',$ids),'created_at'=>date('Y-m-d H:i:s')]);
  59. return ['applied'=>true,'replayed'=>false,'created_ids'=>$ids,'checks'=>'list, agent/status filters, details and existing-data preservation passed'];
  60. });
  61. $rows=(new WaterEnterpriseDashboard())->dashboard(['keyword'=>CUSTOMER_DEMO_TAG,'limit'=>100])['list']['data'];
  62. $result['customers']=array_map(fn($r)=>array_intersect_key($r,array_flip(['id','name','agent_id','agent_name','status','replenishment_status'])),$rows);
  63. }
  64. if (in_array('--http',$argv,true)) {
  65. $token=\Tinywan\Jwt\JwtToken::generateToken(['id'=>1,'username'=>'admin','plat'=>'saiadmin','type'=>'web',
  66. 'client'=>CUSTOMER_DEMO_BATCH,'access_exp'=>120,'refresh_exp'=>120])['access_token'];
  67. $cases=[['keyword'=>CUSTOMER_DEMO_TAG]];
  68. foreach ($agents as $agent) $cases[]=['keyword'=>CUSTOMER_DEMO_TAG,'agent_id'=>(int)$agent['id']];
  69. foreach (['1','2'] as $status) $cases[]=['keyword'=>CUSTOMER_DEMO_TAG,'status'=>$status];
  70. $dashboard=new WaterEnterpriseDashboard(); $checks=0;
  71. foreach ($cases as $filters) {
  72. $url='http://127.0.0.1:8787/core/water/enterprises/dashboard?'.http_build_query($filters+['limit'=>100]);
  73. $ch=curl_init($url);
  74. curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$token]]);
  75. $raw=curl_exec($ch); $status=curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
  76. $body=json_decode((string)$raw,true);
  77. ensure($status===200 && ($body['code']??0)===200,'HTTP客户查询失败');
  78. $expected=$dashboard->dashboard($filters+['limit'=>100])['list'];
  79. ensure(($body['data']['list']['total']??null)===$expected['total'],'HTTP筛选数量不一致');
  80. ensure(array_column($body['data']['list']['data'],'id')===array_column($expected['data'],'id'),'HTTP列表客户不一致');
  81. $checks++;
  82. }
  83. $result['http_read_checks']=$checks;
  84. unset($token);
  85. }
  86. echo json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT).PHP_EOL;