UserLogic.php 17 KB

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