Commit c8faf7ec authored by shiyu's avatar shiyu

Merge remote-tracking branch 'origin/master'

parents a35dfbc3 a8b5493a
package com.wwdz.ch.wx.annotation.support; package com.wwdz.ch.wx.annotation.support;
import com.wwdz.ch.wx.service.UserTokenManager; import com.wwdz.ch.wx.manager.UserTokenManager;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
......
...@@ -12,7 +12,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; ...@@ -12,7 +12,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List; import java.util.List;
@Configuration @Configuration
public class WxWebMvcConfiguration implements WebMvcConfigurer { public class WebMvcConfiguration implements WebMvcConfigurer {
@Bean @Bean
LoginInterceptor loginInterceptor() { LoginInterceptor loginInterceptor() {
return new LoginInterceptor(); return new LoginInterceptor();
......
...@@ -21,7 +21,7 @@ import com.wwdz.ch.wx.entity.request.FavoritesRequestDto; ...@@ -21,7 +21,7 @@ import com.wwdz.ch.wx.entity.request.FavoritesRequestDto;
import com.wwdz.ch.wx.entity.request.UserRequestDto; import com.wwdz.ch.wx.entity.request.UserRequestDto;
import com.wwdz.ch.wx.service.FavoritesService; import com.wwdz.ch.wx.service.FavoritesService;
import com.wwdz.ch.wx.service.UserService; import com.wwdz.ch.wx.service.UserService;
import com.wwdz.ch.wx.service.UserTokenManager; import com.wwdz.ch.wx.manager.UserTokenManager;
import com.wwdz.ch.wx.service.WxLoginService; import com.wwdz.ch.wx.service.WxLoginService;
import com.wwdz.ch.wx.util.IpUtil; import com.wwdz.ch.wx.util.IpUtil;
import com.wwdz.ch.wx.util.StringUtil; import com.wwdz.ch.wx.util.StringUtil;
......
package com.wwdz.ch.wx.service; package com.wwdz.ch.wx.manager;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.HashMap; import java.util.HashMap;
......
package com.wwdz.ch.wx.service; package com.wwdz.ch.wx.manager;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.HashMap; import java.util.HashMap;
......
package com.wwdz.ch.wx.service; package com.wwdz.ch.wx.manager;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.wwdz.ch.core.util.CharUtil; import com.wwdz.ch.core.util.CharUtil;
......
package com.wwdz.ch.wx.service;
import com.wwdz.ch.db.dao.dts.DtsUserDao;
import com.wwdz.ch.wx.dao.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.wwdz.ch.db.domain.User;
@Service
public class UserInfoService {
@Autowired
private DtsUserDao dtsUserDao;
public UserInfo getInfo(Long userId) {
User user = dtsUserDao.findById(userId);
Assert.state(user != null, "用户不存在");
UserInfo userInfo = new UserInfo();
userInfo.setNickName(user.getNickname());
userInfo.setAvatarUrl(user.getAvatar());
return userInfo;
}
}
package com.wwdz.ch.wx.web;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSONObject;
import com.wwdz.ch.core.captcha.CaptchaCodeManager;
import com.wwdz.ch.core.consts.CommConsts;
import com.wwdz.ch.core.notify.NotifyService;
import com.wwdz.ch.core.notify.NotifyType;
import com.wwdz.ch.core.notify.SmsResult;
import com.wwdz.ch.core.type.UserTypeEnum;
import com.wwdz.ch.core.util.CharUtil;
import com.wwdz.ch.core.util.JacksonUtil;
import com.wwdz.ch.core.util.RegexUtil;
import com.wwdz.ch.core.util.ResponseUtil;
import com.wwdz.ch.core.util.bcrypt.BCryptPasswordEncoder;
import com.wwdz.ch.db.dao.dts.DtsUserDao;
import com.wwdz.ch.db.domain.User;
import com.wwdz.ch.wx.annotation.LoginUser;
import com.wwdz.ch.wx.dao.UserInfo;
import com.wwdz.ch.wx.dao.UserToken;
import com.wwdz.ch.wx.dao.WxLoginInfo;
import com.wwdz.ch.wx.service.UserTokenManager;
import com.wwdz.ch.wx.util.IpUtil;
import com.wwdz.ch.wx.util.WxResponseCode;
import com.wwdz.ch.wx.util.WxResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 鉴权服务
*/
@RestController
@RequestMapping("/wx/auth")
@Validated
public class WxAuthController {
private static final Logger logger = LoggerFactory.getLogger(WxAuthController.class);
@Autowired
private DtsUserDao dtsUserDao;
@Autowired
private WxMaService wxService;
@Autowired
private NotifyService notifyService;
@Autowired
private UserTokenManager userTokenManager;
/**
* 账号登录
*
* @param body
* 请求内容,{ username: xxx, password: xxx }
* @param request
* 请求对象
* @return 登录结果
*/
@PostMapping("login")
public Object login(@RequestBody String body, HttpServletRequest request) {
logger.info("【请求开始】账户登录,请求参数,body:{}", body);
String username = JacksonUtil.parseString(body, "username");
String password = JacksonUtil.parseString(body, "password");
if (username == null || password == null) {
return ResponseUtil.badArgument();
}
List<User> userList = dtsUserDao.queryByUsername(username);
User user = null;
if (userList.size() > 1) {
logger.error("账户登录 出现多个同名用户错误,用户名:{},用户数量:{}", username, userList.size());
return ResponseUtil.serious();
} else if (userList.size() == 0) {
logger.error("账户登录 用户尚未存在,用户名:{}", username);
return ResponseUtil.badArgumentValue();
} else {
user = userList.get(0);
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if (!encoder.matches(password, user.getPassword())) {
logger.error("账户登录 ,错误密码:{},{}", password, WxResponseCode.AUTH_INVALID_ACCOUNT.desc());// 错误的密码打印到日志中作为提示也无妨
return WxResponseUtil.fail(WxResponseCode.AUTH_INVALID_ACCOUNT);
}
// userInfo
UserInfo userInfo = new UserInfo();
userInfo.setNickName(username);
userInfo.setAvatarUrl(user.getAvatar());
try {
String registerDate = new SimpleDateFormat("yyyy-MM-dd")
.format(user.getAddTime() == null ? user.getAddTime() : LocalDateTime.now());
userInfo.setRegisterDate(registerDate);
userInfo.setStatus(user.getStatus());
userInfo.setUserLevel(user.getUserLevel());// 用户层级
userInfo.setUserLevelDesc(UserTypeEnum.getInstance(user.getUserLevel()).getDesc());// 用户层级描述
} catch (Exception e) {
logger.error("账户登录:设置用户指定信息出错:"+e.getMessage());
e.printStackTrace();
}
// token
UserToken userToken = null;
try {
userToken = userTokenManager.generateToken(user.getId());
} catch (Exception e) {
logger.error("账户登录失败,生成token失败:{}", user.getId());
e.printStackTrace();
return ResponseUtil.fail();
}
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
logger.info("【请求结束】账户登录,响应结果:{}", JSONObject.toJSONString(result));
return ResponseUtil.ok(result);
}
/**
* 微信登录
*
* @param wxLoginInfo
* 请求内容,{ code: xxx, userInfo: xxx }
* @param request
* 请求对象
* @return 登录结果
*/
@PostMapping("login_by_weixin")
public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
logger.info("【请求开始】微信登录,请求参数,wxLoginInfo:{}", JSONObject.toJSONString(wxLoginInfo));
String code = wxLoginInfo.getCode();
UserInfo userInfo = wxLoginInfo.getUserInfo();
if (code == null || userInfo == null) {
return ResponseUtil.badArgument();
}
Long shareUserId = wxLoginInfo.getShareUserId();
String sessionKey = null;
String openId = null;
try {
WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
sessionKey = result.getSessionKey();
openId = result.getOpenid();
} catch (Exception e) {
e.printStackTrace();
}
if (sessionKey == null || openId == null) {
logger.error("微信登录,调用官方接口失败:{}", code);
return ResponseUtil.fail();
}
User user = dtsUserDao.queryByOid(openId);
if (user == null) {
user = new User();
user.setUsername(openId);
user.setPassword(openId);
user.setWeixinOpenid(openId);
user.setAvatar(userInfo.getAvatarUrl());
user.setNickname(userInfo.getNickName());
user.setGender(userInfo.getGender());
user.setUserLevel((byte) 0);
user.setStatus((byte) 0);
user.setLastLoginTime(new Date());
user.setLastLoginIp(IpUtil.client(request));
user.setShareUserId(shareUserId);
dtsUserDao.add(user);
} else {
user.setLastLoginTime(new Date());
user.setLastLoginIp(IpUtil.client(request));
if (dtsUserDao.updateById(user) == 0) {
return ResponseUtil.updatedDataFailed();
}
}
// token
UserToken userToken = null;
try {
userToken = userTokenManager.generateToken(user.getId());
} catch (Exception e) {
logger.error("微信登录失败,生成token失败:{}", user.getId());
e.printStackTrace();
return ResponseUtil.fail();
}
userToken.setSessionKey(sessionKey);
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
userInfo.setUserId(user.getId());
if (!StringUtils.isEmpty(user.getMobile())) {// 手机号存在则设置
userInfo.setPhone(user.getMobile());
}
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String registerDate = simpleDateFormat.format(user.getAddTime() != null ? user.getAddTime() : new Date());
userInfo.setRegisterDate(registerDate);
userInfo.setStatus(user.getStatus());
userInfo.setUserLevel(user.getUserLevel());// 用户层级
userInfo.setUserLevelDesc(UserTypeEnum.getInstance(user.getUserLevel()).getDesc());// 用户层级描述
} catch (Exception e) {
logger.error("微信登录:设置用户指定信息出错:"+e.getMessage());
e.printStackTrace();
}
result.put("userInfo", userInfo);
logger.info("【请求结束】微信登录,响应结果:{}", JSONObject.toJSONString(result));
return ResponseUtil.ok(result);
}
/**
* 请求验证码
*
* @param body
* 手机号码{mobile}
* @return
*/
@PostMapping("regCaptcha")
public Object registerCaptcha(@RequestBody String body) {
logger.info("【请求开始】请求验证码,请求参数,body:{}", body);
String phoneNumber = JacksonUtil.parseString(body, "mobile");
if (StringUtils.isEmpty(phoneNumber)) {
return ResponseUtil.badArgument();
}
if (!RegexUtil.isMobileExact(phoneNumber)) {
return ResponseUtil.badArgumentValue();
}
if (!notifyService.isSmsEnable()) {
logger.error("请求验证码出错:{}", WxResponseCode.AUTH_CAPTCHA_UNSUPPORT.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_CAPTCHA_UNSUPPORT);
}
String code = CharUtil.getRandomNum(6);
SmsResult smsResult = notifyService.notifySmsTemplate(phoneNumber, NotifyType.CAPTCHA, new String[] { code, "1" });
if (smsResult != null) {
logger.info("*****腾讯云短信发送->请求验证码,短信发送结果:{}",JSONObject.toJSONString(smsResult));
}
boolean successful = CaptchaCodeManager.addToCache(phoneNumber, code,1);
if (!successful) {
logger.error("请求验证码出错:{}", WxResponseCode.AUTH_CAPTCHA_FREQUENCY.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_CAPTCHA_FREQUENCY);
}
logger.info("【请求结束】请求验证码成功");
return ResponseUtil.ok();
}
/**
* 账号注册
*
* @param body
* 请求内容 { username: xxx, password: xxx, mobile: xxx code: xxx }
* 其中code是手机验证码,目前还不支持手机短信验证码
* @param request
* 请求对象
* @return 登录结果 成功则 { errno: 0, errmsg: '成功', data: { token: xxx, tokenExpire:
* xxx, userInfo: xxx } } 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("register")
public Object register(@RequestBody String body, HttpServletRequest request) {
logger.info("【请求开始】账号注册,请求参数,body:{}", body);
String username = JacksonUtil.parseString(body, "username");
String password = JacksonUtil.parseString(body, "password");
String mobile = JacksonUtil.parseString(body, "mobile");
String code = JacksonUtil.parseString(body, "code");
String wxCode = JacksonUtil.parseString(body, "wxCode");
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(mobile)
|| StringUtils.isEmpty(wxCode) || StringUtils.isEmpty(code)) {
return ResponseUtil.badArgument();
}
List<User> userList = dtsUserDao.queryByUsername(username);
if (userList.size() > 0) {
logger.error("请求账号注册出错:{}", WxResponseCode.AUTH_NAME_REGISTERED.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_NAME_REGISTERED);
}
userList = dtsUserDao.queryByMobile(mobile);
if (userList.size() > 0) {
logger.error("请求账号注册出错:{}", WxResponseCode.AUTH_MOBILE_REGISTERED.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_MOBILE_REGISTERED);
}
if (!RegexUtil.isMobileExact(mobile)) {
logger.error("请求账号注册出错:{}", WxResponseCode.AUTH_INVALID_MOBILE.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_INVALID_MOBILE);
}
// 判断验证码是否正确
String cacheCode = CaptchaCodeManager.getCachedCaptcha(mobile);
if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code)) {
logger.error("请求账号注册出错:{}", WxResponseCode.AUTH_CAPTCHA_UNMATCH.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_CAPTCHA_UNMATCH);
}
String openId = null;
try {
WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(wxCode);
openId = result.getOpenid();
} catch (Exception e) {
logger.error("请求账号注册出错:{}", WxResponseCode.AUTH_OPENID_UNACCESS.desc());
e.printStackTrace();
return WxResponseUtil.fail(WxResponseCode.AUTH_OPENID_UNACCESS);
}
userList = dtsUserDao.queryByOpenid(openId);
if (userList.size() > 1) {
return ResponseUtil.serious();
}
if (userList.size() == 1) {
User checkUser = userList.get(0);
String checkUsername = checkUser.getUsername();
String checkPassword = checkUser.getPassword();
if (!checkUsername.equals(openId) || !checkPassword.equals(openId)) {
logger.error("请求账号注册出错:{}", WxResponseCode.AUTH_OPENID_BINDED.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_OPENID_BINDED);
}
}
User user = null;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(password);
user = new User();
user.setUsername(username);
user.setPassword(encodedPassword);
user.setMobile(mobile);
user.setWeixinOpenid(openId);
user.setAvatar(CommConsts.DEFAULT_AVATAR);
user.setNickname(username);
user.setGender((byte) 0);
user.setUserLevel((byte) 0);
user.setStatus((byte) 0);
user.setLastLoginTime(new Date());
user.setLastLoginIp(IpUtil.client(request));
dtsUserDao.add(user);
// userInfo
UserInfo userInfo = new UserInfo();
userInfo.setNickName(username);
userInfo.setAvatarUrl(user.getAvatar());
// token
UserToken userToken = null;
try {
userToken = userTokenManager.generateToken(user.getId());
} catch (Exception e) {
logger.error("账号注册失败,生成token失败:{}", user.getId());
e.printStackTrace();
return ResponseUtil.fail();
}
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
logger.info("【请求结束】账号注册,响应结果:{}", JSONObject.toJSONString(result));
return ResponseUtil.ok(result);
}
/**
* 账号密码重置
*
* @param body
* 请求内容 { password: xxx, mobile: xxx code: xxx }
* 其中code是手机验证码,目前还不支持手机短信验证码
* @param request
* 请求对象
* @return 登录结果 成功则 { errno: 0, errmsg: '成功' } 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("reset")
public Object reset(@RequestBody String body, HttpServletRequest request) {
logger.info("【请求开始】账号密码重置,请求参数,body:{}", body);
String password = JacksonUtil.parseString(body, "password");
String mobile = JacksonUtil.parseString(body, "mobile");
String code = JacksonUtil.parseString(body, "code");
if (mobile == null || code == null || password == null) {
return ResponseUtil.badArgument();
}
// 判断验证码是否正确
String cacheCode = CaptchaCodeManager.getCachedCaptcha(mobile);
if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code)) {
logger.error("账号密码重置出错:{}", WxResponseCode.AUTH_CAPTCHA_UNMATCH.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_CAPTCHA_UNMATCH);
}
List<User> userList = dtsUserDao.queryByMobile(mobile);
User user = null;
if (userList.size() > 1) {
logger.error("账号密码重置出错,账户不唯一,查询手机号:{}", mobile);
return ResponseUtil.serious();
} else if (userList.size() == 0) {
logger.error("账号密码重置出错,账户不存在,查询手机号:{},{}", mobile, WxResponseCode.AUTH_MOBILE_UNREGISTERED.desc());
return WxResponseUtil.fail(WxResponseCode.AUTH_MOBILE_UNREGISTERED);
} else {
user = userList.get(0);
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(password);
user.setPassword(encodedPassword);
if (dtsUserDao.updateById(user) == 0) {
logger.error("账号密码重置更新用户信息出错,id:{}", user.getId());
return ResponseUtil.updatedDataFailed();
}
logger.info("【请求结束】账号密码重置成功!");
return ResponseUtil.ok();
}
/**
* 绑定手机号码
*
* @param userId
* @param body
* @return
*/
@PostMapping("bindPhone")
public Object bindPhone(@LoginUser Long userId, @RequestBody String body) {
logger.info("【请求开始】绑定手机号码,请求参数,body:{}", body);
String sessionKey = userTokenManager.getSessionKey(userId);
String encryptedData = JacksonUtil.parseString(body, "encryptedData");
String iv = JacksonUtil.parseString(body, "iv");
WxMaPhoneNumberInfo phoneNumberInfo = null;
try {
phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
} catch (Exception e) {
logger.error("绑定手机号码失败,获取微信绑定的手机号码出错:{}", body);
e.printStackTrace();
return ResponseUtil.fail();
}
String phone = phoneNumberInfo.getPhoneNumber();
User user = dtsUserDao.findById(userId);
user.setMobile(phone);
if (dtsUserDao.updateById(user) == 0) {
logger.error("绑定手机号码,更新用户信息出错,id:{}", user.getId());
return ResponseUtil.updatedDataFailed();
}
Map<Object, Object> data = new HashMap<Object, Object>();
data.put("phone", phone);
logger.info("【请求结束】绑定手机号码,响应结果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
/**
* 注销登录
*
* @param userId
* @return
*/
@PostMapping("logout")
public Object logout(@LoginUser Long userId) {
logger.info("【请求开始】注销登录,请求参数,userId:{}", userId);
if (userId == null) {
return ResponseUtil.unlogin();
}
try {
userTokenManager.removeToken(userId);
} catch (Exception e) {
logger.error("注销登录出错:userId:{}", userId);
e.printStackTrace();
return ResponseUtil.fail();
}
logger.info("【请求结束】注销登录成功!");
return ResponseUtil.ok();
}
}
package com.wwdz.ch.wx.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import com.wwdz.ch.db.impl.CategoryDaoImpl;
import com.wwdz.ch.db.domain.Category;
import com.wwdz.ch.wx.service.HomeCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.wwdz.ch.core.util.ResponseUtil;
/**
* 类目服务
*/
@RestController
@RequestMapping("/wx/catalog")
@Validated
public class WxCatalogController {
private static final Logger logger = LoggerFactory.getLogger(WxCatalogController.class);
@Autowired
private CategoryDaoImpl categoryManager;
/**
* 分类详情
*
* @param id
* 分类类目ID。 如果分类类目ID是空,则选择第一个分类类目。 需要注意,这里分类类目是一级类目
* @return 分类详情
*/
@GetMapping("index")
public Object index(Integer id) {
logger.info("【请求开始】分类详情,请求参数,id:{}", id);
List<Category> l1CatList;
// 当前一级分类目录
Category currentCategory = null;
// 所有一级分类目录
if (null == id || 0 == id) {
l1CatList = categoryManager.queryByLevel(1, 1, 100);
currentCategory = l1CatList.get(0);
} else {
currentCategory = categoryManager.findById(id);
l1CatList = new ArrayList<>();
l1CatList.add(currentCategory);
}
// 当前一级分类目录对应的二级分类目录
List<Category> currentSubCategory = null;
if (null != currentCategory) {
currentSubCategory = categoryManager.queryByPid(currentCategory.getId());
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("categoryList", l1CatList);
data.put("currentCategory", currentCategory);
data.put("currentSubCategory", currentSubCategory);
logger.info("【请求结束】分类详情,响应结果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
/**
* 所有分类数据
*
* @return 所有分类数据
*/
@GetMapping("all")
public Object queryAll() {
logger.info("【请求开始】所有分类查询...");
// 优先从缓存中读取
if (HomeCacheManager.hasData(HomeCacheManager.CATALOG)) {
return ResponseUtil.ok(HomeCacheManager.getCacheData(HomeCacheManager.CATALOG));
}
// 所有一级分类目录
List<Category> l1CatList = categoryManager.queryByLevel(1, 1, 100);
// 所有子分类列表
Map<Integer, List<Category>> allList = new HashMap<>();
List<Category> sub;
for (Category category : l1CatList) {
sub = categoryManager.queryByPid(category.getId());
allList.put(category.getId(), sub);
}
// 当前一级分类目录
Category currentCategory = l1CatList.get(0);
// 当前一级分类目录对应的二级分类目录
List<Category> currentSubCategory = null;
if (null != currentCategory) {
currentSubCategory = categoryManager.queryByPid(currentCategory.getId());
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("categoryList", l1CatList);
data.put("allList", allList);
data.put("currentCategory", currentCategory);
data.put("currentSubCategory", currentSubCategory);
// 缓存数据
try {
HomeCacheManager.loadData(HomeCacheManager.CATALOG, data);
} catch (Exception e) {
logger.error("所有分类查询出错:缓存分类数据错误:{}", e.getMessage());
e.printStackTrace();
}
logger.info("【请求结束】所有分类查询,响应结果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
/**
* 当前分类栏目
*
* @param id
* 分类类目ID
* @return 当前分类栏目
*/
@GetMapping("current")
public Object current(@NotNull Integer id) {
logger.info("【请求开始】当前分类栏目查询,id:{}", id);
// 当前分类
Category currentCategory = categoryManager.findById(id);
List<Category> currentSubCategory = categoryManager.queryByPid(currentCategory.getId());
Map<String, Object> data = new HashMap<String, Object>();
data.put("currentCategory", currentCategory);
data.put("currentSubCategory", currentSubCategory);
logger.info("【请求结束】当前分类栏目查询,响应结果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
}
\ No newline at end of file
package com.wwdz.ch.wx.web; package com.wwdz.ch.wx.web;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wwdz.ch.core.type.Result; import com.wwdz.ch.core.type.Result;
import com.wwdz.ch.core.util.JacksonUtil;
import com.wwdz.ch.core.util.ResponseUtil;
import com.wwdz.ch.db.dao.ItemDao;
import com.wwdz.ch.db.dao.dts.DtsFootprintDao;
import com.wwdz.ch.db.domain.Footprint;
import com.wwdz.ch.db.domain.Item;
import com.wwdz.ch.wx.annotation.LoginUser;
import com.wwdz.ch.wx.entity.request.FootPrintRequestDto; import com.wwdz.ch.wx.entity.request.FootPrintRequestDto;
import com.wwdz.ch.wx.entity.request.KlDataRequestDto; import com.wwdz.ch.wx.entity.request.KlDataRequestDto;
import com.wwdz.ch.wx.service.FootPrintService; import com.wwdz.ch.wx.service.FootPrintService;
...@@ -19,9 +10,13 @@ import org.slf4j.Logger; ...@@ -19,9 +10,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*; import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
...@@ -32,102 +27,9 @@ import java.util.stream.Collectors; ...@@ -32,102 +27,9 @@ import java.util.stream.Collectors;
@Validated @Validated
public class WxFootprintController { public class WxFootprintController {
private static final Logger logger = LoggerFactory.getLogger(WxFootprintController.class); private static final Logger logger = LoggerFactory.getLogger(WxFootprintController.class);
@Autowired
private DtsFootprintDao dtsFootprintDao;
@Autowired
private ItemDao itemDao;
@Autowired @Autowired
private FootPrintService footPrintService; private FootPrintService footPrintService;
/**
* 删除用户足迹
*
* @param userId
* 用户ID
* @param body
* 请求内容, { id: xxx }
* @return 删除操作结果
*/
@PostMapping("delete")
public Object delete(@LoginUser Long userId, @RequestBody String body) {
logger.info("【请求开始】删除用户足迹,请求参数,userId:{},body:{}", userId, body);
if (userId == null) {
logger.error("删除用户足迹:用户未登录!!!");
return ResponseUtil.unlogin();
}
if (body == null) {
return ResponseUtil.badArgument();
}
Long footprintId = JacksonUtil.parseLong(body, "id");
if (footprintId == null) {
return ResponseUtil.badArgument();
}
Footprint footprint = dtsFootprintDao.findById(footprintId);
if (footprint == null) {
return ResponseUtil.badArgumentValue();
}
if (!footprint.getUserId().equals(userId)) {
return ResponseUtil.badArgumentValue();
}
dtsFootprintDao.deleteById(footprintId);
logger.info("【请求结束】删除用户足迹成功!");
return ResponseUtil.ok();
}
/**
* 用户足迹列表
*
* @param page
* 分页页数
* @param size
* 分页大小
* @return 用户足迹列表
*/
@GetMapping("list")
public Object list(@LoginUser Long userId, @RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
logger.info("【请求开始】用户足迹列表查询,请求参数,userId:{}", userId);
if (userId == null) {
logger.error("删除用户足迹:用户未登录!!!");
return ResponseUtil.unlogin();
}
List<Footprint> footprintList = dtsFootprintDao.queryByAddTime(userId, page, size);
long count = PageInfo.of(footprintList).getTotal();
int totalPages = (int) Math.ceil((double) count / size);
List<Object> footprintVoList = new ArrayList<>(footprintList.size());
for (Footprint footprint : footprintList) {
Map<String, Object> c = new HashMap<String, Object>();
c.put("id", footprint.getId());
c.put("coinsId", footprint.getItemId());
c.put("addTime", footprint.getAddTime());
Item item = itemDao.findById(footprint.getItemId().longValue());
c.put("name", item.getName());
c.put("retailPrice", item.getPrice());
c.put("image", item.getImages().split(";")[0]);
footprintVoList.add(c);
}
Map<String, Object> result = new HashMap<>();
result.put("footprintList", footprintVoList);
result.put("totalPages", totalPages);
logger.info("【请求结束】添加意见反馈,响应结果:{}", JSONObject.toJSONString(result));
return ResponseUtil.ok(result);
}
@PostMapping("/page") @PostMapping("/page")
public Result page(@RequestBody KlDataRequestDto klDataRequestDto) { public Result page(@RequestBody KlDataRequestDto klDataRequestDto) {
String json = klDataRequestDto.getKl_data(); String json = klDataRequestDto.getKl_data();
......
package com.wwdz.ch.wx.web; package com.wwdz.ch.wx.web;
import java.util.*; import com.alibaba.fastjson.JSONObject;
import java.util.concurrent.ArrayBlockingQueue; import com.wwdz.ch.core.util.ResponseUtil;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.NotNull;
import com.wwdz.ch.db.dao.ItemDao; import com.wwdz.ch.db.dao.ItemDao;
import com.wwdz.ch.db.impl.CategoryDaoImpl; import com.wwdz.ch.db.impl.CategoryDaoImpl;
import com.wwdz.ch.wx.annotation.LoginUser; import com.wwdz.ch.wx.annotation.LoginUser;
import com.wwdz.ch.wx.service.HomeCacheManager; import com.wwdz.ch.wx.manager.HomeCacheManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -24,8 +14,12 @@ import org.springframework.web.bind.annotation.GetMapping; ...@@ -24,8 +14,12 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject; import javax.validation.constraints.NotNull;
import com.wwdz.ch.core.util.ResponseUtil; import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/** /**
* 首页服务 * 首页服务
......
package com.wwdz.ch.wx.web; package com.wwdz.ch.wx.web;
import com.alibaba.fastjson.JSONObject;
import com.wwdz.ch.core.type.Result; import com.wwdz.ch.core.type.Result;
import com.wwdz.ch.core.util.ResponseUtil;
import com.wwdz.ch.db.domain.UserAccountObsolete;
import com.wwdz.ch.db.dao.dts.DtsAccountDao;
import com.wwdz.ch.wx.annotation.LoginUser;
import com.wwdz.ch.wx.constant.CacheCodeConstants; import com.wwdz.ch.wx.constant.CacheCodeConstants;
import com.wwdz.ch.wx.entity.request.KlDataRequestDto; import com.wwdz.ch.wx.entity.request.KlDataRequestDto;
import com.wwdz.ch.wx.entity.request.UserRequestDto; import com.wwdz.ch.wx.entity.request.UserRequestDto;
...@@ -18,11 +13,12 @@ import org.slf4j.Logger; ...@@ -18,11 +13,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
/** /**
...@@ -33,63 +29,10 @@ import java.util.Objects; ...@@ -33,63 +29,10 @@ import java.util.Objects;
@Validated @Validated
public class WxUserController { public class WxUserController {
private static final Logger logger = LoggerFactory.getLogger(WxUserController.class); private static final Logger logger = LoggerFactory.getLogger(WxUserController.class);
@Autowired
private DtsAccountDao accountService;
@Autowired @Autowired
private UserService userService; private UserService userService;
/**
* 用户个人页面数据
* <p>
* @param userId
* 用户ID
* @return 用户个人页面数据
*/
@GetMapping("index")
public Object list(@LoginUser Long userId) {
logger.info("【请求开始】用户个人页面数据,请求参数,userId:{}", userId);
if (userId == null) {
logger.error("用户个人页面数据查询失败:用户未登录!!!");
return ResponseUtil.unlogin();
}
Map<Object, Object> data = new HashMap<Object, Object>();
logger.info("【请求结束】用户个人页面数据,响应结果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
/**
* 获取用户
* <p>
* @param userId
* 用户ID
* @return 用户个人页面数据
*/
@GetMapping("getSharedUrl")
public Object getSharedUrl(@LoginUser Integer userId) {
logger.info("【请求开始】获取用户推广二维码图片URL,请求参数,userId:{}", userId);
Map<String, Object> data = new HashMap<>();
data.put("userSharedUrl", "");//默认设置没有
if (userId == null) {
logger.error("获取用户推广二维码图片URL:用户未登录!!!");
} else {
UserAccountObsolete userAccount = accountService.findShareUserAccountByUserId(userId);
//如果没申请,数据则不存在,存在数据且审批通过则会形成推广二维码
if (userAccount != null && StringUtils.isNotBlank(userAccount.getShareUrl())) {
data.put("userSharedUrl", userAccount.getShareUrl());
}
}
logger.info("【请求结束】获取用户推广二维码图片URL,响应结果:{}", JSONObject.toJSONString(data));
return ResponseUtil.ok(data);
}
@ApiOperation(value = "微信登录") @ApiOperation(value = "微信登录")
@PostMapping("/loginByWx") @PostMapping("/loginByWx")
public Result loginByWx(@RequestBody KlDataRequestDto klDataRequestDto, HttpServletRequest request) { public Result loginByWx(@RequestBody KlDataRequestDto klDataRequestDto, HttpServletRequest request) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment