企微短剧业务系统

Test.php 61KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\EsModel;
  4. use App\Log;
  5. use App\Models\AdqPlayletTrendData;
  6. use App\Models\AdqUser;
  7. use App\Models\AuthorizeCorp;
  8. use App\Models\BlackListRecord;
  9. use App\Models\ChatGroupMassMsg;
  10. use App\Models\ChatGroupMassMsgLog;
  11. use App\Models\Customer;
  12. use App\Models\CustomerDetails;
  13. use App\Models\DjDirectInvestmentOrder;
  14. use App\Models\DjOrder;
  15. use App\Models\DjUser;
  16. use App\Models\DramaSeries;
  17. use App\Models\DramaUserRela;
  18. use App\Models\Es\ChatGroupMassMsgLogEs;
  19. use App\Models\Es\CustomerInformationRecord;
  20. use App\Models\Es\MassMsgSendDetailEs;
  21. use App\Models\Es\PlayletAccountDataTrend;
  22. use App\Models\MassMsg;
  23. use App\Models\MassMsgRecord;
  24. use App\Models\MassMsgSendDetail;
  25. use App\Models\MassMsgSendNotice;
  26. use App\Models\MassPopularizData;
  27. use App\Models\MomentRecord;
  28. use App\Models\MomentTask;
  29. use App\Models\MpPlayletTrendData;
  30. use App\Models\OfficialAccount;
  31. use App\Models\OfficialWebUserActionSetId;
  32. use App\Models\PlatformOrderConf;
  33. use App\Models\Report\DjRegUserRangeReport;
  34. use App\Models\Report\PlayletDataTrend;
  35. use App\Models\System\AdminManageCorp;
  36. use App\Models\System\Users;
  37. use App\Models\Tencent\YxOrder;
  38. use App\Models\TencentAdAuth;
  39. use App\Models\UserOpinionFeedback;
  40. use App\RedisModel;
  41. use App\Service\Admin\AdminService;
  42. use App\Service\Admin\PermissionService;
  43. use App\Service\Admin\RoleService;
  44. use App\Service\CustomerTagService;
  45. use App\Service\DjOrderService;
  46. use App\Service\HttpService;
  47. use App\Service\JiuZhouService;
  48. use App\Service\MassMsgService;
  49. use App\Service\PitcherService;
  50. use App\Service\wechatWorkService;
  51. use App\Service\JiaShuService;
  52. use App\Service\MassMsgRuleService;
  53. use App\Support\qyApi\QyCommon;
  54. use App\Support\tencentAdSDK\ReportsOpenApi;
  55. use App\Support\tencentAdSDK\UserActionsOpenApi;
  56. use Illuminate\Console\Command;
  57. use Illuminate\Support\Facades\Hash;
  58. class Test extends Command
  59. {
  60. protected $signature = 'test {startId?}';
  61. protected $description = '测试脚本';
  62. /**
  63. * Create a new command instance.
  64. *
  65. * @return void
  66. */
  67. public function __construct()
  68. {
  69. parent::__construct();
  70. }
  71. /**
  72. * Execute the console command.
  73. *
  74. * @return mixed
  75. */
  76. public function handle()
  77. {
  78. try{
  79. // $this->getOrderCustomerInformation();
  80. # 手动回传22年部分未回传订单
  81. // $type = !empty($this->argument('type')) ? $this->argument('type') : 1;
  82. // if(1 == $type) {
  83. // # 生产
  84. // $this->adqUserActionUploadToRds();
  85. // } else {
  86. // # 消费
  87. // $this->adqUserActionUploadTest();
  88. // }
  89. // $this->xingchengAdqUserActionUploadTest();
  90. // $orderInfo = DjOrder::query()->where('order_id', $type)->first();
  91. // TencentAdAuth::intoActionAddList($orderInfo->toArray());
  92. // $this->updateMassMsgNoticeSendStatus();
  93. // $this->test();
  94. // $this->dealDepartUserRelation();
  95. // $startId = !empty($this->argument('startId')) ? $this->argument('startId') : 0;
  96. // $this->chatGroupMassMsgLogToEsTest($startId);
  97. // $this->dealBlackListCustomerTag();
  98. // $this->checkCustomerTag();
  99. // $this->sysCorpCustomerListTest();
  100. // $this->quitStaffRelationDel();
  101. $this->ECommerceUserActionsDataUpload();
  102. // $this->delRelationData();
  103. // $this->updateDataRecord();
  104. // // 获取所有已激活客服列表
  105. // $followUserList = DjUser::getUserIdList($corpid);
  106. // $followUserList = json_decode(json_encode($followUserList), 1);
  107. //
  108. // // 循环处理配置了客户联系功能的员工,拉取对应的客户信息
  109. // // 如果使用没有配置联系我的内部员工id来请求数据的话,接口会返回user_id异常的错误信息
  110. // $followUserListArr = array_chunk($followUserList, 100);
  111. // foreach ($followUserListArr as $userArr) {
  112. // $value['corpid'] = $corpid;
  113. // $value['user_list'] = $userArr;
  114. // print_r(json_encode($value));
  115. //// RedisModel::lPush(AuthorizeCorp::SYNC_CORP_CUSTOMER, json_encode($value));
  116. // }
  117. } catch (\Exception $exception) {
  118. $this->error('文件'.$exception->getFile().' 在 ' . $exception->getLine() . '行发生异常: ' . $exception->getMessage());
  119. }
  120. }
  121. public function ECommerceUserActionsDataUpload() {
  122. $orderList = YxOrder::query()->where('order_create_time', '>=', '2024-11-24')
  123. ->where('order_create_time', '<', '2024-11-25')->where('order_status', 1)->get();
  124. foreach($orderList as $orderInfo) {
  125. TencentAdAuth::intoActionAddListSecond($orderInfo->toArray());
  126. }
  127. }
  128. public function quitStaffRelationDel() {
  129. }
  130. public function delRelationData() {
  131. for($i = 0; $i < 50; $i++) {
  132. $relationList = CustomerDetails::suffix($i)->where('enable', 1)->whereIn('loss_status', [0, 1])->groupBy(['con_user_cus'])
  133. ->selectRaw('con_user_cus, count(1) as count')->having('count', '>', 1)->get();
  134. $this->info("下标 $i 查询数据 ".$relationList->count().' 条');
  135. if($relationList->isNotEmpty()) {
  136. $delIdArr = [];
  137. foreach($relationList as $relationInfo) {
  138. $dataList = CustomerDetails::suffix($i)->where('enable', 1)->whereIn('loss_status', [0, 1])
  139. ->where('con_user_cus', $relationInfo->con_user_cus)->get();
  140. $dataIdList = array_column($dataList->toArray(), 'id');
  141. $maxId = $dataList->min('id');
  142. $delIdList = array_diff($dataIdList, [$maxId]);
  143. if(!empty($delIdList)) {
  144. $delIdArr = array_merge($delIdArr, $delIdList);
  145. }
  146. }
  147. if(!empty($delIdArr)) {
  148. $this->info("下标 $i 需删除数据 ".count($delIdArr));
  149. Log::logInfo('删除数据记录', ['i' => $i, 'data' => $delIdArr], 'delRelationData');
  150. CustomerDetails::suffix($i)->whereIn('id', $delIdArr)->update(['enable' => 0]);
  151. }
  152. }
  153. }
  154. }
  155. public function updateDataRecord() {
  156. $corpid = 'ww7cfbe30100a1ba87';
  157. $userId = 'HuaMei';
  158. $externalUserId = 'wmGUoUCAAAa25mzyGEdL8XhsRMLJ1lMQ';
  159. $customerInfo = CustomerDetails::suffix($corpid)->where('corpid', $corpid)->where('user_id', $userId)->where('external_userid', $externalUserId)->first();
  160. $this->info('更新前时间为'.$customerInfo->updated_at);
  161. CustomerDetails::suffix($corpid)->updateOrCreate([
  162. 'corpid' => $corpid,
  163. 'user_id' => $userId,
  164. 'external_userid' => $externalUserId,
  165. ],[
  166. 'remark' => $customerInfo->remark,
  167. 'description' => $customerInfo->description,
  168. 'createtime' => $customerInfo->createtime,
  169. 'remark_corp_name' => $customerInfo->remark_corp_name,
  170. 'remark_mobiles' => $customerInfo->remark_mobiles,
  171. 'add_way' => $customerInfo->add_way,
  172. 'wechat_channels' => $customerInfo->wechat_channels,
  173. 'oper_userid' => $customerInfo->oper_userid,
  174. 'state' => $customerInfo->state,
  175. 'enable' => $customerInfo->enable,
  176. 'customer_id' => $customerInfo->customer_id,
  177. 'name' => $customerInfo->name,
  178. 'is_new_customer' => $customerInfo->is_new_customer,
  179. 'is_new_customer_no_loss' => $customerInfo->is_new_customer_no_loss,
  180. 'tag_list' => $customerInfo->tag_list,
  181. 'gender' => $customerInfo->gender,
  182. 'con_user_cus' => $customerInfo->con_user_cus,
  183. 'uni_customer_label' => $customerInfo->uni_customer_label,
  184. ]);
  185. $NewCustomerInfo = CustomerDetails::suffix($corpid)->where('corpid', $corpid)->where('user_id', $userId)->where('external_userid', $externalUserId)->first();
  186. $this->info('更新前时间为'.$NewCustomerInfo->updated_at);
  187. }
  188. public function sysCorpCustomerListTest() {
  189. $sysGroupId = 38;
  190. //todo 其他账号优先处理阿菜还有大浪淘沙,最后处理星橙优品
  191. # 查询杭州猎豆下的所有企微列表
  192. $corpIdList = AdminManageCorp::getSysGroupCorpList($sysGroupId);
  193. $corpDataList = AuthorizeCorp::getCorpIdList($corpIdList);
  194. # 按照企微来获取企微可见范围下的客服数据
  195. $corpDataList = json_decode(json_encode($corpDataList), 1);
  196. foreach($corpDataList as $corpid) {
  197. # 查询企微对应的客服
  198. // list($userList, $errcode) = wechatWorkService::followUserList($corpid);
  199. $userList = DjUser::getUserIdList($corpid);
  200. $userList = json_decode(json_encode($userList), 1);
  201. $count = count($userList);
  202. Log::logInfo('获取可见范围内客服列表', ['corpid' => $corpid, 'user_list' => $userList, 'user_count' => $count], 'sysCorpCustomerListTest');
  203. if(empty($userList)) {
  204. $this->info('企微【' . $corpid . '】暂无客服信息');
  205. continue;
  206. }
  207. $this->info(date('H:i') . ' 企微 ' . $corpid . ' 共查询客服 ' . $count . ' 个');
  208. foreach ($userList as $userid) {
  209. $customerCount = self::getUserCustomerCount($corpid, $userid);
  210. Log::logInfo('获取企微下的客户总数', ['corpid' => $corpid, 'user_id' => $userid, 'customer_count' => $customerCount], 'sysCorpCustomerListTest');
  211. $systemCustomerCount = CustomerDetails::suffix($corpid)->where('corpid', $corpid)->where('enable', 1)
  212. ->where('user_id', $userid)->count();
  213. Log::logInfo('获取系统内的客户总数', ['corpid' => $corpid, 'user_id' => $userid, 'customer_count' => $systemCustomerCount], 'sysCorpCustomerListTest');
  214. if($customerCount != false && $customerCount > $systemCustomerCount) {
  215. $this->info('企微【'.$corpid.'】下的客服【'.$userid.'】企微返回客户总数为'.$customerCount.',系统当前客户总数为'.$systemCustomerCount);
  216. }
  217. }
  218. }
  219. # 依次拉取客服的客户列表,获取客户总数并对比系统中的客户数与企微客户总数大小
  220. # 少于企微客户总数的客服放入待同步客户数据队列当中
  221. $this->info('处理完成');
  222. }
  223. public function getUserCustomerCount($corpid, $userId, $retry = 0) {
  224. $accessToken = AuthorizeCorp::getAccessToken($corpid);
  225. $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=$accessToken&userid=$userId";
  226. $response = HttpService::httpGet($url);
  227. if(empty($response) && $retry < 5) {
  228. $retry++;
  229. sleep(1);
  230. return self::getUserCustomerCount($corpid, $userId, $retry);
  231. }
  232. $response = json_decode($response, 1);
  233. if(isset($response['errcode']) && 0 != $response['errcode']) {
  234. if(in_array($response['errcode'], [701008, 84061])) {
  235. # 客服没有许可,客服下没有客户,
  236. return 0;
  237. }
  238. if(in_array($response['errcode'], [-1])) {
  239. $retry++;
  240. sleep(1);
  241. return self::getUserCustomerCount($corpid, $userId, $retry);
  242. }
  243. $this->error('请求企微可见客户列表失败,响应数据: '.json_encode($response));
  244. return false;
  245. }
  246. return count($response['external_userid']);
  247. }
  248. public function checkCustomerTag() {
  249. for($i = 0; $i < 50; $i++) {
  250. $totalCount = CustomerDetails::suffix($i)->count();
  251. $matchCount = CustomerDetails::suffix($i)->whereRaw('match(`tag_list`) against ("+aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" in boolean mode)')->count();
  252. if($matchCount != $totalCount) {
  253. $this->error('suffix: '.$i.' , total_count: '.$totalCount.', match_count: '.$matchCount);
  254. } else {
  255. $this->info('suffix: '.$i.' , total_count: '.$totalCount.', match_count: '.$matchCount);
  256. }
  257. }
  258. }
  259. public function dealBlackListCustomerTag() {
  260. $blackListCustomerList = BlackListRecord::query()->where('enable', 1)->get();
  261. foreach($blackListCustomerList as $blackListCustomerInfo) {
  262. RedisModel::lPush(CustomerTagService::CUSTOMER_TAG_MARK_RDS, json_encode([
  263. 'corpid' => $blackListCustomerInfo->corpid, 'user_id' => $blackListCustomerInfo->user_id
  264. , 'external_userid' => $blackListCustomerInfo->external_userid,
  265. 'type' => 2, 'tag_group_name' => '猎羽', 'tag_name_list' => ['黑名单客户']
  266. ], 256));
  267. }
  268. $feedBackCustomerList = UserOpinionFeedback::query()->select(['corpid', 'user_id', 'external_userid'])
  269. ->where('enable', 1)->groupBy(['corpid', 'user_id', 'external_userid'])->get();
  270. foreach($feedBackCustomerList as $feedBackCustomerInfo) {
  271. RedisModel::lPush(CustomerTagService::CUSTOMER_TAG_MARK_RDS, json_encode([
  272. 'corpid' => $feedBackCustomerInfo->corpid, 'user_id' => $feedBackCustomerInfo->user_id
  273. , 'external_userid' => $feedBackCustomerInfo->external_userid,
  274. 'type' => 2, 'tag_group_name' => '猎羽', 'tag_name_list' => ['投诉客户']
  275. ], 256));
  276. }
  277. }
  278. public function chatGroupMassMsgLogToEsTest($startId) {
  279. $monthArr = ['2024-02'];
  280. foreach($monthArr as $month) {
  281. $start = date('Y-m-01 00:00:00', strtotime($month));
  282. $end = date('Y-m-01 00:00:00', strtotime($month.' +1 month'));
  283. while(true) {
  284. $msgList = ChatGroupMassMsg::query()->where('send_time', '>=', $start)
  285. ->where('send_time', '<', $end)
  286. ->where('id', '>', $startId)->orderBy('id', 'asc')->limit(100)->get();
  287. if($msgList->isEmpty()) {
  288. if($month == '2024-03') {
  289. break 2;
  290. } else {
  291. break;
  292. }
  293. }
  294. $startId = $msgList->max('id');
  295. $this->info('本次查询最大ID为:'.$startId);
  296. $ruleIdList = array_column($msgList->toArray(), 'id');
  297. $list = ChatGroupMassMsgLog::query()->whereIn('rule_id', $ruleIdList)->get();
  298. $listArr = array_chunk($list->toArray(), 500);
  299. foreach($listArr as $item) {
  300. ChatGroupMassMsgLogEs::repairData($item, $month);
  301. }
  302. }
  303. }
  304. }
  305. public function dealDepartUserRelation() {
  306. # 获取企微列表
  307. $corpList = AuthorizeCorp::query()->where('enable', 1)->where('id', '>=', 19)->get();
  308. foreach($corpList as $corpInfo) {
  309. $this->info('开始处理企微 '.$corpInfo->corp_name.' 数据');
  310. # 通过企微接口查询待分配的成员以及客户列表
  311. $cursor = "";
  312. while(1) {
  313. $responseData = QyCommon::getUnassignedList($corpInfo->corpid, $cursor);
  314. if(isset($responseData['errcode']) && $responseData['errcode'] == 0) {
  315. # 处理返回的数据
  316. $newList = array_map(function($value) {
  317. return '("'.$value['handover_userid'].'","'.$value['external_userid'].'")';
  318. }, $responseData['info']);
  319. if(!empty($newList)) {
  320. CustomerDetails::suffix($corpInfo->corpid)->where('corpid', $corpInfo->corpid)
  321. ->whereRaw("(`user_id`, `external_userid`) in (".implode(',', $newList).')')
  322. ->update(['enable' => 0]);
  323. }
  324. if(empty($responseData['next_cursor'])) {
  325. // 本企微处理完成,开始处理下一个企微的数据
  326. break;
  327. } else {
  328. $cursor = $responseData['next_cursor'];
  329. }
  330. } else {
  331. $this->error('返回数据异常,错误码:'.$responseData['errcode']);
  332. break;
  333. }
  334. }
  335. }
  336. }
  337. public function updateMassMsgNoticeSendStatus() {
  338. $startId = 0;
  339. while(true) {
  340. $list = MassMsgSendNotice::query()->where('enable', 1)->where('id', '>', $startId)
  341. ->orderBy('id', 'asc')->limit(100)->get();
  342. if($list->isEmpty()) {
  343. break;
  344. }
  345. $startId = $list->max('id');
  346. foreach($list as $value) {
  347. $corpid = $value->corpid;
  348. $ruleId = $value->rule_id;
  349. $userId = $value->user_id;
  350. $this->info(date('H:i:s') . ' 开始处理规则id: '.$ruleId.' 的数据');
  351. # 防止同一个群发多个msg_id,其中某n条未执行的情况
  352. $count = MassMsgRecord::query()->where('corpid', $corpid)->where('rule_id', $ruleId)
  353. ->where('sender', $userId)->where('status', 1)->where('msg_id', '>', '')
  354. ->count();
  355. if(0 == $count) {
  356. MassMsgSendNotice::query()->where('corpid', $corpid)->where('rule_id', $ruleId)
  357. ->where('user_id', $userId)->where('msg_type', 1)->update(['send_status' => 2]);
  358. }
  359. }
  360. }
  361. $this->info('处理完成');
  362. }
  363. public function xingchengAdqUserActionUploadTest() {
  364. $accountId = '35574856';
  365. $userActionSetId = '1201835985';
  366. $accessToken = '91f6de2a626add78b141d8ea8a99e864';
  367. $platformArr = config('platform.base');
  368. $interface = 'user_actions/add';
  369. $url = 'https://api.e.qq.com/v1.3/' . $interface;
  370. $orderList = DjOrder::query()->selectRaw('order_id, ma_app_id, ma_open_id, playlet_id, playlet_name,'
  371. .'order_source, pay_money')->where('sys_group_id', 51)->where('pay_status', 1)->where('ma_app_id', '>', '')
  372. ->where('ma_open_id', '>', '')->where('order_source', 7)->orderBy('id', 'asc')->limit(500)->get();
  373. foreach($orderList as $orderInfo) {
  374. $orderInfo = $orderInfo->toArray();
  375. $wechat_app_id = $orderInfo['ma_app_id'];
  376. $wechat_openid = $orderInfo['ma_open_id'];
  377. // 用户标识
  378. $userId = array_filter([
  379. 'wechat_app_id' => $wechat_app_id,
  380. 'wechat_openid' => $wechat_openid,
  381. ]);
  382. $platform = $platformArr[$orderInfo['order_source']];
  383. $parameters = [
  384. 'account_id' => $accountId,
  385. 'user_action_set_id' => $userActionSetId,
  386. 'actions' => [
  387. [
  388. 'action_time' => time(),
  389. 'user_id' => $userId,
  390. 'action_type' => 'PURCHASE',
  391. 'action_param' => [
  392. 'value' => round($orderInfo['pay_money'] / 100),
  393. 'object' => 1,
  394. 'product_name' => empty($orderInfo['playlet_name']) ? "充值活动-{$platform}" : "{$orderInfo['playlet_name']}-{$platform}",
  395. ],
  396. 'channel' => 'TENCENT',
  397. ]
  398. ]
  399. ];
  400. if(!empty($orderInfo['playlet_id'])) {
  401. $parameters['actions'][0]['action_param']['product_id'] = $orderInfo['playlet_id'];
  402. }
  403. $parameters = json_encode($parameters);
  404. $retry = 2;
  405. do {
  406. $common_parameters = [
  407. 'access_token' => $accessToken,
  408. 'timestamp' => time(),
  409. 'nonce' => md5(uniqid('', true))
  410. ];
  411. $request_url = $url . '?' . http_build_query($common_parameters);
  412. try {
  413. $res = HttpService::httpPost($request_url, $parameters, true);
  414. } catch (\Throwable $e) {
  415. Log::logError('数据回传接口请求异常', [
  416. 'params' => json_encode($parameters),
  417. 'msg' => $e->getTraceAsString()
  418. ], 'xingchengAdqUserActionUploadTest');
  419. }
  420. $resArr = json_decode($res, true);
  421. // 记录日志
  422. Log::logInfo('数据上报API:' . $interface, [
  423. 'order_id' => $orderInfo['order_id'],
  424. 'url' => $request_url,
  425. 'params' => $parameters,
  426. 'response' => $res,
  427. ], 'xingchengAdqUserActionUploadTest');
  428. } while(($resArr['code'] != 0) && (--$retry > 0));
  429. }
  430. }
  431. public function adqUserActionUploadToRds() {
  432. $this->info('开始查询22年用户数据');
  433. $id = 2268597;
  434. $key = 'Playlet::adqUserActionUploadTest';
  435. while(true) {
  436. $orderList = DjOrder::query()->selectRaw('max(id) as id, ma_app_id, ma_open_id, pay_money, playlet_id, playlet_name, order_source, order_id')
  437. ->where('ma_app_id', '>', '')->where('ma_open_id', '>', '')
  438. ->whereRaw("`ma_user_register_time` >=(unix_timestamp('2022-01-01 00:00:00')*1000) and `ma_user_register_time` <(unix_timestamp('2023-01-01 00:00:00')*1000)" )
  439. ->where('sys_group_id', 3)->where('pay_status', 1)->where('id', '>', $id)
  440. ->groupBy('ma_open_id')->orderBy('id', 'asc')->limit(1000)->get();
  441. if($orderList->isNotEmpty()){
  442. $id = $orderList->max('id');
  443. foreach($orderList as $orderInfo) {
  444. $value = [
  445. 'order_id' => $orderInfo->order_id,
  446. 'ma_app_id' => $orderInfo->ma_app_id,
  447. 'ma_open_id' => $orderInfo->ma_open_id,
  448. 'playlet_id' => $orderInfo->playlet_id,
  449. 'playlet_name' => $orderInfo->playlet_name,
  450. 'order_source' => $orderInfo->order_source,
  451. 'pay_money' => $orderInfo->pay_money,
  452. ];
  453. RedisModel::lPush($key, json_encode($value, 256));
  454. }
  455. } else {
  456. break;
  457. }
  458. }
  459. $this->info('22年用户数据查询完成,开始查询23年用户数据');
  460. $id = 0;
  461. for($i = 1;$i<=140;$i++) {
  462. $orderList = DjOrder::query()->selectRaw('max(id) as id, ma_app_id, ma_open_id, pay_money, playlet_id, playlet_name, order_source, order_id')
  463. ->where('ma_app_id', '>', '')->where('ma_open_id', '>', '')
  464. ->whereRaw("`ma_user_register_time` >=(unix_timestamp('2023-01-01 00:00:00')*1000)" )
  465. ->where('sys_group_id', 3)->where('pay_status', 1)->where('id', '>', $id)
  466. ->groupBy('ma_open_id')->orderBy('id', 'asc')->limit(1000)->get();
  467. $id = $orderList->max('id');
  468. foreach($orderList as $orderInfo) {
  469. $value = [
  470. 'order_id' => $orderInfo->order_id,
  471. 'ma_app_id' => $orderInfo->ma_app_id,
  472. 'ma_open_id' => $orderInfo->ma_open_id,
  473. 'playlet_id' => $orderInfo->playlet_id,
  474. 'playlet_name' => $orderInfo->playlet_name,
  475. 'order_source' => $orderInfo->order_source,
  476. 'pay_money' => $orderInfo->pay_money,
  477. ];
  478. RedisModel::lPush($key, json_encode($value, 256));
  479. }
  480. }
  481. $this->info('23年用户查询完成');
  482. }
  483. public static function adqUserActionUploadTest() {
  484. # 批量查询22年未回传订单数据
  485. $accountList = [
  486. ['account_id' => '30155755', 'user_action_set_id' => '1201286910', 'access_token' => '672fc653e5b227f5faeefb88b9409ed5'],
  487. ['account_id' => '30156032', 'user_action_set_id' => '1201282364', 'access_token' => '49147257a4843bc8937ae315f1269fab'],
  488. ['account_id' => '28262322', 'user_action_set_id' => '1201136782', 'access_token' => '3439ff7e13cd061732b09bbeac495b13'],
  489. ['account_id' => '30155755', 'user_action_set_id' => '1201286910', 'access_token' => '672fc653e5b227f5faeefb88b9409ed5'],
  490. ];
  491. // $accountId = '24605135';
  492. // $userActionSetId = '1201834449';
  493. // $accessToken = 'cd3a5ab5fb0ef69340e27856cee6a41e';
  494. $platformArr = config('platform.base');
  495. $interface = 'user_actions/add';
  496. $url = 'https://api.e.qq.com/v1.3/' . $interface;
  497. $startTime = time();
  498. $key = 'Playlet::adqUserActionUploadTest';
  499. while(true) {
  500. if(time() - $startTime >= 600) {
  501. break;
  502. }
  503. $value = RedisModel::rPop($key);
  504. if(empty($value)) {
  505. sleep(1);
  506. continue;
  507. }
  508. $orderInfo = json_decode($value, 1);
  509. foreach ($accountList as $accountInfo) {
  510. $accountId = $accountInfo['account_id'];
  511. $accessToken = $accountInfo['access_token'];
  512. $userActionSetId = $accountInfo['user_action_set_id'];
  513. $wechat_app_id = $orderInfo['ma_app_id'];
  514. $wechat_openid = $orderInfo['ma_open_id'];
  515. // 用户标识
  516. $userId = array_filter([
  517. 'wechat_app_id' => $wechat_app_id,
  518. 'wechat_openid' => $wechat_openid,
  519. ]);
  520. $platform = $platformArr[$orderInfo['order_source']];
  521. $parameters = [
  522. 'account_id' => $accountId,
  523. 'user_action_set_id' => $userActionSetId,
  524. 'actions' => [
  525. [
  526. 'action_time' => time(),
  527. 'user_id' => $userId,
  528. 'action_type' => 'PURCHASE',
  529. 'action_param' => [
  530. 'value' => round($orderInfo['pay_money'] / 100),
  531. 'object' => 1,
  532. 'product_name' => empty($orderInfo['playlet_name']) ? "充值活动-{$platform}" : "{$orderInfo['playlet_name']}-{$platform}",
  533. ],
  534. 'channel' => 'TENCENT',
  535. ]
  536. ]
  537. ];
  538. if(!empty($orderInfo['playlet_id'])) {
  539. $parameters['actions'][0]['action_param']['product_id'] = $orderInfo['playlet_id'];
  540. }
  541. $parameters = json_encode($parameters);
  542. $retry = 2;
  543. do {
  544. $common_parameters = [
  545. 'access_token' => $accessToken,
  546. 'timestamp' => time(),
  547. 'nonce' => md5(uniqid('', true))
  548. ];
  549. $request_url = $url . '?' . http_build_query($common_parameters);
  550. try {
  551. $res = HttpService::httpPost($request_url, $parameters, true);
  552. } catch (\Throwable $e) {
  553. Log::logError('数据回传接口请求异常', [
  554. 'params' => json_encode($parameters),
  555. 'msg' => $e->getTraceAsString()
  556. ], 'adqUserActionUploadTest');
  557. }
  558. $resArr = json_decode($res, true);
  559. // 记录日志
  560. Log::logInfo('数据上报API:' . $interface, [
  561. 'order_id' => $orderInfo['order_id'],
  562. 'url' => $request_url,
  563. 'params' => $parameters,
  564. 'response' => $res,
  565. ], 'adqUserActionUploadTest');
  566. } while(($resArr['code'] != 0) && (--$retry > 0));
  567. }
  568. }
  569. }
  570. public function test() {
  571. try{
  572. $massMsgList = MassMsg::query()->where('send_time', '>=', '2023-12-01')->get();
  573. foreach ($massMsgList as $massMsgInfo) {
  574. $this->info('mass_msg rule_id : ' . $massMsgInfo->id);
  575. MassMsgRecord::query()->where('rule_id', $massMsgInfo->id)->update(['create_time' => $massMsgInfo->send_time]);
  576. }
  577. $this->info('开始处理客户朋友圈消息');
  578. $momentList = MomentTask::query()->where('send_time', '>=', '2023-12-01')->get();
  579. foreach($momentList as $momentInfo) {
  580. $this->info('moment rule_id : ' . $momentInfo->id);
  581. MomentRecord::query()->where('rule_id', $momentInfo->id)->update(['create_time' => $momentInfo->send_time]);
  582. }
  583. } catch (\Exception $exception) {
  584. echo $exception->getFile().'('.$exception->getLine().'):'.$exception->getMessage();
  585. }
  586. }
  587. public function writeCustomerInformationToOrder()
  588. {
  589. $date = $startDate = "2023-03-05";
  590. $endDate = "2023-03-13";
  591. while($date <= $endDate) {
  592. $filePath = storage_path('playlet/03-20/OrderUserInformationGet-'.$date.'.log');
  593. $content = file_get_contents($filePath);
  594. $list = explode(' []', $content);
  595. foreach($list as $k => $str) {
  596. if(empty($str)) {
  597. $this->info($date.'日数据处理完成');
  598. break ;
  599. }
  600. $newStr = substr($str, 64);
  601. $arr = json_decode($newStr, 1);
  602. DjOrder::query()->where('order_id', $arr['order_id'])->update([
  603. 'corp_user_id' => $arr['self_user_id']
  604. ]);
  605. }
  606. $date = date('Y-m-d', strtotime('+1 days'));
  607. }
  608. }
  609. public function updateOrderTest()
  610. {
  611. $this->info(date('H:i:s') . ' 开始处理');
  612. $id = 4119077;
  613. $num = 1;
  614. while(true) {
  615. $orderList = DjOrder::query()->select(['id', 'order_id', 'pay_money', 'origin_pay_money'])
  616. ->where('order_source', '7')
  617. ->where('id', '>', $id)
  618. ->where('sys_group_id', 3)
  619. ->orderBy('id', 'asc')
  620. ->limit(1000)->get();
  621. if($orderList->isNotEmpty()) {
  622. $id = $orderList->max('id');
  623. echo $num++;
  624. foreach($orderList as $orderInfo) {
  625. if(substr_count($orderInfo->order_id, "Virtual") >= 1) {
  626. $updateData['pay_type'] = 1;
  627. $updateData['pay_money'] = $orderInfo->origin_pay_money * 0.8;
  628. } else {
  629. $updateData['pay_type'] = 0;
  630. $updateData['pay_money'] = $orderInfo->origin_pay_money * 0.85;
  631. }
  632. DjOrder::query()->where('id', $orderInfo->id)->update($updateData);
  633. }
  634. } else {
  635. break;
  636. }
  637. sleep(1);
  638. }
  639. $this->info(date('H:i:s') . ' 处理完成');
  640. }
  641. public function getOrderCustomerInformation()
  642. {
  643. $startDate = '2023-03-15';
  644. $endDate = '2023-03-16';
  645. $date = $startDate;
  646. while($date<=$endDate) {
  647. $this->info('开始处理 ' . $date . ' 日的数据');
  648. $orderList = DjOrder::query()->selectRaw('id, order_id, mp_open_id, mp_user_register_time,'
  649. .' system_corpid, bind_app_id, corp_user_id, external_userid, order_pay_time')->where('is_ad_user', 1)
  650. ->where('create_time', '>=', $date . ' 00:00:00')->where('create_time', '<=', $date . ' 23:59:59')
  651. ->orderBy('id', 'asc')->get();
  652. if($orderList->isNotEmpty()) {
  653. foreach ($orderList as $orderInfo) {
  654. // 根据企微以及外部联系人ID查询客服ID,如果有多个客服,则将加粉时间和关注时间对比,全部对比失败时找到下单时间之前最后一个关注的客服
  655. if(empty($orderInfo->system_corpid) || empty($orderInfo->external_userid) || empty($orderInfo->mp_user_register_time)){
  656. Log::logError('缺失必要参数', json_decode(json_encode($orderInfo), 1), 'getOrderCustomerInformationTrace');
  657. continue;
  658. }
  659. $customerDetailsList = CustomerDetails::suffix($orderInfo->system_corpid)->where('corpid', $orderInfo->system_corpid)
  660. ->where('external_userid', $orderInfo->external_userid)->orderBy('createtime', 'desc')->get();
  661. if($customerDetailsList->isEmpty()) {
  662. Log::logError('查询客户详情列表为空', [
  663. 'order_info' => json_decode(json_encode($orderInfo), 1),
  664. 'customer_list' => $customerDetailsList->toArray(),
  665. ], 'getOrderCustomerInformationTrace');
  666. continue;
  667. }
  668. $selfUserId = null;
  669. foreach($customerDetailsList as $customerDetails) {
  670. if($customerDetails->createtime <= $orderInfo->mp_user_register_time/1000) {
  671. $selfUserId = $customerDetails->user_id;
  672. break;
  673. }
  674. }
  675. if(empty($selfUserId)) {
  676. Log::logError('获取企微客服失败', [
  677. 'order_info' => json_decode(json_encode($orderInfo), 1),
  678. 'customer_list' => $customerDetailsList->toArray(),
  679. ], 'getOrderCustomerInformationTrace');
  680. continue;
  681. }
  682. if(!empty($orderInfo->corp_user_id) && $orderInfo->corp_user_id != $selfUserId) {
  683. $this->error(date('H:i:s') . ' 查询客服信息与透传客服信息不一致,订单ID为:' . $orderInfo->order_id);
  684. Log::logInfo('查询客服信息与透传客服信息不一致', [
  685. 'self_user_id' => $selfUserId,
  686. 'corpid' => $orderInfo->system_corpid,
  687. 'external_userid' => $orderInfo->external_userid,
  688. 'mp_user_register_time' => $orderInfo->mp_user_register_time,
  689. 'corp_user_id' => $orderInfo->corp_user_id,
  690. 'order_id' => $orderInfo->order_id,
  691. ], 'getOrderCustomerInformationTrace');
  692. }
  693. Log::logInfo('', [
  694. 'order_id' => $orderInfo->order_id,
  695. 'bind_app_id' => $orderInfo->bind_app_id,
  696. 'mp_open_id' => $orderInfo->mp_open_id,
  697. 'mp_user_register_time' => $orderInfo->mp_user_register_time,
  698. 'self_user_id' => $selfUserId,
  699. 'system_corpid' => $orderInfo->system_corpid,
  700. ], 'OrderUserInformationGet-'.$date);
  701. }
  702. }
  703. $date = date('Y-m-d', strtotime($date . ' +1 days'));
  704. }
  705. }
  706. public function jiashuOrderUserRegisterTimeRepair()
  707. {
  708. $startId = 0;
  709. $orderPayTime = strtotime('2022-12-01 00:00:00') * 1000;
  710. $this->info(date('H:i') . ' 开始处理');
  711. while(true){
  712. $orderList = DjOrder::query()->where('sys_group_id', 3)->where('order_source', 2)
  713. ->where('order_pay_time', '>=', $orderPayTime)->where('id', '>', $startId)
  714. ->where('is_ad_user', 1)->orderBy('id', 'asc')->limit(1000)->get();
  715. if(empty($orderList)){
  716. $this->info(date('H:i') . ' 执行完成');
  717. break;
  718. }
  719. $this->info(date('H:i') . ' 本次查询数据共:' . $orderList->count() . '条');
  720. foreach($orderList as $orderInfo) {
  721. $responseData = Customer::getCustomerRegisterTime($orderInfo->system_corpid, null,
  722. $orderInfo->external_userid, null);
  723. $registerTime = $responseData['register_time'];
  724. if(!empty($registerTime)) {
  725. // 系统中没有查询到对应的注册时间,直接使用嘉书返回的时间
  726. DjOrder::query()->where('id', $orderInfo->id)->update([
  727. 'mp_user_register_time' => $registerTime * 1000
  728. ]);
  729. }
  730. $startId = $orderInfo->id;
  731. }
  732. }
  733. }
  734. public function dealTempData()
  735. {
  736. $data = \DB::table('temp')->get();
  737. $data = json_decode(json_encode($data), 1);
  738. $this->info(date('Y-m-d H:i') . ' 开始处理,本次共需要处理数据'.count($data).'条');
  739. $start = time();
  740. foreach($data as $value) {
  741. MassPopularizData::query()
  742. ->updateOrCreate([
  743. 'pid' => strval($value['pid'])
  744. ],[
  745. 'platType' => 4,
  746. 'mpAppId' => $value['maAppId'],
  747. 'popularizTitle' => $value['popularizTitle'],
  748. 'playletTitle' => $value['playletTitle']
  749. ]);
  750. }
  751. $this->info(date('Y-m-d H:i') . ' 处理完成,耗时'. (time() - $start) . '秒');
  752. }
  753. public function jiashuApiTest()
  754. {
  755. $apiKey = '5eb24c607326536d412eba0bc21018c4';
  756. $customerId = 111;
  757. # 获取产品列表信息
  758. $res = JiaShuService::getAppList($apiKey, $customerId);
  759. print_r($res);
  760. die;
  761. # 获取短剧列表
  762. $appId = '';
  763. $dramaList = JiaShuService::getContentList($apiKey, $customerId, 1, $appId);
  764. print_r($dramaList);
  765. # 获取剧集列表
  766. $videoId = '';
  767. $sectionList = JiaShuService::getSectionList($apiKey, $customerId, $appId, $videoId);
  768. print_r($sectionList);
  769. # 生成推广链接
  770. $dramaSort = '';
  771. $res = JiaShuService::savePromotion($apiKey, $customerId, $appId, $videoId, $dramaSort);
  772. print_r($res);
  773. // $this->historyOrderSave();
  774. }
  775. public function customerListSync()
  776. {
  777. $corpid = 'wwa93b0e23b7c5fe91';
  778. // $userList = DjUser::query()
  779. // ->where('corpid', $corpid)
  780. // ->get();
  781. // foreach($userList as $userInfo) {
  782. $userList = [
  783. 'XingDaiLu'
  784. ];
  785. wechatWorkService::getCustomerListByUserId($corpid,$userList);
  786. // }
  787. }
  788. public function historyOrderSave()
  789. {
  790. $startId = 0;
  791. while(true){
  792. $orderList = \DB::table('order_10_10')->where('id', '>', $startId)
  793. ->orderBy('id', 'asc')->limit(1000)->get();
  794. if($orderList->isEmpty()){
  795. return ;
  796. }
  797. $orderList = json_decode(json_encode($orderList), 1);
  798. $insertData = [];
  799. foreach($orderList as $orderInfo) {
  800. $item = [];
  801. $strArr = explode('_', $orderInfo['商户单号']);
  802. $str = $strArr[0];
  803. $str = trim($str);
  804. $orderId = substr($str, 3);
  805. $startId = $orderInfo['id'];
  806. $row = DjOrder::query()
  807. ->where('order_id', $orderId)
  808. ->where('order_source', 4)
  809. ->first();
  810. if(!empty($row)) {
  811. DjOrder::query()->where('id', $row->id)->update(['pay_status' => 1]);
  812. continue;
  813. }
  814. $item['order_id'] = $orderId;
  815. $item['mp_user_register_time'] = strtotime($orderInfo['用户注册时间'])*1000;
  816. $item['pay_money'] = $orderInfo['充值金额']*10000;
  817. $item['pay_status'] = 1;
  818. $item['order_source'] = 4;
  819. $item['is_ad_user'] = 0;
  820. $item['created_ts'] = strtotime($orderInfo['下单时间'])*1000;
  821. $item['order_pay_time'] = strtotime($orderInfo['完成时间'])*1000;
  822. $item['pid'] = $orderInfo['推广链接id'];
  823. $item['platform_id'] = 'test';
  824. $item['sys_group_id'] = 3;
  825. $insertData[] = $item;
  826. }
  827. DjOrder::query()->insert($insertData);
  828. }
  829. }
  830. public function playletDataDeal()
  831. {
  832. $this->info('开始处理mp数据');
  833. $mpNum = 0;
  834. $startId = 0;
  835. $startTime = time();
  836. while(true){
  837. $list = MpPlayletTrendData::query()
  838. ->select(['id', 'playlet_id', 'expense_date', 'ref_date', 'days_type', 'plat_order_type'
  839. , 'scan_follow_count', 'follow_cost', 'first_roi', 'paid', 'active_fans', 'pay_count', 'pay_user'
  840. , 'pay_money', 'pay_count_total', 'pay_user_total', 'pay_money_total', 'day_cost_cover_rate'
  841. , 'enable'])
  842. ->where('enable', 1)
  843. ->where('id', '>', $startId)
  844. ->orderBy('id', 'asc')
  845. ->limit(1000)
  846. ->get();
  847. if($list->isNotEmpty()){
  848. $startId = $list->max('id');
  849. $mpNum += count($list->toArray());
  850. $this->info('已处理'.$mpNum.'条mp数据');
  851. $insertData = [];
  852. foreach($list->toArray() as $key=>$item) {
  853. $insertData[$key] = $item;
  854. $insertData[$key]['ad_type'] = 1;
  855. unset($insertData[$key]['id']);
  856. }
  857. PlayletDataTrend::query()->insert($insertData);
  858. } else {
  859. break;
  860. }
  861. if((time() - $startTime)%60 == 0) {
  862. sleep(1);
  863. $this->info('休息一下');
  864. }
  865. }
  866. $this->info('开始处理adq数据');
  867. $adqNum = 0;
  868. $startId = 0;
  869. $startTime = time();
  870. while(true){
  871. $list = AdqPlayletTrendData::query()
  872. ->select(['id', 'playlet_id', 'expense_date', 'ref_date', 'days_type', 'plat_order_type'
  873. , 'scan_follow_count', 'follow_cost', 'first_roi', 'paid', 'active_fans', 'pay_count', 'pay_user'
  874. , 'pay_money', 'pay_count_total', 'pay_user_total', 'pay_money_total', 'day_cost_cover_rate'
  875. , 'enable'])
  876. ->where('enable', 1)
  877. ->where('id', '>', $startId)
  878. ->orderBy('id', 'asc')
  879. ->limit(1000)
  880. ->get();
  881. if($list->isNotEmpty()){
  882. $startId = $list->max('id');
  883. $adqNum += count($list->toArray());
  884. $this->info('已处理'.$adqNum.'条adq数据');
  885. $insertData = [];
  886. foreach($list->toArray() as $key=>$item) {
  887. $insertData[$key] = $item;
  888. $insertData[$key]['ad_type'] = 2;
  889. unset($insertData[$key]['id']);
  890. }
  891. PlayletDataTrend::query()->insert($insertData);
  892. } else {
  893. break;
  894. }
  895. if((time() - $startTime)%60 == 0) {
  896. sleep(1);
  897. $this->info('休息一下');
  898. }
  899. }
  900. }
  901. public function userActionsUpload()
  902. {
  903. $orderList = DjOrder::query()
  904. ->whereRaw("adq_account_id ='35509830' and mp_user_register_time >= (unix_timestamp('2024-01-19 00:00:00')*1000) and pay_status =1")->get();
  905. foreach($orderList as $orderInfo) {
  906. $this->info('开始处理订单 '.$orderInfo->order_id.' 的数据');
  907. $orderData = $orderInfo->toArray();
  908. $orderData['ignore_black'] = 1;
  909. TencentAdAuth::intoActionAddList($orderData);
  910. }
  911. }
  912. public function adqActionUploadSecond()
  913. {
  914. $orderList = DjDirectInvestmentOrder::query()
  915. ->whereRaw("order_id in ('116334145')")
  916. ->orderBy('id' , 'desc')
  917. ->get();
  918. foreach($orderList->toArray() as $orderInfo) {
  919. $this->info('处理'.$orderInfo['id'].'的数据');
  920. TencentAdAuth::intoActionAddList(array_merge($orderInfo, ['is_direct_investment' => 1]));
  921. }
  922. }
  923. public function adqActionUpload()
  924. {
  925. $orderList = DjOrder::query()
  926. ->where('sys_group_id', 3)
  927. ->whereIn('order_source', [3])
  928. ->where('is_ad_user', 0)
  929. ->where('external_userid', '>', '')
  930. ->where('pay_status', 1)
  931. ->get();
  932. $orderList = $orderList->toArray();
  933. foreach($orderList as $orderInfo) {
  934. $orderPay = [];
  935. $params = $orderInfo['external_userid'];
  936. $params = urldecode($params);
  937. $externalUserId = null;
  938. $userId = null;
  939. if(strstr($params, '|')) {
  940. $paramsData = explode('|', $params);
  941. $systemCorpid = $paramsData[0] ?? null;
  942. $userId = $paramsData[1] ?? null;
  943. $externalUserId = $paramsData[2] ?? null;
  944. } else {
  945. continue;
  946. }
  947. $responseData = Customer::getCustomerRegisterTime($orderInfo['system_corpid'], $orderInfo['unionid'], $externalUserId, $userId);
  948. $registerTime = $responseData['register_time'];
  949. $userActionSetId = $responseData['user_action_set_id'];
  950. $accountId = $responseData['account_id'];
  951. $unionid = $responseData['unionid'];
  952. $joinType = $responseData['join_type'];
  953. $adType = $responseData['ad_type'];
  954. $selfExternalUserId = $responseData['external_userid'];
  955. if(empty($registerTime)) {
  956. $orderPay['mp_user_register_time'] = $orderInfo['mp_user_register_time'];
  957. } else {
  958. $orderPay['mp_user_register_time'] = $registerTime * 1000;
  959. $orderPay['is_ad_user'] = 1;
  960. }
  961. // 查询出的用户unionid不为空,则将查询结果替换接收到的unionid
  962. if(!empty($unionid)){
  963. $orderPay['unionid'] = $unionid;
  964. }
  965. $orderPay['bind_user_action_set_id']= $userActionSetId;
  966. $orderPay['adq_account_id'] = $accountId;
  967. $orderPay['corp_user_id'] = $userId;
  968. $orderPay['join_type'] = $joinType;
  969. $orderPay['order_type'] = empty($adType) ? 1 : $adType;// 订单类型 为空时归属为mp订单 1mp 2adq
  970. $orderPay['external_userid'] = !empty($externalUserId) ? $externalUserId : $selfExternalUserId;
  971. // 推广数据检测区分新老客户-当月下单是新客户
  972. if (isset($orderInfo['pid']) && !empty($orderInfo['pid'])) {
  973. if (
  974. isset($orderPay['mp_user_register_time'], $orderInfo['order_pay_time'])
  975. &&
  976. (!empty($orderPay['mp_user_register_time']) && !empty($orderInfo['order_pay_time']))
  977. ) {
  978. $curMonth = date('Y-m-01 00:00:00', strtotime($orderInfo['order_pay_time']));
  979. $aftMonth = date('Y-m-01 00:00:00', strtotime("+1 months", strtotime($curMonth)));
  980. $regTime = date('Y-m-d H:i:s', $orderPay['mp_user_register_time']);
  981. if ($regTime >= $curMonth && $regTime < $aftMonth) {
  982. $orderPay['p_customer_type'] = 1;// 推广数据新用户
  983. } else {
  984. $orderPay['p_customer_type'] = 2;// 推广数据老用户
  985. }
  986. }
  987. }
  988. DjOrder::query()
  989. ->where('id', $orderInfo['id'])
  990. ->update($orderPay);
  991. $this->info('订单'.$orderInfo['order_id'].'处理完成');
  992. if($orderPay['order_type'] != $orderInfo['order_type']) {
  993. $orderInfo['mp_user_register_time'] = $orderPay['mp_user_register_time'];
  994. $orderInfo['bind_user_action_set_id'] = $orderPay['bind_user_action_set_id'];
  995. $orderInfo['adq_account_id'] = $orderPay['adq_account_id'];
  996. $orderInfo['order_type'] = $orderPay['order_type'];
  997. TencentAdAuth::intoActionAddList($orderInfo);
  998. }
  999. }
  1000. }
  1001. public function getAdqDailyReports()
  1002. {
  1003. $stDate = '2022-12-14';
  1004. $enDate = '2022-12-14';
  1005. $list = TencentAdAuth::query()
  1006. ->where('enable', 1)
  1007. ->whereNull('wechat_account_id')
  1008. ->where('account_id', '26010505')
  1009. ->orderBy('id', 'ASC')
  1010. ->get();
  1011. foreach($list as $accountInfo) {
  1012. $data = [
  1013. 'account_id' => $accountInfo->account_id,
  1014. 'start_date' => $stDate,
  1015. 'end_date' => $enDate,
  1016. 'level' => 'REPORT_LEVEL_ADVERTISER',
  1017. ];
  1018. $res = ReportsOpenApi::dailyReportsGet($data);
  1019. Log::logInfo('getAdqDailyReports', [
  1020. 'params' => $data,
  1021. 'response' => (array) $res,
  1022. ], 'test');
  1023. }
  1024. }
  1025. public function ActionsUpload()
  1026. {
  1027. $upData = [
  1028. "action_time" =>1660712576,
  1029. "wechat_openid" =>"o8aSs5JC3EMDuQBx9meWk08tBvbQ",
  1030. "wechat_app_id" =>"wx1bbc441b0d86bd38",
  1031. "value" =>1990,
  1032. "product_name" =>"\u80a1\u738b\u5e9f\u5a7f-\u67da\u5b50-\u7b2c34\u96c6",
  1033. "account_id" =>"24614521",
  1034. "bind_app_id" =>"wxe56b997561a0eef3",
  1035. "user_action_set_id"=>1200707475,
  1036. "action_type" =>"PURCHASE",
  1037. "object" =>1,
  1038. "access_token" =>'23a203d24ce6ca193d187bfd5e3e9841',
  1039. ];
  1040. $res = UserActionsOpenApi::add($upData);
  1041. if ($res['status'] == 'fail') {
  1042. Log::logError('ADQ数据回传失败', [
  1043. 'actionType' => "PURCHASE",
  1044. 'parm' => json_encode($upData),
  1045. 'msg' => json_encode($res)
  1046. ], 'AdqUserActionsDataUpload');
  1047. return false;
  1048. } else {
  1049. Log::logInfo('ADQ数据回传成功', [
  1050. 'actionType' => "PURCHASE",
  1051. 'parm' => json_encode($upData),
  1052. 'msg' => json_encode($res)
  1053. ], 'AdqUserActionsDataUpload');
  1054. return true;
  1055. }
  1056. }
  1057. public function update_old_report(){
  1058. for ($check_date = strtotime("2021-11-01");$check_date<= strtotime("2022-02-01");$check_date+=86400){
  1059. $check_date_str = date("Y-m-d",$check_date);
  1060. RedisModel::lPush('Playlet::count_user_range_report',"$check_date_str|");
  1061. }
  1062. print "添加成功";
  1063. }
  1064. public function convertToOpenId($corpid)
  1065. {
  1066. $accessToken = AuthorizeCorp::getAccessToken($corpid, '测试外部联系人id转openid');
  1067. $url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/convert_to_openid?access_token='.$accessToken;
  1068. $params['external_userid'] = 'wmVZsnRgAA4Kv6AeVmZZvoF4DszKyK2w';
  1069. $result = HttpService::httpPost($url, json_encode($params), 1);
  1070. $result = json_decode($result);
  1071. dd($result);
  1072. }
  1073. public function generator($idx, $idMin, $ruleId)
  1074. {
  1075. $limit = 500;
  1076. $idMax = MassMsgSendDetail::suffix($idx)
  1077. ->where('rule_id', $ruleId)
  1078. ->where('enable', 1)
  1079. ->max('id') ?? 0;
  1080. echo $idx.'@@'.$ruleId.'@@'.$idMax.PHP_EOL;
  1081. while ($idMin < $idMax) {
  1082. $list = MassMsgSendDetail::suffix($idx)
  1083. ->where('enable', 1)
  1084. ->where('rule_id', $ruleId)
  1085. ->where('id', '>', $idMin)
  1086. ->where('id', '<=', $idMax)
  1087. ->orderBy('id', 'ASC')
  1088. ->limit(500)
  1089. ->get();
  1090. $count = $list->count();
  1091. if ($count == 0) break;
  1092. yield $list->toArray();
  1093. if ($count < $limit) break;
  1094. $idMin = $list->max('id');
  1095. }
  1096. }
  1097. public function dataToEs($listGenerator, $massMsgInfo)
  1098. {
  1099. foreach ($listGenerator as $dataList) {
  1100. // 获取客服信息
  1101. $senderIds = array_unique(array_column($dataList, 'sender'));
  1102. $userList = DjUser::query()
  1103. ->where('corpid', $massMsgInfo->corpid)
  1104. ->whereIn('user_id', $senderIds)
  1105. ->pluck('name', 'user_id');
  1106. // 获取客户信息
  1107. $externalUserids = array_unique(array_column($dataList, 'external_userid'));
  1108. $customerList = Customer::suffix($massMsgInfo->corpid)
  1109. ->select(['external_userid', 'name', 'avatar'])
  1110. ->whereIn('external_userid', $externalUserids)
  1111. ->get()->keyBy('external_userid');
  1112. MassMsgSendDetailEs::repairData($dataList, $massMsgInfo, $userList, $customerList);
  1113. }
  1114. }
  1115. public function updateOrderPCustomerType()
  1116. {
  1117. $listGenerator = $this->orderGenerator();
  1118. foreach ($listGenerator as $list) {
  1119. foreach ($list as $value) {
  1120. echo '更新开始:id:'.$value->id.PHP_EOL;
  1121. $mp_user_register_time = $value->mp_user_register_time;
  1122. $order_pay_time = $value->order_pay_time;
  1123. $cur_month = date('Y-m-01 00:00:00', intval($order_pay_time / 1000));
  1124. $aft_month = date('Y-m-01 00:00:00', strtotime("+1 months", strtotime($cur_month)));
  1125. $reg_time = date('Y-m-d H:i:s', ($mp_user_register_time / 1000));
  1126. echo 'cur_month:'.$cur_month.PHP_EOL;
  1127. echo 'aft_month:'.$aft_month.PHP_EOL;
  1128. echo 'reg_time:'.$reg_time.PHP_EOL;
  1129. if ($reg_time >= $cur_month && $reg_time < $aft_month) {
  1130. echo '更新结束:p_customer_type:1'.PHP_EOL;
  1131. $value->update(['p_customer_type' => 1]);
  1132. } else {
  1133. echo '更新结束:p_customer_type:2'.PHP_EOL;
  1134. $value->update(['p_customer_type' => 2]);
  1135. }
  1136. }
  1137. }
  1138. }
  1139. public function orderGenerator()
  1140. {
  1141. $limit = 500;
  1142. $idMin = 0;
  1143. $idMax = DjOrder::query()->whereNotNull('pid')->max('id');
  1144. while ($idMin < $idMax) {
  1145. $list = DjOrder::query()
  1146. ->whereNotNull('pid')
  1147. ->where('id', '>', $idMin)
  1148. ->where('id', '<=', $idMax)
  1149. ->orderBy('id', 'ASC')
  1150. ->limit($limit)
  1151. ->get();
  1152. $count = $list->count();
  1153. if ($count == 0) break;
  1154. yield $list;
  1155. if ($count < $limit) break;
  1156. $idMin = $list->max('id');
  1157. }
  1158. }
  1159. public function repairData()
  1160. {
  1161. $massMsgRuleList = MassMsg::query()->where('send_time', '>=', date('Y-m-d 00:00:00'))
  1162. ->where('estimated_user', 0)->where('operate_type', 1)->get();
  1163. foreach ($massMsgRuleList as $massMsgRuleInfo) {
  1164. if(2 == $massMsgRuleInfo->operate_type){
  1165. RedisModel::lPush(MassMsg::MASS_MSG_ESTIMATED_MULTIPLE_CORP_USER_COUNT_RDS, $massMsgRuleInfo->id);
  1166. } else {
  1167. RedisModel::lPush(MassMsg::MASS_MSG_ESTIMATED_USER_COUNT_RDS, $massMsgRuleInfo->id);
  1168. }
  1169. }
  1170. }
  1171. public function repairData2($listGenerator)
  1172. {
  1173. foreach ($listGenerator as $list) {
  1174. foreach ($list as $item) {
  1175. echo 'id:'.$item->id.PHP_EOL;
  1176. $dataJson = $item->attachments;
  1177. if (empty($dataJson)) continue;
  1178. $data = json_decode($dataJson, true);
  1179. if (!is_array($data)) {
  1180. Log::logError('存储的数据格式不合法', $data, 'test');
  1181. continue;
  1182. }
  1183. $pid = null;
  1184. $res = $this->drawPid($data, $pid, 'test');
  1185. if ($res) {
  1186. if (!is_null($pid)) {
  1187. $upDb['pids'] = $pid;
  1188. $item->update($upDb);
  1189. }
  1190. }
  1191. }
  1192. }
  1193. }
  1194. public function massGenerator()
  1195. {
  1196. $limit = 500;
  1197. $idMin = 0;
  1198. $idMax = MassMsg::query()->where('is_draw', 1)->max('id');
  1199. while ($idMin < $idMax) {
  1200. $list = MassMsg::query()
  1201. ->where('is_draw', 1)
  1202. ->where('id', '>', $idMin)
  1203. ->where('id', '<=', $idMax)
  1204. ->orderBy('id', 'ASC')
  1205. ->limit($limit)
  1206. ->get();
  1207. $count = $list->count();
  1208. if ($count == 0) break;
  1209. yield $list;
  1210. if ($count < $limit) break;
  1211. $idMin = $list->max('id');
  1212. }
  1213. }
  1214. public function momentGenerator()
  1215. {
  1216. $limit = 500;
  1217. $idMin = 0;
  1218. $idMax = MomentTask::query()->where('is_draw', 1)->max('id');
  1219. while ($idMin < $idMax) {
  1220. $list = MomentTask::query()
  1221. ->where('is_draw', 1)
  1222. ->where('id', '>', $idMin)
  1223. ->where('id', '<=', $idMax)
  1224. ->orderBy('id', 'ASC')
  1225. ->limit($limit)
  1226. ->get();
  1227. $count = $list->count();
  1228. if ($count == 0) break;
  1229. yield $list;
  1230. if ($count < $limit) break;
  1231. $idMin = $list->max('id');
  1232. }
  1233. }
  1234. public function drawPid($attachments, &$pid, $logName)
  1235. {
  1236. Log::logInfo('提取开始', $attachments, $logName);
  1237. $drawPids = [];
  1238. foreach ($attachments as $datum) {
  1239. if (isset($datum['msgtype'])) {
  1240. $url = null;
  1241. // 小程序
  1242. if (
  1243. ($datum['msgtype'] == 'miniprogram')
  1244. &&
  1245. isset($datum['miniprogram']['page'])
  1246. &&
  1247. !empty($datum['miniprogram']['page'])
  1248. ) {
  1249. $url = $datum['miniprogram']['page'];
  1250. }
  1251. // 链接
  1252. if (
  1253. ($datum['msgtype'] == 'link')
  1254. &&
  1255. isset($datum['link']['url'])
  1256. &&
  1257. !empty($datum['link']['url'])
  1258. ) {
  1259. $url = $datum['link']['url'];
  1260. }
  1261. // H5推广
  1262. if (
  1263. ($datum['msgtype'] == 'promote')
  1264. &&
  1265. isset($datum['promote']['jump_url'])
  1266. &&
  1267. !empty($datum['promote']['jump_url'])
  1268. ) {
  1269. $url = $datum['promote']['jump_url'];
  1270. }
  1271. // 欢迎语中的H5推广会被转换成普通链接方式
  1272. if (
  1273. ($datum['msgtype'] == 'link')
  1274. &&
  1275. isset($datum['link']['jump_url'])
  1276. &&
  1277. !empty($datum['link']['jump_url'])
  1278. ) {
  1279. $url = $datum['link']['jump_url'];
  1280. }
  1281. // 属于其他类型
  1282. if (is_null($url)) continue;
  1283. Log::logInfo('提取URL', [
  1284. 'url' => $url
  1285. ], $logName);
  1286. // 处理url
  1287. $filedExistNum = 0;
  1288. $this->dealUrl($url, $filedExistNum, $drawPids, $logName);
  1289. if ($filedExistNum > 1) {
  1290. Log::logError('提取推广链接PID存在多个字段', $datum, $logName);
  1291. return false;
  1292. }
  1293. }
  1294. // if (count($drawPids) > 1) {
  1295. // Log::logError('提取推广链接PID存在多个值', $datum, $logName);
  1296. // return false;
  1297. // }
  1298. if (!empty($drawPids)) $pid = json_encode(array_filter($drawPids));
  1299. Log::logInfo('提取结束', $attachments, $logName);
  1300. }
  1301. return true;
  1302. }
  1303. public function dealUrl($url, &$filedExistNum, &$drawPids, $logName)
  1304. {
  1305. $url = str_replace("%25", "%", $url);
  1306. $url = str_replace("&amp;", "&", $url);
  1307. $url = urldecode($url);
  1308. $urlArr = parse_url($url);
  1309. if (!isset($urlArr['query']) && empty($urlArr['query'])) return false;
  1310. Log::logInfo('提取url', [
  1311. 'url' => $url,
  1312. 'filedExistNum' => $filedExistNum,
  1313. 'drawPids' => $drawPids
  1314. ], $logName);
  1315. parse_str($urlArr['query'], $query);
  1316. // 柚子 pathId
  1317. if (isset($query['pathId']) && !empty($query['pathId'])) {
  1318. $filedExistNum ++;
  1319. $drawPids[] = $query['pathId'];
  1320. }
  1321. // 嘉书 article
  1322. if (isset($query['article']) && !empty($query['article'])) {
  1323. $filedExistNum ++;
  1324. $drawPids[] = $query['article'];
  1325. }
  1326. // 迈步 pid
  1327. if (isset($query['pid']) && !empty($query['pid'])) {
  1328. $filedExistNum ++;
  1329. $drawPids[] = $query['pid'];
  1330. }
  1331. // 点众阳光 referral_id
  1332. if (isset($query['referral_id']) && !empty($query['referral_id'])) {
  1333. $filedExistNum ++;
  1334. $drawPids[] = $query['referral_id'];
  1335. }
  1336. foreach ($query as $urlVal) {
  1337. $this->dealUrl($urlVal, $filedExistNum, $drawPids, $logName);
  1338. }
  1339. Log::logInfo('提取url结果', [
  1340. 'url' => $url,
  1341. 'filedExistNum' => $filedExistNum,
  1342. 'drawPids' => $drawPids
  1343. ], $logName);
  1344. }
  1345. }