123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989 |
- <?php
- // +----------------------------------------------------------------------
- // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
- // +----------------------------------------------------------------------
- // | Author: CRMEB Team <admin@crmeb.com>
- // +----------------------------------------------------------------------
- namespace app\common\repositories\user;
- use app\common\dao\BaseDao;
- use app\common\dao\user\UserDao;
- use app\common\model\user\User;
- use app\common\model\user\UserGroup;
- use app\common\model\wechat\WechatUser;
- use app\common\repositories\BaseRepository;
- use app\common\repositories\store\coupon\StoreCouponRepository;
- use app\common\repositories\store\order\StoreOrderRepository;
- use app\common\repositories\system\attachment\AttachmentRepository;
- use app\common\repositories\wechat\RoutineQrcodeRepository;
- use crmeb\exceptions\AuthException;
- use crmeb\jobs\AutoUserPosterJob;
- use crmeb\jobs\SendNewPeopleCouponJob;
- use crmeb\services\JwtTokenService;
- use crmeb\services\QrcodeService;
- use crmeb\services\UploadService;
- use FormBuilder\Exception\FormBuilderException;
- use FormBuilder\Factory\Elm;
- use FormBuilder\Form;
- use Swoole\Coroutine;
- use Swoole\Coroutine\Channel;
- use think\exception\ValidateException;
- use think\facade\Queue;
- use think\model\Relation;
- use function GuzzleHttp\Psr7\str;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\DbException;
- use think\db\exception\ModelNotFoundException;
- use think\facade\Cache;
- use think\facade\Config;
- use think\facade\Db;
- use think\facade\Route;
- use think\Model;
- /**
- * Class UserRepository
- * @package app\common\repositories\user
- * @author xaboy
- * @day 2020-04-28
- * @mixin UserDao
- */
- class UserRepository extends BaseRepository
- {
- /**
- * UserRepository constructor.
- * @param UserDao $dao
- */
- public function __construct(UserDao $dao)
- {
- $this->dao = $dao;
- }
- public function promoter($uid)
- {
- return $this->dao->update($uid, ['is_promoter' => 1, 'promoter_time' => date('Y-m-d H:i:s')]);
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws FormBuilderException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-09
- */
- public function userForm($id)
- {
- $user = $this->dao->get($id);
- $user['uid'] = (string)$user['uid'];
- return Elm::createForm(Route::buildUrl('systemUserUpdate', compact('id'))->build(), [
- Elm::input('uid', '会员 ID', '')->disabled(true)->required(true),
- Elm::input('real_name', '真实姓名'),
- Elm::input('phone', '手机号'),
- Elm::date('birthday', '生日'),
- Elm::input('card_id', '身份证'),
- Elm::input('addres', '用户地址'),
- Elm::textarea('mark', '备注'),
- Elm::select('group_id', '会员分组')->options(function () {
- $data = app()->make(UserGroupRepository::class)->allOptions();
- $options = [];
- foreach ($data as $value => $label) {
- $options[] = compact('value', 'label');
- }
- return $options;
- }),
- Elm::selectMultiple('label_id', '会员标签')->options(function () {
- $data = app()->make(UserLabelRepository::class)->allOptions();
- $options = [];
- foreach ($data as $value => $label) {
- $value = (string)$value;
- $options[] = compact('value', 'label');
- }
- return $options;
- }),
- Elm::radio('is_promoter', '推广员', 1)->options([
- ['value' => 0, 'label' => '关闭'],
- ['value' => 1, 'label' => '开启'],
- ])->required()
- ])->setTitle('编辑')->formData($user->toArray());
- }
- /**
- * @param array $where
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-07
- */
- public function getList(array $where, $page, $limit)
- {
- $query = $this->dao->search($where)->with(['spread' => function ($query) {
- $query->field('uid,nickname,spread_uid');
- }, 'group']);
- $make = app()->make(UserLabelRepository::class);
- $count = $query->count($this->dao->getPk());
- $list = $query->page($page, $limit)->select()->each(function ($item) use ($make) {
- return $item->label = count($item['label_id']) ? $make->labels($item['label_id']) : [];
- });
- return compact('count', 'list');
- }
- public function merList(string $keyword, $page, $limit)
- {
- $query = $this->dao->searchMerUser($keyword);
- $count = $query->count($this->dao->getPk());
- $list = $query->page($page, $limit)->setOption('field', [])->field('uid,nickname,avatar,user_type,sex')->select();
- return compact('count', 'list');
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeGroupForm($id)
- {
- $isArray = is_array($id);
- if (!$isArray)
- $user = $this->dao->get($id);
- /** @var UserGroupRepository $make */
- $data = app()->make(UserGroupRepository::class)->allOptions();
- return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeGroup' : 'systemUserChangeGroup', $isArray ? [] : compact('id'))->build(), [
- Elm::hidden('ids', $isArray ? $id : [$id]),
- Elm::select('group_id', '用户分组', $isArray ? '' : $user->group_id)->options(function () use ($data) {
- $options = [['label' => '不设置', 'value' => '0']];
- foreach ($data as $value => $label) {
- $options[] = compact('value', 'label');
- }
- return $options;
- })
- ])->setTitle('修改用户分组');
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeLabelForm($id)
- {
- $isArray = is_array($id);
- if (!$isArray)
- $user = $this->dao->get($id);
- /** @var UserLabelRepository $make */
- $data = app()->make(UserLabelRepository::class)->allOptions();
- return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeLabel' : 'systemUserChangeLabel', $isArray ? [] : compact('id'))->build(), [
- Elm::hidden('ids', $isArray ? $id : [$id]),
- Elm::selectMultiple('label_id', '用户标签', $isArray ? [] : $user->label_id)->options(function () use ($data) {
- $options = [];
- foreach ($data as $value => $label) {
- $value = (string)$value;
- $options[] = compact('value', 'label');
- }
- return $options;
- })
- ])->setTitle('修改用户标签');
- }
- /**
- * @param $id
- * @return Form
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeNowMoneyForm($id)
- {
- return Elm::createForm(Route::buildUrl('systemUserChangeNowMoney', compact('id'))->build(), [
- Elm::radio('type', '修改余额', 1)->options([
- ['label' => '增加', 'value' => 1],
- ['label' => '减少', 'value' => 0],
- ])->required(),
- Elm::number('now_money', '金额')->required()->min(0)
- ])->setTitle('修改用户余额');
- }
- /**
- * @param $id
- * @param $adminId
- * @param $type
- * @param $nowMoney
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeNowMoney($id, $adminId, $type, $nowMoney)
- {
- $user = $this->dao->get($id);
- Db::transaction(function () use ($id, $adminId, $user, $type, $nowMoney) {
- $balance = $type == 1 ? bcadd($user->now_money, $nowMoney, 2) : bcsub($user->now_money, $nowMoney, 2);
- $user->save(['now_money' => $balance]);
- /** @var UserBillRepository $make */
- $make = app()->make(UserBillRepository::class);
- if ($type == 1) {
- $make->incBill($id, 'now_money', 'sys_inc_money', [
- 'link_id' => $adminId,
- 'status' => 1,
- 'title' => '系统增加余额',
- 'number' => $nowMoney,
- 'mark' => '系统增加了' . floatval($nowMoney) . '余额',
- 'balance' => $balance
- ]);
- } else {
- $make->decBill($id, 'now_money', 'sys_dec_money', [
- 'link_id' => $adminId,
- 'status' => 1,
- 'title' => '系统减少余额',
- 'number' => $nowMoney,
- 'mark' => '系统减少了' . floatval($nowMoney) . '余额',
- 'balance' => $balance
- ]);
- }
- });
- }
- /**
- * @param $password
- * @return false|string|null
- * @author xaboy
- * @day 2020/6/22
- */
- public function encodePassword($password)
- {
- return password_hash($password, PASSWORD_BCRYPT);
- }
- /**
- * @param WechatUser $wechatUser
- * @return BaseDao|array|Model|null
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-04-28
- */
- public function syncWechatUser(WechatUser $wechatUser, $userType = 'wechat')
- {
- $user = $this->dao->wechatUserIdBytUser($wechatUser->wechat_user_id);
- $request = request();
- if ($user) {
- $user->save([
- 'nickname' => $wechatUser['nickname'] ?: '',
- 'avatar' => $wechatUser['headimgurl'] ?: '',
- 'sex' => $wechatUser['sex'] ?: 0,
- 'last_time' => date('Y-m-d H:i:s'),
- 'last_ip' => $request->ip(),
- ]);
- } else
- $user = $this->create($userType, [
- 'account' => 'wx' . $wechatUser->wechat_user_id . time(),
- 'wechat_user_id' => $wechatUser->wechat_user_id,
- 'pwd' => $this->encodePassword(123456),
- 'nickname' => $wechatUser['nickname'] ?: '',
- 'avatar' => $wechatUser['headimgurl'] ?: '',
- 'sex' => $wechatUser['sex'] ?: 0,
- 'spread_uid' => 0,
- 'is_promoter' => 0,
- 'last_time' => date('Y-m-d H:i:s'),
- 'last_ip' => $request->ip()
- ]);
- return $user;
- }
- /**
- * @param string $type
- * @param array $userInfo
- * @return BaseDao|Model
- * @author xaboy
- * @day 2020-04-28
- */
- public function create(string $type, array $userInfo)
- {
- $userInfo['user_type'] = $type;
- $user = $this->dao->create($userInfo);
- try {
- Queue::push(SendNewPeopleCouponJob::class, $user->uid);
- } catch (\Exception $e) {
- }
- return $user;
- }
- /**
- * @param User $user
- * @return array
- * @author xaboy
- * @day 2020-04-29
- */
- public function createToken(User $user)
- {
- $service = new JwtTokenService();
- $exp = intval(Config::get('admin.user_token_valid_exp', 15));
- $token = $service->createToken($user->uid, 'user', strtotime("+ {$exp}day"));
- $this->cacheToken($token['token'], $token['out']);
- return $token;
- }
- /**
- * //TODO 登录成功后
- * @param User $user
- * @author xaboy
- * @day 2020/6/22
- */
- public function loginAfter(User $user)
- {
- $user->last_time = date('Y-m-d H:i:s', time());
- $user->last_ip = request()->ip();
- $user->save();
- }
- /**
- * @param string $token
- * @param int $exp
- * @author xaboy
- * @day 2020-04-29
- */
- public function cacheToken(string $token, int $exp)
- {
- Cache::store('file')->set('user_' . $token, time() + $exp, $exp);
- }
- /**
- * @param string $token
- * @author xaboy
- * @day 2020-04-29
- */
- public function checkToken(string $token)
- {
- $cache = Cache::store('file');
- $has = $cache->has('user_' . $token);
- if (!$has)
- throw new AuthException('无效的token');
- $lastTime = $cache->get('user_' . $token);
- if (($lastTime + (intval($cache->get('admin.user_token_valid_exp', 15))) * 24 * 60 * 60) < time())
- throw new AuthException('token 已过期');
- }
- /**
- * @param string $token
- * @author xaboy
- * @day 2020-04-29
- */
- public function updateToken(string $token)
- {
- Cache::store('file')->set('user_' . $token, time(), intval(Config::get('admin.user_token_valid_exp', 15)) * 24 * 60 * 60);
- }
- /**
- * @param string $token
- * @author xaboy
- * @day 2020-04-29
- */
- public function clearToken(string $token)
- {
- Cache::delete('user_' . $token);
- }
- /**
- * @param string $key
- * @param string $code
- * @author xaboy
- * @day 2020/6/1
- */
- public function checkCode(string $key, string $code)
- {
- $_code = Cache::get('am_captcha' . $key);
- if (!$_code) {
- throw new ValidateException('验证码过期');
- }
- if (strtolower($_code) != strtolower($code)) {
- throw new ValidateException('验证码错误');
- }
- //删除code
- Cache::delete('am_captcha' . $key);
- }
- /**
- * @param string $code
- * @return string
- * @author xaboy
- * @day 2020/6/1
- */
- public function createLoginKey(string $code)
- {
- $key = uniqid(microtime(true), true);
- Cache::set('am_captcha' . $key, $code, Config::get('admin.captcha_exp', 5) * 60);
- return $key;
- }
- public function registr(string $phone, ?string $pwd, $user_type = 'h5')
- {
- $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
- $data = [
- 'account' => $phone,
- 'pwd' => $pwd,
- 'nickname' => substr($phone, 0, 3) . '****' . substr($phone, 7, 4),
- 'avatar' => '/static/f.png',
- 'phone' => $phone,
- 'last_ip' => app('request')->ip()
- ];
- return $this->create($user_type, $data);
- }
- public function routineSpreadImage(User $user)
- {
- //小程序
- $name = md5('surt' . $user['uid'] . $user['is_promoter'] . date('Ymd')) . '.jpg';
- $attachmentRepository = app()->make(AttachmentRepository::class);
- $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
- $spreadBanner = systemGroupData('spread_banner');
- if (!count($spreadBanner)) return [];
- $siteName = systemConfig('site_name');
- $siteUrl = systemConfig('site_url');
- $uploadType = (int)systemConfig('upload_type') ?: 1;
- $urlCode = app()->make(QrcodeService::class)->getRoutineQrcodePath($name, 'pages/index/index', 'spid=' . $user['uid']);
- if (!$urlCode)
- throw new ValidateException('二维码生成失败');
- $filelink = [
- 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- ];
- if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
- if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
- $resRoutine = true;
- foreach ($spreadBanner as $key => &$item) {
- $posterInfo = '海报生成失败:(';
- $config = array(
- 'image' => array(
- array(
- 'url' => $urlCode, //二维码资源
- 'stream' => 0,
- 'left' => 114,
- 'top' => 790,
- 'right' => 0,
- 'bottom' => 0,
- 'width' => 120,
- 'height' => 120,
- 'opacity' => 100
- )
- ),
- 'text' => array(
- array(
- 'text' => $user['nickname'],
- 'left' => 250,
- 'top' => 840,
- 'fontPath' => $filelink['Bold'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '40,40,40', //字体颜色
- 'angle' => 0,
- ),
- array(
- 'text' => '邀请您加入' . $siteName,
- 'left' => 250,
- 'top' => 880,
- 'fontPath' => $filelink['Normal'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '40,40,40', //字体颜色
- 'angle' => 0,
- )
- ),
- 'background' => $item['pic']
- );
- $resRoutine = $resRoutine && $posterInfo = setSharePoster($config, 'routine/spread/poster');
- if (!is_array($posterInfo)) throw new ValidateException($posterInfo);
- $posterInfo['dir'] = tidy_url($posterInfo['dir'], 0, $siteUrl);
- if ($resRoutine) {
- $attachmentRepository->create($uploadType, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $posterInfo['name'],
- 'attachment_src' => $posterInfo['dir']
- ]);
- $item['poster'] = $posterInfo['dir'];
- }
- }
- return $spreadBanner;
- }
- public function wxQrcode(User $user)
- {
- $name = md5('uwx_i' . $user['uid'] . date('Ymd')) . '.jpg';
- return app()->make(QrcodeService::class)->getWechatQrcodePath($name, rtrim(systemConfig('site_url'), '/') . '?spread=' . $user['uid'] . '&spid=' . $user['uid']);
- }
- public function mpQrcode(User $user)
- {
- $name = md5('surt_i' . $user['uid'] . $user['is_promoter'] . date('Ymd')) . '.jpg';
- return app()->make(QrcodeService::class)->getRoutineQrcodePath($name, 'pages/index/index', 'spid=' . $user['uid']);
- }
- public function wxSpreadImage(User $user)
- {
- $name = md5('uwx' . $user['uid'] . $user['is_promoter'] . date('Ymd')) . '.jpg';
- $spreadBanner = systemGroupData('spread_banner');
- if (!count($spreadBanner)) return [];
- $siteName = systemConfig('site_name');
- $attachmentRepository = app()->make(AttachmentRepository::class);
- $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
- $siteUrl = rtrim(systemConfig('site_url'), '/');
- $uploadType = (int)systemConfig('upload_type') ?: 1;
- $resWap = true;
- //检测远程文件是否存在
- if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
- $imageInfo->delete();
- $imageInfo = null;
- }
- if (!$imageInfo) {
- $codeUrl = $siteUrl . '?spread=' . $user['uid'] . '&spid=' . $user['uid'];//二维码链接
- $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
- if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
- $imageInfo['dir'] = tidy_url($imageInfo['dir'], null, $siteUrl);
- $attachmentRepository->create(systemConfig('upload_type') ?: 1, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $imageInfo['name'],
- 'attachment_src' => $imageInfo['dir']
- ]);
- $urlCode = $imageInfo['dir'];
- } else $urlCode = $imageInfo['attachment_src'];
- $filelink = [
- 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- ];
- if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
- if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
- foreach ($spreadBanner as $key => &$item) {
- $posterInfo = '海报生成失败:(';
- $config = array(
- 'image' => array(
- array(
- 'url' => $urlCode, //二维码资源
- 'stream' => 0,
- 'left' => 114,
- 'top' => 790,
- 'right' => 0,
- 'bottom' => 0,
- 'width' => 120,
- 'height' => 120,
- 'opacity' => 100
- )
- ),
- 'text' => array(
- array(
- 'text' => $user['nickname'],
- 'left' => 250,
- 'top' => 840,
- 'fontPath' => $filelink['Bold'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '40,40,40', //字体颜色
- 'angle' => 0,
- ),
- array(
- 'text' => '邀请您加入' . $siteName,
- 'left' => 250,
- 'top' => 880,
- 'fontPath' => $filelink['Normal'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '40,40,40', //字体颜色
- 'angle' => 0,
- )
- ),
- 'background' => $item['pic']
- );
- $resWap = $resWap && $posterInfo = setSharePoster($config, 'wap/spread/poster');
- if (!is_array($posterInfo)) throw new ValidateException('海报生成失败');
- $posterInfo['dir'] = tidy_url($posterInfo['dir'], null, $siteUrl);
- $attachmentRepository->create($uploadType, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $posterInfo['name'],
- 'attachment_src' => $posterInfo['dir']
- ]);
- if ($resWap) {
- $item['wap_poster'] = $posterInfo['dir'];
- }
- }
- return $spreadBanner;
- }
- public function getUsername($uid)
- {
- return User::getDB()->where('uid', $uid)->value('nickname');
- }
- /**
- * @param $uid
- * @param $inc
- * @param string $type
- * @author xaboy
- * @day 2020/6/22
- */
- public function incBrokerage($uid, $inc, $type = '+')
- {
- $weekKey = 'b_top_' . date('Y-m');
- $moneyKey = 'b_top_' . monday();
- //TODO 佣金周榜
- $brokerage = Cache::zscore($weekKey, $uid);
- $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
- Cache::zadd($weekKey, $brokerage, $uid);
- //TODO 佣金月榜
- $brokerage = Cache::zscore($moneyKey, $uid);
- $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
- Cache::zadd($moneyKey, $brokerage, $uid);
- }
- public function brokerageWeekTop($uid, $page, $limit)
- {
- $key = 'b_top_' . monday();
- return $this->topList($key, $page, $limit) + ['position' => $this->userPosition($key, $uid)];
- }
- public function brokerageMonthTop($uid, $page, $limit)
- {
- $key = 'b_top_' . date('Y-m');
- return $this->topList($key, $page, $limit) + ['position' => $this->userPosition($key, $uid)];
- }
- /**
- * //TODO 绑定上下级关系
- * @param User $user
- * @param int $spreadUid
- * @throws DbException
- * @author xaboy
- * @day 2020/6/22
- */
- public function bindSpread(User $user, int $spreadUid)
- {
- if ($spreadUid && !$user->spread_uid && $user->uid != $spreadUid && $this->dao->exists($spreadUid)) {
- $config = systemConfig(['extension_limit', 'extension_limit_day']);
- Db::transaction(function () use ($spreadUid, $user, $config) {
- $user->spread_uid = $spreadUid;
- $user->spread_time = date('Y-m-d H:i:s');
- if ($config['extension_limit'] && $config['extension_limit_day']) {
- $user->spread_limit = date('Y-m-d H:i:s', strtotime('+ ' . $config['extension_limit_day'] . ' day'));
- }
- $this->dao->update($spreadUid, [
- 'spread_count' => Db::raw('spread_count +1')
- ]);
- $user->save();
- //TODO 推广人月榜
- Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
- //TODO 推广人周榜
- Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
- });
- }
- }
- public function userPosition($key, $uid)
- {
- $index = Cache::zrevrank($key, $uid);
- if ($index === false)
- return 0;
- else
- return $index + 1;
- }
- public function topList($key, $page, $limit)
- {
- $res = Cache::zrevrange($key, ($page - 1) * $limit, $limit, true);
- $ids = array_keys($res);
- $index = array_flip($ids);
- $count = Cache::zcard($key);
- $list = count($ids) ? $this->dao->users($ids, 'uid,avatar,nickname')->toArray() : [];
- foreach ($list as $k => $v) {
- $list[$k]['count'] = $res[$v['uid']] ?? 0;
- }
- $sort = array_column($list, 'count');
- array_multisort($sort, SORT_DESC, $list);
- return compact('count', 'list');
- }
- public function spreadWeekTop($page, $limit)
- {
- $key = 's_top_' . monday();
- return $this->topList($key, $page, $limit);
- }
- public function spreadMonthTop($page, $limit)
- {
- $key = 's_top_' . date('Y-m');
- return $this->topList($key, $page, $limit);
- }
- /**
- * @param $uid
- * @param $nickname
- * @param $sort
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/6/22
- */
- public function getOneLevelList($uid, $nickname, $sort, $page, $limit)
- {
- $query = $this->search(['spread_uid' => $uid, 'nickname' => $nickname, 'sort' => $sort]);
- $count = $query->count();
- $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
- return compact('list', 'count');
- }
- /**
- * @param $uid
- * @param $nickname
- * @param $sort
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/6/22
- */
- public function getTwoLevelList($uid, $nickname, $sort, $page, $limit)
- {
- $ids = $this->dao->getSubIds($uid);
- if (count($ids)) {
- $query = $this->search(['spread_uids' => $ids, 'nickname' => $nickname, 'sort' => $sort]);
- $count = $query->count();
- $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
- } else {
- $list = [];
- $count = 0;
- }
- return compact('list', 'count');
- }
- public function getLevelList($uid, array $where, $page, $limit)
- {
- if (!$where['level']) {
- $ids = $this->dao->getSubIds($uid);
- $ids[] = $uid;
- $where['spread_uids'] = $ids;
- } else if ($where['level'] == 2) {
- $ids = $this->dao->getSubIds($uid);
- if (!count($ids)) return ['list' => [], 'count' => 0];
- $where['spread_uids'] = $ids;
- } else {
- $where['spread_uid'] = $uid;
- }
- $query = $this->search($where);
- $count = $query->count();
- $list = $query->setOption('field', [])->field('uid,avatar,nickname,is_promoter,pay_count,pay_price,spread_count,create_time,spread_time,spread_limit')->page($page, $limit)->select();
- return compact('list', 'count');
- }
- /**
- * @param $uid
- * @param $page
- * @param $limit
- * @param array $where
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/6/26
- */
- public function subOrder($uid, $page, $limit, array $where = [])
- {
- if (isset($where['level'])) {
- if (!$where['level']) {
- $ids = $this->dao->getSubIds($uid);
- $subIds = $ids ? $this->dao->getSubAllIds($ids) : [];
- } else if ($where['level'] == 2) {
- $ids = $this->dao->getSubIds($uid);
- $subIds = $ids ? $this->dao->getSubAllIds($ids) : [];
- $ids = [];
- } else {
- $ids = $this->dao->getSubIds($uid);
- $subIds = [];
- }
- } else {
- $ids = $this->dao->getSubIds($uid);
- $subIds = $ids ? $this->dao->getSubAllIds($ids) : [];
- }
- $all = array_merge($ids, $subIds);
- if (!count($all)) return ['count' => 0, 'list' => []];
- $query = app()->make(StoreOrderRepository::class)->usersOrderQuery($where, $all);
- $count = $query->count();
- $list = $query->page($page, $limit)->field('uid,order_sn,pay_time,extension_one,extension_two,is_selfbuy')->with(['user' => function ($query) {
- $query->field('avatar,nickname,uid');
- }])->select()->toArray();
- foreach ($list as $k => $item) {
- if ($item['is_selfbuy']) {
- $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_two'] : 0;
- } else {
- $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_one'] : $item['extension_two'];
- }
- unset($list[$k]['extension_one'], $list[$k]['extension_two']);
- }
- return compact('count', 'list');
- }
- /**
- * @param User $user
- * @return User
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/7/2
- */
- public function mainUser(User $user): User
- {
- if (!$user->main_uid || $user->uid == $user->main_uid) return $user;
- $switchUser = $this->dao->get($user->main_uid);
- if (!$switchUser) return $user;
- if ($user->wechat_user_id && !$switchUser->wechat_user_id) {
- $switchUser->wechat_user_id = $user->wechat_user_id;
- $switchUser->save();
- }
- return $switchUser;
- }
- public function switchUser(User $user, $uid)
- {
- if ($user->uid == $uid || !$this->dao->existsWhere(['uid' => $uid, 'phone' => $user->phone]))
- throw new ValidateException('操作失败');
- $this->dao->update($user->uid, ['main_uid' => $uid]);
- $switchUser = $this->dao->get($uid);
- return $switchUser;
- }
- public function returnToken($user, $tokenInfo)
- {
- $user = $user->hidden(['label_id', 'group_id', 'main_uid', 'pwd', 'addres', 'card_id', 'last_time', 'last_ip', 'create_time', 'mark', 'status', 'spread_uid', 'spread_time', 'real_name', 'birthday', 'brokerage_price'])->toArray();
- return [
- 'token' => $tokenInfo['token'],
- 'exp' => $tokenInfo['out'],
- 'user' => $user
- ];
- }
- public function switchBrokerage(User $user, $brokerage)
- {
- $user->now_money = bcadd($user->now_money, $brokerage, 2);
- $user->brokerage_price = bcsub($user->brokerage_price, $brokerage, 2);
- Db::transaction(function () use ($brokerage, $user) {
- $user->save();
- app()->make(UserBillRepository::class)->incBill($user->uid, 'now_money', 'brokerage', [
- 'link_id' => 0,
- 'status' => 1,
- 'title' => '佣金转入余额',
- 'number' => $brokerage,
- 'mark' => '成功转入余额' . floatval($brokerage) . '元',
- 'balance' => $user->now_money
- ]);
- app()->make(UserBillRepository::class)->decBill($user->uid, 'brokerage', 'now_money', [
- 'link_id' => 0,
- 'status' => 1,
- 'title' => '佣金转入余额',
- 'number' => $brokerage,
- 'mark' => '成功转入余额' . floatval($brokerage) . '元',
- 'balance' => $user->brokerage_price
- ]);
- });
- }
- public function rmLabel($id)
- {
- return $this->search(['label_id' => $id])->update([
- 'label_id' => Db::raw('trim(BOTH \',\' FROM replace(CONCAT(\',\',label_id,\',\'),\',' . $id . ',\',\',\'))')
- ]);
- }
- public function changeSpreadForm($id)
- {
- $user = $this->dao->get($id);
- $form = Elm::createForm(Route::buildUrl('systemUserSpreadChange', compact('id'))->build(), [
- [
- 'type' => 'span',
- 'title' => '用户昵称',
- 'children' => [$user->nickname]
- ], [
- 'type' => 'span',
- 'title' => '上级推荐人 Id',
- 'children' => [$user->spread ? (string)$user->spread->uid : '无']
- ], [
- 'type' => 'span',
- 'title' => '上级推荐人昵称',
- 'children' => [$user->spread ? (string)$user->spread->nickname : '无']
- ], Elm::frameImage('spid', '上级推荐人', '/' . config('admin.admin_prefix') . '/setting/referrerList?field=spid')->prop('srcKey', 'src')->value($user->spread ? [
- 'src' => $user->spread->avatar,
- 'id' => $user->spread->uid,
- ] : [])->modal(['modal' => false])->width('896px')->height('480px'),
- ]);
- return $form->setTitle('修改推荐人');
- }
- public function changeSpread($uid, $spread_id, $admin = 0)
- {
- $spreadLogRepository = app()->make(UserSpreadLogRepository::class);
- $user = $this->dao->get($uid);
- if ($user->spread_uid == $spread_id)
- return;
- $config = systemConfig(['extension_limit', 'extension_limit_day']);
- Db::transaction(function () use ($config, $user, $spreadLogRepository, $spread_id, $admin) {
- $old = $user->spread_uid ?: 0;
- $spreadLogRepository->add($user->uid, $spread_id, $old, $admin);
- $user->spread_time = date('Y-m-d H:i:s');
- if ($config['extension_limit'] && $config['extension_limit_day']) {
- $user->spread_limit = date('Y-m-d H:i:s', strtotime('+ ' . $config['extension_limit_day'] . ' day'));
- }
- $user->spread_uid = $spread_id;
- $user->save();
- });
- }
- public function syncSpreadStatus()
- {
- if (systemConfig('extension_limit')) {
- $this->dao->syncSpreadStatus();
- }
- }
- }
|