DeleteRepeatCustomer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\command;
  4. use app\model\Customer;
  5. use app\model\CustomersSubscribe;
  6. use app\model\CustomerTop;
  7. use app\model\CustomerVisitLog;
  8. use app\model\Org;
  9. use think\console\Command;
  10. use think\console\Input;
  11. use think\console\input\Argument;
  12. use think\console\input\Option;
  13. use think\console\Output;
  14. class DeleteRepeatCustomer extends Command
  15. {
  16. protected function configure()
  17. {
  18. // 指令配置
  19. $this->setName('deleterepeatcustomer')
  20. ->addArgument('root_id', Argument::OPTIONAL, '组织根id')
  21. ->setDescription('the deleterepeatcustomer command');
  22. }
  23. protected function execute(Input $input, Output $output)
  24. {
  25. $root_id = trim($input->getArgument('root_id'));
  26. $root = Org::find($root_id);
  27. if (empty($root)) {
  28. $output->writeln('根组织不存在');
  29. return;
  30. }
  31. $orgIdList = Org::where([['path', 'like', $root->path . '%']])->column('id');
  32. // 查询电话号码重复的数据
  33. $rs = Customer::where([['org_id', 'in', $orgIdList]])->group('phone')->having('count(id)>1')->column('phone');
  34. foreach ($rs as $v) {
  35. // 查询该电话号码中最新的一条数据id
  36. $idList = Customer::where([['org_id', 'in', $orgIdList], ['phone', '=', $v]])->column('id');
  37. // 1)从追踪记录中查找最新的记录
  38. $newCustomerId = CustomerVisitLog::where([['customer_id', 'in', $idList]])->order('addtime desc')->value('customer_id');
  39. if (empty($newCustomerId)) {
  40. $newCustomerId = Customer::where([['org_id', 'in', $orgIdList], ['phone', '=', $v]])->order('last_contact_date desc, updatetime desc, addtime desc')->value('id');
  41. }
  42. // 剔除多余数据
  43. $newKey = array_search($newCustomerId, $idList);
  44. unset($idList[$newKey]);
  45. // 删除多余数据
  46. Customer::where([['id', 'in', $idList]])->delete();
  47. $output->writeln($v.'删除:'.count($idList).'条');
  48. // 删除客户追踪记录
  49. CustomerVisitLog::where([['customer_id', 'in', $idList]])->delete();
  50. // 删除客户置顶
  51. CustomerTop::where([['customer_id', 'in', $idList]])->delete();
  52. // 预约记录
  53. CustomersSubscribe::where([['customer_id', 'in', $idList]])->delete();
  54. }
  55. // 指令输出
  56. $output->writeln('ok');
  57. }
  58. }