UserLogic.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 think\facade\Cache;
  8. use think\facade\Db;
  9. class UserLogic
  10. {
  11. public function getList($page, $limit, $where, $sort, $userMap)
  12. {
  13. $where[] = ['status', '<>', 3];
  14. $userDao = new User();
  15. $count = $userDao->getCount($where, $userMap);
  16. $list = $userDao->getPageList($page, $limit, $where, $sort, $userMap);
  17. foreach ($list as &$item) {
  18. //团队会员(包括1、2级和自身)的积分账户合计、余额账户合计
  19. // 计算团队成员(包括1、2级和自身)ID
  20. $teamIds = $this->getTeamMoneyAndScore($item['id']);
  21. // 积分账户合计
  22. $item['score_total'] = $teamIds['score'];
  23. // 余额账户合计
  24. $item['money_total'] = $teamIds['money'];
  25. }
  26. $data = [
  27. 'code' => 0,
  28. 'msg' => Db::getLastSql(),
  29. 'count' => $count,
  30. 'data' => $list,
  31. ];
  32. return json($data);
  33. }
  34. /**
  35. * 获取团队
  36. * @param $uid
  37. */
  38. private function getTeamMoneyAndScore($uid)
  39. {
  40. $cacheKey = 'userLogicTeamIds_' . $uid;
  41. if (!Cache::has($cacheKey)) {
  42. // 自身
  43. $user = Db::table(User::$table)
  44. ->where('id', $uid)
  45. ->field(['id', 'score', 'money'])
  46. ->find();
  47. $totalScore = $user['score'];
  48. $totalMoney = $user['money'];
  49. // 一级子用户
  50. Db::table(User::$table)
  51. ->where('pid', $uid)
  52. ->field(['id', 'score', 'money'])
  53. ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
  54. foreach ($users as $user) {
  55. $uids[] = $user['id'];
  56. $totalScore += $user['score'];
  57. $totalMoney += $user['money'];
  58. }
  59. // 二级子用户
  60. Db::table(User::$table)
  61. ->whereIn('pid', $uids)
  62. ->field(['id', 'score', 'money'])
  63. ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
  64. foreach ($users as $user) {
  65. $totalScore += $user['score'];
  66. $totalMoney += $user['money'];
  67. }
  68. });
  69. }, ['score', 'money']);
  70. Cache::set($cacheKey, ['score' => $totalScore, 'money' => sprintf("%.2f", $totalMoney)], 5 * 60);
  71. }
  72. return Cache::get($cacheKey);
  73. }
  74. /**
  75. * 修改用户手机号码
  76. * @param mixed $uid
  77. * @param mixed $phone
  78. */
  79. public function modifyPhone($uid, $phone)
  80. {
  81. // 判断手机号码是否使用过
  82. $user = User::getUserById($uid);
  83. if ($user['mobile'] == $phone) {
  84. return "请输入新的手机号码";
  85. }
  86. $user = User::getUserByMobile($phone);
  87. if ($user) {
  88. return "该手机号码已注册";
  89. }
  90. // 修改用户信息
  91. try {
  92. $result = User::ModifyMobile($uid, $phone);
  93. if (!$result) {
  94. return "更新手机号码失败,请稍后重试";
  95. }
  96. } catch (\Exception $e) {
  97. return '失败' . $e->getMessage();
  98. }
  99. return true;
  100. }
  101. /**
  102. * 修改用户所属上级
  103. * @param mixed $uid
  104. * @param mixed $pid
  105. */
  106. public function modifypid($uid, $pid)
  107. {
  108. // 查询pid是否存在用户path中
  109. $user = User::getUserById($uid);
  110. if ($uid == $pid) {
  111. return "不能修改自己为上级";
  112. }
  113. if ($user['pid'] == $pid) {
  114. return "该用户已所属待变更的上级,不能修改";
  115. }
  116. // 当前用户关系层级链路
  117. $newUserPath = "";
  118. if ($pid == 0) {
  119. $newPathPrefix = $user['id'];
  120. } else {
  121. $pUser = User::getUserById($pid);
  122. if (empty($pUser)) {
  123. return "待变更的上级用户不存在";
  124. }
  125. $userPathArr = explode(',', $user['path']);
  126. if (in_array($pid, $userPathArr)) {
  127. $pidIndex = array_search($pid, $userPathArr);
  128. $userPathArrPrefix = array_slice($userPathArr, 0, $pidIndex + 1);
  129. } else {
  130. $pidIndex = array_search($user['pid'], $userPathArr);
  131. $userPathArrPrefix = array_slice($userPathArr, 0, $pidIndex);
  132. $userPathArrPrefix[] = $pid;
  133. }
  134. $newUserPath = implode(',', $userPathArrPrefix);
  135. // 子级用户Path待替换关系层级前部分链表
  136. $userPathArrPrefix[] = $user['id'];
  137. $newPathPrefix = implode(',', $userPathArrPrefix);
  138. }
  139. // 子级用户Path被替换关系层级前部分链表
  140. $oldPathPrefix = $user['path'] == 0 ? $uid : $user['path'] . ',' . $uid;
  141. Db::startTrans();
  142. try {
  143. // 子级path变更
  144. $result = Db::table(User::$table)
  145. ->where([
  146. ['path', 'like', $oldPathPrefix . '%'],
  147. ['id', '<>', $uid]
  148. ])
  149. ->field(['id', 'path'])
  150. ->chunk(100, function ($users) use ($pid, $oldPathPrefix, $newPathPrefix, $uid) {
  151. foreach ($users as $user) {
  152. $newPath = str_replace($oldPathPrefix, $newPathPrefix, $user['path']);
  153. User::modifyUserPath($user['id'], $newPath);
  154. }
  155. });
  156. if (!$result) {
  157. Db::rollback();
  158. return "修改用户所属上级失败,请确认用户的层级关系";
  159. }
  160. // 更新用户Pid,Path
  161. User::modifyUserPidAndPath($uid, $pid, $newUserPath);
  162. Db::commit();
  163. } catch (\Exception $exception) {
  164. Db::rollback();
  165. return "失败:" . $exception->getMessage();
  166. }
  167. return true;
  168. }
  169. /**
  170. * 修改余额
  171. * @param mixed $post
  172. */
  173. public function ModifyMoney($post)
  174. {
  175. $user = User::getUserById($post['uid']);
  176. if (empty($user)) {
  177. return "用户不存在";
  178. }
  179. Db::startTrans();
  180. try {
  181. if ($post['state'] == 1) {
  182. $afterMoney = $user['money'] + $post['money'];
  183. } else {
  184. $afterMoney = $user['money'] - $post['money'];
  185. if ($afterMoney < 0) {
  186. return "账号余额不足";
  187. }
  188. }
  189. $afterMoney = round($afterMoney, 2);
  190. $moneyLog = [
  191. 'uid' => $post['uid'],
  192. 'type' => $post['type'] ?? 0,
  193. 'money' => $post['money'],
  194. 'create_at' => date('Y-m-d H:i:s'),
  195. 'state' => $post['state'] ?? '0',
  196. 'from_id' => $post['from_id'] ?? '0',
  197. 'before_money' => $user['money'],
  198. 'after_money' => $afterMoney,
  199. 'uid2' => $post['uid2'] ?? 0,
  200. 'free_type' => $post['free_type'] ?? '',
  201. 'remark' => $post['remark'],
  202. ];
  203. // 子级path变更
  204. MoneyLog::AddMoneyLog($moneyLog);
  205. User::UpdateUserMoney($user['id'], $afterMoney);
  206. Db::commit();
  207. } catch (\Exception $exception) {
  208. Db::rollback();
  209. return "失败:" . $exception->getMessage();
  210. }
  211. return true;
  212. }
  213. /**
  214. * 修改积分
  215. * @param mixed $post
  216. */
  217. public function ModifyScore($post)
  218. {
  219. $user = User::getUserById($post['uid']);
  220. if (empty($user)) {
  221. return "用户不存在";
  222. }
  223. Db::startTrans();
  224. try {
  225. if ($post['state'] == 1) {
  226. $afterScore = $user['score'] + $post['score'];
  227. } else {
  228. $afterScore = $user['score'] - $post['score'];
  229. if ($afterScore < 0) {
  230. return "账号积分不足";
  231. }
  232. }
  233. $moneyLog = [
  234. 'uid' => $post['uid'],
  235. 'type' => $post['type'] ?? 0,
  236. 'score' => $post['score'],
  237. 'create_at' => date('Y-m-d H:i:s'),
  238. 'scene' => $post['scene'] ?? 0,
  239. 'from_id' => $post['from_id'] ?? '0',
  240. 'state' => $post['state'] ?? '0',
  241. 'before_score' => $user['score'],
  242. 'after_score' => $afterScore,
  243. 'uid2' => $post['uid2'] ?? 0,
  244. ];
  245. // 子级path变更
  246. ScoreLog::AddScoreLog($moneyLog);
  247. User::UpdateUserScore($user['id'], $afterScore);
  248. Db::commit();
  249. } catch (\Exception $exception) {
  250. Db::rollback();
  251. return "失败:" . $exception->getMessage();
  252. }
  253. return true;
  254. }
  255. /**
  256. * 删除用户
  257. * @param $id
  258. */
  259. public function delUser($id)
  260. {
  261. $user = User::getUserById($id);
  262. if (empty($user)) {
  263. return "用户不存在";
  264. }
  265. if (User::updateState($id, 3) !== 1) {
  266. return false;
  267. }
  268. return true;
  269. }
  270. /* 注册用户数量统计
  271. * @param string $time 时间节点如:2023-03-01
  272. * @return mixed
  273. * @throws \think\db\exception\DbException
  274. */
  275. public static function getCountByTime($time = '0')
  276. {
  277. $cacheKey = "caches:user:counts_{$time}";
  278. if (!Cache::has($cacheKey)) {
  279. $data = UserModel::where(['status' => 1])
  280. ->where(function ($query) use ($time) {
  281. if ($time) {
  282. $query->where('reg_time', '>=', $time);
  283. }
  284. })->count('id');
  285. if ($data) {
  286. Cache::set($cacheKey, $data, rand(3, 5));
  287. }
  288. return $data;
  289. }
  290. return Cache::get($cacheKey);
  291. }
  292. }