diff --git a/app/command/CrmRotateUserCommand.php b/app/command/CrmRotateUserCommand.php new file mode 100644 index 0000000..5defb24 --- /dev/null +++ b/app/command/CrmRotateUserCommand.php @@ -0,0 +1,105 @@ +setHelp('查询 user 表中 status=2 且 corp_id=3 的用户, +然后查找其关联的 crm_customer 记录, +按顺序将这些 crm_customer.user_id 轮流设置为 1、2、3。'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $corpId = 3; + $status = 2; + $roundRobinUserIds = [64,63,83,93,118,131,132,143,145,150,156,157,158,160]; + + $output->writeln('开始执行 crm:rotate-user'); + + try { + // 1) 找到 user 表中满足条件的用户ID,派卡离职用户 + $userRows = Db::table('user') + ->where('corp_id', $corpId) + ->where('status', $status) + ->get(['id','name']); + + $userIds = []; + $userNames = []; + foreach ($userRows as $row) { + $userIds[] = (int)$row->id; + $userNames[] = $row->name; + } + + if (empty($userIds)) { + $output->writeln('未找到满足条件的用户(status=2 且 corp_id=3)。无需处理。'); + return self::SUCCESS; + } + + $output->writeln('匹配到用户数:' . count($userIds) .' '. implode(',',$userNames) . ''); + + // 2) 查找 crm_customer 中属于这些用户的记录 + $customers = Db::table('crm_customer') + ->whereIn('user_id', $userIds) + ->orderBy('id', 'asc') + ->get(['id','user_id']); + + if (!$customers || count($customers) === 0) { + $output->writeln('未找到相关的 crm_customer 记录。'); + return self::SUCCESS; + } + + $output->writeln('需要处理的 crm_customer 数量:' . count($customers) . ''); + + // 3) 事务中按顺序轮流设置 + // 初始化 UID 轮询器 + $uidRotator = new \app\common\utils\RedisUidRotator('email_parsed_result_20250804'); + $uidRotator->setUids([64, 63, 83, 93, 118, 131, 132, 143, 145, 150, 156, 157, 158, 160], false); + + Db::connection()->transaction(function () use ($customers, $roundRobinUserIds, $output, $uidRotator) { + $assignCount = 0; + $targetCount = count($roundRobinUserIds); + + foreach ($customers as $index => $customer) { + // 获取下一个分配的UID + $newUserId = $uidRotator->next(); + Db::table('crm_customer') + ->where('id', $customer->id) + ->update(['user_id' => $newUserId]); + + $his = CustomerHis::create([ + 'customer_id' => $customer->id, + 'user_his' => $customer->user_id, + 'user_id' => $newUserId, + ]); + + + $assignCount++; + + if ($assignCount % 500 === 0) { + $output->writeln('已处理:' . $assignCount . ''); + } + } + + $output->writeln('处理完成,共更新 crm_customer:' . $assignCount . ' 条'); + }); + + return self::SUCCESS; + } catch (\Throwable $e) { + $output->writeln('执行失败:' . $e->getMessage() . ''); + return self::FAILURE; + } + } +} +