UserLogic.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. namespace app\api\logic;
  3. use app\api\controller\Account;
  4. use app\common\basics\Logic;
  5. use app\common\enum\ClientEnum;
  6. use app\common\logic\ChatLogic;
  7. use app\common\model\goods\GoodsCollect;
  8. use app\common\model\kefu\ChatRecord;
  9. use app\common\model\kefu\ChatRelation;
  10. use app\common\model\kefu\Kefu;
  11. use app\common\model\user\User;
  12. use app\common\model\order\Order;
  13. use app\common\model\AfterSale;
  14. use app\common\model\CouponList;
  15. use app\common\model\user\UserAuth;
  16. use app\common\model\user\UserLevel;
  17. use app\common\server\ConfigServer;
  18. use app\common\model\AccountLog;
  19. use app\common\server\UrlServer;
  20. use app\common\server\WeChatServer;
  21. use app\common\server\storage\Driver as StorageDriver;
  22. use think\facade\Db;
  23. use EasyWeChat\Factory;
  24. use EasyWeChat\Kernel\Exceptions\Exception;
  25. class UserLogic extends Logic
  26. {
  27. public static function center($user_id)
  28. {
  29. $user = User::findOrEmpty($user_id);
  30. if($user->isEmpty()) {
  31. return [];
  32. }
  33. // 头像
  34. $user->avatar = UrlServer::getFileUrl($user->avatar);
  35. //待支付
  36. $user->wait_pay = Order::where(['del'=>0,'user_id'=>$user_id,'order_status'=>Order::STATUS_WAIT_PAY,'pay_status'=>0])->count();
  37. //待发货
  38. $user->wait_delivery = Order::where(['del'=>0,'user_id'=>$user_id,'order_status'=>Order::STATUS_WAIT_DELIVERY,'pay_status'=>1])->count();
  39. //待收货
  40. $user->wait_take = Order::where(['del'=>0,'user_id'=>$user_id,'order_status'=>Order::STATUS_WAIT_RECEIVE,'pay_status'=>1])->count();
  41. //待评论
  42. $user->wait_comment = Order::alias('o')
  43. ->join('order_goods og','o.id = og.order_id')
  44. ->where(['del'=>0,'user_id'=>$user_id,'order_status'=>Order::STATUS_FINISH,'og.is_comment'=>0])
  45. ->count('og.id');
  46. //售后中
  47. $user->after_sale = AfterSale::where(['del'=>0,'user_id'=>$user_id])
  48. ->where('status','<>',AfterSale::STATUS_SUCCESS_REFUND)
  49. ->count();
  50. // 优惠券
  51. $user->coupon = self::ableUsedCouponCount($user_id);
  52. //分销开关
  53. $user->distribution_setting = ConfigServer::get('distribution', 'is_open',1);
  54. //消息数量
  55. $user->notice_num = 0;
  56. //收藏商品数量
  57. $user->collect = GoodsCollect::where(['user_id' => $user_id, 'status' => 1])->count();
  58. // 会员等级
  59. $level_list = UserLevel::where(['del'=>0])->order('growth_value', 'asc')->column('id,name,growth_value,image,background_image', 'id');
  60. $user['level_name'] = isset($level_list[$user['level']]) ? $level_list[$user['level']]['name'] : '-';
  61. $user['vip'] = 0;
  62. $level_list = array_values($level_list);
  63. foreach($level_list as $k=>$v){
  64. if($v['id'] == $user['level']) {
  65. $user['vip'] = $k + 1;
  66. }
  67. }
  68. //下个会员等级提示
  69. $user_level = UserLevel::where([
  70. ['id','>',$user->getData('level')],
  71. ['del','=',0]
  72. ])->order('growth_value asc')
  73. ->findOrEmpty();
  74. $user['next_level_tips'] = '';
  75. if(!$user_level->isEmpty()){
  76. $user['next_level_tips'] = '距离升级还差'.intval($user_level['growth_value'] - $user['user_growth']);
  77. }
  78. // 是否设置支付密码
  79. $user['hasPayPassword'] = $user['pay_password'] ? 1: 0;
  80. $user->visible(['id','nickname','sn','avatar', 'mobile', 'hasPayPassword','next_level_tips','user_money','total_order_amount','total_recharge_amount',
  81. 'coupon','user_integral','level','wait_pay','wait_take','wait_delivery',
  82. 'wait_comment','after_sale', 'distribution_setting', 'distribution_code', 'notice_num', 'collect','level_name','vip','is_new_user']);
  83. $user = $user->toArray();
  84. return $user;
  85. }
  86. public static function accountLog($user_id,$source,$type,$page,$size){
  87. $source_type = '';
  88. $where[] = ['user_id','=',$user_id];
  89. switch ($source){
  90. case 1:
  91. $source_type = AccountLog::money_change;
  92. break;
  93. case 2:
  94. $source_type = AccountLog::integral_change;
  95. break;
  96. case 3:
  97. $source_type = AccountLog::growth_change;
  98. }
  99. $where[] = ['source_type','in',$source_type];
  100. if($type && $type != 0){
  101. $where[] = ['change_type','=',$type];
  102. }
  103. $count = AccountLog::where($where)->count();
  104. $list = AccountLog::where($where)
  105. ->page($page,$size)
  106. ->order('id desc')
  107. ->field('id,change_amount,change_amount as change_amount_format,source_type,change_type,create_time,create_time as create_time_format')
  108. ->select()
  109. ->toArray();
  110. $more = is_more($count,$page,$size); //是否有下一页
  111. $data = [
  112. 'list' => $list,
  113. 'page_no' => $page,
  114. 'page_size' => $size,
  115. 'count' => $count,
  116. 'more' => $more
  117. ];
  118. return $data;
  119. }
  120. public static function getUserLevelInfo($id)
  121. {
  122. $user = User::field('id,avatar,nickname,level,user_growth')->findOrEmpty($id);
  123. if($user->isEmpty()) {
  124. return ['error_msg' => '会员不存在'];
  125. }
  126. $user = $user->toArray();
  127. $level_list = UserLevel::where(['del'=>0])->order('growth_value', 'asc')->column('id,name,growth_value,image,background_image', 'id');
  128. // 用户会员等级
  129. $user['level_name'] = isset($level_list[$user['level']]) ? $level_list[$user['level']]['name'] : '-';
  130. // 用户头像
  131. $user['avatar'] = UrlServer::getFileUrl($user['avatar']);
  132. // 重置会员等级列表索引
  133. $level_list = array_values($level_list);
  134. // 获取当前用户对应等级的索引
  135. $index = null;
  136. foreach($level_list as $key => $item) {
  137. if($item['id'] == $user['level']) {
  138. $index = $key;
  139. }
  140. }
  141. // 遍历标识每个会员等级信息
  142. foreach($level_list as $key => &$item) {
  143. $diff_growth_percent = 0; //距离下个等级成长百分比
  144. if($index === false || $index < $key) {
  145. $item['lock_desc'] = '未解锁';
  146. $item['tips1'] = '当前成长值 '. $user['user_growth'];
  147. $item['tips2'] = '还需'.($item['growth_value'] - $user['user_growth']).'成长值';
  148. $item['current_level_status'] = -1;
  149. }else if($index > $key) {
  150. $item['lock_desc'] = '已解锁';
  151. $item['tips1'] = '当前高于该等级 ';
  152. $item['tips2'] = '';
  153. $item['current_level_status'] = 0;
  154. }else if($index == $key) {
  155. $item['current_level_status'] = 1;
  156. $item['lock_desc'] = '当前等级';
  157. $item['tips1'] = '当前成长值 '. $user['user_growth'];
  158. //下个等级
  159. $next_level = $level_list[$key+1] ?? [];
  160. if($next_level) {
  161. $diff_growth_percent = round($user['user_growth'] / $next_level['growth_value'],2);
  162. $item['tips2'] = '满'.$next_level['growth_value'].'可升级';
  163. } else {
  164. $item['tips2'] = '';
  165. }
  166. }
  167. $item['diff_growth_percent'] = $diff_growth_percent;
  168. $item['image'] = empty($item['image']) ? '' : UrlServer::getFileUrl($item['image']);
  169. $item['background_image'] = empty($item['background_image']) ? '' : UrlServer::getFileUrl($item['background_image']);
  170. }
  171. $level_intro = ConfigServer::get('user_level', 'intro', '');
  172. $data = [
  173. 'user' => $user,
  174. 'level' => $level_list,
  175. 'level_intro' => $level_intro
  176. ];
  177. return $data;
  178. }
  179. public static function getGrowthList($get)
  180. {
  181. $user_growth = User::where(['id'=>$get['user_id']])->value('user_growth');
  182. $where = [
  183. ['user_id', '=', $get['user_id']],
  184. ['source_type', 'in', AccountLog::growth_change]
  185. ];
  186. $lists = AccountLog::field('id,source_type,change_amount as change_amount_format,change_type,create_time as create_time_format')
  187. ->where($where)
  188. ->order('create_time', 'desc')
  189. ->page($get['page_no'], $get['page_size'])
  190. ->select()
  191. ->toArray();
  192. $count = AccountLog::field('id,source_type,change_amount as change_amount_format,change_type,create_time as create_time_format')
  193. ->where($where)
  194. ->count();
  195. $data = [
  196. 'count' => $count,
  197. 'lists' => $lists,
  198. 'page_no' => $get['page_no'],
  199. 'page_size' => $get['page_size'],
  200. 'more' => is_more($count, $get['page_no'], $get['page_size']),
  201. 'user_growth' => $user_growth
  202. ];
  203. return $data;
  204. }
  205. public static function myWallet($user_id)
  206. {
  207. $info = User::where(['id'=>$user_id])
  208. ->field('user_money,total_order_amount,total_recharge_amount')
  209. ->findOrEmpty();
  210. if($info->isEmpty()) {
  211. self::$error = '用户不存在';
  212. return false;
  213. }
  214. $info = $info->toArray();
  215. $info['open_racharge'] = ConfigServer::get('recharge','open_racharge',0);
  216. return $info;
  217. }
  218. //获取用户信息
  219. public static function getUserInfo($user_id)
  220. {
  221. $info = User::where(['id' => $user_id])
  222. ->field('id,sn,nickname,avatar,mobile,sex,create_time,password,pay_password')
  223. ->find()
  224. ->toArray();
  225. $info['avatar'] = $info['avatar'] ? UrlServer::getFileUrl($info['avatar']) : '';
  226. $info['has_password'] = $info['password'] ? 1: 0;
  227. $info['has_pay_password'] = $info['password'] ? 1: 0;
  228. unset($info['password']);
  229. unset($info['pay_password']);
  230. $info['oa_auth'] = UserAuth::where('user_id', $info['id'])->where('client', ClientEnum::oa)->value('id') ? 1: 0;
  231. $info['mnp_auth'] = UserAuth::where('user_id', $info['id'])->where('client', ClientEnum::mnp)->value('id') ? 1: 0;
  232. return $info;
  233. }
  234. //设置个人信息
  235. public static function setUserInfo($post)
  236. {
  237. try{
  238. $field = $post['field'];
  239. $value = $post['value'];
  240. if ($field == 'avatar') {
  241. $value = UrlServer::setFileUrl($value);
  242. }
  243. User::where(['id'=> $post['user_id']])
  244. ->update([$field => $value]);
  245. return true;
  246. }catch(\Exception $e) {
  247. self::$error = $e->getMessage();
  248. return false;
  249. }
  250. }
  251. //更新微信信息
  252. public static function updateWechatInfo($user_id, $post)
  253. {
  254. Db::startTrans();
  255. try{
  256. $time = time();
  257. $avatar_url = $post['avatar'];
  258. $nickanme = $post['nickname'];
  259. $sex = $post['sex'];
  260. $config = [
  261. 'default' => ConfigServer::get('storage', 'default', 'local'),
  262. 'engine' => ConfigServer::get('storage_engine')
  263. ];
  264. $avatar = ''; //头像路径
  265. if ($config['default'] == 'local') {
  266. $file_name = md5($user_id . $time. rand(10000, 99999)) . '.jpeg';
  267. $avatar = download_file($avatar_url, 'uploads/user/avatar/', $file_name);
  268. } else {
  269. $avatar = 'uploads/user/avatar/' . md5($user_id . $time. rand(10000, 99999)) . '.jpeg';
  270. $StorageDriver = new StorageDriver($config);
  271. if (!$StorageDriver->fetch($avatar_url, $avatar)) {
  272. throw new Exception( '头像保存失败:'. $StorageDriver->getError());
  273. }
  274. }
  275. User::where(['id' => $user_id])->update([
  276. 'nickname' => $nickanme,
  277. 'avatar' => $avatar,
  278. 'sex' => $sex
  279. ]);
  280. Db::commit();
  281. return true;
  282. } catch(\Exception $e) {
  283. Db::rollback();
  284. self::$error = $e->getMessage();
  285. return false;
  286. }
  287. }
  288. //获取微信手机号
  289. public static function getMobileByMnp($post)
  290. {
  291. Db::startTrans();
  292. try {
  293. $config = WeChatServer::getMnpConfig();
  294. $app = Factory::miniProgram($config);
  295. $response = $app->auth->session($post['code']);
  296. if (!isset($response['session_key'])) {
  297. throw new Exception('获取用户信息失败');
  298. }
  299. $response = $app->encryptor->decryptData($response['session_key'], $post['iv'], $post['encrypted_data']);
  300. $isExist = User::where([
  301. ['mobile', '=', $response['phoneNumber']],
  302. ['id', '<>', $post['user_id']]
  303. ])->findOrEmpty();
  304. if (!$isExist->isEmpty()) {
  305. throw new Exception('手机号已被其他账号绑定');
  306. }
  307. User::update(['id' => $post['user_id'], 'mobile' => $response['phoneNumber']]);
  308. Db::commit();
  309. return true;
  310. } catch (Exception $e) {
  311. Db::rollback();
  312. self::$error = $e->getMessage();
  313. return false;
  314. }
  315. }
  316. //修改手机号
  317. public static function changeMobile($user_id, $data)
  318. {
  319. $user = User::find($user_id);
  320. $user->mobile = $data['new_mobile'];
  321. $user->save();
  322. return $user;
  323. }
  324. //我的粉丝列表
  325. public static function fans($user_id, $get, $page, $size)
  326. {
  327. $where = [];
  328. if (isset($get['keyword']) && $get['keyword'] != ''){
  329. $where[] = ['nickname|mobile','like','%'.$get['keyword'].'%'];
  330. }
  331. //查询条件
  332. $type = $get['type'] ?? 'all';
  333. switch ($type){
  334. case 'first':
  335. $where[] = ['first_leader', '=', $user_id];
  336. break;
  337. case 'second':
  338. $where[] = ['second_leader', '=', $user_id];
  339. break;
  340. default:
  341. $where[] = ['first_leader|second_leader', '=', $user_id];
  342. }
  343. $field = 'u.id, avatar, nickname, mobile, u.create_time, order_num as fans_order,
  344. order_amount as fans_money, fans as fans_team';
  345. $count = User::alias('u')
  346. ->field($field)
  347. ->leftJoin('user_distribution d', 'd.user_id = u.id')
  348. ->where($where)
  349. ->count();
  350. $lists = User::alias('u')
  351. ->field($field)
  352. ->leftJoin('user_distribution d', 'd.user_id = u.id')
  353. ->where($where)
  354. ->page($page, $size)
  355. ->order(self::fansListsSort($get))
  356. ->select();
  357. foreach ($lists as &$item) {
  358. $item['avatar'] = UrlServer::getFileUrl($item['avatar']);
  359. $item['fans_team'] = $item['fans_team'] ?? 0;
  360. $item['fans_order'] = $item['fans_order'] ?? 0;
  361. $item['fans_money'] = $item['fans_money'] ?? 0;
  362. unset($item['fans'], $item['distribution_order_num'], $item['distribution_money']);
  363. }
  364. $data = [
  365. 'list' => $lists,
  366. 'page' => $page,
  367. 'size' => $size,
  368. 'count' => $count,
  369. 'more' => is_more($count, $page, $size)
  370. ];
  371. return $data;
  372. }
  373. //粉丝列表排序
  374. public static function fansListsSort($get)
  375. {
  376. if (isset($get['fans']) && $get['fans'] != ''){
  377. return ['fans_team' => $get['fans'], 'u.id' => 'desc'];
  378. }
  379. if (isset($get['money']) && $get['money'] != ''){
  380. return ['fans_money' => $get['money'], 'u.id' => 'desc'];
  381. }
  382. if (isset($get['order']) && $get['order'] != ''){
  383. return ['fans_order' => $get['order'], 'u.id' => 'desc'];
  384. }
  385. return ['u.id' => 'desc'];
  386. }
  387. /**
  388. * @notes 获取聊天记录
  389. * @param $user_id
  390. * @param $shop_id
  391. * @param $page
  392. * @param $size
  393. * @return array
  394. * @throws \think\db\exception\DataNotFoundException
  395. * @throws \think\db\exception\DbException
  396. * @throws \think\db\exception\ModelNotFoundException
  397. * @author 段誉
  398. * @date 2021/12/29 18:20
  399. */
  400. public static function getChatRecord($user_id, $shop_id, $page, $size)
  401. {
  402. $map1 = [
  403. ['shop_id', '=', $shop_id],
  404. ['from_id', '=', $user_id],
  405. ['from_type', '=', 'user'],
  406. ];
  407. $map2 = [
  408. ['shop_id', '=', $shop_id],
  409. ['to_id', '=', $user_id],
  410. ['to_type', '=', 'user'],
  411. ];
  412. // 通信记录
  413. $records = ChatRecord::whereOr([$map1, $map2])
  414. ->order('id desc')
  415. ->page($page, $size)
  416. ->select()->toArray();
  417. $count = ChatRecord::whereOr([$map1, $map2])->count();
  418. // 上一个客服关系
  419. $kefu = self::getLastRelation((int)$user_id, (int)$shop_id);
  420. // 当前在线的所有客服
  421. $online = ChatLogic::getOnlineKefu($shop_id);
  422. // 后台配置=>[1=>人工客服; 2=>在线客服]
  423. if ($shop_id > 0) {
  424. $config = ConfigServer::get('shop_customer_service', 'type', 1, $shop_id);
  425. } else {
  426. $config = ConfigServer::get('customer_service', 'type', 1);
  427. }
  428. $kefu_id = $kefu['kefu_id'] ?? 0;
  429. $records = ChatLogic::formatChatRecords($records, $count, $page, $size);
  430. // 没有在线客服或者后台配置为 人工客服
  431. if (empty($online) || $config == 1) {
  432. return ['config' => $config, 'kefu' => [], 'record' => $records];
  433. }
  434. // 没有聊天记录(未与客服聊天) 或者 曾经的聊天客服不在线
  435. if (empty($kefu) || !in_array($kefu_id, $online)) {
  436. // 随机分配客服
  437. $rand = rand(0, count($online) - 1);
  438. $kefu_id = $online[$rand];
  439. }
  440. $kefu = Kefu::where(['id' => $kefu_id])
  441. ->field(['id', 'nickname', 'avatar'])
  442. ->findOrEmpty();
  443. return ['config' => $config, 'kefu' => $kefu, 'record' => $records];
  444. }
  445. /**
  446. * @notes 获取用户最后通信的客服id
  447. * @param int $user_id
  448. * @param int $shop_id
  449. * @return array|\think\Model
  450. * @author 段誉
  451. * @date 2021/12/29 18:20
  452. */
  453. public static function getLastRelation(int $user_id, int $shop_id)
  454. {
  455. $relation = ChatRelation::where([
  456. 'user_id' => $user_id,
  457. 'shop_id' => $shop_id
  458. ])->order('update_time desc')->findOrEmpty();
  459. return $relation;
  460. }
  461. /**
  462. * @notes 可用优惠券数量
  463. * @param $get
  464. * @return int
  465. * @author 段誉
  466. * @date 2023/2/20 15:10
  467. */
  468. public static function ableUsedCouponCount($user_id)
  469. {
  470. // 提取用户未删除的优惠券
  471. $where = [
  472. ['cl.del', '=', 0],
  473. ['cl.user_id', '=', $user_id]
  474. ];
  475. $field = 'cl.*, c.name,c.use_time_type,c.use_time_start,c.use_time_end,c.use_time as coupon_use_time,
  476. c.condition_type,c.condition_money,c.money,c.use_goods_type';
  477. $count_list = CouponList::alias('cl')
  478. ->leftJoin('coupon c', 'c.id=cl.coupon_id')
  479. ->field($field)
  480. ->where($where)
  481. ->order('id', 'desc')
  482. ->select()
  483. ->toArray();
  484. // 循环标识每条记录的券是否过期
  485. foreach($count_list as &$item) {
  486. $item['is_expired'] = 0; // 默认先标识为未过期
  487. switch($item['use_time_type']) {
  488. case 1: // 固定时间
  489. if($item['use_time_end'] <= time()) {
  490. $item['is_expired'] = 1;
  491. }
  492. break;
  493. case 2: // 领券当天起
  494. $days = '+'.$item['coupon_use_time'].' day';
  495. $expired_time = strtotime($days, strtotime($item['create_time']));
  496. if($expired_time <= time()) {
  497. $item['is_expired'] = 1;
  498. }
  499. break;
  500. case 3: // 领券次日起
  501. $days = '+'.($item['coupon_use_time']+1).' day';
  502. $expired_time = strtotime($days, strtotime($item['create_time']));
  503. if($expired_time <= time()) {
  504. $item['is_expired'] = 1;
  505. }
  506. break;
  507. }
  508. }
  509. $valid_array = array_filter($count_list, function($item) {
  510. return $item['status'] == 0 && $item['is_expired'] == 0; // 未使用,未过期
  511. });
  512. return count($valid_array);
  513. }
  514. }