UserClass.php 20 KB

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