UserClass.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. <?php
  2. namespace bizMall\user\classes;
  3. use bizMall\custom\classes\CustomClass;
  4. use bizMall\merchant\classes\MerchantAssetClass;
  5. use bizMall\merchant\classes\MerchantClass;
  6. use bizMall\user\services\UserIntegralService;
  7. use common\components\dict;
  8. use common\components\stringUtil;
  9. use common\components\util;
  10. use common\components\wxUtil;
  11. use common\services\ImageService;
  12. use common\services\xhMerchantExtendService;
  13. use common\services\xhUserCapitalService;
  14. use Yii;
  15. use bizMall\base\classes\BaseClass;
  16. class UserClass extends BaseClass
  17. {
  18. public static $baseFile = '\bizMall\user\models\User';
  19. //用户和收入来源
  20. public static $sourceType = [
  21. 2 => '朋友圈',
  22. 1 => '门店',
  23. 0 => '公众号',
  24. 3 => '淘宝',
  25. ];
  26. //用户来源分类
  27. public static $userSource = [
  28. 0 => ['name' => 'official', 'title' => '公众号'],
  29. 1 => ['name' => 'alipay', 'title' => '支付宝'],
  30. 2 => ['name' => 'mini', 'title' => '小程序'],
  31. 3 => ['name' => 'friend', 'title' => '朋友圈'],
  32. 4 => ['name' => 'meituan', 'title' => '美团'],
  33. 5 => ['name' => 'system', 'title' => '系统'],
  34. ];
  35. //用户来源分类ID
  36. public static $userSourceId = [
  37. 'official' => ['id' => 0, 'name' => 'official'],
  38. 'alipay' => ['id' => 1, 'name' => 'alipay'],
  39. 'mini' => ['id' => 2, 'name' => 'mini'],
  40. 'friend' => ['id' => 3, 'name' => 'friend'],
  41. 'meituan' => ['id' => 4, 'name' => 'meituan'],
  42. 'system' => ['id' => 5, 'name' => 'system'],
  43. ];
  44. public static function updateUserInfo($user, $data)
  45. {
  46. $userId = $user->id ?? 0;
  47. UserClass::updateById($userId, $data);
  48. //更新客户相关信息
  49. if (isset($data['name'])) {
  50. $originName = $user->name ?? '';
  51. $newName = $data['name'];
  52. if ($originName != $newName) {
  53. $customList = CustomClass::getAllByCondition(['userId' => $userId], null, '*', null, true);
  54. if (!empty($customList)) {
  55. foreach ($customList as $custom) {
  56. if ($custom->originName == $custom->name) {
  57. $custom->originName = $newName;
  58. $custom->name = $newName;
  59. } else {
  60. $custom->originName = $newName;
  61. }
  62. $custom->save();
  63. }
  64. }
  65. }
  66. unset($data['name']);
  67. }
  68. CustomClass::updateByCondition(['userId' => $userId], $data);
  69. }
  70. //组合客户基本和资产信息
  71. public static function groupUserBaseInfo($list)
  72. {
  73. //取客户资产
  74. $ids = array_column($list, 'id');
  75. $ids = array_unique($ids);
  76. $asset = UserAssetClass::getByUserIds($ids, 'userId');
  77. foreach ($list as $key => $val) {
  78. $userId = $val['id'];
  79. //访问时间
  80. $visitTime = date("m-d H:i", $val['visitTime']);
  81. if (date("m-d") == date("m-d", $val['visitTime'])) {
  82. $visitTime = '今天 ' . date("H:i", $val['visitTime']);
  83. }
  84. $list[$key]['visitTimeFormat'] = $visitTime;
  85. $list[$key]['userAsset'] = isset($asset[$userId]) ? $asset[$userId] : [];
  86. }
  87. return $list;
  88. }
  89. //获取客户基本和资产信息 ssh 2019.11.29
  90. public static function getUserInfo($id)
  91. {
  92. $list = self::getByIds([$id]);
  93. $data = self::groupUserBaseInfo($list);
  94. return current($data);
  95. }
  96. //根据手机号查询客户 ssh 2019.12.1
  97. public static function getByMobile($mobile, $sjId)
  98. {
  99. return self::getByCondition(['sjId' => $sjId, 'mobile' => $mobile]);
  100. }
  101. public static function generateUser($getUserInfo)
  102. {
  103. $date = date("Y-m-d H:i:s");
  104. $time = time();
  105. //替换掉微信名称不支持的图片
  106. $userName = isset($getUserInfo['userName']) ? preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $getUserInfo['userName']) : '';
  107. $getUserInfo['name'] = $userName;
  108. $getUserInfo['sex'] = isset($getUserInfo['sex']) ? $getUserInfo['sex'] : 0;//未知
  109. $getUserInfo['identity'] = 0;
  110. $subscribe = isset($getUserInfo['subscribe']) ? $getUserInfo['subscribe'] : 0;
  111. $getUserInfo['subscribe'] = $subscribe;
  112. $getUserInfo['status'] = 0;
  113. //默认没有完整用户信息
  114. $isFull = isset($getUserInfo['headImgUrl']) && !empty($getUserInfo['headImgUrl']) ? 1 : 0;
  115. $getUserInfo['isFull'] = $isFull;
  116. $getUserInfo['createTime'] = $date;
  117. $getUserInfo['avatar'] = '';
  118. $getUserInfo['password'] = '';
  119. $getUserInfo['payPassword'] = '';
  120. $getUserInfo['mobile'] = isset($getUserInfo['mobile']) ? $getUserInfo['mobile'] : '';
  121. $getUserInfo['addTime'] = $time;
  122. $getUserInfo['visitTime'] = $time;
  123. $getUserInfo['source'] = isset($getUserInfo['source']) ? $getUserInfo['source'] : 0;
  124. $getUserInfo['hasSubscribe'] = 0;
  125. //生成用户基础信息
  126. $user = self::add($getUserInfo, true);
  127. $userId = $user->id;
  128. if (empty($userName)) {
  129. $user->name = '游客';
  130. $user->save();
  131. }
  132. //保存头像
  133. if (isset($getUserInfo['headImgUrl']) && !empty($getUserInfo['headImgUrl'])) {
  134. if (empty($preUser) || (isset($preUser['avatar']) && empty($preUser['avatar']))) {
  135. $imgUrl = $getUserInfo['headImgUrl'];
  136. $currentImg = ImageService::generateAvatar(0, $imgUrl);
  137. if (!empty($currentImg)) {
  138. $user->avatar = $currentImg;
  139. $user->save();
  140. }
  141. }
  142. }
  143. return $user->attributes;
  144. }
  145. public static function updateUser($originalUser, $getUserInfo)
  146. {
  147. $data = [];
  148. $userId = $originalUser['id'];
  149. //替换掉微信不支持的图片
  150. $userName = isset($getUserInfo['userName']) ? preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $getUserInfo['userName']) : '';
  151. if (!empty($userName)) {
  152. $data['name'] = $userName;
  153. }
  154. if (isset($getUserInfo['openId']) && !empty($getUserInfo['openId'])) {
  155. $openId = $getUserInfo['openId'];
  156. $data['openId'] = $openId;
  157. }
  158. if (isset($getUserInfo['miniOpenId']) && !empty($getUserInfo['miniOpenId'])) {
  159. $data['miniOpenId'] = $getUserInfo['miniOpenId'];
  160. }
  161. if (isset($getUserInfo['unionId']) && !empty($getUserInfo['unionId'])) {
  162. $data['unionId'] = $getUserInfo['unionId'];
  163. }
  164. if (isset($getUserInfo['sex'])) {
  165. $data['sex'] = $getUserInfo['sex'];
  166. }
  167. if (isset($getUserInfo['subscribe'])) {
  168. $data['subscribe'] = $getUserInfo['subscribe'];
  169. }
  170. if (isset($getUserInfo['subscribeTime'])) {
  171. $data['subscribeTime'] = $getUserInfo['subscribeTime'];
  172. }
  173. if (isset($getUserInfo['alipayId']) && !empty($getUserInfo['alipayId'])) {
  174. $data['alipayId'] = $getUserInfo['alipayId'];
  175. }
  176. if (isset($getUserInfo['isFull'])) {
  177. $data['isFull'] = $getUserInfo['isFull'];
  178. }
  179. if (isset($getUserInfo['headImgUrl']) && !empty($getUserInfo['headImgUrl'])) {
  180. $data['isFull'] = 1;
  181. }
  182. self::updateById($userId, $data);
  183. $user = self::getById($userId);
  184. return $user;
  185. }
  186. public static function getByMiniOpenId($miniOpenId)
  187. {
  188. return self::getByCondition(['miniOpenId' => $miniOpenId]);
  189. }
  190. public static function getByOpenId($openId)
  191. {
  192. return self::getByCondition(['openId' => $openId]);
  193. }
  194. public static function getByUnionId($unionId)
  195. {
  196. return self::getByCondition(['unionId' => $unionId]);
  197. }
  198. //合并用户
  199. public static function mergeUser($delUser, $retainUser)
  200. {
  201. $connection = Yii::$app->db;
  202. $transaction = $connection->beginTransaction();
  203. try {
  204. $delUserId = $delUser['id'];
  205. $retainUserId = $retainUser['id'];
  206. $userName = $retainUser['userName'];
  207. $sjId = $retainUser['sjId'];
  208. //合并记录
  209. $return = UserMergeClass::add([
  210. 'delUserId' => $delUserId,
  211. 'sjId' => $sjId,
  212. 'retainUserId' => $retainUserId,
  213. 'addTime' => time(),
  214. 'createTime' => date("Y-m-d H:i:s")
  215. ]);
  216. $targetId = $return['id'];
  217. $capitalType = dict::getDict('capitalType', 'xhMergeUser', 'id');
  218. $now = time();
  219. $date = date("Y-m-d H:i:s");
  220. //数据迁移
  221. $updateData = [];
  222. $updateKey = [
  223. 'mobile',
  224. 'password',
  225. 'payPassword',
  226. 'subscribe',
  227. 'hasSubscribe',
  228. 'subscribeTime',
  229. 'alipayId',
  230. 'openId',
  231. 'miniOpenId',
  232. 'unionId',
  233. ];
  234. foreach ($updateKey as $key) {
  235. if (isset($delUser[$key]) && !empty($delUser[$key])) {
  236. $updateData[$key] = $delUser[$key];
  237. }
  238. }
  239. if (!empty($updateData)) {
  240. $updateData['visitTime'] = time();
  241. self::updateById($retainUserId, $updateData);
  242. }
  243. //资产累加
  244. $addData = [];
  245. $delUserAsset = UserAssetClass::getByUserId($delUserId);
  246. $retainUserAsset = UserAssetClass::getByUserId($retainUserId);
  247. if (!empty($delUserAsset)) {
  248. //累计消费
  249. $delTotalExpend = isset($delUserAsset['totalExpend']) ? $delUserAsset['totalExpend'] : 0;
  250. if (!empty($delTotalExpend)) {
  251. $addData['totalExpend'] = $retainUserAsset['totalExpend'] + $delTotalExpend;
  252. //变化记录要增加
  253. }
  254. //累计收入
  255. $delTotalIncome = isset($delUserAsset['totalIncome']) ? $delUserAsset['totalIncome'] : 0;
  256. if (!empty($delTotalIncome)) {
  257. $addData['totalIncome'] = $retainUserAsset['totalIncome'] + $delTotalIncome;
  258. //变化记录要增加
  259. }
  260. //累计充值
  261. $delTotalRecharge = isset($delUserAsset['totalRecharge']) ? $delUserAsset['totalRecharge'] : 0;
  262. if (!empty($delTotalRecharge)) {
  263. $addData['totalRecharge'] = $retainUserAsset['totalRecharge'] + $delTotalRecharge;
  264. //变化记录要增加
  265. }
  266. //累计购买数量
  267. $delTotalBuyNum = isset($delUserAsset['totalBuyNum']) ? $delUserAsset['totalBuyNum'] : 0;
  268. if (!empty($delTotalBuyNum)) {
  269. $addData['totalBuyNum'] = $retainUserAsset['totalBuyNum'] + $delTotalBuyNum;
  270. //变化记录要增加
  271. }
  272. //余额
  273. $delBalance = isset($delUserAsset['balance']) ? $delUserAsset['balance'] : 0;
  274. if (!empty($delBalance)) {
  275. $addData['balance'] = $retainUserAsset['balance'] + $delBalance;
  276. //变化记录要增加
  277. $userCapitalData = [
  278. 'relateId' => $targetId,
  279. 'balance' => $addData['balance'],
  280. 'totalIncome' => $retainUserAsset['totalIncome'] + $delBalance,
  281. 'totalExpend' => $retainUserAsset['totalExpend'],
  282. 'amount' => $delBalance,
  283. 'io' => 1,
  284. 'payWay' => 0,
  285. 'event' => '帐号合并',
  286. 'sjId' => $sjId,
  287. 'userId' => $retainUserId,
  288. 'alipayId' => '',
  289. 'userName' => $userName,
  290. 'operateId' => 0,
  291. 'createTime' => $date,
  292. 'addTime' => $now,
  293. 'capitalType' => $capitalType,
  294. ];
  295. xhUserCapitalService::add($userCapitalData);//用户资金流水增加
  296. }
  297. //成长值
  298. $delGrowth = isset($delUserAsset['growth']) ? $delUserAsset['growth'] : 0;
  299. if (!empty($delGrowth)) {
  300. $addData['growth'] = $retainUserAsset['growth'] + $delGrowth;
  301. //注意会员等级要进行重新计算!!!!!还有积分变化记录要增加
  302. $growthData = [
  303. 'userId' => $retainUserId,
  304. 'userName' => $userName,
  305. 'sjId' => $sjId,
  306. 'relateId' => $targetId,
  307. 'integral' => $addData['growth'],
  308. 'num' => $delGrowth,
  309. 'io' => 1,
  310. 'payWay' => 0,
  311. 'alipayId' => '',
  312. 'event' => '帐号合并',
  313. 'operatorId' => 0,
  314. 'createTime' => $date,
  315. 'capitalType' => $capitalType,
  316. 'addTime' => $now,
  317. ];
  318. UserGrowthClass::add($growthData);
  319. //成长值增加升级
  320. $preLevel = $retainUserAsset['member'];
  321. $preGrowth = $retainUserAsset['growth'];
  322. $merchantExtend = xhMerchantExtendService::getBySjId($sjId);
  323. UserIntegralService::increaseToUpgrade($preGrowth, $addData['growth'], $preLevel, $retainUserId, $sjId, $merchantExtend);
  324. }
  325. if (!empty($addData)) {
  326. UserAssetClass::updateByUserId($retainUserId, $addData);
  327. }
  328. }
  329. //删除用户
  330. $clearData = ['openId' => '', 'miniOpenId' => '', 'unionId' => '', 'alipayId' => '', 'sjId' => 0, 'mobile' => ''];
  331. self::updateById($delUserId, $clearData);
  332. UserAssetClass::updateByUserId($delUserId, ['sjId' => 0]);
  333. //如果有支付宝信息则清除支付宝用户
  334. UserAlipayClass::updateByUserId($delUserId, ['alipayId' => '', 'alipayAccount' => '', 'sjId' => 0]);
  335. //合并帐号减少客户数 ssh 2020.5.13
  336. MerchantAssetClass::mergeToReduceUser($sjId);
  337. $transaction->commit();
  338. return self::getById($retainUserId);
  339. } catch (Exception $e) {
  340. $transaction->rollBack();
  341. Yii::info("合并userid $delUserId $retainUserId 时事务回滚,原因:" . $e->getMessage());
  342. return [];
  343. }
  344. }
  345. //找出相同unionId的用户
  346. public static function getSameUnionId($unionId)
  347. {
  348. return self::getAllByCondition(['unionId' => $unionId], 'addTime desc', '*', 'id');
  349. }
  350. public static function valid($info, $sjId)
  351. {
  352. if (empty($info)) {
  353. util::fail('找不到客户');
  354. }
  355. if ($info['sjId'] != $sjId) {
  356. util::fail('这个客户您无法操作');
  357. }
  358. }
  359. //根据消费次数和有没领优惠券来判断是不是新人
  360. public static function newUser($userInfo)
  361. {
  362. $asset = isset($userInfo['userAsset']) ? $userInfo['userAsset'] : [];
  363. $totalBuyNum = isset($asset['totalBuyNum']) ? $asset['totalBuyNum'] : 0;
  364. if ($totalBuyNum > 0) {
  365. return false;
  366. }
  367. $getCouponNum = isset($asset['getCouponNum']) ? $asset['getCouponNum'] : 0;
  368. if ($getCouponNum) {
  369. return false;
  370. }
  371. return true;
  372. }
  373. public static function getUserByIds($ids)
  374. {
  375. $info = self::getByIds($ids, null, 'id');
  376. if (empty($info)) {
  377. return [];
  378. }
  379. $data = self::groupUserBaseInfo($info);
  380. return $data;
  381. }
  382. //将微信和小程序获取的用户信息转成可以保存的用户信息
  383. public static function switchUserInfo($info, $source)
  384. {
  385. $openId = '';
  386. if (isset($info['openid']) && !empty($info['openid'])) {
  387. $openId = $info['openid'];
  388. unset($info['openid']);
  389. }
  390. if (isset($info['openId']) && !empty($info['openId'])) {
  391. $openId = $info['openId'];
  392. unset($info['openId']);
  393. }
  394. if (!empty($openId)) {
  395. $userSource = self::$userSourceId;
  396. switch ($source) {
  397. case $userSource['mini']['name']:
  398. $info['miniOpenId'] = $openId;
  399. break;
  400. case $userSource['official']['name']:
  401. $info['openId'] = $openId;
  402. break;
  403. default:
  404. }
  405. }
  406. if (isset($info['miniOpenId'])) {
  407. $info['miniOpenId'] = $info['miniOpenId'];
  408. }
  409. if (isset($info['nickName'])) {
  410. $info['userName'] = $info['nickName'];
  411. $info['nickName'] = $info['nickName'];
  412. }
  413. if (isset($info['unionid'])) {
  414. $info['unionId'] = $info['unionid'];
  415. }
  416. if (isset($info['unionId'])) {
  417. $info['unionId'] = $info['unionId'];
  418. }
  419. if (isset($info['headimgurl'])) {
  420. $info['headImgUrl'] = $info['headimgurl'];
  421. }
  422. if (isset($info['avatarUrl'])) {
  423. $info['headImgUrl'] = $info['avatarUrl'];
  424. }
  425. if (isset($info['subscribe_time'])) {
  426. $info['subscribeTime'] = $info['subscribe_time'];
  427. }
  428. if (isset($info['subscribe'])) {
  429. $info['subscribe'] = $info['subscribe'];
  430. }
  431. return $info;
  432. }
  433. //创建以及更新用户 ssh 2020.2.7
  434. public static function replaceUser($info)
  435. {
  436. $mobile = $info['mobile'] ?? '';
  437. if (!empty($info['name'])) {
  438. $name = $info['name'];
  439. } else {
  440. $name = '尾号' . substr($mobile, -4);
  441. }
  442. $miniOpenId = $info['miniOpenId'] ?? '';
  443. if (!stringUtil::isMobile($mobile)) {
  444. util::fail('手机号错误');
  445. }
  446. $user = self::getByCondition(['mobile' => $mobile], true);
  447. if (empty($user)) {
  448. $user = self::add(['mobile' => $mobile, 'name' => $name, 'miniOpenId' => $miniOpenId], true);
  449. } else {
  450. if (isset($user->miniOpenId) && empty($user->miniOpenId)) {
  451. $user->miniOpenId = $miniOpenId;
  452. $user->save();
  453. }
  454. }
  455. return $user;
  456. }
  457. //拉取粉丝 ssh 2020.2.7
  458. public static function syncWxUser($sjId, $nextOpenId = '')
  459. {
  460. $merchant = MerchantClass::getMerchantById($sjId);
  461. //一次拉取调用最多拉取10000个关注者的OpenID
  462. $result = wxUtil::getSubscribeUserList($merchant, $nextOpenId);
  463. $total = isset($result['total']) ? $result['total'] : 0;
  464. $next_openid = isset($result['next_openid']) ? $result['next_openid'] : '';
  465. $count = isset($result['count']) ? $result['count'] : 0;
  466. $openIdList = isset($result['data']['openid']) ? $result['data']['openid'] : [];
  467. $currentTotal = count($openIdList);
  468. if ($count == 0 || $currentTotal == 0) {
  469. return ['total' => $total, 'count' => $count, 'nextOpenId' => $next_openid];
  470. }
  471. $currentTotalPage = $currentTotal > 100 ? ceil($currentTotal / 100) : 1;
  472. $userSource = Yii::$app->dict->getValue('userSourceGetId', 'official');
  473. $source = $userSource['name'];
  474. for ($m = 1; $m <= $currentTotalPage; $m++) {
  475. $offset = ($m - 1) * 100;
  476. $subIdList = array_slice($openIdList, $offset, 100);
  477. $info = wxUtil::batchGetUserInfo($merchant, $subIdList);
  478. if (empty($info) || isset($info['user_info_list']) == false || empty($info['user_info_list'])) {
  479. continue;
  480. }
  481. $user_info_list = $info['user_info_list'];
  482. foreach ($user_info_list as $val) {
  483. $val['isFull'] = 1;
  484. $val['unionId'] = $val['unionid'];
  485. $val['headImgUrl'] = $val['headimgurl'];
  486. $val['openId'] = $val['openid'];
  487. //去掉不支持的字符
  488. $val['nickName'] = isset($val['nickname']) ? preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $val['nickname']) : '';
  489. $val['sjId'] = $sjId;
  490. self::replaceUser($val, $source, $sjId);
  491. }
  492. }
  493. return ['total' => $total, 'count' => $count, 'nextOpenId' => $next_openid];
  494. }
  495. }