migrate_water_agents.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. /** Additive checkpoint: php scripts/migrate_water_agents.php --apply. Old tables remain intact. */
  3. require dirname(__DIR__) . '/vendor/autoload.php';
  4. \Dotenv\Dotenv::createUnsafeMutable(dirname(__DIR__))->load();
  5. \support\App::loadAllConfig(['route']);
  6. \Webman\ThinkOrm\ThinkOrm::start(null);
  7. use support\think\Db;
  8. if (!in_array('--apply', $argv, true)) {
  9. echo "Plan: create water agent directory and copy explicit legacy profiles; no deletion or permission changes.\n";
  10. exit(0);
  11. }
  12. Db::execute(file_get_contents(dirname(__DIR__) . '/plugin/saiadmin/db/20260909_water_agent.sql'));
  13. $tables = array_map(fn($row) => array_values($row)[0], Db::query('SHOW TABLES'));
  14. $imported = 0;
  15. if (in_array('sa_agent_profile', $tables, true)) {
  16. Db::transaction(function () use (&$imported, $tables) {
  17. foreach (Db::table('sa_agent_profile')->select()->toArray() as $profile) {
  18. $userId = (int)$profile['agent_id'];
  19. if (Db::table('sa_water_agent')->where('user_id', $userId)->find()) continue;
  20. $user = Db::table('sa_system_user')->where('id', $userId)->find();
  21. if (!$user) throw new RuntimeException('Legacy agent has no identity record; review before cleanup');
  22. $contract = in_array('sa_agent_contract', $tables, true)
  23. ? Db::table('sa_agent_contract')->where('agent_id', $userId)->find() : null;
  24. $now = date('Y-m-d H:i:s');
  25. Db::table('sa_water_agent')->insert([
  26. 'user_id'=>$userId, 'name'=>$user['realname'] ?: $user['username'],
  27. 'contact'=>$user['realname'] ?: $user['username'], 'phone'=>$user['phone'] ?? '',
  28. 'region'=>implode(' ', array_filter([$profile['province'], $profile['city'], $profile['district']])),
  29. 'address'=>$profile['company_address'] ?? '',
  30. 'status'=>empty($user['delete_time']) && (int)$user['status'] === 1 ? 1 : 2,
  31. 'contract_urls'=>$contract['contract_urls'] ?? null,
  32. 'identity_urls'=>$contract['identity_urls'] ?? null,
  33. 'extra_urls'=>$contract['extra_urls'] ?? null,
  34. 'created_at'=>$profile['create_time'] ?: $now, 'updated_at'=>$now,
  35. ]);
  36. $imported++;
  37. }
  38. });
  39. }
  40. echo "Water agent migration complete: imported {$imported}; total ".Db::table('sa_water_agent')->count().". No legacy data deleted.\n";