UserLogic.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. <?php
  2. namespace app\admin\logic;
  3. use app\admin\model\dao\MoneyLog;
  4. use app\admin\model\dao\ScoreLog;
  5. use app\admin\model\dao\User;
  6. use app\common\model\UserModel;
  7. use app\common\model\UserMoneyModel;
  8. use think\facade\Cache;
  9. use think\facade\Db;
  10. use function Qiniu\explodeUpToken;
  11. class UserLogic
  12. {
  13. public static function forbid($id)
  14. {
  15. $user = User::getUserOrEmptyById($id);
  16. if (empty($user)) return [false, '数据不存在'];
  17. if ($user['status'] == 0) return [false, '该用户已被禁用'];
  18. $result = User::updateStatus($id, 0);
  19. return $result ? [true, '禁用成功'] : [false, '禁用失败'];
  20. }
  21. public static function enable($id)
  22. {
  23. $user = User::getUserOrEmptyById($id);
  24. if (empty($user)) return [false, '数据不存在'];
  25. if ($user['status'] == 1) return [false, '该用户已启用'];
  26. $result = User::updateStatus($id, 1);
  27. return $result ? [true, '禁用成功'] : [false, '禁用失败'];
  28. }
  29. public static function getUserDetail($id)
  30. {
  31. $user = new User();
  32. return $user->getUserDetail($id);
  33. }
  34. public static function levelset($post)
  35. {
  36. $level = $post['level'];
  37. if ($level > 4) {
  38. return '最高等级4级';
  39. }
  40. $user = User::getUserOrEmptyById($post['id']);
  41. if (empty($user)) return '用户不存在';
  42. $level_type = 1;
  43. if ($level > $user['level']) {
  44. $level_type = 2;
  45. }
  46. Db::startTrans();
  47. try {
  48. $userData = ['level' => $level, 'level_type' => $level_type];
  49. User::update($post['id'], $userData);
  50. Db::commit();
  51. } catch (\Exception $e) {
  52. Db::rollback();
  53. return '失败' . $e->getMessage();
  54. }
  55. return true;
  56. }
  57. public static function lookpidlevel($id)
  58. {
  59. $path = Db::name('user')->where('id', $id)->value('path');
  60. $arr = explode(',', $path);
  61. $ids = $arr;
  62. $ids = implode(',', $ids);
  63. $order = 'field(id,' . $ids . ')';
  64. $where = array();
  65. $where[] = ['uid', 'in', $arr];
  66. sr_log($where);
  67. $user = new UserModel();
  68. $count = $user
  69. ->withJoin('userData', 'INNER')
  70. ->where($where)
  71. ->count();
  72. $list = $user
  73. ->withJoin('userData', 'INNER')
  74. ->where($where)
  75. ->order(Db::raw($order))
  76. ->select();
  77. return [$count, $list];
  78. }
  79. public static function getExportList($where, $page, $limit)
  80. {
  81. return (new UserModel())
  82. ->where($where)
  83. ->withJoin('userData', 'INNER')
  84. ->where($where)
  85. ->page($page, $limit)
  86. ->order('id', 'desc')
  87. ->select()
  88. ->toArray();
  89. }
  90. public static function recycleCountSet($post)
  91. {
  92. $user = User::getUserById($post['id']);
  93. if (empty($user)) return '用户不存在';
  94. if (empty($post['recycle_count']) || !preg_match("/^[1-9][0-9]*$/", $post['recycle_count']) || $post['recycle_count'] > 500) {
  95. return '回收卡数量格式有误';
  96. }
  97. try {
  98. $updateData = ['recycle_count' => $post['recycle_count']];
  99. $result = User::update($user['id'], $updateData);
  100. if (!$result) return "更新临时卡数量失败";
  101. } catch (\Exception $e) {
  102. return '失败' . $e->getMessage();
  103. }
  104. return true;
  105. }
  106. public function getList($page, $limit, $where, $sort, $userMap)
  107. {
  108. $where[] = ['status', '<>', 3];
  109. $userDao = new User();
  110. $count = $userDao->getCount($where, $userMap);
  111. $list = $userDao->getPageList($page, $limit, $where, $sort, $userMap);
  112. foreach ($list as &$item) {
  113. //团队会员(包括1、2级和自身)的积分账户合计、余额账户合计
  114. // 计算团队成员(包括1、2级和自身)ID
  115. $teamIds = $this->getTeamMoneyAndScore($item['id']);
  116. // 积分账户合计
  117. $item['score_total'] = $teamIds['score'];
  118. // 余额账户合计
  119. $item['money_total'] = $teamIds['money'];
  120. }
  121. $data = [
  122. 'code' => 0,
  123. 'msg' => Db::getLastSql(),
  124. 'count' => $count,
  125. 'data' => $list,
  126. ];
  127. return json($data);
  128. }
  129. /**
  130. * 获取团队自身,一级、二级自己的余额/积分
  131. * @param $uid
  132. */
  133. private function getTeamMoneyAndScore($uid)
  134. {
  135. $cacheKey = 'userLogicTeamIds_' . $uid;
  136. if (!Cache::has($cacheKey)) {
  137. // 自身
  138. $user = Db::table(User::$table)
  139. ->where('id', $uid)
  140. ->field(['id', 'score', 'money'])
  141. ->find();
  142. $totalScore = $user['score'];
  143. $totalMoney = $user['money'];
  144. // 一级子用户
  145. Db::table(User::$table)
  146. ->where('pid', $uid)
  147. ->field(['id', 'score', 'money'])
  148. ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
  149. foreach ($users as $user) {
  150. $uids[] = $user['id'];
  151. $totalScore += $user['score'];
  152. $totalMoney += $user['money'];
  153. }
  154. // 二级子用户
  155. Db::table(User::$table)
  156. ->whereIn('pid', $uids)
  157. ->field(['id', 'score', 'money'])
  158. ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
  159. foreach ($users as $user) {
  160. $totalScore += $user['score'];
  161. $totalMoney += $user['money'];
  162. }
  163. });
  164. }, ['score', 'money']);
  165. Cache::set($cacheKey, ['score' => $totalScore, 'money' => sprintf("%.2f", $totalMoney)], 5 * 60);
  166. }
  167. return Cache::get($cacheKey);
  168. }
  169. /**
  170. * 修改用户手机号码
  171. * @param $uid
  172. * @param $phone
  173. */
  174. public function modifyPhone($uid, $phone)
  175. {
  176. // 判断手机号码是否使用过
  177. $user = User::getUserById($uid);
  178. if (empty($user)) return '用户不存在';
  179. if ($user['mobile'] == $phone) return "请输入新的手机号码";
  180. if (User::getUserByMobile($phone)) return "该手机号码已注册";
  181. // 修改用户信息
  182. try {
  183. $updateData = [
  184. 'mobile' => $phone,
  185. ];
  186. // 按照账号原规则,手机号码作为用户名,同时修改新的用户名
  187. if ($user['mobile'] == $user['user_name']) {
  188. $updateData['user_name'] = $phone;
  189. }
  190. $result = User::update($uid, $updateData);
  191. if (!$result) return "更新手机号码失败,请稍后重试";
  192. } catch (\Exception $e) {
  193. return '失败' . $e->getMessage();
  194. }
  195. return true;
  196. }
  197. /**
  198. * 修改用户所属上级
  199. * @param $uid
  200. * @param $pid
  201. */
  202. public function modifypid($uid, $pid)
  203. {
  204. $user = User::getUserById($uid);
  205. if (empty($user)) return '用户不存在';
  206. // 查询pid是否存在用户path中
  207. if ($uid == $pid) {
  208. return "不能修改自己为上级";
  209. }
  210. if ($user['pid'] == $pid) {
  211. return "该用户已所属待变更的上级,不能修改";
  212. }
  213. $parentUser = User::getUserById($pid);
  214. if (empty($parentUser)) {
  215. return '所属上级不存在';
  216. }
  217. // 判断降级或升级
  218. // 判断升级,降级、插入
  219. list($operateType, $prefixPath) = $this->getOperateType($user['id'], $user['path'], $pid, $parentUser['path']);
  220. Db::startTrans();
  221. try {
  222. if ($operateType) {
  223. $result = $this->modifypidByResetTopLevel($user['id'], $user['path'], $pid, $parentUser['path'], $prefixPath);
  224. } else {
  225. // 正常,迭代修改下级
  226. $result = $this->modifypidByUpdateNextLevel($user['id'], $user['pid'], $user['path'], $pid, $parentUser['path']);
  227. }
  228. if (!$result) {
  229. Db::rollback();
  230. return "修改用户所属上级失败,请确认用户的层级关系";
  231. }
  232. Db::commit();
  233. } catch (\Exception $exception) {
  234. Db::rollback();
  235. return "失败:" . $exception->getMessage();
  236. }
  237. return true;
  238. // 升级,abcdef,e升级到b后 分为两种情况 1.abef 2.abcd
  239. // 降级 abcdef,c降级到e后 分为两种情况 1. ecf 2.abcd
  240. // 插入 abcdef,插入j到b后 分为两种情况 1.abj 2.abcdef
  241. }
  242. /**
  243. * 修改余额
  244. * @param $post
  245. */
  246. public function ModifyMoney($post)
  247. {
  248. if (strlen(substr(strrchr($post['money'], "."), 1)) > 4) {
  249. return "变更金额格式错误";
  250. }
  251. $user = User::getUserById($post['uid']);
  252. if (empty($user)) {
  253. return "用户不存在";
  254. }
  255. Db::startTrans();
  256. try {
  257. if ($post['state'] == 1) {
  258. $afterMoney = $user['money'] + $post['money'];
  259. } else {
  260. $afterMoney = $user['money'] - $post['money'];
  261. if ($afterMoney < 0) {
  262. return "账号余额不足";
  263. }
  264. }
  265. $afterMoney = round($afterMoney, 4);
  266. $moneyLog = [
  267. 'uid' => $post['uid'],
  268. 'type' => $post['type'] ?? 0,
  269. 'money' => $post['money'],
  270. 'create_at' => date('Y-m-d H:i:s'),
  271. 'state' => $post['state'] ?? '0',
  272. 'from_id' => $post['from_id'] ?? '0',
  273. 'before_money' => $user['money'],
  274. 'after_money' => $afterMoney,
  275. 'uid2' => $post['uid2'] ?? 0,
  276. 'free_type' => $post['free_type'] ?? '',
  277. 'remark' => $post['remark'],
  278. ];
  279. // 子级path变更
  280. MoneyLog::AddMoneyLog($moneyLog);
  281. User::UpdateUserMoney($user['id'], $afterMoney);
  282. Db::commit();
  283. } catch (\Exception $exception) {
  284. Db::rollback();
  285. return "失败:" . $exception->getMessage();
  286. }
  287. return true;
  288. }
  289. /**
  290. * 修改积分
  291. * @param $post
  292. */
  293. public function ModifyScore($post)
  294. {
  295. $user = User::getUserById($post['uid']);
  296. if (empty($user)) {
  297. return "用户不存在";
  298. }
  299. Db::startTrans();
  300. try {
  301. if ($post['state'] == 1) {
  302. $afterScore = $user['score'] + $post['score'];
  303. } else {
  304. $afterScore = $user['score'] - $post['score'];
  305. if ($afterScore < 0) {
  306. return "账号积分不足";
  307. }
  308. }
  309. $moneyLog = [
  310. 'uid' => $post['uid'],
  311. 'type' => $post['type'] ?? 0,
  312. 'score' => $post['score'],
  313. 'create_at' => date('Y-m-d H:i:s'),
  314. 'scene' => $post['scene'] ?? 0,
  315. 'from_id' => $post['from_id'] ?? '0',
  316. 'state' => $post['state'] ?? '0',
  317. 'before_score' => $user['score'],
  318. 'after_score' => $afterScore,
  319. 'uid2' => $post['uid2'] ?? 0,
  320. ];
  321. // 子级path变更
  322. ScoreLog::AddScoreLog($moneyLog);
  323. User::UpdateUserScore($user['id'], $afterScore);
  324. Db::commit();
  325. } catch (\Exception $exception) {
  326. Db::rollback();
  327. return "失败:" . $exception->getMessage();
  328. }
  329. return true;
  330. }
  331. /**
  332. * 删除用户
  333. * @param $id
  334. */
  335. public function delUser($id)
  336. {
  337. $user = User::getUserById($id);
  338. if (empty($user)) {
  339. return "用户不存在";
  340. }
  341. if (User::updateStatus($id, 3) !== 1) {
  342. return false;
  343. }
  344. return true;
  345. }
  346. /* 注册用户数量统计
  347. * @param string $time 时间节点如:2023-03-01
  348. * @return
  349. * @throws \think\db\exception\DbException
  350. */
  351. public static function getCountByTime($time = '0')
  352. {
  353. $cacheKey = "caches:user:counts_{$time}";
  354. if (!Cache::has($cacheKey)) {
  355. $data = UserModel::where(['status' => 1])
  356. ->where(function ($query) use ($time) {
  357. if ($time) {
  358. $query->where('reg_time', '>=', $time);
  359. }
  360. })->count('id');
  361. if ($data) {
  362. Cache::set($cacheKey, $data, rand(3, 5));
  363. }
  364. return $data;
  365. }
  366. return Cache::get($cacheKey);
  367. }
  368. /**
  369. * 判断操作类型,true-死循环 false-正常
  370. * @param $pid
  371. * @param $path
  372. * @return int
  373. */
  374. private function getOperateType($uid, $path, $pid, $pUserPath)
  375. {
  376. // $pUserPathArr = explode(',', $pUserPath);
  377. list($isFallLevel, $prefixPath) = $this->isFallLevel($uid, $pid);
  378. if ($isFallLevel) {
  379. return [true, $prefixPath];
  380. }
  381. return [false, null];
  382. }
  383. private function modifypidByUpdateNextLevel($id, $userPid, $path, $pid, $parentUserPath)
  384. {
  385. $newPath = explode(',', $parentUserPath);
  386. $newPath[] = $pid;
  387. // 1. 修改$pidUser['pid'] = $idUser['pid'], $pidUser['path'] = $idUser['path']
  388. User::modifyUserPidAndPath($id, $pid, implode(',', $newPath));
  389. // 迭代更新子级path
  390. $this->iteraMidifyPathByPid($newPath, $id);
  391. return true;
  392. }
  393. private function iteraMidifyPathByPid($newUserPathArr, $pid)
  394. {
  395. $newUserPathArr[] = $pid;
  396. $result = Db::table(User::$table)
  397. ->where([
  398. 'pid' => $pid
  399. ])
  400. ->field(['id', 'path'])
  401. ->chunk(100, function ($users) use ($pid, $newUserPathArr) {
  402. foreach ($users as $user) {
  403. User::modifyUserPath($user['id'], implode(',', $newUserPathArr));
  404. $this->iteraMidifyPathByPid($newUserPathArr, $user['id']);
  405. }
  406. });
  407. return $result;
  408. }
  409. private function modifypidByResetTopLevel($id, $path, $pid, $parentUserPath, $prefixPath)
  410. {
  411. // 1.迭代更新id所有下级的path,从path = ‘’开始
  412. $usersList = Db::table(User::$table)
  413. ->where(['pid' => $id])
  414. ->field(['id', 'path'])
  415. ->select();
  416. foreach ($usersList as $user) {
  417. $this->iteraMidifyPathByPid([], $user['id']);
  418. }
  419. // 2.修改id的下一级用户的pid =0 ,path = ‘’
  420. User::modifyUserPidAndPathByPid($id, 0, '');
  421. // 3. 修改$post['id']的pid = post['pid'],path = pUserPath.',pid'
  422. $parentUser = User::getUserById($pid);
  423. if (!empty($parentUser['path'])) {
  424. $newUserPathArr = explode(',', $parentUser['path']);
  425. }
  426. $newUserPathArr[] = $pid;
  427. User::modifyUserPidAndPath($id, $pid, implode(',', $newUserPathArr));
  428. return true;
  429. }
  430. private function isFallLevel($uid, $pid)
  431. {
  432. $user = Db::query(sprintf("SELECT id,path,pid FROM db_user WHERE FIND_IN_SET('%s',path) and FIND_IN_SET('%s',path) LIMIT 1;", $uid, $pid));
  433. if (empty($user)) {
  434. return [false, null];
  435. }
  436. $userPath = explode(',', $user[0]['path']);
  437. $uidIndex = array_search($uid, $userPath);
  438. if ($uidIndex < array_search($pid, $userPath)) {
  439. $returnPath = [];
  440. if (isset($userPath[$uidIndex - 1])) {
  441. $returnPath[] = $userPath[$uidIndex - 1];
  442. }
  443. $returnPath[] = $userPath[$uidIndex];
  444. $returnPath[] = $userPath[$uidIndex + 1];
  445. return [true, $returnPath];
  446. }
  447. return [false, null];
  448. }
  449. private function updatePidAndPathByPath($uid, $prefixPath)
  450. {
  451. $newTopUid = $prefixPath[count($prefixPath) - 1];
  452. // 从阶段处更新,分支出来作为第一层
  453. User::modifyUserPidAndPath($newTopUid, 0, '');
  454. User::modifyUserPidAndPathByPid($uid, 0, '');
  455. $newUserPathArr = [];
  456. return $this->iteraMidifyPathByPid($newUserPathArr, $newTopUid);
  457. }
  458. }