12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190 |
- <?php
- namespace App\Service;
- use App\Log;
- use App\Models\CustomerDetails;
- use App\Models\DjUser;
- use App\Models\Es\PeriodMassMsgSendDetailEs;
- use App\Models\PeriodMassMsg\PeriodMassMsg;
- use App\Models\PeriodMassMsg\PeriodMassMsgConf;
- use App\Models\PeriodMassMsg\PeriodMassMsgGroup;
- use App\Models\PeriodMassMsg\PeriodMassMsgRecord;
- use App\Models\PeriodMassMsg\PeriodMassMsgTemplate;
- use App\Models\PeriodMassMsg\PeriodTempGroup;
- use App\Models\System\Users;
- use App\Support\EmailQueue;
- use Illuminate\Support\Facades\DB;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- class PeriodMassMsgService
- {
- public static function setRule($ruleId, $params)
- {
- try {
- # 获取分组对应的客服配置
- $userConfig = PeriodMassMsgGroup::where('id', $params['group_id'])->first();
- if(empty($userConfig)) return 5224;
- if(!$userConfig->corpid) {
- $ruleDetail = PeriodMassMsg::where('enable', 1)->where('status', 1)->where('group_id', $params['group_id'])
- ->where('corpid', '>', '')->orderBy('updated_at', 'desc')->first();
- if(!empty($ruleDetail)) {
- $userConfig->operate_type = $ruleDetail->operate_type;
- $userConfig->is_operation = $ruleDetail->is_operation;
- $userConfig->operator_group_id = $ruleDetail->operator_group_id;
- $userConfig->corpid = $ruleDetail->corpid;
- $userConfig->is_all = $ruleDetail->is_all;
- $userConfig->senders = $ruleDetail->senders;
- }
- }
- $params['operate_type'] = $userConfig->operate_type;
- $params['is_operation'] = $userConfig->is_operation;
- $params['operator_group_id'] = $userConfig->operator_group_id;
- $params['multiple_senders'] = $userConfig->senders;
- $params['is_all'] = $userConfig->is_all;
- $params['corpid'] = $userConfig->corpid;
-
- if(2 == $params['operate_type']){
- if(1 == $params['is_operation']) {
- $senders = MassMsgRuleService::getSenderListByOperatorGroupId($params['operator_group_id']);
- $params['senders'] = '';
- } else {
- $senders = json_decode($params['multiple_senders'], 1);
- $params['senders'] = $params['multiple_senders'];
- }
- $corpIdList = MassMsgRuleService::getCorpIdListBySenders($senders);
- $params['corpid'] = implode(',', $corpIdList);
- } else {
- # 校验附件信息合法性
- $attachmentsVerifyCode = MassMsgRuleService::attachmentsVerify($params['attachments'], $params['corpid']);
- if($attachmentsVerifyCode) return $attachmentsVerifyCode;
- $params['senders'] = $userConfig->senders;
- }
- // if(!$params['is_all'] && !$params['senders'] && !$params['is_operation']) {
- // return 2204;
- // }
- DB::beginTransaction();
- # 写入数据到period_mass_msg表
- $relationId = PeriodMassMsg::setMsgRelation($ruleId, $params);
- if(!$relationId) {
- DB::rollBack();
- return 5222;
- }
- # 设置时间规则period_mass_msg_conf表
- $confData = json_decode($params['send_conf'], true);
- foreach ($confData as $conf) {
- $confId = isset($conf['conf_id']) ? $conf['conf_id'] : 0;
- $naturalDay = $conf['natural_day'];
- $sendTime = $conf['send_time'];
- $addStartTime = null;
- $addEndTime = null;
- if($naturalDay == 1) { // 处理用户添加的时间段设置
- $addStartTime = $conf['add_start_time'] ?? null;
- $addEndTime = $conf['add_end_time'] ?? null;
- }
- # 获取下次发送时间
- if(strtotime($sendTime) >= time()) {
- $nextSendTime = date('Y-m-d') . ' ' . $sendTime;
- } else {
- $date = date('Y-m-d', strtotime('+1 day'));
- $nextSendTime = $date . ' ' . $sendTime;
- }
- $status = $conf['status'] ?? 1;
- $result = PeriodMassMsgConf::setMsg(
- $params['group_id'], $params['operate_type'], $confId, $naturalDay, $sendTime, $status, $relationId, $nextSendTime, $addStartTime, $addEndTime
- );
- if(!$result) {
- DB::rollBack();
- return 5222;
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('设置智能群发规则过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'data' => $params
- ], 'PeriodMassMsgRuleSet-Exception');
- return 5223;
- }
- return 0;
- }
- /**
- * 配置智能群发模板
- * */
- public static function setTemplate($templateId, $params)
- {
- # 写入数据到period_mass_msg_template表
- $errno = PeriodMassMsgTemplate::setMsgRelation($templateId, $params);
- return $errno;
- }
- /**
- * 获取智能群发列表
- * @param $groupId string 分组ID
- * @param $corpid string 企业ID
- * @param $creatorId integer 创建人ID集合
- * @param $createTimeStart string 创建时间查询-结束时间
- * @param $createTimeEnd string 创建时间查询-结束时间
- * @param $page integer 当前页码数
- * @param $pageSize integer 每页显示条数
- * */
- public static function ruleList($groupId, $keyword, $corpid, $creatorId, $createTimeStart,$createTimeEnd, $page, $pageSize, &$errno)
- {
- try {
- list($list, $count) = PeriodMassMsg::getRuleLists(
- $groupId, $keyword, $corpid, $creatorId, $createTimeStart, $createTimeEnd, $page, $pageSize
- );
- # 获取创建人信息
- $adminIds = $list->pluck('admin_id');
- $adminData = Users::select(['id','name'])->whereIn('id', $adminIds)->get();
- # 配置信息
- $ruleIds = $list->pluck('rule_id');
- $confList = PeriodMassMsgConf::whereIn('rule_id', $ruleIds)->where('status', 1)
- ->where('enable', 1)->get();
- # 处理数据
- foreach($list as $datum) {
- # 创建人信息
- $adminInfo = $adminData->where('id', $datum->admin_id)->first();
- $datum->creator = isset($adminInfo->name) ? $adminInfo->name : '';
- # 发送配置描述
- $desc = '';
- $sendConf = $confList->whereIn('rule_id', $datum->rule_id)->all();
- foreach ($sendConf as $conf) {
- if($conf->natural_day == 1 && $conf->add_start_time && $conf->add_end_time) {
- $desc .= '客户加客服第'.$conf->natural_day.'天,添加时间段在【'.$conf->add_start_time . '~' . $conf->add_end_time .'】的用户,当天'.$conf->send_time.'提醒发送;';
- } else {
- $desc .= '客户加客服第'.$conf->natural_day.'天,当天'.$conf->send_time.'提醒发送;';
- }
- }
- $datum->desc = $desc;
- unset($datum->admin_id);
- }
- } catch (\Exception $e) {
- Log::logError('获取智能群发列表过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- ], 'PeriodMassMsgRuleList');
- $errno = 2105;
- return [[], 0];
- }
- return [$list, $count];
- }
- /**
- * 智能群发模板列表
- * */
- public static function templateList($adminId, $sysGroupId, $groupId, $title, $createTimeStart,$createTimeEnd, $status, $page, $pageSize)
- {
- list($list, $count) = PeriodMassMsgTemplate::getTemplateLists($adminId, $sysGroupId, $groupId, $title, $createTimeStart, $createTimeEnd, $status, $page, $pageSize);
-
- # 处理数据
- foreach ($list as $item) {
- # 发送配置描述
- $desc = '';
- $sendConf = json_decode($item->send_conf, true);
- foreach ($sendConf as $conf) {
- if($conf['natural_day'] == 1 && $conf['add_start_time'] && $conf['add_end_time']) {
- $desc .= '客户加客服第'.$conf['natural_day'].'天,添加时间段在【'.$conf['add_start_time'] . '~' . $conf['add_end_time'] .'】的用户,当天'.$conf['send_time'].'提醒发送;';
- } else {
- $desc .= '客户加客服第'.$conf['natural_day'].'天,当天'.$conf['send_time'].'提醒发送;';
- }
- }
- $item->desc = $desc;
- unset($item->send_conf);
- }
- return [$list, $count];
- }
- /**
- * 获取群发详情
- * @param $corpid string 企业ID
- * @param $ruleId integer 群发规则ID
- * */
- public static function ruleDetail($corpid, $ruleId, &$errno)
- {
- try{
- $detail = PeriodMassMsg::selectRaw('id as rule_id, admin_id, corpid, name, is_all, '
- .'senders, content, attachments, status, gender, tag_screen_type, tag_list, exclude_tag_list, '
- .'pay_status, pay_num_min, pay_num_max, operate_type, operator_group_id, is_operation, group_id')
- ->where('id', $ruleId)->where('enable', 1)
- ->first();
- if(empty($detail)) return [];
- # 发送人
- if(!$detail->is_all) {
- $detail->sender_name = DjUser::query()->where("corpid",$corpid)
- ->whereIn("user_id", explode(',',$detail->senders))
- ->pluck("name");
- } else {
- $detail->sender_name = [];
- }
- # 获取创建人信息
- $detail->creator = Users::where('id', $detail->admin_id)->value('name');
- $attachments = json_decode($detail->attachments, true);
- if(!empty($attachments)) {
- foreach ($attachments as $key=>&$attachment) {
- if(isset($attachment['msgtype']) && $attachment['msgtype'] == 'radar') { // 雷达附件信息回显
- $radarId = $attachment['radar']['radar_id'] ?? 0;
- $radarInfo = RadarService::getRadarContent($corpid, $radarId);
- if(empty($radarInfo)) {
- unset($attachment[$key]);
- continue;
- }
- $attachment['radar'] = $radarInfo;
- }
- }
- }
- # 获取发送时间配置
- $confList = PeriodMassMsgConf::query()->selectRaw('id as conf_id, natural_day, send_time, status, add_start_time, add_end_time')
- ->where('rule_id', $detail->rule_id)->where('status', 1)->where('enable', 1)->get();
- $detail->send_conf = $confList;
- if($detail->operate_type == 2) {
- $detail->multiple_senders = $detail->senders;
- }
- } catch (\Exception $e) {
- Log::logError('智能群发详情获取过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'rule_id' => $ruleId
- ], 'CircleMassMsgRuleDetail');
- $errno = 2104;
- return [];
- }
- return $detail;
- }
- /**
- * 获取模板详情
- * */
- public static function templateDetail($templateId, $sysGroupId, $adminId, &$errno)
- {
- $detail = PeriodMassMsgTemplate::selectRaw('id as template_id, title, send_conf, content, attachments, group_id')
- ->where('id', $templateId)->where('sys_group_id', $sysGroupId)
- ->where('enable', 1)
- ->first();
- if(empty($detail)) {
- $errno = 4831;
- return [];
- }
- return $detail;
- }
- /**
- * 更新群发状态
- * */
- public static function updateRuleStatus($corpid, $ruleId, $status, $adminId)
- {
- # 验证规则是否存在
- $ruleExist = PeriodMassMsg::whereRaw("FIND_IN_SET('".$corpid."', `corpid`)")->where('id', $ruleId)
- ->where('enable', 1)->exists();
- if(!$ruleExist) return 2106;
- $result = PeriodMassMsg::where('id', $ruleId)->where('status', '!=', $status)->update([
- 'status' => $status, 'admin_id' => $adminId
- ]);
- if(!$result) return 2107;
- if($status == 1) { // 分组启用时重置规则下次发送时间
- $periodMassMsgConfList = PeriodMassMsgConf::where('rule_id', $ruleId)->where('enable', 1)->get();
- foreach ($periodMassMsgConfList as $item) {
- $todaySendTime = date('Y-m-d') . ' ' . $item->send_time;
- if(strtotime($todaySendTime) >= time()) {
- $nextSendTime = $todaySendTime;
- } else {
- $nextSendTime = date('Y-m-d', strtotime('+1 day')) . ' ' . $item->send_time;
- }
- PeriodMassMsgConf::where('id', $item->id)->update(['next_send_time' => $nextSendTime, 'rule_status' => $status]);
- }
- } else {
- PeriodMassMsgConf::where('rule_id', $ruleId)->where('status', '!=', $status)->update(['rule_status' => $status]);
- }
- return 0;
- }
- /**
- * 智能群发模板状态修改
- * */
- public static function templateChangeStatus($templateId, $adminId, $sysGroupId, $status)
- {
- # 验证规则是否存在
- $templateInfo = PeriodMassMsgTemplate::where('id', $templateId)->where('sys_group_id', $sysGroupId)
- ->where('enable', 1)->first();
- if(empty($templateInfo)) return 4832;
- if($templateInfo->status == $status) return 4834;
- # 变更规则状态
- $result = PeriodMassMsgTemplate::where('id', $templateId)->where('admin_id', $adminId)
- ->update(['status' => $status]);
- if(!$result) return 4833;
- return 0;
- }
- /**
- * 获取群发列表
- * @param $corpid string 企业ID
- * @param $ruleId integer
- * @param $sendTimeStart string 发送时间查询-起始时间
- * @param $sendTimeEnd string 发送时间查询-结束时间
- * @param $sortColumn string 排序字段
- * @param $sortMethod string 排序方式*
- * @param $page integer 当前页码数
- * @param $pageSize integer 每页显示条数
- * @return mixed
- * */
- public static function recordList($corpid, $ruleId, $sendTimeStart, $sendTimeEnd, $sortColumn, $sortMethod, $page, $pageSize, &$errno)
- {
- try {
- list($list, $count) = PeriodMassMsgRecord::getRecordLists($corpid, $ruleId, $sendTimeStart, $sendTimeEnd, $sortColumn, $sortMethod, $page, $pageSize);
- # 将该企微下的所有客服信息查询出来备用
- $adminData = Users::query()->select(['id','name'])->get();
- # 处理数据
- foreach($list as $datum) {
- # 解析json,读取发送规则以及标题
- $filterData = json_decode($datum->filter_data, 1);
- $adminId = $filterData['admin_id'] ?? 0;
- # 创建人信息
- $adminInfo = $adminData->where('id', $adminId)->first();
- $datum->creator = isset($adminInfo->name) ? $adminInfo->name : '';
- # 群发标题
- $datum->name = $filterData['name'] ?? '';
- # 群发规则
- $datum->rule_detail = '客户加客服第'.($filterData['natural_day'] ?? '-').'天,当天'.($filterData['time_point'] ?? '-').'提醒发送;';
- unset($datum->filter_data);
- }
- } catch (\Exception $e) {
- Log::logError('获取群发列表过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- ], 'CircleMassMsgRuleList');
- $errno = 3601;
- return [[], 0];
- }
- return [$list, $count];
- }
- /**
- * 获取群发详情
- * @param $corpid string 企业ID
- * @param $ruleId integer 群发规则ID
- * @param $sendNum integer
- * @param $sendDate string
- * @return mixed
- * */
- public static function recordDetail($corpid, $ruleId, $sendNum, $sendDate, &$errno)
- {
- try{
- $detail = [];
- # 获取发送记录
- $recordList = PeriodMassMsgRecord::selectRaw('corpid, rule_id, send_num, create_time
- , send_date, content, attachments, filter_data, status')->where('corpid', $corpid)
- ->where('rule_id', $ruleId)->where('send_num', $sendNum)
- ->where('send_date', $sendDate)->get();
- if($recordList->isEmpty()) return [];
- # 判断发送状态
- $statusList = array_column($recordList->toArray(), 'status');
- foreach($recordList as $recordInfo) {
- $detail = json_decode(json_encode($recordInfo), 1);
- }
- $detail['status'] = self::getRecordSendStatus($statusList);
- # 群发规则信息
- $ruleInfo = json_decode($detail['filter_data'], 1);
- $detail['rule_info'] = $ruleInfo;
- if($ruleInfo['is_all'] != 1 && !empty($ruleInfo['senders'])) {
- # 发送人
- $detail['sender_name'] = DjUser::query()->where("corpid",$corpid)
- ->whereIn("user_id",explode(',',$ruleInfo['senders']))
- ->pluck("name")->toArray();
- }
- # 群发规则
- $detail['rule_detail'] = '客户加客服第'.($ruleInfo['natural_day'] ?? '-').'天,当天'.($ruleInfo['time_point'] ?? '-').'提醒发送;';
- # 获取创建人信息
- $detail['creator'] = Users::query()->where('id', $ruleInfo['admin_id'])->value('name');
- # 处理附件
- $attachments = json_decode($detail['attachments'], 1);
- if(!empty($attachments)) {
- foreach ($attachments as $key=>&$attachment) {
- if(isset($attachment['msgtype']) && $attachment['msgtype'] == 'radar') { // 雷达附件信息回显
- $radarId = $attachment['radar']['radar_id'] ?? 0;
- $radarInfo = RadarService::getRadarContent($corpid, $radarId);
- if(empty($radarInfo)) {
- unset($attachment[$key]);
- continue;
- }
- $attachment['radar'] = $radarInfo;
- }
- }
- }
- # 消息条数
- $contentCount = empty($detail['content']) ? 0 : 1;
- $attachmentCount = empty($detail['attachments']) ? 0 : count($attachments);
- $detail['msg_count'] = $contentCount + $attachmentCount;
- $detail['attachments'] = json_encode($attachments, 256);
- unset($detail['filter_data']);
- } catch (\Exception $e) {
- Log::logError('群发V2详情获取过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'rule_id' => $ruleId,
- 'send_date' => $sendDate,
- 'send_num' => $sendNum,
- ], 'PeriodRecordDetail');
- $errno = 3602;
- return [];
- }
- return $detail;
- }
- public static function overview($corpid, $ruleId, $sendNum, $sendDate)
- {
- $sendRecordTotal = PeriodMassMsgRecord::where("corpid",$corpid)
- ->where("rule_id",$ruleId)->where('send_num', $sendNum)->where('send_date', $sendDate)
- ->selectRaw("count(CASE WHEN status = 1 THEN 1 END) as un_sender_count") // 未发送成员
- ->selectRaw("count(CASE WHEN status = 2 THEN 1 END) as sender_count") // 已发送成员
- ->selectRaw("sum(send_success) as send_success") // 发送成功
- ->selectRaw("sum(send_fail) as send_fail") // 未送达人数
- ->first();
- $sendRecordTotal->send_success = empty($sendRecordTotal->send_success) ? 0 : $sendRecordTotal->send_success;
- $sendRecordTotal->send_fail = empty($sendRecordTotal->send_fail) ? 0 : $sendRecordTotal->send_fail;
- $retData = [];
- #已发送人员
- $retData['executed_sender_count'] = $sendRecordTotal->sender_count;
- #发送用户
- $retData['receive_customer_count'] = $sendRecordTotal->send_success;
- #未发送成员
- $retData['un_execute_sender_count'] = $sendRecordTotal->un_sender_count;
- #未送达客户
- $retData['un_receive_customer_count'] = $sendRecordTotal->send_fail ;
- #客户接收达上限
- $retData['receive_fail_with_limit'] = PeriodMassMsgSendDetailEs::massSendCustCount($ruleId, $sendNum, $sendDate, null,3);
- #因为不是好友发送失败
- $retData['receive_fail_with_not_friend'] = PeriodMassMsgSendDetailEs::massSendCustCount($ruleId, $sendNum, $sendDate, null,4);
- return $retData;
- }
- public static function senderList($corpid, $ruleId, $sendNum, $sendDate, $type, $keyword, $page, $pageSize)
- {
- /**已发送成员统计**/
- $sendRecord = PeriodMassMsgRecord::where("corpid",$corpid)
- ->where("rule_id",$ruleId)->where('send_num', $sendNum)->where('send_date', $sendDate)
- ->select(["sender", "filter_data"])
- ->selectRaw("min(send_time) as send_time") //发送时间
- ->selectRaw("sum(send_fail) as send_fail") //失败次数
- ->selectRaw("sum(send_success) as send_success") //成功次数
- ->groupBy("sender")
- ->get()->toArray();
- $ruleInfo = isset($sendRecord[0]['filter_data']) ? json_decode($sendRecord[0]['filter_data'], 1) : [];
- $lastSendTime = isset($ruleInfo['natural_day']) ? strtotime('-'.($ruleInfo['natural_day']-1) . ' day', strtotime($sendDate . ' 00:00:00')) : null;
- if($lastSendTime) {
- $nextSendTime = strtotime('-'.($ruleInfo['natural_day']-1) . ' day', strtotime($sendDate . ' 23:59:59'));
- } else {
- $nextSendTime = null;
- }
- $sendRecord = array_column($sendRecord, null, 'sender');
- #根据查询类型不同,获取当页展示的成员ID集合
- $allSendersIdArr = [];
- switch ($type){
- case "all": //全部成员
- $allSendersIdArr = PeriodMassMsgRecord::select('sender')
- ->where("rule_id",$ruleId)
- ->where('send_num', $sendNum)
- ->where('send_date', $sendDate)
- ->pluck('sender');
- break;
- case "sent": //已发送的成员
- $allSendersIdArr = PeriodMassMsgRecord::select('sender')
- ->where("rule_id",$ruleId)
- ->where('send_num', $sendNum)
- ->where('send_date', $sendDate)
- ->where('status', 2)
- ->pluck('sender');
- break;
- case "unsent": //未发送的成员
- $allSendersIdArr = PeriodMassMsgRecord::select('sender')
- ->where("rule_id",$ruleId)
- ->where('send_num', $sendNum)
- ->where('send_date', $sendDate)
- ->where('status', 1)
- ->pluck('sender');
- break;
- case "fail": //发送失败的成员
- $allSendersIdArr = PeriodMassMsgRecord::select('sender')
- ->where("rule_id",$ruleId)
- ->where('send_num', $sendNum)
- ->where('send_date', $sendDate)
- ->where('status', -1)
- ->pluck('sender');
- break;
- }
- if(!empty($allSendersIdArr) && !is_array($allSendersIdArr)) $allSendersIdArr = $allSendersIdArr->toArray();
- /**查询发送成员**/
- $query = DjUser::query()->where("corpid",$corpid)
- ->whereIn("user_id",$allSendersIdArr);
- /**关键词查询**/
- if(!empty($keyword)){
- $query->where("name","like","%$keyword%");
- }
- $total = $query->count(); //总计总数
- $list = $query->select("user_id","name","avatar")
- ->offset(($page-1)*$pageSize)
- ->limit($pageSize)
- ->get()->toArray();
- /**查询客服对应客户数**/
- $userCustomerCountList = CustomerDetails::suffix($corpid)
- ->selectRaw('user_id, count(1) as count')
- ->where('loss_status', 1)
- ->where('corpid', $corpid)
- ->whereIn('user_id', array_column($list,'user_id'))
- ->where(function($query) use ($lastSendTime, $nextSendTime) {
- if($lastSendTime && $nextSendTime){
- $query->where('createtime', '>=', $lastSendTime)
- ->where('createtime', '<', $nextSendTime);
- }
- })
- ->groupBy('user_id')
- ->get()
- ->keyBy('user_id')
- ->toArray();
- foreach ($list as $k => $item){
- #补充最早群发时间
- $list[$k]['send_time'] = isset($sendRecord[$item['user_id']]['send_time']) ? $sendRecord[$item['user_id']]['send_time'] : '';
- #补充好友数量
- $list[$k]['customer_num'] = isset($userCustomerCountList[$item['user_id']]['count']) ? $userCustomerCountList[$item['user_id']]['count'] : 0;
- #已送达人数
- $list[$k]['send_fail'] = isset($sendRecord[$item['user_id']]['send_fail']) ? $sendRecord[$item['user_id']]['send_fail'] : 0;
- #未送达人数
- $list[$k]['send_success'] = isset($sendRecord[$item['user_id']]['send_success']) ? $sendRecord[$item['user_id']]['send_success'] : 0;
- }
- return [$total,$list];
- }
- /*
- * 群发详情-客户详情列表
- */
- public static function massSendCustList($ruleId, $sendNum, $sendDate, $sender, $name, $type, $page, $pageSize)
- {
- return PeriodMassMsgSendDetailEs::massSendCustList($ruleId, $sendNum, $sendDate, null, $sender, $name, $type, $page, $pageSize);
- }
- public static function senderListExport($corpid, $ruleId, $sendNum, $sendDate, $type,$keyword)
- {
- try {
- list($total, $list) = self::senderList($corpid, $ruleId, $sendNum, $sendDate, $type, $keyword, 1, 100000);
- $spreadSheet = new Spreadsheet();
- $sheet = $spreadSheet->getActiveSheet();
- $rowIndex = 1;
- $columnIndex = 1;
- /**设置标题**/
- $title = ['成员昵称', '群发时间', '好友数量', '已送达人数', '发送失败次数'];
- foreach ($title as $name) {
- $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $name);
- }
- /**列表内容**/
- foreach ($list as $row => $item) {
- $rowIndex++;
- $columnIndex = 1; //重置列索引
- $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $item['name']);
- $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $item['send_time']);
- $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $item['customer_num']);
- $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $item['send_success']);
- $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $item['send_fail']);
- }
- $exportType = [
- 'all' => '全部成员',
- 'sent' => '已发送成员',
- 'unsent' => '未发送成员',
- 'fail' => '发送失败成员',
- ];
- $fileNameExt = isset($exportType[$type]) ? $exportType[$type] : "列表";
- $writer = IOFactory::createWriter($spreadSheet, 'Xlsx');
- header('Content-Type:application/vnd.ms-excel');
- header('Content-Disposition:attachment;filename=客户群发成员详情导出-' . $fileNameExt . '.xlsx');
- header('Cache-Control:max-age=0');
- $writer->save('php://output');
- } catch (\Exception $e) {
- $logContent = [
- 'params' => "corpid=$corpid , ruleId=$ruleId , sendNum=$sendNum, sendDate=$sendDate, type=$type, keyword=$keyword",
- 'msg' => $e->getMessage(),
- 'line' => $e->getLine()
- ];
- EmailQueue::rPush('导出客户群发V2成员详情出现错误', json_encode($logContent), ['xiaohua.hou@kuxuan-inc.com'], '猎羽');
- return false;
- }
- }
- /*
- * 群发详情-客户详情列表
- **/
- public static function massSendCustListExport($ruleId, $sendNum, $sendDate, $sender, $name, $type)
- {
- try {
- $spreadSheet = new Spreadsheet();
- $sheet = $spreadSheet->getActiveSheet();
- $rowIndex = 1;
- $columnIndex = 1;
- /**设置标题**/
- $title = ['客户昵称','发送成员','送达时间','状态描述'];
- foreach ($title as $titleVal){
- $sheet->setCellValueByColumnAndRow($columnIndex++,$rowIndex,$titleVal);
- }
- $page = 1;
- $pageSize = 1000;
- while (1){
- list($list,$total) = PeriodMassMsgSendDetailEs::massSendCustList($ruleId, $sendNum, $sendDate, null
- , $sender, $name, $type, $page++, $pageSize);
- /**列表内容**/
- foreach ($list as $row =>$item){
- $rowIndex++;
- $columnIndex=1; //重置列索引
- $sheet->setCellValueByColumnAndRow($columnIndex++,$rowIndex,$item['external_username']);
- $sheet->setCellValueByColumnAndRow($columnIndex++,$rowIndex,$item['sender_name']);
- $sheet->setCellValueByColumnAndRow($columnIndex++,$rowIndex,$item['send_time']);
- $sheet->setCellValueByColumnAndRow($columnIndex++,$rowIndex,$item['status_description']);
- }
- if ($total<$pageSize) break; //停止游标获取完整列表
- }
- $writer = IOFactory::createWriter($spreadSheet, 'Xlsx');
- header('Content-Type:application/vnd.ms-excel');
- header('Content-Disposition:attachment;filename=客户群发详情导出.xlsx');
- header('Cache-Control:max-age=0');
- $writer->save('php://output');
- } catch(\Exception $e) {
- $logContent = [
- 'params' => " ruleId=$ruleId , sendNum=$sendNum, sendDate=$sendDate, sender=$sender , name=$name , type=$type",
- 'msg' => $e->getMessage(),
- 'line' => $e->getLine()
- ];
- EmailQueue::rPush('导出客户群发V2详情出现错误', json_encode($logContent), ['xiaohua.hou@kuxuan-inc.com'], []);
- return false;
- }
- }
- public static function getRecordSendStatus($statusList)
- {
- if(array_search('-1', $statusList)){// 含有-1(发送失败状态)
- return -1;
- } else if(array_search('1', $statusList)){// 含有1 (发送中状态)
- return 2;
- } else {// 全部为2(发送完成状态)
- return 3;
- }
- }
- public static function deleteRule($corpid, $ruleId) {
- # 验证规则是否存在
- $isExist = PeriodMassMsg::query()->where('corpid', $corpid)->where('id', $ruleId)
- ->where('enable', 1)->exists();
- if(!$isExist) return 2106;
- # 变更规则状态
- $result = PeriodMassMsg::query()->where('corpid', $corpid)->where('id', $ruleId)
- ->update(['enable' => 0, 'status' => 0]);
- if(!$result) {
- return 2107;
- }
- PeriodMassMsgConf::query()->where('rule_id', $ruleId)->where('enable', 1)
- ->where('status', 1)->update(['enable' => 0, 'status' => 0]);
- return 0;
- }
- /**
- * 批量删除智能群发模板
- * */
- public static function delTemplate($templateIds, $adminId)
- {
- $templateIds = explode(',', $templateIds);
- if(empty($templateIds)) return 4835;
- # 执行删除
- $result = PeriodMassMsgTemplate::whereIn('id', $templateIds)
- ->where('admin_id', $adminId)->where('enable', 1)
- ->update(['enable' => 0]);
- return $result ? 0 : 4836;
- }
- /**
- * 智能群发分组新建/编辑
- * */
- public static function editGroup(
- $groupId, $groupName, $sysGroupId, $adminId, $operateType, $isOperation, $operatorGroupId, $corpid,
- $isAll, $senders, $multipleSenders
- )
- {
- try {
- if(2 == $operateType){
- if(1 == $isOperation) {
- $senderList = MassMsgRuleService::getSenderListByOperatorGroupId($operatorGroupId);
- $senders = '';
- } else {
- $senderList = json_decode($multipleSenders, true);
- $senders = $multipleSenders;
- }
- $corpIdList = MassMsgRuleService::getCorpIdListBySenders($senderList);
- $corpid = implode(',', $corpIdList);
- }
- DB::beginTransaction();
- # 创建/编辑 素材组
- $errno = PeriodMassMsgGroup::editGroup(
- $groupId, $groupName, $sysGroupId, $adminId, $operateType, $isOperation, $operatorGroupId, $corpid, $isAll, $senders
- );
- if($errno) {
- DB::rollBack();
- return [0, $errno];
- }
- # 更新分组内的使用客服数据
- PeriodMassMsg::where('group_id', $groupId)->where('enable', 1)->update([
- 'operate_type' => $operateType,
- 'operator_group_id' => $operatorGroupId,
- 'is_operation' => $isOperation,
- 'corpid' => $corpid,
- 'is_all' => $isAll,
- 'senders' => $senders
- ]);
- # 更新配置表内的发送类型
- PeriodMassMsgConf::where('group_id', $groupId)->where('enable', 1)->update(['operate_type' => $operateType]);
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- EmailQueue::rPush('智能群发分组编辑出现异常', $e->getTraceAsString(), ['xiaohua.hou@kuxuan-inc.com'], '猎羽');
- Log::logError('智能群发分组编辑出现异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'group_id' => $groupId,
- 'operateType' => $operateType,
- 'isOperation' => $isOperation,
- 'operatorGroupId' => $operatorGroupId,
- 'corpid' => $corpid,
- 'isAll' => $isAll,
- 'senders' => $senders,
- ], 'PeriodEditGroup');
- return [0, 4849];
- }
- return [$groupId, $errno];
- }
- public static function groupDetail($groupId, $sysGroupId)
- {
- $detail = PeriodMassMsgGroup::selectRaw('id as group_id, operate_type, is_operation, operator_group_id, corpid, is_all, senders, title')
- ->where('id', $groupId)->where('sys_group_id', $sysGroupId)->where('enable', 1)
- ->first();
- if(!$detail->corpid) { // 历史分组数据没有使用成员信息,需进行补充
- $ruleDetail = PeriodMassMsg::where('enable', 1)->where('status', 1)->where('group_id', $groupId)
- ->where('corpid', '>', '')->orderBy('updated_at', 'desc')->first();
-
- if(!empty($ruleDetail)) {
- $detail->operate_type = $ruleDetail->operate_type;
- $detail->is_operation = $ruleDetail->is_operation;
- $detail->operator_group_id = $ruleDetail->operator_group_id;
- $detail->corpid = $ruleDetail->corpid;
- $detail->is_all = $ruleDetail->is_all;
- $detail->senders = $ruleDetail->senders;
- }
- }
- return $detail;
- }
- /**
- * 智能群发模板分组新建/编辑
- * */
- public static function editTempGroup($groupId, $groupName, $sysGroupId, $adminId)
- {
- # 创建/编辑 素材组
- $errno = PeriodTempGroup::editGroup($groupId, $groupName, $sysGroupId, $adminId);
- return [$groupId, $errno];
- }
- /**
- * 智能群发分组禁用/启用
- * */
- public static function changeGroupStatus($groupId, $adminId, $sysGroupId, $status)
- {
- try {
- DB::beginTransaction();
- # 修改分组状态
- $groupInfo = PeriodMassMsgGroup::where('id', $groupId)->where('sys_group_id', $sysGroupId)->where('enable', 1)->first();
- if(empty($groupInfo)) {
- DB::rollBack();
- return 4842;
- }
- if($groupInfo->status == $status) {
- DB::rollBack();
- return 4839;
- }
- $groupInfo->status = $status;
- if(!$groupInfo->save()) { // 状态修改失败
- DB::rollBack();
- return 4840;
- }
- # 修改分组内规则状态
- $ruleExist = PeriodMassMsg::where('group_id', $groupId)->where('status', '!=', $status)->exists();
- if($ruleExist) {
- PeriodMassMsg::where('group_id', $groupId)->where('status', '!=', $status)->update([
- 'status' => $status, 'admin_id' => $adminId
- ]);
- if($status == 1) { // 分组启用时重置规则下次发送时间
- $periodMassMsgConfList = PeriodMassMsgConf::where('group_id', $groupId)->where('enable', 1)->get();
- foreach ($periodMassMsgConfList as $item) {
- $todaySendTime = date('Y-m-d') . ' ' . $item->send_time;
- if(strtotime($todaySendTime) >= time()) {
- $nextSendTime = $todaySendTime;
- } else {
- $nextSendTime = date('Y-m-d', strtotime('+1 day')) . ' ' . $item->send_time;
- }
- PeriodMassMsgConf::where('id', $item->id)->update(['status' => $status, 'next_send_time' => $nextSendTime, 'rule_status' => $status]);
- }
- } else {
- PeriodMassMsgConf::where('group_id', $groupId)->where('status', '!=', $status)->update(['status' => $status, 'rule_status' => $status]);
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('智能群发分组状态修改流程出现异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getTraceAsString()
- ], 'PeriodMsgChangeGroupStatus');
- return 4838;
- }
- return 0;
- }
- /**
- * 模板分组禁用/启用
- * */
- public static function changeTempGroupStatus($groupId, $adminId, $sysGroupId, $status)
- {
- try {
- DB::beginTransaction();
- # 修改分组状态
- $groupInfo = PeriodTempGroup::where('id', $groupId)->where('sys_group_id', $sysGroupId)->where('enable', 1)->first();
- if(empty($groupInfo)) {
- DB::rollBack();
- return 4842;
- }
- if($groupInfo->status == $status) {
- DB::rollBack();
- return 4839;
- }
- $groupInfo->status = $status;
- if(!$groupInfo->save()) { // 状态修改失败
- DB::rollBack();
- return 4840;
- }
- # 修改分组内模板状态
- $ruleExist = PeriodMassMsgTemplate::where('group_id', $groupId)->where('status', '!=', $status)->exists();
- if($ruleExist) {
- PeriodMassMsgTemplate::where('group_id', $groupId)->where('status', '!=', $status)->update([
- 'status' => $status, 'admin_id' => $adminId
- ]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('智能群发模板分组状态修改流程出现异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getTraceAsString()
- ], 'PeriodTemplateChangeGroupStatus');
- return 4847;
- }
- return 0;
- }
- /**
- * 删除分组
- * */
- public static function delGroup($groupId, $adminId, $sysGroupId)
- {
- try {
- DB::beginTransaction();
- # 修改分组状态
- $groupInfo = PeriodMassMsgGroup::where('id', $groupId)->where('sys_group_id', $sysGroupId)->where('enable', 1)->first();
- if(empty($groupInfo)) {
- DB::rollBack();
- return 4842;
- }
- $groupInfo->enable = 0;
- $groupInfo->admin_id = $adminId;
- if(!$groupInfo->save()) { // 分组删除失败
- DB::rollBack();
- return 4843;
- }
- # 删除分组内规则
- $ruleExist = PeriodMassMsg::where('group_id', $groupId)->where('enable', 1)->exists();
- if($ruleExist) {
- PeriodMassMsg::where('group_id', $groupId)->where('enable', 1)->update(['enable' => 0]);
- PeriodMassMsgConf::where('group_id', $groupId)->where('enable', 1)->update(['enable' => 0]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('智能群发分组状态删除流程出现异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getTraceAsString()
- ], 'PeriodMsgGroupDel');
- return 4844;
- }
- return 0;
- }
- /**
- * 删除分组
- * */
- public static function delTempGroup($groupId, $adminId, $sysGroupId)
- {
- try {
- DB::beginTransaction();
- # 修改分组状态
- $groupInfo = PeriodTempGroup::where('id', $groupId)->where('sys_group_id', $sysGroupId)->where('enable', 1)->first();
- if(empty($groupInfo)) {
- DB::rollBack();
- return 4842;
- }
- $groupInfo->enable = 0;
- $groupInfo->admin_id = $adminId;
- if(!$groupInfo->save()) { // 分组删除失败
- DB::rollBack();
- return 4843;
- }
- # 删除分组内模板
- $ruleExist = PeriodMassMsgTemplate::where('group_id', $groupId)->where('enable', 1)->exists();
- if($ruleExist) {
- PeriodMassMsgTemplate::where('group_id', $groupId)->where('enable', 1)->update(['enable' => 0, 'admin_id' => $adminId]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('智能群发分组状态删除流程出现异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getTraceAsString()
- ], 'PeriodMsgGroupDel');
- return 4844;
- }
- return 0;
- }
- /**
- * 获取分组列表
- * */
- public static function groupList($sysGroupId, $creatorId, $status, $keyword, $createTimeStart, $createTimeEnd, $page, $pageSize, &$errno)
- {
- list($list, $count) = PeriodMassMsgGroup::getGroupList(
- $sysGroupId, $creatorId, $status, $keyword, $createTimeStart, $createTimeEnd, $page, $pageSize
- );
- if(!$count) return [[], 0];
- # 获取创建人信息
- $adminIds = $list->pluck('admin_id');
- $adminData = Users::select(['id','name'])->whereIn('id', $adminIds)->get();
- foreach ($list as $datum) {
- # 创建人信息
- $adminInfo = $adminData->where('id', $datum->admin_id)->first();
- $datum->creator = isset($adminInfo->name) ? $adminInfo->name : '';
- unset($datum->admin_id);
- }
- return [$list, $count];
- }
- /**
- * 获取分组列表
- * */
- public static function tempGroupList($sysGroupId, $creatorId, $status, $keyword, $createTimeStart, $createTimeEnd, $page, $pageSize, &$errno)
- {
- list($list, $count) = PeriodTempGroup::getGroupList(
- $sysGroupId, $creatorId, $status, $keyword, $createTimeStart, $createTimeEnd, $page, $pageSize
- );
- if(!$count) return [[], 0];
- # 获取创建人信息
- $adminIds = $list->pluck('admin_id');
- $adminData = Users::select(['id','name'])->whereIn('id', $adminIds)->get();
- foreach ($list as $datum) {
- # 创建人信息
- $adminInfo = $adminData->where('id', $datum->admin_id)->first();
- $datum->creator = isset($adminInfo->name) ? $adminInfo->name : '';
- unset($datum->admin_id);
- }
- return [$list, $count];
- }
- /**
- * 批量移动分组
- * */
- public static function changeGroupBatch($groupId, $sysGroupId, $adminId, $ruleIds)
- {
- $ruleIds = explode(',', $ruleIds);
- if(empty($ruleIds)) return 4841;
- # 判断分组是否存在
- $isExist = PeriodMassMsgGroup::where('sys_group_id', $sysGroupId)->where('enable', 1)->where('id', $groupId)->exists();
- if(!$isExist) return 4842;
- # 移动分组
- PeriodMassMsg::whereIn('id', $ruleIds)->update(['group_id' => $groupId, 'admin_id' => $adminId]);
- PeriodMassMsgConf::whereIn('rule_id', $ruleIds)->update(['group_id' => $groupId]);
- return 0;
- }
- /**
- * 批量移动模板分组
- * */
- public static function changeTempGroupBatch($groupId, $sysGroupId, $adminId, $ruleIds)
- {
- $ruleIds = explode(',', $ruleIds);
- if(empty($ruleIds)) return 4848;
- # 判断分组是否存在
- $isExist = PeriodTempGroup::where('sys_group_id', $sysGroupId)->where('enable', 1)->where('id', $groupId)->exists();
- if(!$isExist) return 4842;
- # 移动分组
- PeriodMassMsgTemplate::whereIn('id', $ruleIds)->update(['group_id' => $groupId, 'admin_id' => $adminId]);
- return 0;
- }
- }
|