Files
nuttyreading-java/src/main/java/com/peanut/modules/book/controller/MyUserController.java
2024-04-11 16:32:37 +08:00

727 lines
26 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.peanut.modules.book.controller;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peanut.common.utils.MD5Utils;
import com.peanut.common.utils.MailUtil;
import com.peanut.modules.book.service.*;
import com.peanut.modules.book.to.PageIdDto;
import com.peanut.modules.common.entity.BookBuyConfigEntity;
import com.peanut.modules.common.entity.BookEntity;
import com.peanut.modules.common.entity.MyUserEntity;
import com.peanut.modules.common.entity.TransactionDetailsEntity;
import com.peanut.modules.sys.service.SysUserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.peanut.common.utils.PageUtils;
import com.peanut.common.utils.R;
/**
*
*
* @author yl
* @email yl328572838@163.com
* @date 2022-08-10 14:20:12
*/
@Slf4j
@RestController
@RequestMapping("book/user")
public class MyUserController {
@Autowired
private MyUserService userService;
@Autowired
private BuyOrderService buyOrderService;
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private SysUserTokenService sysUserTokenService;
@Autowired
private CouponHistoryService couponHistoryService;
@Autowired
private BookBuyConfigService bookBuyConfigService;
@Autowired
private BookService bookService;
@Autowired
private TransactionDetailsService transactionDetailsService;
/**
* 列表
*/
@RequestMapping("/list")
// @RequiresPermissions("book:user:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = userService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 获取用户列表
* @param p
* @return
*/
@RequestMapping("/getUserList")
public R getUserList(@RequestBody PageIdDto p){
LambdaQueryWrapper<MyUserEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.and(p.getKey()!="",k->k.like(MyUserEntity::getName,p.getKey()).or().like(MyUserEntity::getTel,p.getKey()).or().like(MyUserEntity::getEmail,p.getKey()));
wrapper.orderByDesc(MyUserEntity::getCreateTime);
Page<MyUserEntity> myUserEntityPage = userService.getBaseMapper().selectPage(new Page<MyUserEntity>(p.getPage(), p.getLimit()), wrapper);
return R.ok().put("user",myUserEntityPage);
}
/**
* 管理员添加用户
* @return
*/
@RequestMapping("/addUserForAdmin")
public R addUserForAdmin(){
return null;
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
// @RequiresPermissions("book:user:info")
public R info(@PathVariable("id") String id){
MyUserEntity user = userService.getById(id);
// List<CouponHistoryEntity> list = couponHistoryService.getBaseMapper().selectList(new QueryWrapper<CouponHistoryEntity>().eq("member_id", id)
// .eq("use_status", 0));
// user.setConponsCount(list.size());
return R.ok().put("user", user);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody MyUserEntity user){
String password = user.getPassword();
String saltMD5 = MD5Utils.getSaltMD5(password);
user.setPassword(saltMD5);
userService.save(user);
return R.ok();
}
/**
* 修改用户信息
*/
@RequestMapping("/update")
public R update(@RequestBody MyUserEntity user){
boolean b = userService.checkUserTelOrEmail(user);
if(!b){
return R.error("电话或邮箱已存在");
}
userService.updateById(user);
return R.ok();
}
/**
* 修改用户密码
* @param user
* @return
*/
@RequestMapping("/updateUserPassword")
public R updateUserPassword(@RequestBody MyUserEntity user){
String password = user.getPassword();
if(password.equals(null)){
return R.error("密码不能为空");
}
String saltMD5 = MD5Utils.getSaltMD5(password);
user.setPassword(saltMD5);
userService.updateById(user);
return R.ok();
}
/**
* 审核用户是否有某书的权限
* @return
*/
@RequestMapping("/checkUserBook")
public R checkUserBook(@RequestBody Map<String,Object> param){
Integer userId = Integer.valueOf(param.get("userId").toString());
Integer bookId = Integer.valueOf(param.get("bookId").toString());
boolean b = userService.checkUserBook(userId, bookId);
if (b){
return R.ok();
}else {
return R.error("鉴权失败");
}
}
/**
* 删除
*/
@RequestMapping("/delete")
// @RequiresPermissions("book:user:delete")
public R delete(@RequestBody Integer[] ids){
userService.removeByIds(Arrays.asList(ids));
return R.ok();
}
/**
* 常规注册 发短信验证码
*/
@RequestMapping("/sms/sendcode")
public R registerSms(@RequestParam("phone") String phone,@RequestParam(required = false) String areaCode) throws Exception {
int areacode=0;
if(areaCode==null||areaCode.equals("")){
areacode=0;
}else{
areacode = Integer.valueOf(areaCode);
}
//验证一分钟内是否已经发过
String redisCode = redisTemplate.opsForValue().get("RegistCode" + phone);
if (!StringUtils.isEmpty(redisCode)) {
long l = Long.parseLong(redisCode.split("_")[1]);
if (System.currentTimeMillis() - l < 60000) {
//60s 内不能再发
return R.error(500,"短信验证码频率过高,请稍后再试!");
}
}
//生成随机五位数
Random random = new Random();
String i = random.nextInt(99999) + "";
StringBuffer sb = new StringBuffer();
for (int j = 0; j < 5 - i.length(); j++) {
sb.append("0");
}
i = sb.toString() + i;
String code = i + "_"+System.currentTimeMillis();
//redis 缓存验证码
redisTemplate.opsForValue().set("RegistCode"+phone,code,5, TimeUnit.MINUTES);
//发送
userService.sendCodeForRegister(phone,code,areacode);
return R.ok();
}
/**
* 常规注册 发送邮箱验证码
*/
@RequestMapping("/getMailCaptcha")
public R getMailCaptcha(String email) throws Exception {
//验证一分钟内是否已经发过
String redisCode = redisTemplate.opsForValue().get("RegistCode" + email);
if (!StringUtils.isEmpty(redisCode)) {
long l = Long.parseLong(redisCode.split("_")[1]);
if (System.currentTimeMillis() - l < 60000) {
//60s 内不能再发
return R.error(500,"验证码频率过高,请稍后再试!");
}
}
//生成随机五位数
Random random = new Random();
String code = random.nextInt(99999) + "";
String timeCode = code + "_"+System.currentTimeMillis();
//redis 缓存验证码
redisTemplate.opsForValue().set("RegistCode"+email,timeCode,5, TimeUnit.MINUTES);
//发送
return MailUtil.sendMail("疯子读书邮箱验证码",code,email);
}
/**
* 绑定用户电话号
* @return
*/
@RequestMapping("/updateUserTel")
public R updateUserTel(@RequestBody Map<String,Object> map){
String phone = map.get("phone").toString();
String code = map.get("code").toString();
Integer id = Integer.valueOf(map.get("id").toString());
String redisCode = redisTemplate.opsForValue().get("RegistCode"+phone);
if(StringUtils.isEmpty(redisCode)){
return R.error("验证码已过期,请重试");
}
String lcode = redisCode.split("_")[0];
if (!lcode.equals(code)) {
return R.error("短信验证码不符!");
}
MyUserEntity userInfo = userService.getById(id);
userInfo.setTel(phone);
userService.updateById(userInfo);
return R.ok();
}
/**
* 绑定用户邮件
* @return
*/
@RequestMapping("/updateUserEmail")
public R updateUserEmail(@RequestBody Map<String,Object> map){
String email = map.get("email").toString();
String code = map.get("code").toString();
Integer id = Integer.valueOf(map.get("id").toString());
//查询是否存在当前邮箱
LambdaQueryWrapper<MyUserEntity> wrapper = new LambdaQueryWrapper();
wrapper.eq(MyUserEntity::getEmail,email);
MyUserEntity userEntity = userService.getOne(wrapper);
if (userEntity == null) {
String redisCode = redisTemplate.opsForValue().get("RegistCode"+email);
if(StringUtils.isEmpty(redisCode)){
return R.error("验证码已过期,请重试");
}
String lcode = redisCode.split("_")[0];
if (!lcode.equals(code)) {
return R.error("短信验证码不符!");
}
MyUserEntity userInfo = userService.getById(id);
userInfo.setEmail(email);
userService.updateById(userInfo);
return R.ok();
}else {
return R.error("邮箱已被绑定!");
}
}
@RequestMapping("/register")
public R register(@RequestParam("tel") String tel,
@RequestParam("code") String code,
@RequestParam("password") String password){
String redisCode = redisTemplate.opsForValue().get("RegistCode" + tel);
if (StringUtils.isEmpty(redisCode)){
return R.error(500,"短信验证码已过期,请重试");
}
String lcode = redisCode.split("_")[0];
if (!lcode.equals(code)) {
return R.error(500,"短信验证码不符!");
}
MyUserEntity user = userService.getBaseMapper().selectOne(new QueryWrapper<MyUserEntity>().eq("tel", tel));
if(!ObjectUtil.isEmpty(user)){
return R.error(500,"该手机号已经注册!");
}
String saltMD5 = MD5Utils.getSaltMD5(password);
MyUserEntity myUserEntity = new MyUserEntity();
myUserEntity.setTel(tel);
myUserEntity.setPassword(saltMD5);
userService.save(myUserEntity);
R r = sysUserTokenService.createToken(myUserEntity.getId());
return R.ok("注册成功").put("userInfo",myUserEntity).put("token",r);
}
/**
* 常规注册 / 验证码 登录
*/
@RequestMapping("/registerOrLogin")
public R register(String tel, String code) {
String redisCode = redisTemplate.opsForValue().get("RegistCode" + tel);
System.out.println(redisCode);
if (StringUtils.isEmpty(redisCode)){
return R.error(500,"验证码已过期,请重试");
}
String lcode = redisCode.split("_")[0];
if (!lcode.equals(code)) {
return R.error(500,"验证码不符!");
}
//查询是否存在当前用户手机号
LambdaQueryWrapper<MyUserEntity> wrapper = new LambdaQueryWrapper();
if (tel.contains("@")){
wrapper.eq(MyUserEntity::getEmail,tel);
}else {
wrapper.eq(MyUserEntity::getTel,tel);
}
wrapper.orderByDesc(MyUserEntity::getLastLoginTime);
//防止多账号报错
List<MyUserEntity> userList = userService.getBaseMapper().selectList(wrapper);
if (userList == null || userList.size() == 0) {
// 用户不存在则创建用户 注册成功
MyUserEntity myUserEntity = new MyUserEntity();
if (tel.contains("@")){
myUserEntity.setEmail(tel);
}else {
myUserEntity.setTel(tel);
}
userService.save(myUserEntity);
R r = sysUserTokenService.createToken(myUserEntity.getId());
return R.ok("注册成功").put("userInfo",myUserEntity).put("token",r);
}else {
R r = sysUserTokenService.createToken(userList.get(0).getId());
return R.ok("登录成功!").put("userInfo",userList.get(0)).put("token",r);
}
}
/**
* 常规 密码登录
*/
@RequestMapping("/login")
public R login(@RequestParam("phone") String phone,
@RequestParam("password") String password) {
LambdaQueryWrapper<MyUserEntity> wrapper = new LambdaQueryWrapper();
if (phone.contains("@")) {
wrapper.eq(MyUserEntity::getEmail,phone);
}else {
wrapper.eq(MyUserEntity::getTel,phone);
}
//防止多账号报错
List<MyUserEntity> userList = userService.getBaseMapper().selectList(wrapper);
if (userList == null || userList.size() == 0) {
return R.error(500,"用户不存在!");
}else {
int flag = 0;
for (MyUserEntity user : userList) {
if (user.getPassword() == null|| user.getPassword().equals("")) {
flag++;
continue;
}
if (MD5Utils.getSaltverifyMD5(password,user.getPassword())){
R r = sysUserTokenService.createToken(user.getId());
return R.ok("登陆成功!").put("userInfo",user).put("token",r);
}
}
if (flag>0){
return R.error(500,"当前未设置密码,请使用验证码登录!");
}
return R.error(500,"密码不正确,请重试!");
}
}
/**
* 常规 设置密码
*/
@RequestMapping("/setPassword")
public R setPassword(@RequestParam("phone") String phone,
@RequestParam("password") String password,
@RequestParam("code") String code) {
String redisCode = redisTemplate.opsForValue().get("RegistCode" + phone);
System.out.println(redisCode);
if (StringUtils.isEmpty(redisCode)){
return R.error(500,"验证码已过期,请重试");
}
String lcode = redisCode.split("_")[0];
if (!lcode.equals(code)) {
return R.error(500,"验证码不符!");
}
//查询是否存在当前用户手机号
LambdaQueryWrapper<MyUserEntity> wrapper = new LambdaQueryWrapper<>();
if (phone.contains("@")){
wrapper.eq(MyUserEntity::getEmail, phone);
}else {
wrapper.eq(MyUserEntity::getTel, phone);
}
MyUserEntity userEntity = userService.getBaseMapper().selectOne(wrapper);
if (userEntity == null) {
return R.error(500,"当前用户不存在!");
}
String saltMD5 = MD5Utils.getSaltMD5(password);
userEntity.setPassword(saltMD5);
userService.updateById(userEntity);
return R.ok("成功");
}
/**
* 获取 一路健康用户信息
*/
@RequestMapping("/getEverhealthInfo")
public R getEverhealthInfo(@RequestParam("phone") String phone,
@RequestParam("password") String password,
@RequestParam(value = "hsuserId", required = false) Integer hsuserId) {
String s = HttpUtil.get("http://101.201.146.165:8088/App-EH/app/phone.do?login&loginName="+ phone +"&loginPwd="+ password +"");
System.out.println(s);
//将结果转成json 取值
JSONObject jsonObject = JSON.parseObject(s);
if (jsonObject.getString("msg").equals("登录名或密码错误!")) {
return R.error(404,jsonObject.getString("msg"));
}
String yljkOid = jsonObject.getJSONObject("obj").getString("customerOid");
String cellPhone = jsonObject.getJSONObject("obj").getString("cellPhone");
String customerIcons = jsonObject.getJSONObject("obj").getString("customerIcons");
String nameCN = jsonObject.getJSONObject("obj").getString("nameCN");
// String password = jsonObject.getJSONObject("obj").getString("pass");
System.out.println("=====================yljkOid=============================="+yljkOid);
//查询 当前 花生账号 和 当前绑定的 一路健康账号是否有绑定 关系
MyUserEntity user = userService.getBaseMapper().selectOne(new QueryWrapper<MyUserEntity>().eq("yljk_oid", yljkOid));
if (user != null ) {
// 判断 hsuserId 是否为空 查询 传入的 花生id 和 查询的花生 id 是否一致
if (hsuserId != null && user.getId() == hsuserId){
MyUserEntity myUserEntity = userService.getBaseMapper().selectById(hsuserId);
//绑定
myUserEntity.setYljkOid(yljkOid);
userService.updateById(myUserEntity);
return R.ok("绑定成功!");
}
//如果系统存在该用户 并且绑定关系 成立 登录成功 ,返回用户信息
R r = sysUserTokenService.createToken(user.getId());
return R.ok("登陆成功").put("userInfo",user).put("token",r);
}
//不存在 返回 手机号 oid 姓名 头像
HashMap<Object, Object> map = new HashMap<>();
map.put("cellPhone",cellPhone);
map.put("customerIcons",customerIcons);
map.put("yljkOid",yljkOid);
map.put("nameCN",nameCN);
return R.ok("绑定信息").put("everhealthInfo",map);
}
/**
* 一路健康账号注册花生
*/
@RequestMapping("/registerHs")
public R registerHs(@RequestParam("phone") String phone,
@RequestParam("code") String code,
@RequestParam("yljkOid") String yljkOid,
@RequestParam("userName") String userName,
@RequestParam("customerIcons") String customerIcons) {
String redisCode = redisTemplate.opsForValue().get("RegistCode" + phone);
System.out.println(redisCode);
if (StringUtils.isEmpty(redisCode)){
return R.error(500,"短信验证码已过期,请重试");
}
String lcode = redisCode.split("_")[0];
if (!lcode.equals(code)) {
return R.error(500,"短信验证码不符!");
}
//查询是否存在当前用户手机号
MyUserEntity userEntity = userService.getBaseMapper().selectOne(new QueryWrapper<MyUserEntity>().eq("tel", phone));
if (userEntity == null) {
MyUserEntity myUserEntity = new MyUserEntity();
myUserEntity.setTel(phone);
myUserEntity.setYljkOid(yljkOid);
myUserEntity.setName(userName);
myUserEntity.setAvatar(customerIcons);
userService.save(myUserEntity);
R r = sysUserTokenService.createToken(myUserEntity.getId());
return R.ok().put("userInfo",myUserEntity).put("token",r);
}
//判断当前手机号用户是否绑定过一路健康账号
if (userEntity.getYljkOid() != null){
return R.error(500,"当前手机号已绑定一路健康账号!");
}
//直接绑定 返回登录信息
userEntity.setTel(phone);
userEntity.setYljkOid(yljkOid);
userEntity.setName(userName);
userEntity.setAvatar(customerIcons);
userService.updateById(userEntity);
R r = sysUserTokenService.createToken(userEntity.getId());
// todo 为什么验证成功以后不能实现页面跳转登录 R返回更新生成的token和电话
return R.ok().put("userInfo",userEntity).put("token",r);
}
@RequestMapping("/test")
public R test() {
// userService.openMember("15022449475",1);
// userService.rechargeHSPoint("15022449475",100);
return R.ok();
}
/**
* 电子书购买
*/
@RequestMapping("/buyEbook")
public R buyEbook(@RequestParam Map<String, Object> params){
String msg = "";
String bookId = (String) params.get("bookId");
String userId = (String) params.get("userId");
String couponId = (String) params.get("couponId");
BookEntity book = this.bookService.getById(bookId);
MyUserEntity user = this.userService.getById(userId);
if(1 == book.getIsVip()){
if(!"1".equals(user.getVip())){
msg ="当前书籍为VIP书籍请开通VIP后购买";
return R.ok().put("msg", msg).put("status","error");
}
}
msg = userService.buyEbook(userId, bookId,couponId);
if (msg.equals("当前书籍以购买,请勿重复购买!")) {
return R.ok().put("msg",msg).put("status","error");
}else if (msg.equals("余额不足,请充值!")) {
return R.ok().put("msg",msg).put("status","error");
}else {
return R.ok().put("msg",msg).put("status","success");
}
}
/**
* 花生币充扣
*/
@Transactional
@RequestMapping("/pointChange")
public R pointChange(@RequestParam Map<String, String> params){
String pointType = params.get("pointType");
String pointAmount = params.get("pointAmount");
String id = params.get("id");
MyUserEntity byId = userService.getById(id);
int i = 0;
if (pointType.equals("0")) {
i = byId.getPeanutCoin().intValue() + Integer.valueOf(pointAmount);
byId.setPeanutCoin(new BigDecimal(i));
}else {
i = byId.getPeanutCoin().intValue() - Integer.valueOf(pointAmount);
if (i >= 0) {
byId.setPeanutCoin(new BigDecimal(i));
}else {
return R.error("余额不足!扣除失败!");
}
}
TransactionDetailsEntity transactionDetailsEntity = new TransactionDetailsEntity();
transactionDetailsEntity.setUserId(Integer.valueOf(id));
transactionDetailsEntity.setOrderType("后台充扣操作");
transactionDetailsEntity.setTel(byId.getTel());
transactionDetailsEntity.setUserName(byId.getNickname());
transactionDetailsEntity.setNote(params.get("note"));
if (pointType.equals("0")) {
transactionDetailsEntity.setChangeAmount(new BigDecimal(Integer.valueOf(pointAmount)));
transactionDetailsEntity.setRemark("充值");
}else {
transactionDetailsEntity.setChangeAmount(new BigDecimal(Integer.valueOf(pointAmount)).negate());
transactionDetailsEntity.setRemark("扣费");
}
BigDecimal balance = new BigDecimal(i);
transactionDetailsEntity.setUserBalance(balance);
transactionDetailsService.save(transactionDetailsEntity);
// 插入 花生币 充值记录
// IosPayOrderEntity payPaymentOrderEntity = new IosPayOrderEntity();
// payPaymentOrderEntity.setUserId(Integer.valueOf(id));
// payPaymentOrderEntity.setRealAmount(new BigDecimal(byId.getPeanutCoin()));
// payPaymentOrderEntity.setRechargeAmount(new BigDecimal(i));
// payPaymentOrderEntity.setRechargeChannel("后台手动充值");
// payPaymentOrderEntity.setRechargeStatus("success");
// payPaymentOrderEntity.setSuccessTime(new Date());
// payPaymentOrderService.save(payPaymentOrderEntity);
userService.updateById(byId);
return R.ok();
}
/**
* 使用虚拟币开通vip
* @return
*/
@RequestMapping("/openVipByVirtualCoin")
public R openVipByVirtualCoin(@RequestParam Map<String,Object> params){
Integer configId = Integer.valueOf(params.get("configId").toString());
String orderSn = params.get("orderSn").toString();
Integer userId = Integer.valueOf(params.get("userId").toString());
// 根据userId查找用户信息
MyUserEntity user = this.userService.getById(userId);
BookBuyConfigEntity bookBuyConfigEntity = bookBuyConfigService.getById(configId);
String month = bookBuyConfigEntity.getMonth();
BigDecimal amount = new BigDecimal(bookBuyConfigEntity.getRealMoney());
if(user.getPeanutCoin().compareTo(amount) >= 0){
user.setPeanutCoin(user.getPeanutCoin().subtract(amount));
this.userService.updateById(user);
// 添加消费信息
TransactionDetailsEntity transactionDetailsEntity = new TransactionDetailsEntity();
transactionDetailsEntity.setRemark("购买"+bookBuyConfigEntity.getType()+",金额"+bookBuyConfigEntity.getMoney());
transactionDetailsEntity.setUserId(user.getId());
transactionDetailsEntity.setUserName(user.getNickname());
transactionDetailsEntity.setChangeAmount(amount.negate());
transactionDetailsEntity.setUserBalance(user.getPeanutCoin());
transactionDetailsEntity.setTel(user.getTel());
transactionDetailsEntity.setOrderType("购买会员!");
transactionDetailsService.save(transactionDetailsEntity);
userService.openMember(userId,Integer.valueOf(month));
// 插入 开通记录
buyOrderService.updateOrderStatus(userId,orderSn,"2");
}else{
return R.error(500,"余额不足,请检查后操作!");
}
return R.ok();
}
//
// /**
// * @Description: app微信登陆
// * @Author: z.hw
// */
// @RequestMapping("/appUserAuthorLogin")
//// @ApiOperation(value = "getUserInfoByAppCode", notes = "不分页", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//// @ApiResponses(value = {
//// @ApiResponse(code = 404, message = "Not Found"),
//// @ApiResponse(code = 400, message = "No Name Provided"),
//// })
// public R getUserInfoByApp(@Validated @RequestBody UserAppAuthorEntity userAppAuthorEntity) {
//
// return userService.getUserInfoByApp(userAppAuthorEntity);
// }
//
}