UserLogic.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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']) || $post['recycle_count'] < 0 || $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. // 死循环,分支
  224. $result = $this->modifypidByResetTopLevel($user['id'], $user['path'], $pid, $parentUser['path'], $prefixPath);
  225. } else {
  226. // 正常,迭代修改下级
  227. $result = $this->modifypidByUpdateNextLevel($user['id'], $user['pid'], $user['path'], $pid, $parentUser['path']);
  228. }
  229. if (!$result) {
  230. Db::rollback();
  231. return "修改用户所属上级失败,请确认用户的层级关系";
  232. }
  233. Db::commit();
  234. } catch (\Exception $exception) {
  235. Db::rollback();
  236. return "失败:" . $exception->getMessage();
  237. }
  238. return true;
  239. // 升级,abcdef,e升级到b后 分为两种情况 1.abef 2.abcd
  240. // 插入位置的 path 作为新的path
  241. // 插入位置的 前一位的 作为新的pid
  242. // 迭代修改父节点的子节点
  243. // 降级 abcdef,c降级到e后 分为两种情况 1. ecf 2.abcd
  244. // 插入 abcdef,插入j到b后 分为两种情况 1.abj 2.abcdef
  245. }
  246. /**
  247. * 修改余额
  248. * @param $post
  249. */
  250. public function ModifyMoney($post)
  251. {
  252. $user = User::getUserById($post['uid']);
  253. if (empty($user)) {
  254. return "用户不存在";
  255. }
  256. Db::startTrans();
  257. try {
  258. if ($post['state'] == 1) {
  259. $afterMoney = $user['money'] + $post['money'];
  260. } else {
  261. $afterMoney = $user['money'] - $post['money'];
  262. if ($afterMoney < 0) {
  263. return "账号余额不足";
  264. }
  265. }
  266. $afterMoney = round($afterMoney, 2);
  267. $moneyLog = [
  268. 'uid' => $post['uid'],
  269. 'type' => $post['type'] ?? 0,
  270. 'money' => $post['money'],
  271. 'create_at' => date('Y-m-d H:i:s'),
  272. 'state' => $post['state'] ?? '0',
  273. 'from_id' => $post['from_id'] ?? '0',
  274. 'before_money' => $user['money'],
  275. 'after_money' => $afterMoney,
  276. 'uid2' => $post['uid2'] ?? 0,
  277. 'free_type' => $post['free_type'] ?? '',
  278. 'remark' => $post['remark'],
  279. ];
  280. // 子级path变更
  281. MoneyLog::AddMoneyLog($moneyLog);
  282. User::UpdateUserMoney($user['id'], $afterMoney);
  283. Db::commit();
  284. } catch (\Exception $exception) {
  285. Db::rollback();
  286. return "失败:" . $exception->getMessage();
  287. }
  288. return true;
  289. }
  290. /**
  291. * 修改积分
  292. * @param $post
  293. */
  294. public function ModifyScore($post)
  295. {
  296. $user = User::getUserById($post['uid']);
  297. if (empty($user)) {
  298. return "用户不存在";
  299. }
  300. Db::startTrans();
  301. try {
  302. if ($post['state'] == 1) {
  303. $afterScore = $user['score'] + $post['score'];
  304. } else {
  305. $afterScore = $user['score'] - $post['score'];
  306. if ($afterScore < 0) {
  307. return "账号积分不足";
  308. }
  309. }
  310. $moneyLog = [
  311. 'uid' => $post['uid'],
  312. 'type' => $post['type'] ?? 0,
  313. 'score' => $post['score'],
  314. 'create_at' => date('Y-m-d H:i:s'),
  315. 'scene' => $post['scene'] ?? 0,
  316. 'from_id' => $post['from_id'] ?? '0',
  317. 'state' => $post['state'] ?? '0',
  318. 'before_score' => $user['score'],
  319. 'after_score' => $afterScore,
  320. 'uid2' => $post['uid2'] ?? 0,
  321. ];
  322. // 子级path变更
  323. ScoreLog::AddScoreLog($moneyLog);
  324. User::UpdateUserScore($user['id'], $afterScore);
  325. Db::commit();
  326. } catch (\Exception $exception) {
  327. Db::rollback();
  328. return "失败:" . $exception->getMessage();
  329. }
  330. return true;
  331. }
  332. /**
  333. * 删除用户
  334. * @param $id
  335. */
  336. public function delUser($id)
  337. {
  338. $user = User::getUserById($id);
  339. if (empty($user)) {
  340. return "用户不存在";
  341. }
  342. if (User::updateStatus($id, 3) !== 1) {
  343. return false;
  344. }
  345. return true;
  346. }
  347. /* 注册用户数量统计
  348. * @param string $time 时间节点如:2023-03-01
  349. * @return
  350. * @throws \think\db\exception\DbException
  351. */
  352. public static function getCountByTime($time = '0')
  353. {
  354. $cacheKey = "caches:user:counts_{$time}";
  355. if (!Cache::has($cacheKey)) {
  356. $data = UserModel::where(['status' => 1])
  357. ->where(function ($query) use ($time) {
  358. if ($time) {
  359. $query->where('reg_time', '>=', $time);
  360. }
  361. })->count('id');
  362. if ($data) {
  363. Cache::set($cacheKey, $data, rand(3, 5));
  364. }
  365. return $data;
  366. }
  367. return Cache::get($cacheKey);
  368. }
  369. /**
  370. * 判断操作类型,true-死循环 false-正常
  371. * @param $pid
  372. * @param $path
  373. * @return int
  374. */
  375. private function getOperateType($uid, $path, $pid, $pUserPath)
  376. {
  377. // $pUserPathArr = explode(',', $pUserPath);
  378. list($isFallLevel, $prefixPath) = $this->isFallLevel($uid, $pid);
  379. if ($isFallLevel) {
  380. return [true, $prefixPath];
  381. }
  382. return [false, null];
  383. }
  384. private function modifypidByUpdateNextLevel($id, $userPid, $path, $pid, $parentUserPath)
  385. {
  386. $userPath = explode(',', $path);
  387. // 上级的节点信息
  388. User::modifyUserPidAndPath($pid, $userPid, $path);
  389. $this->iteraMidifyPathByPid($userPath, $pid);
  390. // 更新被修改的节点信息
  391. $newUserPathArr = $userPath;
  392. $newUserPathArr[] = $pid;
  393. User::modifyUserPidAndPath($id, $pid, implode(',', $newUserPathArr));
  394. $this->iteraMidifyPathByPid($newUserPathArr, $id);
  395. return true;
  396. }
  397. private function iteraMidifyPathByPid($newUserPathArr, $pid)
  398. {
  399. $newUserPathArr[] = $pid;
  400. $result = Db::table(User::$table)
  401. ->where([
  402. 'pid' => $pid
  403. ])
  404. ->field(['id', 'path'])
  405. ->chunk(100, function ($users) use ($pid, $newUserPathArr) {
  406. foreach ($users as $user) {
  407. User::modifyUserPath($user['id'], implode(',', $newUserPathArr));
  408. $this->iteraMidifyPathByPid($newUserPathArr, $user['id']);
  409. }
  410. });
  411. return $result;
  412. }
  413. private function modifypidByResetTopLevel($id, $path, $pid, $parentUserPath, $prefixPath)
  414. {
  415. $newUserPathArr[] = $pid;
  416. $this->updatePidAndPathByPath($id, $prefixPath);
  417. $parentUser = User::getUserById($pid);
  418. $newUserPathArr = explode(',', $parentUser['path']);
  419. $newUserPathArr[] = $pid;
  420. User::modifyUserPidAndPath($id, $pid, implode(',', $newUserPathArr));
  421. $this->iteraMidifyPathByPid($newUserPathArr, $id);
  422. return true;
  423. // $result = User::modifyUserPidAndPath($pid, 0, '');
  424. // if (!$result) return false;
  425. // return User::modifyUserPidAndPath($id, $pid, implode(',', $newUserPathArr));
  426. }
  427. private function isFallLevel($uid, $pid)
  428. {
  429. $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));
  430. if (empty($user)) {
  431. return [false, null];
  432. }
  433. $userPath = explode(',', $user[0]['path']);
  434. $uidIndex = array_search($uid, $userPath);
  435. if ($uidIndex < array_search($pid, $userPath)) {
  436. $returnPath = [];
  437. if (isset($userPath[$uidIndex - 1])) {
  438. $returnPath[] = $userPath[$uidIndex - 1];
  439. }
  440. $returnPath[] = $userPath[$uidIndex];
  441. $returnPath[] = $userPath[$uidIndex + 1];
  442. return [true, $returnPath];
  443. }
  444. return [false, null];
  445. }
  446. private function updatePidAndPathByPath($uid, $prefixPath)
  447. {
  448. $newTopUid = $prefixPath[count($prefixPath) - 1];
  449. // 从阶段处更新,分支出来作为第一层
  450. User::modifyUserPidAndPath($newTopUid, 0, '');
  451. User::modifyUserPidAndPathByPid($uid, 0, '');
  452. $newUserPathArr = [];
  453. return $this->iteraMidifyPathByPid($newUserPathArr, $newTopUid);
  454. }
  455. }