Files

621 lines
20 KiB
PHP

<?php
namespace addons\shopro\controller\user;
use think\Db;
use think\Exception;
use app\common\library\Sms;
use app\admin\model\zy\Club;
use app\admin\model\zy\Menber;
use think\exception\PDOException;
use app\admin\model\zy\link\Apply;
use addons\shopro\controller\Common;
use app\admin\model\zy\link\Message;
use app\admin\model\zy\link\Visitor;
use app\admin\model\zy\link\Relation;
use app\admin\model\shopro\ThirdOauth;
use think\exception\ValidateException;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use app\admin\model\shopro\order\Aftersale as AftersaleModel;
class User extends Common
{
protected $noNeedLogin = ['smsRegister', 'accountLogin', 'smsLogin', 'resetPassword'];
protected $noNeedRight = ['*'];
public function _initialize()
{
parent::_initialize();
\think\Lang::load(APP_PATH . 'api/lang/zh-cn/user.php'); // 加载语言包
}
/**
* 用户数据
*/
public function data()
{
$user = auth_user();
// 查询用户优惠券数量
$data['coupons_num'] = UserCouponModel::geted()->where('user_id', $user->id)->count();
// 订单数量
$orderNum = [];
$orderNum['unpaid'] = OrderModel::where('user_id', $user->id)->unpaid()->count();
$orderNum['nosend'] = OrderModel::where('user_id', $user->id)->pretendPaid()->nosend()->count();
$orderNum['noget'] = OrderModel::where('user_id', $user->id)->pretendPaid()->noget()->count();
$orderNum['nocomment'] = OrderModel::where('user_id', $user->id)->paid()->nocomment()->count();
$orderNum['aftersale'] = AftersaleModel::where('user_id', $user->id)->needOper()->count();
$data['order_num'] = $orderNum;
$this->success('用户数据', $data);
}
/**
* 第三方授权信息
*/
public function thirdOauth()
{
$user = auth_user();
$provider = $this->request->param('provider', '');
$platform = $this->request->param('platform', '');
if (!in_array($platform, ['miniProgram', 'officialAccount', 'openPlatform'])) {
$this->error(__('Invalid parameters'));
}
$where = [
'platform' => $platform,
'user_id' => $user->id
];
if ($provider !== '') {
$where['provider'] = $provider;
}
$oauth = ThirdOauth::where($where)->field('nickname, avatar, platform, provider')->find();
$this->success('', $oauth);
}
/**
* 用户信息
*/
public function profile()
{
//TODO @ldh: 1.账号被禁用 2.连表查group
$self = auth_user(true); //自己
$user_id = $self->id;
$params = $this->request->param();
if (!empty($params['user_id'])) {
$user_id = $params['user_id'];
$relation = Relation::where('user_id', $self->id)->where('target_id', $user_id)->find();
$content = json_decode($relation->content ?? '', true);
$visitor = Visitor::where('type', 2)->where('obj_id', $user_id)->where('user_id', $self->id)->find();
if (empty($visitor)) {
$visitor = new Visitor;
}
$visitor->allowField(true)->save([
'type' => 2,
'obj_id' => $user_id,
'user_id' => $self->id,
'nickname' => $self['nickname'],
'avatar' => $self['avatar'],
'gender' => $self['gender'],
'times' => empty($visitor->times) ? 1 : $visitor->times + 1
]);
}
$user = UserModel::with(['parent_user', 'third_oauth'])->where('id', $user_id)->find();
$user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);
$user = $user->toArray();
$user['msg_num'] = Message::where('user_id', $user['id'])->where('status', 0)->count();
$user['club_list'] = Menber::alias('m')->join([Club::$tableName => 'c'], 'c.id=m.club_id')->field('m.*,c.name')->where('user_id', $user['id'])->where('role', '>', 0)->select();
$user['club_num'] = count($user['club_list']);
$user['card_num'] = 0;
if (isset($content)) {
if (empty($content['phone'])) $user['mobile'] = ''; //手机查看权限
if (empty($content['wechat'])) $user['wechat'] = ''; //微信查看权限
if (empty($content['qq'])) $user['qq'] = ''; //qq查看权限
$user['content'] = $content; //权限
}
$this->success('个人详情', $user);
}
/**
* 更新用户资料
*/
public function update()
{
$user = auth_user();
$params = $this->request->only(['avatar', 'nickname', 'mobile', 'gender', 'qq', 'wechat', 'years', 'bio']);
$this->svalidate($params);
$user->save($params);
$user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);
$this->success('更新成功', $user);
}
/**
* 账号密码登录
*/
public function accountLogin()
{
$user = auth_user();
if ($user) {
$this->error('您已登录,不需要重新登录');
}
$params = $this->request->only(['account', 'password']);
$this->svalidate($params, '.accountLogin');
$ret = $this->auth->login($params['account'], $params['password']);
if ($ret) {
set_token_in_header($this->auth->getToken());
$this->success(__('Logged in successful'));
} else {
$this->error($this->auth->getError() ?: '注册失败');
}
}
/**
* 短信验证码登陆
*/
public function smsLogin()
{
$user = auth_user();
if ($user) {
$this->error('您已登录,不需要重新登录');
}
$params = $this->request->only(['mobile', 'code']);
$this->svalidate($params, '.smsLogin');
if (!Sms::check($params['mobile'], $params['code'], 'mobilelogin')) {
$this->error(__('Captcha is incorrect'));
}
$user = UserModel::getByMobile($params['mobile']);
if ($user) {
if ($user->status != 'normal') {
$this->error(__('Account is locked'));
}
//如果已经有账号则直接登录
$ret = $this->auth->direct($user->id);
} else {
$this->error('该手机号暂未注册');
}
if (isset($ret) && $ret) {
Sms::flush($params['mobile'], 'mobilelogin');
set_token_in_header($this->auth->getToken());
$this->success(__('Logged in successful'));
} else {
$this->error($this->auth->getError() ?: '登录失败');
}
}
/**
* 短信验证码注册
*/
public function smsRegister()
{
$user = auth_user();
if ($user) {
$this->error('您已登录,请先退出登录');
}
$params = $this->request->only(['mobile', 'code', 'password']);
$this->svalidate($params, '.smsRegister');
$ret = Sms::check($params['mobile'], $params['code'], 'register');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
// 注册
$userAuth = new UserAuth();
$auth = $userAuth->register($params);
set_token_in_header($auth->getToken());
$this->success(__('Sign up successful'));
}
/**
* 修改密码
*/
public function changePassword()
{
$user = auth_user();
$params = $this->request->only(['oldPassword', 'newPassword']);
$this->svalidate($params, '.changePassword');
$userAuth = new UserAuth();
$userAuth->changePassword($params['newPassword'], $params['oldPassword']);
$this->auth->direct($user->id);
set_token_in_header($this->auth->getToken());
$this->success(__('Change password successful'));
}
/**
* 重置/忘记密码
*/
public function resetPassword()
{
$params = $this->request->only(['mobile', 'code', 'password']);
$this->svalidate($params, '.resetPassword');
$ret = Sms::check($params['mobile'], $params['code'], 'resetpwd');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
$userAuth = new UserAuth();
$userAuth->resetPassword($params);
$this->success(__('Reset password successful'));
}
/**
* 更换手机号
*/
public function changeMobile()
{
$params = $this->request->only(['mobile', 'code']);
$this->svalidate($params, '.changeMobile');
$ret = Sms::check($params['mobile'], $params['code'], 'changemobile');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
$userAuth = new UserAuth();
$userAuth->changeMobile($params);
$this->success('绑定成功');
}
/**
* 修改用户名
*/
public function changeUsername()
{
$user = auth_user(true);
$params = $this->request->only(['username']);
$this->svalidate($params, '.changeUsername');
$userAuth = new UserAuth();
$userAuth->changeUsername($params);
$this->success('绑定成功');
}
/**
* 更新小程序头像和昵称
*/
public function updateMpUserInfo()
{
$user = auth_user(true);
$params = $this->request->only(['avatar', 'nickname']);
$this->svalidate($params, '.updateMpUserInfo');
$user->save($params);
$thirdOauth = \app\admin\model\shopro\ThirdOauth::where('user_id', $user->id)->where([
'provider' => 'wechat',
'platform' => 'miniProgram'
])->find();
$thirdOauth->save($params);
$this->success('绑定成功');
}
/**
* 登出
*/
public function logout()
{
$userAuth = new UserAuth();
$userAuth->logout();
$this->success(__('Logout successful'));
}
/**
* 用户注销
*/
public function logoff()
{
$userAuth = new UserAuth();
$userAuth->logoff();
$this->success('注销成功');
}
// 发送用户消息
public function sendMsg()
{
$params = $this->request->param();
if ($params['user_id'] == $this->auth->id) {
$this->error('不能发送给自己');
}
$user = auth_user();
$target = UserModel::get($params['user_id']);
if (empty($target)) {
$this->error('用户不存在');
}
Db::startTrans();
try {
$result = (new Message())->allowField(true)->save([
'type' => 2,
'name' => $user['nickname'],
'avatar' => $user['avatar'],
'from_id' => $user['id'],
'user_id' => $params['user_id'],
'content' => json_encode([
'topic' => '好友消息',
'time' => date('Y-m-d H:i:s'),
'content' => $params['content']
]),
'status' => 0
]);
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result === false) {
$this->error('操作失败');
}
$this->success('Success');
}
// 分类消息
public function msgGroup()
{
$params = $this->request->param();
$member = Menber::where('user_id', $this->auth->id)->where('role', '>', 1)->column('club_id');
if (!empty($member)) {
$query1 = Message::field('*,count(*) as num')->where(function ($q1) use ($member) {
$q1->where('user_id', $this->auth->id)
->whereOr(function ($q2) use ($member) {
$q2->where('type', 3)->whereIn('from_id', $member);
});
});
$query2 = Message::field('*,count(*) as num')->where(function ($q1) use ($member) {
$q1->where('user_id', $this->auth->id)
->whereOr(function ($q2) use ($member) {
$q2->where('type', 3)->whereIn('from_id', $member);
});
});
} else {
$query1 = Message::field('*,count(*) as num')->where('user_id', $this->auth->id);
$query2 = Message::field('*,count(*) as num')->where('user_id', $this->auth->id);
}
if (isset($params['type'])) {
$query1->where('type', $params['type']);
$query2->where('type', $params['type']);
}
$query1->group('from_id')->order('update_time', 'desc');
$query2->group('from_id')->order('update_time', 'desc');
$num = $query2->where('status', 0)->column('count(*) as num', 'from_id');
$res = $query1->paginate($params['pageSize'] ?? 10);
$list = $res->items();
foreach ($list as &$r) {
$r['content'] = json_decode($r['content'], true);
$r['num'] = $num[$r['from_id']] ?? 0;
}
$this->success('Success', ['list' => $list, 'count' => $res->total()]);
}
// 用户消息
public function msg()
{
$params = $this->request->param();
$member = Menber::where('user_id', $this->auth->id)->where('role', '>', 1)->column('club_id');
if (!empty($member)) {
$query = Message::where(function ($q1) use ($member) {
$q1->where('user_id', $this->auth->id) //用户消息
->whereOr(function ($q2) use ($member) { //俱乐部消息
$q2->where('type', 3)->whereIn('from_id', $member);
});
});
} else {
$query = Message::where('user_id', $this->auth->id);
}
if (isset($params['type'])) {
$query->where('type', $params['type']);
}
$res = $query->paginate($params['pageSize'] ?? 10);
$list = $res->items();
foreach ($list as &$r) {
$r['content'] = json_decode($r['content'], true);
}
$this->success('Success', ['list' => $list, 'count' => $res->total()]);
}
// 消息读取
public function msgRead()
{
$params = $this->request->param();
$model = Message::get($params['msg_id'] ?? NULL);
if (empty($model)) {
$this->error(__('No rows were found'));
}
$model->save(['status' => 1]); //已读
$model['content'] = json_decode($model['content'], true);
$this->success('Success', $model);
}
// 申请联系信息
public function apply()
{
$params = $this->request->param();
if (empty($params['content'])) {
return $this->error('申请内容不能为空');
}
Db::startTrans();
try {
$fromUser = auth_user();
$user = UserModel::get($params['user_id'] ?? NULL);
if (empty($user)) {
return $this->error('用户不存在');
}
$apply = (new Apply);
if ($apply::get(['type' => 2, 'user_id' => $fromUser->id, 'target_id' => $user->id, 'status' => 1])) {
return $this->error('申请处理中');
}
$apply->allowField(true)->save([ // 记录申请
'type' => 2,
'user_id' => $fromUser->id,
'target_id' => $user->id,
'content' => $params['content'],
'reason' => $params['reason'] ?? '',
'status' => 1
]);
// (new Message())->allowField(true)->save([ // 消息通知
// 'type' => 2,
// 'name' => $fromUser->nickname,
// 'avatar' => $fromUser->avatar,
// 'from_id' => $fromUser->id,
// 'user_id' => $user->id,
// 'content' => json_encode([
// 'topic' => '申请联系信息',
// '申请人' => $fromUser->nickname,
// '申请时间' => date('Y-m-d H:i:s'),
// 'reason' => $params['reason'] ?? '',
// 'apply_id' => $apply->id
// ])
// ]);
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('已邀请,请等候审核');
}
// 获取申请列表
public function applyList()
{
$params = $this->request->param();
$query = Apply::where('type', 2)->where('target_id', $this->auth->id);
if (isset($params['status'])) {
$query->where('status', $params['status']);
}
$applyList = $query->select();
$this->success('Success', $applyList);
}
// 处理申请
public function handle()
{
$params = $this->request->param();
Db::startTrans();
try {
$apply = Apply::get(['id' => $params['apply_id'], 'user_id' => $this->auth->id, 'status' => 1]);
if (empty($apply)) {
return $this->error('申请记录不存在');
}
if ($params['status'] == 2) { //同意
$relation = Relation::get(['user_id' => $apply['user_id'], 'target_id' => $apply['user_id']]);
if (empty($relation)) {
$relation = new Relation;
}
$relation->allowField(true)->save([
'target_id' => $apply['user_id'],
'user_id' => $apply['target_id'],
'status' => 1,
'content' => $params['content'],
]);
}
$apply->save([
'status' => $params['status'],
'reply' => $params['reply'] ?? ''
]);
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('Success');
}
// 好友关系
public function relation()
{
$params = $this->request->param();
if (!isset($params['status'])) {
$this->error('缺少参数:status');
}
$ids = explode(',', $params['user_id']);
if (empty($ids)) {
$this->error('缺少参数:user_id');
}
foreach ($ids as $id) {
if ($id == $this->auth->id) {
$this->error('不能设置与自己的好友关系');
}
}
Db::startTrans();
try {
$dbUserId = UserModel::where('id', 'IN', $ids)->column('id');
if (!empty($diffId = array_diff($ids, $dbUserId))) {
return $this->error('用户不存在:' . implode(',', $diffId));
}
$res = Relation::where('user_id', $this->auth->id)->where('target_id', 'IN', $ids)->update(['status' => $params['status']]);
if ($res < count($ids)) {
$target = Relation::where('user_id', $this->auth->id)->where('target_id', 'IN', $ids)->column("target_id");
$_relationModel = new Relation;
foreach ((array_diff($ids, $target)) as $id) {
(clone $_relationModel)->allowField(true)->save([
'user_id' => $this->auth->id,
'target_id' => $id,
'status' => $params['status'],
]);
}
}
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('Success');
}
// 获取关系列表
public function list()
{
$params = $this->request->param();
$query = Relation::alias('r')
->join([UserModel::$tableName => 'u'], 'u.id=r.target_id')
->field('r.*,u.avatar,u.gender,u.nickname')
->where('user_id', $this->auth->id);
if (isset($params['status'])) {
$query->where('r.status', $params['status']);
} else {
$query->where('r.status', '<>', 0);
}
$list = $query->select();
foreach ($list as &$l) {
$l['content'] = json_decode($l['content'] ?? '[]', true);
}
$this->success('Success', $list);
}
}