UserLogic.php 16 KB

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