| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569 |
- <?php
- namespace app\admin\logic;
- use app\admin\model\dao\MoneyLog;
- use app\admin\model\dao\ScoreLog;
- use app\admin\model\dao\User;
- use app\common\model\UserModel;
- use app\common\model\UserMoneyModel;
- use think\facade\Cache;
- use think\facade\Db;
- use function Qiniu\explodeUpToken;
- class UserLogic
- {
- public static function forbid($id)
- {
- $user = User::getUserOrEmptyById($id);
- if (empty($user)) return [false, '数据不存在'];
- if ($user['status'] == 0) return [false, '该用户已被禁用'];
- $result = User::updateStatus($id, 0);
- return $result ? [true, '禁用成功'] : [false, '禁用失败'];
- }
- public static function enable($id)
- {
- $user = User::getUserOrEmptyById($id);
- if (empty($user)) return [false, '数据不存在'];
- if ($user['status'] == 1) return [false, '该用户已启用'];
- $result = User::updateStatus($id, 1);
- return $result ? [true, '禁用成功'] : [false, '禁用失败'];
- }
- public static function getUserDetail($id)
- {
- $user = new User();
- return $user->getUserDetail($id);
- }
- public static function levelset($post)
- {
- $level = $post['level'];
- if ($level > 4) {
- return '最高等级4级';
- }
- $user = User::getUserOrEmptyById($post['id']);
- if (empty($user)) return '用户不存在';
- $level_type = 1;
- if ($level > $user['level']) {
- $level_type = 2;
- }
- Db::startTrans();
- try {
- $userData = ['level' => $level, 'level_type' => $level_type];
- User::update($post['id'], $userData);
- Db::commit();
- } catch (\Exception $e) {
- Db::rollback();
- return '失败' . $e->getMessage();
- }
- return true;
- }
- public static function lookpidlevel($id)
- {
- $path = Db::name('user')->where('id', $id)->value('path');
- if (empty($path)) {
- return [0, []];
- }
- $arr = explode(',', $path);
- $ids = $arr;
- $ids = implode(',', $ids);
- $order = 'field(id,' . $ids . ')';
- $where = array();
- $where[] = ['uid', 'in', $arr];
- sr_log($where);
- $user = new UserModel();
- $count = $user
- ->withJoin('userData', 'INNER')
- ->where($where)
- ->count();
- $list = $user
- ->withJoin('userData', 'INNER')
- ->where($where)
- ->order(Db::raw($order))
- ->select();
- return [$count, $list];
- }
- public static function getExportList($where, $page, $limit)
- {
- return (new UserModel())
- ->where($where)
- ->withJoin('userData', 'INNER')
- ->where($where)
- ->page($page, $limit)
- ->order('id', 'desc')
- ->select()
- ->toArray();
- }
- public static function recycleCountSet($post)
- {
- $user = User::getUserById($post['id']);
- if (empty($user)) return '用户不存在';
- if (empty($post['recycle_count']) || !preg_match("/^[1-9][0-9]*$/", $post['recycle_count']) || $post['recycle_count'] > 500) {
- return '回收卡数量格式有误';
- }
- try {
- $updateData = ['recycle_count' => $post['recycle_count']];
- $result = User::update($user['id'], $updateData);
- if (!$result) return "更新临时卡数量失败";
- } catch (\Exception $e) {
- return '失败' . $e->getMessage();
- }
- return true;
- }
- public function getList($page, $limit, $where, $sort, $userMap)
- {
- $where[] = ['status', '<>', 3];
- $userDao = new User();
- $count = $userDao->getCount($where, $userMap);
- $list = $userDao->getPageList($page, $limit, $where, $sort, $userMap);
- foreach ($list as &$item) {
- //团队会员(包括1、2级和自身)的积分账户合计、余额账户合计
- // 计算团队成员(包括1、2级和自身)ID
- $teamIds = $this->getTeamMoneyAndScore($item['id']);
- // 积分账户合计
- $item['score_total'] = $teamIds['score'];
- // 余额账户合计
- $item['money_total'] = $teamIds['money'];
- }
- $data = [
- 'code' => 0,
- 'msg' => Db::getLastSql(),
- 'count' => $count,
- 'data' => $list,
- ];
- return json($data);
- }
- /**
- * 获取团队自身,一级、二级自己的余额/积分
- * @param $uid
- */
- private function getTeamMoneyAndScore($uid)
- {
- $cacheKey = 'userLogicTeamIds_' . $uid;
- if (!Cache::has($cacheKey)) {
- // 自身
- $user = Db::table(User::$table)
- ->where('id', $uid)
- ->field(['id', 'score', 'money'])
- ->find();
- $totalScore = $user['score'];
- $totalMoney = $user['money'];
- // 一级子用户
- Db::table(User::$table)
- ->where('pid', $uid)
- ->field(['id', 'score', 'money'])
- ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
- foreach ($users as $user) {
- $uids[] = $user['id'];
- $totalScore += $user['score'];
- $totalMoney += $user['money'];
- }
- // 二级子用户
- Db::table(User::$table)
- ->whereIn('pid', $uids)
- ->field(['id', 'score', 'money'])
- ->chunk(100, function ($users) use (&$totalScore, &$totalMoney) {
- foreach ($users as $user) {
- $totalScore += $user['score'];
- $totalMoney += $user['money'];
- }
- });
- }, ['score', 'money']);
- Cache::set($cacheKey, ['score' => $totalScore, 'money' => sprintf("%.2f", $totalMoney)], 5 * 60);
- }
- return Cache::get($cacheKey);
- }
- /**
- * 修改用户手机号码
- * @param $uid
- * @param $phone
- */
- public function modifyPhone($uid, $phone)
- {
- // 判断手机号码是否使用过
- $user = User::getUserById($uid);
- if (empty($user)) return '用户不存在';
- if ($user['mobile'] == $phone) return "请输入新的手机号码";
- if (User::getUserByMobile($phone)) return "该手机号码已注册";
- // 修改用户信息
- try {
- $updateData = [
- 'mobile' => $phone,
- ];
- // 按照账号原规则,手机号码作为用户名,同时修改新的用户名
- if ($user['mobile'] == $user['user_name']) {
- $updateData['user_name'] = $phone;
- }
- $result = User::update($uid, $updateData);
- if (!$result) return "更新手机号码失败,请稍后重试";
- } catch (\Exception $e) {
- return '失败' . $e->getMessage();
- }
- return true;
- }
- /**
- * 修改用户所属上级
- * @param $uid
- * @param $pid
- */
- public function modifypid($uid, $pid)
- {
- $user = User::getUserById($uid);
- if (empty($user)) return '用户不存在';
- // 查询pid是否存在用户path中
- if ($uid == $pid) {
- return "不能修改自己为上级";
- }
- if ($user['pid'] == $pid) {
- return "该用户已所属待变更的上级,不能修改";
- }
- $parentUser = User::getUserById($pid);
- if (empty($parentUser)) {
- return '所属上级不存在';
- }
- // 判断降级或升级
- // 判断升级,降级、插入
- list($operateType, $prefixPath) = $this->getOperateType($user['id'], $user['path'], $pid, $parentUser['path']);
- Db::startTrans();
- try {
- if ($operateType) {
- $result = $this->modifypidByResetTopLevel($user['id'], $user['path'], $pid, $parentUser['path'], $prefixPath);
- } else {
- // 正常,迭代修改下级
- $result = $this->modifypidByUpdateNextLevel($user['id'], $user['pid'], $user['path'], $pid, $parentUser['path']);
- }
- if (!$result) {
- Db::rollback();
- return "修改用户所属上级失败,请确认用户的层级关系";
- }
- Db::commit();
- } catch (\Exception $exception) {
- Db::rollback();
- return "失败:" . $exception->getMessage();
- }
- return true;
- // 升级,abcdef,e升级到b后 分为两种情况 1.abef 2.abcd
- // 降级 abcdef,c降级到e后 分为两种情况 1. ecf 2.abcd
- // 插入 abcdef,插入j到b后 分为两种情况 1.abj 2.abcdef
- }
- /**
- * 修改余额
- * @param $post
- */
- public function ModifyMoney($post)
- {
- if (strlen(substr(strrchr($post['money'], "."), 1)) > 4) {
- return "变更金额格式错误";
- }
- $user = User::getUserById($post['uid']);
- if (empty($user)) {
- return "用户不存在";
- }
- Db::startTrans();
- try {
- if ($post['state'] == 1) {
- $afterMoney = $user['money'] + $post['money'];
- } else {
- $afterMoney = $user['money'] - $post['money'];
- if ($afterMoney < 0) {
- return "账号余额不足";
- }
- }
- $afterMoney = round($afterMoney, 4);
- $moneyLog = [
- 'uid' => $post['uid'],
- 'type' => $post['type'] ?? 0,
- 'money' => $post['money'],
- 'create_at' => date('Y-m-d H:i:s'),
- 'state' => $post['state'] ?? '0',
- 'from_id' => $post['from_id'] ?? '0',
- 'before_money' => $user['money'],
- 'after_money' => $afterMoney,
- 'uid2' => $post['uid2'] ?? 0,
- 'free_type' => $post['free_type'] ?? '',
- 'remark' => $post['remark'],
- ];
- // 子级path变更
- MoneyLog::AddMoneyLog($moneyLog);
- User::UpdateUserMoney($user['id'], $afterMoney);
- Db::commit();
- } catch (\Exception $exception) {
- Db::rollback();
- return "失败:" . $exception->getMessage();
- }
- return true;
- }
- /**
- * 修改积分
- * @param $post
- */
- public function ModifyScore($post)
- {
- $user = User::getUserById($post['uid']);
- if (empty($user)) {
- return "用户不存在";
- }
- Db::startTrans();
- try {
- if ($post['state'] == 1) {
- $afterScore = $user['score'] + $post['score'];
- } else {
- $afterScore = $user['score'] - $post['score'];
- if ($afterScore < 0) {
- return "账号积分不足";
- }
- }
- $moneyLog = [
- 'uid' => $post['uid'],
- 'type' => $post['type'] ?? 0,
- 'score' => $post['score'],
- 'create_at' => date('Y-m-d H:i:s'),
- 'scene' => $post['scene'] ?? 0,
- 'from_id' => $post['from_id'] ?? '0',
- 'state' => $post['state'] ?? '0',
- 'before_score' => $user['score'],
- 'after_score' => $afterScore,
- 'uid2' => $post['uid2'] ?? 0,
- ];
- // 子级path变更
- ScoreLog::AddScoreLog($moneyLog);
- User::UpdateUserScore($user['id'], $afterScore);
- Db::commit();
- } catch (\Exception $exception) {
- Db::rollback();
- return "失败:" . $exception->getMessage();
- }
- return true;
- }
- /**
- * 删除用户
- * @param $id
- */
- public function delUser($id)
- {
- $user = User::getUserById($id);
- if (empty($user)) {
- return "用户不存在";
- }
- if (User::updateStatus($id, 3) !== 1) {
- return false;
- }
- return true;
- }
- /* 注册用户数量统计
- * @param string $time 时间节点如:2023-03-01
- * @return
- * @throws \think\db\exception\DbException
- */
- public static function getCountByTime($time = '0')
- {
- $cacheKey = "caches:user:counts_{$time}";
- if (!Cache::has($cacheKey)) {
- $data = UserModel::where(['status' => 1])
- ->where(function ($query) use ($time) {
- if ($time) {
- $query->where('reg_time', '>=', $time);
- }
- })->count('id');
- if ($data) {
- Cache::set($cacheKey, $data, rand(3, 5));
- }
- return $data;
- }
- return Cache::get($cacheKey);
- }
- /**
- * 判断操作类型,true-死循环 false-正常
- * @param $pid
- * @param $path
- * @return int
- */
- private function getOperateType($uid, $path, $pid, $pUserPath)
- {
- // $pUserPathArr = explode(',', $pUserPath);
- list($isFallLevel, $prefixPath) = $this->isFallLevel($uid, $pid);
- if ($isFallLevel) {
- return [true, $prefixPath];
- }
- return [false, null];
- }
- private function modifypidByUpdateNextLevel($id, $userPid, $path, $pid, $parentUserPath)
- {
- $newPath = explode(',', $parentUserPath);
- $newPath[] = $pid;
- // 1. 修改$pidUser['pid'] = $idUser['pid'], $pidUser['path'] = $idUser['path']
- User::modifyUserPidAndPath($id, $pid, implode(',', $newPath));
- // 迭代更新子级path
- $this->iteraMidifyPathByPid($newPath, $id);
- return true;
- }
- private function iteraMidifyPathByPid($newUserPathArr, $pid)
- {
- $newUserPathArr[] = $pid;
- $result = Db::table(User::$table)
- ->where([
- 'pid' => $pid
- ])
- ->field(['id', 'path'])
- ->chunk(100, function ($users) use ($pid, $newUserPathArr) {
- foreach ($users as $user) {
- User::modifyUserPath($user['id'], implode(',', $newUserPathArr));
- $this->iteraMidifyPathByPid($newUserPathArr, $user['id']);
- }
- });
- return $result;
- }
- private function modifypidByResetTopLevel($id, $path, $pid, $parentUserPath, $prefixPath)
- {
- // 1.迭代更新id所有下级的path,从path = ‘’开始
- $usersList = Db::table(User::$table)
- ->where(['pid' => $id])
- ->field(['id', 'path'])
- ->select();
- foreach ($usersList as $user) {
- $this->iteraMidifyPathByPid([], $user['id']);
- }
- // 2.修改id的下一级用户的pid =0 ,path = ‘’
- User::modifyUserPidAndPathByPid($id, 0, '');
- // 3. 修改$post['id']的pid = post['pid'],path = pUserPath.',pid'
- $parentUser = User::getUserById($pid);
- if (!empty($parentUser['path'])) {
- $newUserPathArr = explode(',', $parentUser['path']);
- }
- $newUserPathArr[] = $pid;
- User::modifyUserPidAndPath($id, $pid, implode(',', $newUserPathArr));
- return true;
- }
- private function isFallLevel($uid, $pid)
- {
- $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));
- if (empty($user)) {
- return [false, null];
- }
- $userPath = explode(',', $user[0]['path']);
- $uidIndex = array_search($uid, $userPath);
- if ($uidIndex < array_search($pid, $userPath)) {
- $returnPath = [];
- if (isset($userPath[$uidIndex - 1])) {
- $returnPath[] = $userPath[$uidIndex - 1];
- }
- $returnPath[] = $userPath[$uidIndex];
- $returnPath[] = $userPath[$uidIndex + 1];
- return [true, $returnPath];
- }
- return [false, null];
- }
- private function updatePidAndPathByPath($uid, $prefixPath)
- {
- $newTopUid = $prefixPath[count($prefixPath) - 1];
- // 从阶段处更新,分支出来作为第一层
- User::modifyUserPidAndPath($newTopUid, 0, '');
- User::modifyUserPidAndPathByPid($uid, 0, '');
- $newUserPathArr = [];
- return $this->iteraMidifyPathByPid($newUserPathArr, $newTopUid);
- }
- }
|