Files
fdesk/app/command/CustomerCodeCommand.php
T

62 lines
2.1 KiB
PHP
Raw Normal View History

2025-08-06 17:42:24 +08:00
<?php
namespace app\command;
use app\crm\model\Customer;
use support\Log;
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Webman\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CustomerCodeCommand extends SymfonyCommand
{
protected static $defaultName = 'customer:generate-code';
protected function configure()
{
$this->setDescription('为crm_customer表所有记录生成唯一code码,分批处理');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$batchSize = 1000;
$total = Customer::withTrashed()->where('code','')->count();
$output->writeln("总计需处理:$total 条记录");
$processed = 0;
do {
// 查询一批未生成code的记录
$customers = Customer::withTrashed()->where('code','')->limit($batchSize)->get();
if ($customers->isEmpty()) {
break;
}
// Eloquent 批量处理
foreach ($customers as $customer) {
// 生成唯一16位code,CM+14位
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14));
$code = 'CM' . $unique;
// 防止极小概率重复
while (Customer::where('code', $code)->exists()) {
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14));
$code = 'CM' . $unique;
}
2025-08-14 20:08:57 +08:00
$created_at = $customer->created_at->getTimestamp();
$obtain = $created_at > strtotime('2025-07-29')?$created_at:strtotime('2025-07-29');
2025-08-06 17:42:24 +08:00
$customer->code = $code;
$customer->obtain = $obtain;
$customer->save();
$processed++;
}
$output->writeln("已处理:$processed / $total");
} while (true);
$output->writeln('<info>全部处理完成!</info>');
return self::SUCCESS;
}
}