工作台及场景获客字段同步

This commit is contained in:
wong
2025-08-12 09:28:57 +08:00
parent 14b1230f72
commit 239e518676
4 changed files with 526 additions and 365 deletions

View File

@@ -58,8 +58,8 @@ class ContentLibraryController extends Controller
$data = [
'name' => $param['name'],
// 数据来源配置
'sourceFriends' => $sourceType == 1 ? json_encode($param['friends']) : json_encode([]), // 选择的微信好友
'sourceGroups' => $sourceType == 2 ? json_encode($param['groups']) : json_encode([]), // 选择的微信群
'sourceFriends' => $sourceType == 1 ? json_encode($param['friendsGroups']) : json_encode([]), // 选择的微信好友
'sourceGroups' => $sourceType == 2 ? json_encode($param['wechatGroups']) : json_encode([]), // 选择的微信群
'groupMembers' => $sourceType == 2 ? json_encode($param['groupMembers']) : json_encode([]), // 群组成员
// 关键词配置
'keywordInclude' => $keywordInclude, // 包含的关键词
@@ -220,11 +220,12 @@ class ContentLibraryController extends Controller
}
// 处理JSON字段转数组
$library['sourceFriends'] = json_decode($library['sourceFriends'] ?: '[]', true);
$library['sourceGroups'] = json_decode($library['sourceGroups'] ?: '[]', true);
$library['friendsGroups'] = json_decode($library['sourceFriends'] ?: '[]', true);
$library['wechatGroups'] = json_decode($library['sourceGroups'] ?: '[]', true);
$library['keywordInclude'] = json_decode($library['keywordInclude'] ?: '[]', true);
$library['keywordExclude'] = json_decode($library['keywordExclude'] ?: '[]', true);
$library['groupMembers'] = json_decode($library['groupMembers'] ?: '[]', true);
unset($library['sourceFriends'],$library['sourceGroups']);
// 将时间戳转换为日期格式(精确到日)
if (!empty($library['timeStart'])) {
@@ -235,8 +236,8 @@ class ContentLibraryController extends Controller
}
// 获取好友详细信息
if (!empty($library['sourceFriends'])) {
$friendIds = $library['sourceFriends'];
if (!empty($library['friendsGroups'])) {
$friendIds = $library['friendsGroups'];
$friendsInfo = [];
if (!empty($friendIds)) {
@@ -249,12 +250,14 @@ class ContentLibraryController extends Controller
}
// 将好友信息添加到返回数据中
$library['selectedFriends'] = $friendsInfo;
$library['friendsGroupsOptions'] = $friendsInfo;
}else{
$library['friendsGroupsOptions'] = [];
}
// 获取群组详细信息
if (!empty($library['sourceGroups'])) {
$groupIds = $library['sourceGroups'];
if (!empty($library['wechatGroups'])) {
$groupIds = $library['wechatGroups'];
$groupsInfo = [];
if (!empty($groupIds)) {
@@ -267,7 +270,9 @@ class ContentLibraryController extends Controller
}
// 将群组信息添加到返回数据中
$library['selectedGroups'] = $groupsInfo;
$library['wechatGroupsOptions'] = $groupsInfo;
}else{
$library['wechatGroupsOptions'] = [];
}
return json([
@@ -319,8 +324,8 @@ class ContentLibraryController extends Controller
// 更新内容库基本信息
$library->name = $param['name'];
$library->sourceType = isset($param['sourceType']) ? $param['sourceType'] : 1;
$library->sourceFriends = $param['sourceType'] == 1 ? json_encode($param['friends']) : json_encode([]);
$library->sourceGroups = $param['sourceType'] == 2 ? json_encode($param['groups']) : json_encode([]);
$library->sourceFriends = $param['sourceType'] == 1 ? json_encode($param['friendsGroups']) : json_encode([]);
$library->sourceGroups = $param['sourceType'] == 2 ? json_encode($param['wechatGroups']) : json_encode([]);
$library->groupMembers = $param['sourceType'] == 2 ? json_encode($param['groupMembers']) : json_encode([]);
$library->keywordInclude = $keywordInclude;
$library->keywordExclude = $keywordExclude;

View File

@@ -75,8 +75,8 @@ class WorkbenchController extends Controller
$config->startTime = $param['startTime'];
$config->endTime = $param['endTime'];
$config->contentTypes = json_encode($param['contentTypes']);
$config->devices = json_encode($param['devices']);
$config->friends = json_encode($param['friends']);
$config->devices = json_encode($param['deveiceGroups']);
$config->friends = json_encode($param['friendsGroups']);
// $config->targetGroups = json_encode($param['targetGroups']);
// $config->tagOperator = $param['tagOperator'];
$config->friendMaxLikes = $param['friendMaxLikes'];
@@ -95,8 +95,8 @@ class WorkbenchController extends Controller
$config->startTime = $param['startTime'];
$config->endTime = $param['endTime'];
$config->accountType = $param['accountType'];
$config->devices = json_encode($param['devices']);
$config->contentLibraries = json_encode($param['contentLibraries'] ?? []);
$config->devices = json_encode($param['deveiceGroups']);
$config->contentLibraries = json_encode($param['contentGroups'] ?? []);
$config->createTime = time();
$config->updateTime = time();
$config->save();
@@ -111,8 +111,10 @@ class WorkbenchController extends Controller
$config->pushOrder = $param['pushOrder']; // 推送顺序
$config->isLoop = !empty($param['isLoop']) ? 1 : 0; // 是否循环
$config->status = !empty($param['status']) ? 1 : 0; // 是否启用
$config->groups = json_encode($param['groups'], JSON_UNESCAPED_UNICODE); // 群组信息
$config->contentLibraries = json_encode($param['contentLibraries'], JSON_UNESCAPED_UNICODE); // 内容库信息
$config->groups = json_encode($param['wechatGroups'], JSON_UNESCAPED_UNICODE); // 群组信息
$config->contentLibraries = json_encode($param['contentGroups'], JSON_UNESCAPED_UNICODE); // 内容库信息
$config->socialMediaId = !empty($param['socialMediaId']) ? $param['socialMediaId'] : '';
$config->promotionSiteId = !empty($param['promotionSiteId']) ? $param['promotionSiteId'] : '';
$config->createTime = time();
$config->updateTime = time();
$config->save();
@@ -123,7 +125,7 @@ class WorkbenchController extends Controller
$config->groupNamePrefix = $param['groupNamePrefix'];
$config->maxGroups = $param['maxGroups'];
$config->membersPerGroup = $param['membersPerGroup'];
$config->devices = json_encode($param['devices']);
$config->devices = json_encode($param['deveiceGroups']);
$config->targetGroups = json_encode($param['targetGroups']);
$config->createTime = time();
$config->updateTime = time();
@@ -137,9 +139,9 @@ class WorkbenchController extends Controller
$config->timeType = $param['timeType'];
$config->startTime = $param['startTime'];
$config->endTime = $param['endTime'];
$config->devices = json_encode($param['devices'], JSON_UNESCAPED_UNICODE);
$config->devices = json_encode($param['deveiceGroups'], JSON_UNESCAPED_UNICODE);
$config->pools = json_encode($param['pools'], JSON_UNESCAPED_UNICODE);
$config->account = json_encode($param['account'], JSON_UNESCAPED_UNICODE);
$config->account = json_encode($param['accountGroups'], JSON_UNESCAPED_UNICODE);
$config->createTime = time();
$config->updateTime = time();
$config->save();
@@ -169,12 +171,12 @@ class WorkbenchController extends Controller
['userId', '=', $this->request->userInfo['id']],
['isDel', '=', 0]
];
// 添加类型筛选
if ($type !== '') {
$where[] = ['type', '=', $type];
}
// 添加名称模糊搜索
if ($keyword !== '') {
$where[] = ['name', 'like', '%' . $keyword . '%'];
@@ -182,19 +184,19 @@ class WorkbenchController extends Controller
// 定义关联关系
$with = [
'autoLike' => function($query) {
'autoLike' => function ($query) {
$query->field('workbenchId,interval,maxLikes,startTime,endTime,contentTypes,devices,friends');
},
'momentsSync' => function($query) {
'momentsSync' => function ($query) {
$query->field('workbenchId,syncInterval,syncCount,syncType,startTime,endTime,accountType,devices,contentLibraries');
},
'trafficConfig' => function($query) {
'trafficConfig' => function ($query) {
$query->field('workbenchId,distributeType,maxPerDay,timeType,startTime,endTime,devices,pools,account');
},
'groupPush' => function($query) {
'groupPush' => function ($query) {
$query->field('workbenchId,pushType,startTime,endTime,maxPerDay,pushOrder,isLoop,status,groups,contentLibraries');
},
'user' => function($query) {
'user' => function ($query) {
$query->field('id,username');
}
];
@@ -212,9 +214,9 @@ class WorkbenchController extends Controller
if (!empty($item->autoLike)) {
$item->config = $item->autoLike;
$item->config->devices = json_decode($item->config->devices, true);
$item->config->contentTypes = json_decode($item->config->contentTypes, true);
$item->config->contentTypes = json_decode($item->config->contentTypes, true);
$item->config->friends = json_decode($item->config->friends, true);
// 添加今日点赞数
$startTime = strtotime(date('Y-m-d') . ' 00:00:00');
$endTime = strtotime(date('Y-m-d') . ' 23:59:59');
@@ -222,16 +224,16 @@ class WorkbenchController extends Controller
->where('workbenchId', $item->id)
->whereTime('createTime', 'between', [$startTime, $endTime])
->count();
// 添加总点赞数
$totalLikeCount = Db::name('workbench_auto_like_item')
->where('workbenchId', $item->id)
->count();
$item->config->todayLikeCount = $todayLikeCount;
$item->config->totalLikeCount = $totalLikeCount;
}
unset($item->autoLike,$item->auto_like);
unset($item->autoLike, $item->auto_like);
break;
case self::TYPE_MOMENTS_SYNC:
if (!empty($item->momentsSync)) {
@@ -242,7 +244,7 @@ class WorkbenchController extends Controller
$sendNum = Db::name('workbench_moments_sync_item')->where(['workbenchId' => $item->id])->count();
$item->syncCount = $sendNum;
$lastTime = Db::name('workbench_moments_sync_item')->where(['workbenchId' => $item->id])->order('id DESC')->value('createTime');
$item->lastSyncTime = !empty($lastTime) ? date('Y-m-d H:i',$lastTime) : '--';
$item->lastSyncTime = !empty($lastTime) ? date('Y-m-d H:i', $lastTime) : '--';
// 获取内容库名称
@@ -254,7 +256,7 @@ class WorkbenchController extends Controller
$item->config->contentLibraryNames = [];
}
}
unset($item->momentsSync,$item->moments_sync);
unset($item->momentsSync, $item->moments_sync);
break;
case self::TYPE_GROUP_PUSH:
if (!empty($item->groupPush)) {
@@ -270,7 +272,7 @@ class WorkbenchController extends Controller
$item->config->contentLibraries = json_decode($item->config->contentLibraries, true);
$item->config->lastPushTime = '22222';
}
unset($item->groupPush,$item->group_push);
unset($item->groupPush, $item->group_push);
break;
case self::TYPE_GROUP_CREATE:
if (!empty($item->groupCreate)) {
@@ -278,7 +280,7 @@ class WorkbenchController extends Controller
$item->config->devices = json_decode($item->config->devices, true);
$item->config->targetGroups = json_decode($item->config->targetGroups, true);
}
unset($item->groupCreate,$item->group_create);
unset($item->groupCreate, $item->group_create);
break;
case self::TYPE_TRAFFIC_DISTRIBUTION:
if (!empty($item->trafficConfig)) {
@@ -287,10 +289,10 @@ class WorkbenchController extends Controller
$item->config->pools = json_decode($item->config->pools, true);
$item->config->account = json_decode($item->config->account, true);
$config_item = Db::name('workbench_traffic_config_item')->where(['workbenchId' => $item->id])->order('id DESC')->find();
$item->config->lastUpdated = !empty($config_item) ? date('Y-m-d H:i',$config_item['createTime']) : '--';
$item->config->lastUpdated = !empty($config_item) ? date('Y-m-d H:i', $config_item['createTime']) : '--';
//统计
$labels = $item->config->pools;
$labels = $item->config->pools;
$totalUsers = Db::table('s2_wechat_friend')->alias('wf')
->join(['s2_company_account' => 'sa'], 'sa.id = wf.accountId', 'left')
->join(['s2_wechat_account' => 'wa'], 'wa.id = wf.wechatAccountId', 'left')
@@ -299,8 +301,8 @@ class WorkbenchController extends Controller
['sa.departmentId', '=', $item->companyId]
])
->whereIn('wa.currentDeviceId', $item->config->devices);
if(!empty($labels) && count($labels) > 0){
if (!empty($labels) && count($labels) > 0) {
$totalUsers = $totalUsers->where(function ($q) use ($labels) {
foreach ($labels as $label) {
$q->whereOrRaw("JSON_CONTAINS(wf.labels, '\"{$label}\"')");
@@ -314,13 +316,13 @@ class WorkbenchController extends Controller
$totalAccounts = count($item->config->account);
$dailyAverage = Db::name('workbench_traffic_config_item')
->where('workbenchId', $item->id)
->count();
->where('workbenchId', $item->id)
->count();
$day = (time() - strtotime($item->createTime)) / 86400;
$day = intval($day);
if($dailyAverage > 0 && $totalAccounts > 0 && $day > 0){
if ($dailyAverage > 0 && $totalAccounts > 0 && $day > 0) {
$dailyAverage = $dailyAverage / $totalAccounts / $day;
}
@@ -332,7 +334,7 @@ class WorkbenchController extends Controller
'totalUsers' => $totalUsers >> 0
];
}
unset($item->trafficConfig,$item->traffic_config);
unset($item->trafficConfig, $item->traffic_config);
break;
}
// 添加创建人名称
@@ -370,16 +372,16 @@ class WorkbenchController extends Controller
// 定义关联关系
$with = [
'autoLike' => function($query) {
'autoLike' => function ($query) {
$query->field('workbenchId,interval,maxLikes,startTime,endTime,contentTypes,devices,friends,friendMaxLikes,friendTags,enableFriendTags');
},
'momentsSync' => function($query) {
'momentsSync' => function ($query) {
$query->field('workbenchId,syncInterval,syncCount,syncType,startTime,endTime,accountType,devices,contentLibraries');
},
'trafficConfig' => function($query) {
'trafficConfig' => function ($query) {
$query->field('workbenchId,distributeType,maxPerDay,timeType,startTime,endTime,devices,pools,account');
},
'groupPush' => function($query) {
'groupPush' => function ($query) {
$query->field('workbenchId,pushType,startTime,endTime,maxPerDay,pushOrder,isLoop,status,groups,contentLibraries');
},
// 'groupCreate' => function($query) {
@@ -392,9 +394,9 @@ class WorkbenchController extends Controller
['userId', '=', $this->request->userInfo['id']],
['isDel', '=', 0]
])
->field('id,name,type,status,autoStart,createTime,updateTime,companyId')
->with($with)
->find();
->field('id,name,type,status,autoStart,createTime,updateTime,companyId')
->with($with)
->find();
if (empty($workbench)) {
return json(['code' => 404, 'msg' => '工作台不存在']);
@@ -402,14 +404,15 @@ class WorkbenchController extends Controller
// 处理配置信息
switch ($workbench->type) {
//自动点赞
case self::TYPE_AUTO_LIKE:
if (!empty($workbench->autoLike)) {
$workbench->config = $workbench->autoLike;
$workbench->config->devices = json_decode($workbench->config->devices, true);
$workbench->config->friends = json_decode($workbench->config->friends, true);
$workbench->config->deveiceGroups = json_decode($workbench->config->devices, true);
$workbench->config->friendsGroups = json_decode($workbench->config->friends, true);
//$workbench->config->targetGroups = json_decode($workbench->config->targetGroups, true);
$workbench->config->contentTypes = json_decode($workbench->config->contentTypes, true);
// 添加今日点赞数
$startTime = strtotime(date('Y-m-d') . ' 00:00:00');
$endTime = strtotime(date('Y-m-d') . ' 23:59:59');
@@ -417,156 +420,122 @@ class WorkbenchController extends Controller
->where('workbenchId', $workbench->id)
->whereTime('createTime', 'between', [$startTime, $endTime])
->count();
// 添加总点赞数
$totalLikeCount = Db::name('workbench_auto_like_item')
->where('workbenchId', $workbench->id)
->count();
$workbench->config->todayLikeCount = $todayLikeCount;
$workbench->config->totalLikeCount = $totalLikeCount;
unset($workbench->autoLike,$workbench->auto_like);
unset($workbench->autoLike, $workbench->auto_like);
}
break;
//自动同步朋友圈
case self::TYPE_MOMENTS_SYNC:
if (!empty($workbench->momentsSync)) {
$workbench->config = $workbench->momentsSync;
$workbench->config->devices = json_decode($workbench->config->devices, true);
$workbench->config->contentLibraries = json_decode($workbench->config->contentLibraries, true);
$workbench->config->deveiceGroups = json_decode($workbench->config->devices, true);
$workbench->config->contentGroups = json_decode($workbench->config->contentLibraries, true);
//同步记录
$sendNum = Db::name('workbench_moments_sync_item')->where(['workbenchId' => $workbench->id])->count();
$workbench->syncCount = $sendNum;
$lastTime = Db::name('workbench_moments_sync_item')->where(['workbenchId' => $workbench->id])->order('id DESC')->value('createTime');
$workbench->lastSyncTime = !empty($lastTime) ? date('Y-m-d H:i',$lastTime) : '--';
// 获取内容库名称
if (!empty($workbench->config->contentLibraries)) {
$libraryNames = ContentLibrary::where('id', 'in', $workbench->config->contentLibraries)
->select();
$workbench->config->contentLibraries = $libraryNames;
} else {
$workbench->config->contentLibraryNames = [];
}
if(!empty($workbench->config->devices)){
$deviceList = DeviceModel::alias('d')
->field([
'd.id', 'd.imei', 'd.memo', 'd.alive',
'l.wechatId',
'a.nickname', 'a.alias', 'a.avatar','a.alias'
])
->leftJoin('device_wechat_login l', 'd.id = l.deviceId and l.alive =' . DeviceWechatLoginModel::ALIVE_WECHAT_ACTIVE . ' and l.companyId = d.companyId')
->leftJoin('wechat_account a', 'l.wechatId = a.wechatId')
->whereIn('d.id',$workbench->config->devices)
->order('d.id desc')
->select();
$workbench->config->deviceList = $deviceList;
}else{
$workbench->config->deviceList = [];
}
unset($workbench->momentsSync,$workbench->moments_sync);
$workbench->lastSyncTime = !empty($lastTime) ? date('Y-m-d H:i', $lastTime) : '--';
unset($workbench->momentsSync, $workbench->moments_sync);
}
break;
//群推送
case self::TYPE_GROUP_PUSH:
if (!empty($workbench->groupPush)) {
$workbench->config = $workbench->groupPush;
$workbench->config->groups = json_decode($workbench->config->groups, true);
$workbench->config->wechatGroups = json_decode($workbench->config->groups, true);
$workbench->config->contentLibraries = json_decode($workbench->config->contentLibraries, true);
// 获取群
$groupList = Db::name('wechat_group')->alias('wg')
->join('wechat_account wa', 'wa.wechatId = wg.ownerWechatId')
->where('wg.id', 'in', $workbench->config->groups)
->order('wg.id', 'desc')
->field('wg.id,wg.name as groupName,wg.ownerWechatId,wa.nickName,wa.avatar,wa.alias,wg.avatar as groupAvatar')
->select();
$workbench->config->groupList = $groupList;
// 获取群组内容库
/* // 获取群组内容库
$contentLibraryList = ContentLibrary::where('id', 'in', $workbench->config->contentLibraries)
->field('id,name,sourceFriends,sourceGroups,keywordInclude,keywordExclude,aiEnabled,aiPrompt,timeEnabled,timeStart,timeEnd,status,sourceType,userId,createTime,updateTime')
->with(['user' => function($query) {
$query->field('id,username');
}])
->order('id', 'desc')
->select();
->field('id,name,sourceFriends,sourceGroups,keywordInclude,keywordExclude,aiEnabled,aiPrompt,timeEnabled,timeStart,timeEnd,status,sourceType,userId,createTime,updateTime')
->with(['user' => function ($query) {
$query->field('id,username');
}])
->order('id', 'desc')
->select();
// 处理JSON字段
foreach ($contentLibraryList as &$item) {
$item['sourceFriends'] = json_decode($item['sourceFriends'] ?: '[]', true);
$item['sourceGroups'] = json_decode($item['sourceGroups'] ?: '[]', true);
$item['keywordInclude'] = json_decode($item['keywordInclude'] ?: '[]', true);
$item['keywordExclude'] = json_decode($item['keywordExclude'] ?: '[]', true);
// 添加创建人名称
$item['creatorName'] = $item['user']['username'] ?? '';
$item['itemCount'] = Db::name('content_item')->where('libraryId', $item['id'])->count();
// 处理JSON字段
foreach ($contentLibraryList as &$item) {
$item['sourceFriends'] = json_decode($item['sourceFriends'] ?: '[]', true);
$item['sourceGroups'] = json_decode($item['sourceGroups'] ?: '[]', true);
$item['keywordInclude'] = json_decode($item['keywordInclude'] ?: '[]', true);
$item['keywordExclude'] = json_decode($item['keywordExclude'] ?: '[]', true);
// 添加创建人名称
$item['creatorName'] = $item['user']['username'] ?? '';
$item['itemCount'] = Db::name('content_item')->where('libraryId', $item['id'])->count();
// 获取好友详细信息
if (!empty($item['sourceFriends'] && $item['sourceType'] == 1)) {
$friendIds = $item['sourceFriends'];
$friendsInfo = [];
// 获取好友详细信息
if (!empty($item['sourceFriends'] && $item['sourceType'] == 1)) {
$friendIds = $item['sourceFriends'];
$friendsInfo = [];
if (!empty($friendIds)) {
// 查询好友信息使用wechat_friendship表
$friendsInfo = Db::name('wechat_friendship')->alias('wf')
->field('wf.id,wf.wechatId, wa.nickname, wa.avatar')
->join('wechat_account wa', 'wf.wechatId = wa.wechatId')
->whereIn('wf.id', $friendIds)
->select();
}
// 将好友信息添加到返回数据中
$item['selectedFriends'] = $friendsInfo;
if (!empty($friendIds)) {
// 查询好友信息使用wechat_friendship表
$friendsInfo = Db::name('wechat_friendship')->alias('wf')
->field('wf.id,wf.wechatId, wa.nickname, wa.avatar')
->join('wechat_account wa', 'wf.wechatId = wa.wechatId')
->whereIn('wf.id', $friendIds)
->select();
}
if (!empty($item['sourceGroups']) && $item['sourceType'] == 2) {
$groupIds = $item['sourceGroups'];
$groupsInfo = [];
if (!empty($groupIds)) {
// 查询群组信息
$groupsInfo = Db::name('wechat_group')->alias('g')
->field('g.id, g.chatroomId, g.name, g.avatar, g.ownerWechatId')
->whereIn('g.id', $groupIds)
->select();
}
// 将群组信息添加到返回数据中
$item['selectedGroups'] = $groupsInfo;
}
unset($item['user']); // 移除关联数据
// 将好友信息添加到返回数据中
$item['selectedFriends'] = $friendsInfo;
}
$workbench->config->contentLibraryList = $contentLibraryList;
if (!empty($item['sourceGroups']) && $item['sourceType'] == 2) {
$groupIds = $item['sourceGroups'];
$groupsInfo = [];
if (!empty($groupIds)) {
// 查询群组信息
$groupsInfo = Db::name('wechat_group')->alias('g')
->field('g.id, g.chatroomId, g.name, g.avatar, g.ownerWechatId')
->whereIn('g.id', $groupIds)
->select();
}
// 将群组信息添加到返回数据中
$item['selectedGroups'] = $groupsInfo;
}
unset($item['user']); // 移除关联数据
}
$workbench->config->contentLibraryList = $contentLibraryList;*/
unset($workbench->groupPush, $workbench->group_push);
}
break;
//建群助手
case self::TYPE_GROUP_CREATE:
if (!empty($workbench->groupCreate)) {
$workbench->config = $workbench->groupCreate;
$workbench->config->devices = json_decode($workbench->config->devices, true);
$workbench->config->deveiceGroups = json_decode($workbench->config->devices, true);
$workbench->config->targetGroups = json_decode($workbench->config->targetGroups, true);
}
break;
//流量分发
case self::TYPE_TRAFFIC_DISTRIBUTION:
if (!empty($workbench->trafficConfig)) {
$workbench->config = $workbench->trafficConfig;
$workbench->config->devices = json_decode($workbench->config->devices, true);
$workbench->config->deveiceGroups = json_decode($workbench->config->devices, true);
$workbench->config->accountGroups = json_decode($workbench->config->account, true);
$workbench->config->pools = json_decode($workbench->config->pools, true);
$workbench->config->account = json_decode($workbench->config->account, true);
$config_item = Db::name('workbench_traffic_config_item')->where(['workbenchId' => $workbench->id])->order('id DESC')->find();
$workbench->config->lastUpdated = !empty($config_item) ? date('Y-m-d H:i',$config_item['createTime']) : '--';
$workbench->config->lastUpdated = !empty($config_item) ? date('Y-m-d H:i', $config_item['createTime']) : '--';
//统计
$labels = $workbench->config->pools;
$labels = $workbench->config->pools;
$totalUsers = Db::table('s2_wechat_friend')->alias('wf')
->join(['s2_company_account' => 'sa'], 'sa.id = wf.accountId', 'left')
->join(['s2_wechat_account' => 'wa'], 'wa.id = wf.wechatAccountId', 'left')
@@ -574,45 +543,110 @@ class WorkbenchController extends Controller
['wf.isDeleted', '=', 0],
['sa.departmentId', '=', $workbench->companyId]
])
->whereIn('wa.currentDeviceId', $workbench->config->devices)
->whereIn('wa.currentDeviceId', $workbench->config->deveiceGroups)
->field('wf.id,wf.wechatAccountId,wf.wechatId,wf.labels,sa.userName,wa.currentDeviceId as deviceId')
->where(function ($q) use ($labels) {
foreach ($labels as $label) {
$q->whereOrRaw("JSON_CONTAINS(wf.labels, '\"{$label}\"')");
}
})->count();
foreach ($labels as $label) {
$q->whereOrRaw("JSON_CONTAINS(wf.labels, '\"{$label}\"')");
}
})->count();
$totalAccounts = Db::table('s2_company_account')
->alias('a')
->where(['a.departmentId' => $workbench->companyId, 'a.status' => 0])
->whereNotLike('a.userName', '%_offline%')
->whereNotLike('a.userName', '%_delete%')
->group('a.id')
->count();
->alias('a')
->where(['a.departmentId' => $workbench->companyId, 'a.status' => 0])
->whereNotLike('a.userName', '%_offline%')
->whereNotLike('a.userName', '%_delete%')
->group('a.id')
->count();
$dailyAverage = Db::name('workbench_traffic_config_item')
->where('workbenchId', $workbench->id)
->count();
->where('workbenchId', $workbench->id)
->count();
$day = (time() - strtotime($workbench->createTime)) / 86400;
$day = intval($day);
if($dailyAverage > 0){
if ($dailyAverage > 0) {
$dailyAverage = $dailyAverage / $totalAccounts / $day;
}
$workbench->config->total = [
'dailyAverage' => intval($dailyAverage),
'totalAccounts' => $totalAccounts,
'deviceCount' => count($workbench->config->devices),
'deviceCount' => count($workbench->config->deveiceGroups),
'poolCount' => count($workbench->config->pools),
'totalUsers' => $totalUsers >> 0
];
unset($workbench->trafficConfig,$workbench->traffic_config);
unset($workbench->trafficConfig, $workbench->traffic_config);
}
break;
}
unset($workbench->autoLike, $workbench->momentsSync, $workbench->groupPush, $workbench->groupCreate);
unset(
$workbench->autoLike,
$workbench->momentsSync,
$workbench->groupPush,
$workbench->groupCreate,
$workbench->config->devices,
$workbench->config->friends,
$workbench->config->groups,
$workbench->config->contentLibraries,
$workbench->config->account,
);
//获取设备信息
if (!empty($workbench->config->deveiceGroups)) {
$deviceList = DeviceModel::alias('d')
->field([
'd.id', 'd.imei', 'd.memo', 'd.alive',
'l.wechatId',
'a.nickname', 'a.alias', 'a.avatar', 'a.alias'
])
->leftJoin('device_wechat_login l', 'd.id = l.deviceId and l.alive =' . DeviceWechatLoginModel::ALIVE_WECHAT_ACTIVE . ' and l.companyId = d.companyId')
->leftJoin('wechat_account a', 'l.wechatId = a.wechatId')
->whereIn('d.id', $workbench->config->deveiceGroups)
->order('d.id desc')
->select();
$workbench->config->deveiceGroupsOptions = $deviceList;
} else {
$workbench->config->deveiceGroupsOptions = [];
}
// 获取群
if (!empty($workbench->config->wechatGroups)){
$groupList = Db::name('wechat_group')->alias('wg')
->join('wechat_account wa', 'wa.wechatId = wg.ownerWechatId')
->where('wg.id', 'in', $workbench->config->groups)
->order('wg.id', 'desc')
->field('wg.id,wg.name as groupName,wg.ownerWechatId,wa.nickName,wa.avatar,wa.alias,wg.avatar as groupAvatar')
->select();
$workbench->config->wechatGroupsOptions = $groupList;
}else{
$workbench->config->wechatGroupsOptions = [];
}
// 获取内容库名称
if (!empty($workbench->config->contentGroups)) {
$libraryNames = ContentLibrary::where('id', 'in', $workbench->config->contentGroups)->select();
$workbench->config->contentGroupsOptions = $libraryNames;
} else {
$workbench->config->contentGroupsOptions = [];
}
//账号
if (!empty($workbench->config->accountGroups)){
$account = Db::table('s2_company_account')->alias('a')
->where(['a.departmentId' => $this->request->userInfo['companyId'], 'a.status' => 0])
->whereIn('a.id', $workbench->config->accountGroups)
->whereNotLike('a.userName', '%_offline%')
->whereNotLike('a.userName', '%_delete%')
->field('a.id,a.userName,a.realName,a.nickname,a.memo')
->select();
$workbench->config->accountGroupsOptions = $account;
}else{
$workbench->config->accountGroupsOptions = [];
}
return json(['code' => 200, 'msg' => '获取成功', 'data' => $workbench]);
}
@@ -664,8 +698,8 @@ class WorkbenchController extends Controller
$config->startTime = $param['startTime'];
$config->endTime = $param['endTime'];
$config->contentTypes = json_encode($param['contentTypes']);
$config->devices = json_encode($param['devices']);
$config->friends = json_encode($param['friends']);
$config->devices = json_encode($param['deveiceGroups']);
$config->friends = json_encode($param['friendsGroups']);
// $config->targetGroups = json_encode($param['targetGroups']);
// $config->tagOperator = $param['tagOperator'];
$config->friendMaxLikes = $param['friendMaxLikes'];
@@ -679,25 +713,25 @@ class WorkbenchController extends Controller
case self::TYPE_MOMENTS_SYNC:
$config = WorkbenchMomentsSync::where('workbenchId', $param['id'])->find();
if ($config) {
if (!empty($param['contentLibraries'])){
foreach ($param['contentLibraries'] as $library){
if(isset($library['id']) && !empty($library['id'])){
if (!empty($param['contentGroups'])) {
foreach ($param['contentGroups'] as $library) {
if (isset($library['id']) && !empty($library['id'])) {
$contentLibraries[] = $library['id'];
}else{
} else {
$contentLibraries[] = $library;
}
}
}else{
} else {
$contentLibraries = [];
}
$config->syncInterval = $param['syncInterval'];
$config->syncCount = $param['syncCount'];
$config->syncType = $param['syncType'];
$config->startTime = $param['startTime'];
$config->endTime = $param['endTime'];
$config->accountType = $param['accountType'];
$config->devices = json_encode($param['devices']);
$config->devices = json_encode($param['deveiceGroups']);
$config->contentLibraries = json_encode($contentLibraries);
$config->updateTime = time();
$config->save();
@@ -714,8 +748,10 @@ class WorkbenchController extends Controller
$config->pushOrder = $param['pushOrder']; // 推送顺序
$config->isLoop = !empty($param['isLoop']) ? 1 : 0; // 是否循环
$config->status = !empty($param['status']) ? 1 : 0; // 是否启用
$config->groups = json_encode($param['groups'], JSON_UNESCAPED_UNICODE); // 群组信息
$config->contentLibraries = json_encode($param['contentLibraries'], JSON_UNESCAPED_UNICODE); // 内容库信息
$config->groups = json_encode($param['wechatGroups'], JSON_UNESCAPED_UNICODE); // 群组信息
$config->contentLibraries = json_encode($param['contentGroups'], JSON_UNESCAPED_UNICODE); // 内容库信息
$config->socialMediaId = !empty($param['socialMediaId']) ? $param['socialMediaId'] : '';
$config->promotionSiteId = !empty($param['promotionSiteId']) ? $param['promotionSiteId'] : '';
$config->updateTime = time();
$config->save();
}
@@ -727,7 +763,7 @@ class WorkbenchController extends Controller
$config->groupNamePrefix = $param['groupNamePrefix'];
$config->maxGroups = $param['maxGroups'];
$config->membersPerGroup = $param['membersPerGroup'];
$config->devices = json_encode($param['devices']);
$config->devices = json_encode($param['deveiceGroups']);
$config->targetGroups = json_encode($param['targetGroups']);
$config->updateTime = time();
$config->save();
@@ -741,9 +777,9 @@ class WorkbenchController extends Controller
$config->timeType = $param['timeType'];
$config->startTime = $param['startTime'];
$config->endTime = $param['endTime'];
$config->devices = json_encode($param['devices']);
$config->devices = json_encode($param['deveiceGroups']);
$config->pools = json_encode($param['pools']);
$config->account = json_encode($param['account']);
$config->account = json_encode($param['accountGroups']);
$config->updateTime = time();
$config->save();
}
@@ -768,9 +804,9 @@ class WorkbenchController extends Controller
return json(['code' => 400, 'msg' => '请求方式错误']);
}
$id = $this->request->param('id','');
$id = $this->request->param('id', '');
if(empty($id)){
if (empty($id)) {
return json(['code' => 400, 'msg' => '参数错误']);
}
@@ -976,7 +1012,7 @@ class WorkbenchController extends Controller
// 处理时间格式
$item['likeTime'] = date('Y-m-d H:i:s', $item['likeTime']);
$item['momentTime'] = !empty($item['momentTime']) ? date('Y-m-d H:i:s', $item['momentTime']) : '';
// 处理资源链接
if (!empty($item['resUrls'])) {
$item['resUrls'] = json_decode($item['resUrls'], true);
@@ -1036,11 +1072,10 @@ class WorkbenchController extends Controller
->page($page, $limit)
->select();
foreach ($list as &$item) {
$item['resUrls'] = json_decode($item['resUrls'], true);
$item['urls'] = json_decode($item['urls'], true);
}
foreach ($list as &$item) {
$item['resUrls'] = json_decode($item['resUrls'], true);
$item['urls'] = json_decode($item['urls'], true);
}
// 获取总记录数
@@ -1074,7 +1109,7 @@ class WorkbenchController extends Controller
// 获取今日数据
$todayStart = strtotime(date('Y-m-d') . ' 00:00:00');
$todayEnd = strtotime(date('Y-m-d') . ' 23:59:59');
$todayStats = Db::name('workbench_moments_sync_item')
->where([
['workbenchId', '=', $workbenchId],
@@ -1158,7 +1193,7 @@ class WorkbenchController extends Controller
foreach ($list as &$item) {
// 处理时间格式
$item['distributeTime'] = date('Y-m-d H:i:s', $item['distributeTime']);
// 处理性别
$genderMap = [
0 => '未知',
@@ -1207,7 +1242,7 @@ class WorkbenchController extends Controller
// 获取今日数据
$todayStart = strtotime(date('Y-m-d') . ' 00:00:00');
$todayEnd = strtotime(date('Y-m-d') . ' 23:59:59');
$todayStats = Db::name('workbench_traffic_distribution_item')
->where([
['workbenchId', '=', $workbenchId],
@@ -1289,7 +1324,7 @@ class WorkbenchController extends Controller
// 处理数据
$detail['distributeTime'] = date('Y-m-d H:i:s', $detail['distributeTime']);
// 处理性别
$genderMap = [
0 => '未知',
@@ -1347,10 +1382,10 @@ class WorkbenchController extends Controller
'updateTime' => time()
]);
Db::commit();
return json(['code'=>200, 'msg'=>'创建成功']);
return json(['code' => 200, 'msg' => '创建成功']);
} catch (\Exception $e) {
Db::rollback();
return json(['code'=>500, 'msg'=>'创建失败:'.$e->getMessage()]);
return json(['code' => 500, 'msg' => '创建失败:' . $e->getMessage()]);
}
}
@@ -1400,14 +1435,13 @@ class WorkbenchController extends Controller
// 搜索过滤
if (!empty($keyword)) {
$labels = array_filter($labels, function($label) use ($keyword) {
$labels = array_filter($labels, function ($label) use ($keyword) {
return mb_stripos($label, $keyword) !== false;
});
$labels = array_values($labels); // 重新索引数组
}
// 分页处理
$labels2 = array_slice($labels, ($page - 1) * $limit, $limit);
@@ -1415,9 +1449,9 @@ class WorkbenchController extends Controller
$newLabel = [];
foreach ($labels2 as $label) {
$friendCount = Db::table('s2_wechat_friend')
->whereIn('ownerWechatId',$wechatIds)
->where('labels', 'like', '%"'.$label.'"%')
->count();
->whereIn('ownerWechatId', $wechatIds)
->where('labels', 'like', '%"' . $label . '"%')
->count();
$newLabel[] = [
'label' => $label,
'count' => $friendCount
@@ -1426,8 +1460,8 @@ class WorkbenchController extends Controller
// 返回结果
return json([
'code' => 200,
'msg' => '获取成功',
'code' => 200,
'msg' => '获取成功',
'data' => [
'list' => $newLabel,
'total' => count($labels),
@@ -1461,9 +1495,9 @@ class WorkbenchController extends Controller
$total = $query->count();
$list = $query->order('wg.id', 'desc')
->field('wg.id,wg.name as groupName,wg.ownerWechatId,wa.nickName,wg.createTime,wa.avatar,wa.alias,wg.avatar as groupAvatar')
->page($page, $limit)
->select();
->field('wg.id,wg.name as groupName,wg.ownerWechatId,wa.nickName,wg.createTime,wa.avatar,wa.alias,wg.avatar as groupAvatar')
->page($page, $limit)
->select();
// 优化:格式化时间,头像兜底
$defaultGroupAvatar = '';
@@ -1474,7 +1508,7 @@ class WorkbenchController extends Controller
$item['avatar'] = $item['avatar'] ?: $defaultAvatar;
}
return json(['code' => 200, 'msg' => '获取成功', 'data' => ['total' => $total,'list' => $list]]);
return json(['code' => 200, 'msg' => '获取成功', 'data' => ['total' => $total, 'list' => $list]]);
}
@@ -1484,19 +1518,18 @@ class WorkbenchController extends Controller
$page = $this->request->param('page', 1);
$limit = $this->request->param('limit', 10);
$query = Db::table('s2_company_account')
->alias('a')
->where(['a.departmentId' => $companyId, 'a.status' => 0])
->whereNotLike('a.userName', '%_offline%')
->whereNotLike('a.userName', '%_delete%');
->alias('a')
->where(['a.departmentId' => $companyId, 'a.status' => 0])
->whereNotLike('a.userName', '%_offline%')
->whereNotLike('a.userName', '%_delete%');
$total = $query->count();
$list = $query->field('a.id,a.userName,a.realName,a.nickname,a.memo')
->page($page, $limit)
->select();
->page($page, $limit)
->select();
return json(['code' => 200, 'msg' => '获取成功', 'data' => ['total' => $total,'list' => $list]]);
return json(['code' => 200, 'msg' => '获取成功', 'data' => ['total' => $total, 'list' => $list]]);
}
@@ -1527,11 +1560,9 @@ class WorkbenchController extends Controller
return json(['code' => 500, 'msg' => '参数缺失']);
}
$data = Db::name('jd_promotion_site')->where('jdSocialMediaId',$id)->order('id DESC')->select();
$data = Db::name('jd_promotion_site')->where('jdSocialMediaId', $id)->order('id DESC')->select();
return json(['code' => 200, 'msg' => '获取成功', 'data' => $data]);
}
}
}

View File

@@ -2,6 +2,8 @@
namespace app\cunkebao\controller\plan;
use app\common\model\Device as DeviceModel;
use app\common\model\DeviceWechatLogin as DeviceWechatLoginModel;
use library\ResponseHelper;
use think\Controller;
use think\Db;
@@ -116,10 +118,53 @@ class GetAddFriendPlanDetailV1Controller extends Controller
// 解析JSON字段
$sceneConf = json_decode($plan['sceneConf'], true) ?: [];
$sceneConf['wechatGroups'] = $sceneConf['groupSelected'];
$reqConf = json_decode($plan['reqConf'], true) ?: [];
$reqConf['deveiceGroups'] = $reqConf['device'];
$msgConf = json_decode($plan['msgConf'], true) ?: [];
$tagConf = json_decode($plan['tagConf'], true) ?: [];
if(!empty($sceneConf['wechatGroups'])){
$groupList = Db::name('wechat_group')->alias('wg')
->join('wechat_account wa', 'wa.wechatId = wg.ownerWechatId')
->where('wg.id', 'in', $sceneConf['wechatGroups'])
->order('wg.id', 'desc')
->field('wg.id,wg.name as groupName,wg.ownerWechatId,wa.nickName,wa.avatar,wa.alias,wg.avatar as groupAvatar')
->select();
$sceneConf['wechatGroupsOptions'] = $groupList;
}else{
$sceneConf['wechatGroupsOptions'] = [];
}
if (!empty($reqConf['deveiceGroups'])){
$deveiceGroupsOptions = DeviceModel::alias('d')
->field([
'd.id', 'd.imei', 'd.memo', 'd.alive',
'l.wechatId',
'a.nickname', 'a.alias', '0 totalFriend'
])
->leftJoin('device_wechat_login l', 'd.id = l.deviceId and l.alive =' . DeviceWechatLoginModel::ALIVE_WECHAT_ACTIVE . ' and l.companyId = d.companyId')
->leftJoin('wechat_account a', 'l.wechatId = a.wechatId')
->order('d.id desc')
->whereIn('d.id',$reqConf['deveiceGroups'])
->select();
$reqConf['deveiceGroupsOptions'] = $deveiceGroupsOptions;
}else{
$reqConf['deveiceGroupsOptions'] = [];
}
unset(
$reqConf['device'],
$sceneConf['groupSelected'],
);
// 合并数据
$newData['messagePlans'] = $msgConf;
$newData = array_merge($newData, $sceneConf, $reqConf, $tagConf, $plan);

View File

@@ -20,21 +20,21 @@ class PostUpdateAddFriendPlanV1Controller extends Controller
{
try {
$params = $this->request->param();
// 验证必填字段
if (empty($params['planId'])) {
return ResponseHelper::error('计划ID不能为空', 400);
}
if (empty($params['name'])) {
return ResponseHelper::error('计划名称不能为空', 400);
}
if (empty($params['sceneId'])) {
return ResponseHelper::error('场景ID不能为空', 400);
}
if (empty($params['device'])) {
if (empty($params['deveiceGroups'])) {
return ResponseHelper::error('请选择设备', 400);
}
@@ -51,17 +51,23 @@ class PostUpdateAddFriendPlanV1Controller extends Controller
$msgConf = isset($params['messagePlans']) ? $params['messagePlans'] : [];
$tagConf = [
'scenarioTags' => $params['scenarioTags'] ?? [],
'customTags' => $params['customTags'] ?? [],
'customTags' => $params['customTags'] ?? [],
];
$reqConf = [
'device' => $params['device'] ?? [],
'remarkType' => $params['remarkType'] ?? '',
'greeting' => $params['greeting'] ?? '',
'device' => $params['deveiceGroups'] ?? [],
'remarkType' => $params['remarkType'] ?? '',
'greeting' => $params['greeting'] ?? '',
'addFriendInterval' => $params['addFriendInterval'] ?? '',
'startTime' => $params['startTime'] ?? '',
'endTime' => $params['endTime'] ?? '',
'startTime' => $params['startTime'] ?? '',
'endTime' => $params['endTime'] ?? '',
];
if (isset($params['wechatGroups'])){
$params['wechatGroups'] = $params['groupSelected'];
}
// 其余参数归为sceneConf
$sceneConf = $params;
unset(
@@ -75,7 +81,7 @@ class PostUpdateAddFriendPlanV1Controller extends Controller
$sceneConf['messagePlans'],
$sceneConf['scenarioTags'],
$sceneConf['customTags'],
$sceneConf['device'],
$sceneConf['deveiceGroups'],
$sceneConf['orderTableFileName'],
$sceneConf['userInfo'],
$sceneConf['textUrl'],
@@ -89,162 +95,236 @@ class PostUpdateAddFriendPlanV1Controller extends Controller
// 构建更新数据
$data = [
'name' => $params['name'],
'sceneId' => $params['sceneId'],
'name' => $params['name'],
'sceneId' => $params['sceneId'],
'sceneConf' => json_encode($sceneConf, JSON_UNESCAPED_UNICODE),
'reqConf' => json_encode($reqConf, JSON_UNESCAPED_UNICODE),
'msgConf' => json_encode($msgConf, JSON_UNESCAPED_UNICODE),
'tagConf' => json_encode($tagConf, JSON_UNESCAPED_UNICODE),
'updateTime'=> time(),
'reqConf' => json_encode($reqConf, JSON_UNESCAPED_UNICODE),
'msgConf' => json_encode($msgConf, JSON_UNESCAPED_UNICODE),
'tagConf' => json_encode($tagConf, JSON_UNESCAPED_UNICODE),
'updateTime' => time(),
];
try {
// 更新数据
$result = Db::name('customer_acquisition_task')
->where('id', $params['planId'])
->update($data);
if ($result === false) {
throw new \Exception('更新计划失败');
}
//订单
if($params['sceneId'] == 2){
if(!empty($params['orderTableFile'])){
// 先下载到本地临时文件,再分析,最后删除
$originPath = $params['orderTableFile'];
$tmpFile = tempnam(sys_get_temp_dir(), 'order_');
// 判断是否为远程文件
if (preg_match('/^https?:\/\//i', $originPath)) {
// 远程URL下载到本地
$fileContent = file_get_contents($originPath);
if ($fileContent === false) {
exit('远程文件下载失败: ' . $originPath);
}
file_put_contents($tmpFile, $fileContent);
} else {
// 本地文件直接copy
if (!file_exists($originPath)) {
exit('文件不存在: ' . $originPath);
}
copy($originPath, $tmpFile);
//订单
if ($params['sceneId'] == 2) {
if (!empty($params['orderTableFile'])) {
// 先下载到本地临时文件,再分析,最后删除
$originPath = $params['orderTableFile'];
$tmpFile = tempnam(sys_get_temp_dir(), 'order_');
// 判断是否为远程文件
if (preg_match('/^https?:\/\//i', $originPath)) {
// 远程URL下载到本地
$fileContent = file_get_contents($originPath);
if ($fileContent === false) {
exit('远程文件下载失败: ' . $originPath);
}
file_put_contents($tmpFile, $fileContent);
} else {
// 本地文件直接copy
if (!file_exists($originPath)) {
exit('文件不存在: ' . $originPath);
}
copy($originPath, $tmpFile);
}
// 解析临时文件
$ext = strtolower(pathinfo($originPath, PATHINFO_EXTENSION));
$rows = [];
if (in_array($ext, ['xls', 'xlsx'])) {
// 直接用composer自动加载的PHPExcel
$excel = \PHPExcel_IOFactory::load($tmpFile);
$sheet = $excel->getActiveSheet();
$data = $sheet->toArray();
if (count($data) > 1) {
array_shift($data); // 去掉表头
}
// 解析临时文件
$ext = strtolower(pathinfo($originPath, PATHINFO_EXTENSION));
$rows = [];
if (in_array($ext, ['xls', 'xlsx'])) {
// 直接用composer自动加载的PHPExcel
$excel = \PHPExcel_IOFactory::load($tmpFile);
$sheet = $excel->getActiveSheet();
$data = $sheet->toArray();
if (count($data) > 1) {
array_shift($data); // 去掉表头
}
foreach ($data as $cols) {
$rows[] = [
'name' => isset($cols[0]) ? trim($cols[0]) : '',
'phone' => isset($cols[1]) ? trim($cols[1]) : '',
'wechat' => isset($cols[2]) ? trim($cols[2]) : '',
'source' => isset($cols[3]) ? trim($cols[3]) : '',
'orderAmount' => isset($cols[4]) ? trim($cols[4]) : '',
'orderDate' => isset($cols[5]) ? trim($cols[5]) : '',
];
}
} elseif ($ext === 'csv') {
$content = file_get_contents($tmpFile);
$lines = preg_split('/\r\n|\r|\n/', $content);
if (count($lines) > 1) {
array_shift($lines); // 去掉表头
foreach ($lines as $line) {
if (trim($line) === '') continue;
$cols = str_getcsv($line);
if (count($cols) >= 6) {
$rows[] = [
'name' => isset($cols[0]) ? trim($cols[0]) : '',
'phone' => isset($cols[1]) ? trim($cols[1]) : '',
'wechat' => isset($cols[2]) ? trim($cols[2]) : '',
'source' => isset($cols[3]) ? trim($cols[3]) : '',
'orderAmount' => isset($cols[4]) ? trim($cols[4]) : '',
'orderDate' => isset($cols[5]) ? trim($cols[5]) : '',
];
}
foreach ($data as $cols) {
$rows[] = [
'name' => isset($cols[0]) ? trim($cols[0]) : '',
'phone' => isset($cols[1]) ? trim($cols[1]) : '',
'wechat' => isset($cols[2]) ? trim($cols[2]) : '',
'source' => isset($cols[3]) ? trim($cols[3]) : '',
'orderAmount' => isset($cols[4]) ? trim($cols[4]) : '',
'orderDate' => isset($cols[5]) ? trim($cols[5]) : '',
];
}
} elseif ($ext === 'csv') {
$content = file_get_contents($tmpFile);
$lines = preg_split('/\r\n|\r|\n/', $content);
if (count($lines) > 1) {
array_shift($lines); // 去掉表头
foreach ($lines as $line) {
if (trim($line) === '') continue;
$cols = str_getcsv($line);
if (count($cols) >= 6) {
$rows[] = [
'name' => isset($cols[0]) ? trim($cols[0]) : '',
'phone' => isset($cols[1]) ? trim($cols[1]) : '',
'wechat' => isset($cols[2]) ? trim($cols[2]) : '',
'source' => isset($cols[3]) ? trim($cols[3]) : '',
'orderAmount' => isset($cols[4]) ? trim($cols[4]) : '',
'orderDate' => isset($cols[5]) ? trim($cols[5]) : '',
];
}
}
} else {
unlink($tmpFile);
exit('暂不支持的文件类型: ' . $ext);
}
// 删除临时文件
} else {
unlink($tmpFile);
exit('暂不支持的文件类型: ' . $ext);
}
// 删除临时文件
unlink($tmpFile);
// 1000条为一组进行批量处理
$batchSize = 1000;
$totalRows = count($rows);
for ($i = 0; $i < $totalRows; $i += $batchSize) {
$batchRows = array_slice($rows, $i, $batchSize);
if (!empty($batchRows)) {
// 1. 提取当前批次的phone
$phones = [];
foreach ($batchRows as $row) {
$phone = !empty($row['phone']) ? $row['phone'] : $row['wechat'];
if (!empty($phone)) {
$phones[] = $phone;
}
}
// 2. 批量查询已存在的phone
$existingPhones = [];
if (!empty($phones)) {
$existing = Db::name('task_customer')
->where('task_id', $params['planId'])
->where('phone', 'in', $phones)
->field('phone')
->select();
$existingPhones = array_column($existing, 'phone');
}
// 3. 过滤出新数据,批量插入
$newData = [];
foreach ($batchRows as $row) {
$phone = !empty($row['phone']) ? $row['phone'] : $row['wechat'];
if (!empty($phone) && !in_array($phone, $existingPhones)) {
$newData[] = [
'task_id' => $params['planId'],
'name' => $row['name'] ?? '',
'source' => $row['source'] ?? '',
'phone' => $phone,
'tags' => json_encode([], JSON_UNESCAPED_UNICODE),
'siteTags' => json_encode([], JSON_UNESCAPED_UNICODE),
'createTime' => time(),
];
}
}
// 4. 批量插入新数据
if (!empty($newData)) {
Db::name('task_customer')->insertAll($newData);
// 1000条为一组进行批量处理
$batchSize = 1000;
$totalRows = count($rows);
for ($i = 0; $i < $totalRows; $i += $batchSize) {
$batchRows = array_slice($rows, $i, $batchSize);
if (!empty($batchRows)) {
// 1. 提取当前批次的phone
$phones = [];
foreach ($batchRows as $row) {
$phone = !empty($row['phone']) ? $row['phone'] : $row['wechat'];
if (!empty($phone)) {
$phones[] = $phone;
}
}
// 2. 批量查询已存在的phone
$existingPhones = [];
if (!empty($phones)) {
$existing = Db::name('task_customer')
->where('task_id', $params['planId'])
->where('phone', 'in', $phones)
->field('phone')
->select();
$existingPhones = array_column($existing, 'phone');
}
// 3. 过滤出新数据,批量插入
$newData = [];
foreach ($batchRows as $row) {
$phone = !empty($row['phone']) ? $row['phone'] : $row['wechat'];
if (!empty($phone) && !in_array($phone, $existingPhones)) {
$newData[] = [
'task_id' => $params['planId'],
'name' => $row['name'] ?? '',
'source' => $row['source'] ?? '',
'phone' => $phone,
'tags' => json_encode([], JSON_UNESCAPED_UNICODE),
'siteTags' => json_encode([], JSON_UNESCAPED_UNICODE),
'createTime' => time(),
];
}
}
// 4. 批量插入新数据
if (!empty($newData)) {
Db::name('task_customer')->insertAll($newData);
}
}
}
}
}
//群获客
if ($params['sceneId'] == 7) {
if (!empty($params['groupSelected']) && is_array($params['groupSelected'])) {
$rows = Db::name('wechat_group_member')->alias('gm')
->join('wechat_account wa', 'gm.identifier = wa.wechatId')
->where('gm.companyId', $this->getUserInfo('companyId'))
->whereIn('gm.groupId', $params['groupSelected'])
->group('gm.identifier')
->column('wa.id,wa.wechatId,wa.alias,wa.phone');
// 1000条为一组进行批量处理
$batchSize = 1000;
$totalRows = count($rows);
for ($i = 0; $i < $totalRows; $i += $batchSize) {
$batchRows = array_slice($rows, $i, $batchSize);
if (!empty($batchRows)) {
// 1. 提取当前批次的phone
$phones = [];
foreach ($batchRows as $row) {
if (!empty($row['phone'])) {
$phone = !empty($row['phone']);
} elseif (!empty($row['alias'])) {
$phone = $row['alias'];
} else {
$phone = $row['wechatId'];
}
if (!empty($phone)) {
$phones[] = $phone;
}
}
// 2. 批量查询已存在的phone
$existingPhones = [];
if (!empty($phones)) {
$existing = Db::name('task_customer')
->where('task_id', $params['planId'])
->where('phone', 'in', $phones)
->field('phone')
->select();
$existingPhones = array_column($existing, 'phone');
}
// 3. 过滤出新数据,批量插入
$newData = [];
foreach ($batchRows as $row) {
if (!empty($row['phone'])) {
$phone = !empty($row['phone']);
} elseif (!empty($row['alias'])) {
$phone = $row['alias'];
} else {
$phone = $row['wechatId'];
}
if (!empty($phone) && !in_array($phone, $existingPhones)) {
$newData[] = [
'task_id' => $params['planId'],
'name' => '',
'source' => '场景获客_' . $params['name'] ?? '',
'phone' => $phone,
'tags' => json_encode([], JSON_UNESCAPED_UNICODE),
'siteTags' => json_encode([], JSON_UNESCAPED_UNICODE),
'createTime' => time(),
];
}
}
// 4. 批量插入新数据
if (!empty($newData)) {
Db::name('task_customer')->insertAll($newData);
}
}
}
}
}
return ResponseHelper::success(['planId' => $params['planId']], '更新计划任务成功');
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
throw $e;
}
} catch (\Exception $e) {
return ResponseHelper::error('系统错误: ' . $e->getMessage(), 500);
}