UserLogic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 function getList($page, $limit, $where, $sort, $userMap)
  90. {
  91. $where[] = ['status', '<>', 3];
  92. $userDao = new User();
  93. $count = $userDao->getCount($where, $userMap);
  94. $list = $userDao->getPageList($page, $limit, $where, $sort, $userMap);
  95. foreach ($list as &$item) {
  96. //团队会员(包括1、2级和自身)的积分账户合计、余额账户合计
  97. // 计算团队成员(包括1、2级和自身)ID
  98. $teamIds = $this->getTeamMoneyAndScore($item['id']);
  99. // 积分账户合计
  100. $item['score_total'] = $teamIds['score'];
  101. // 余额账户合计
  102. $item['money_total'] = $teamIds['money'];
  103. }
  104. $data = [
  105. 'code' => 0,
  106. 'msg' => Db::getLastSql(),
  107. 'count' => $count,
  108. 'data' => $list,
  109. ];
  110. return json($data);
  111. }
  112. /**
  113. * 获取团队自身,一级、二级自己的余额/积分
  114. * @param $uid
  115. */
  116. private function getTeamMoneyAndScore($uid)
  117. {
  118. $cacheKey = 'userLogicTeamIds_' . $uid;
  119. if (!Cache::has($cacheKey)) {
  120. // 自身
  121. $user = Db::table(User::$table)
  122. ->where('id', $uid)
  123. ->field(['id', 'score', 'money'])
  124. ->find();
  125. $totalScore = $user['score'];
  126. $totalMoney = $user['money'];
  127. // 一级子用户
  128. Db::table(User::$table)
  129. ->where('pid', $uid)
  130. ->field(['id', 'score', 'money'])
  131. ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
  132. foreach ($users as $user) {
  133. $uids[] = $user['id'];
  134. $totalScore += $user['score'];
  135. $totalMoney += $user['money'];
  136. }
  137. // 二级子用户
  138. Db::table(User::$table)
  139. ->whereIn('pid', $uids)
  140. ->field(['id', 'score', 'money'])
  141. ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
  142. foreach ($users as $user) {
  143. $totalScore += $user['score'];
  144. $totalMoney += $user['money'];
  145. }
  146. });
  147. }, ['score', 'money']);
  148. Cache::set($cacheKey, ['score' => $totalScore, 'money' => sprintf("%.2f", $totalMoney)], 5 * 60);
  149. }
  150. return Cache::get($cacheKey);
  151. }
  152. /**
  153. * 修改用户手机号码
  154. * @param mixed $uid
  155. * @param mixed $phone
  156. */
  157. public function modifyPhone($uid, $phone)
  158. {
  159. // 判断手机号码是否使用过
  160. $user = User::getUserById($uid);
  161. if (empty($user)) return '用户不存在';
  162. if ($user['mobile'] == $phone) return "请输入新的手机号码";
  163. if (User::getUserByMobile($phone)) return "该手机号码已注册";
  164. // 修改用户信息
  165. try {
  166. $result = User::ModifyMobile($uid, $phone);
  167. if (!$result) return "更新手机号码失败,请稍后重试";
  168. } catch (\Exception $e) {
  169. return '失败' . $e->getMessage();
  170. }
  171. return true;
  172. }
  173. /**
  174. * 修改用户所属上级
  175. * @param mixed $uid
  176. * @param mixed $pid
  177. */
  178. public function modifypid($uid, $pid)
  179. {
  180. $user = User::getUserById($uid);
  181. if (empty($user)) return '用户不存在';
  182. // 查询pid是否存在用户path中
  183. if ($uid == $pid) {
  184. return "不能修改自己为上级";
  185. }
  186. if ($user['pid'] == $pid) {
  187. return "该用户已所属待变更的上级,不能修改";
  188. }
  189. // 当前用户关系层级链路
  190. $newUserPath = "";
  191. if ($pid == 0) {
  192. $newPathPrefix = $user['id'];
  193. } else {
  194. $pUser = User::getUserById($pid);
  195. if (empty($pUser)) {
  196. return "待变更的上级用户不存在";
  197. }
  198. $userPathArr = explode(',', $user['path']);
  199. if (in_array($pid, $userPathArr)) {
  200. $pidIndex = array_search($pid, $userPathArr);
  201. $userPathArrPrefix = array_slice($userPathArr, 0, $pidIndex + 1);
  202. } else {
  203. $pidIndex = array_search($user['pid'], $userPathArr);
  204. $userPathArrPrefix = array_slice($userPathArr, 0, $pidIndex);
  205. $userPathArrPrefix[] = $pid;
  206. }
  207. $newUserPath = implode(',', $userPathArrPrefix);
  208. // 子级用户Path待替换关系层级前部分链表
  209. $userPathArrPrefix[] = $user['id'];
  210. $newPathPrefix = implode(',', $userPathArrPrefix);
  211. }
  212. // 子级用户Path被替换关系层级前部分链表
  213. $oldPathPrefix = $user['path'] == 0 ? $uid : $user['path'] . ',' . $uid;
  214. Db::startTrans();
  215. try {
  216. // 子级path变更
  217. $result = Db::table(User::$table)
  218. ->where([
  219. ['path', 'like', $oldPathPrefix . '%'],
  220. ['id', '<>', $uid]
  221. ])
  222. ->field(['id', 'path'])
  223. ->chunk(100, function ($users) use ($pid, $oldPathPrefix, $newPathPrefix, $uid) {
  224. foreach ($users as $user) {
  225. $newPath = str_replace($oldPathPrefix, $newPathPrefix, $user['path']);
  226. User::modifyUserPath($user['id'], $newPath);
  227. }
  228. });
  229. if (!$result) {
  230. Db::rollback();
  231. return "修改用户所属上级失败,请确认用户的层级关系";
  232. }
  233. // 更新用户Pid,Path
  234. User::modifyUserPidAndPath($uid, $pid, $newUserPath);
  235. Db::commit();
  236. } catch (\Exception $exception) {
  237. Db::rollback();
  238. return "失败:" . $exception->getMessage();
  239. }
  240. return true;
  241. }
  242. /**
  243. * 修改余额
  244. * @param mixed $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 mixed $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 mixed
  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. }