Commit 99193c62 authored by renandong's avatar renandong 🇨🇳

1,增加标签后台管理

2,增加为用户打标签功能等
parent f4dd76c4
......@@ -35,6 +35,9 @@
<lombok.version>1.18.12</lombok.version>
<easypoi.version>4.1.0</easypoi.version>
<thumbnailator.version>0.4.13</thumbnailator.version>
<!-- <apache-poi.version>3.17</apache-poi.version>-->
<apache-poi.version>3.9</apache-poi.version>
<locationtech.version>0.8</locationtech.version>
</properties>
<dependencies>
......@@ -176,9 +179,9 @@
<dependency>
<groupId>org.locationtech.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.8</version>
<version>${locationtech.version}</version>
</dependency>
<!-- excel-->
<!-- excel-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
......@@ -194,16 +197,16 @@
<artifactId>easypoi-annotation</artifactId>
<version>${easypoi.version}</version>
</dependency>
<!-- excel-->
<!-- excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
<version>${apache-poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
<version>${apache-poi.version}</version>
</dependency>
<!--thumbnailator图片处理-->
<dependency>
......
......@@ -8,12 +8,24 @@ public class CommonResult<T> {
protected CommonResult() {
}
protected CommonResult(long code, String message) {
this.code = code;
this.message = message;
}
protected CommonResult(long code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回结果
*/
public static <T> CommonResult<T> success() {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage());
}
/**
* 成功返回结果
*
......@@ -35,6 +47,7 @@ public class CommonResult<T> {
/**
* 失败返回结果
*
* @param errorCode 错误码
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode) {
......@@ -43,6 +56,7 @@ public class CommonResult<T> {
/**
* 失败返回结果
*
* @param message 提示信息
*/
public static <T> CommonResult<T> failed(String message) {
......@@ -65,6 +79,7 @@ public class CommonResult<T> {
/**
* 参数验证失败返回结果
*
* @param message 提示信息
*/
public static <T> CommonResult<T> validateFailed(String message) {
......
package com.weface.common.utils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.util.HashSet;
import java.util.Set;
/**
* @author : Administrator
*/
public class BeanUtils {
/**
* 拷贝对象时忽略空属性
*
* @param source 源数据
* @return 空字段
*/
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
}
package com.weface.common.validator;
import com.weface.common.exception.RRException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
/**
* hibernate-validator校验工具类
* <p>
* 参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
*
* @author Mark sunlightcs@gmail.com
*/
public class ValidatorUtils {
private static final Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* 校验对象
*
* @param object 待校验对象
* @param groups 待校验的组
* @throws RRException 校验不通过,则报RRException异常
*/
public static void validateEntity(Object object, Class<?>... groups)
throws RRException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for (ConstraintViolation<Object> constraint : constraintViolations) {
msg.append(constraint.getMessage()).append("\n");
}
throw new RRException(msg.toString());
}
}
}
......@@ -16,10 +16,6 @@ import java.io.Serializable;
public class MessageTemplate implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 请求唯一标识号,10-32位之间;如果request_id重复,会导致消息丢失
*/
private String request_id;
/**
* 任务组
*/
......@@ -36,11 +32,6 @@ public class MessageTemplate implements Serializable {
* 个推推送消息参数
*/
private PushMessage push_message;
/**
* 厂商推送消息参数,包含ios消息参数,android厂商消息参数
*/
private PushChannel push_channel;
/**
* 推送目标用户该接口audience 对应值为all,表示推送所有用户
*/
......@@ -131,54 +122,4 @@ public class MessageTemplate implements Serializable {
private Integer force;
}
}
/**
* 厂商推送消息参数,包含ios消息参数,android厂商消息参数
*/
@Data
public static class PushChannel implements Serializable {
private static final long serialVersionUID = 1L;
private Android android;
/**
* ios通道推送消息内容
*/
@Data
public static class Ios implements Serializable {
private static final long serialVersionUID = 1L;
}
/**
* android通道推送消息内容
*/
@Data
public static class Android implements Serializable {
private static final long serialVersionUID = 1L;
private Ups ups;
@Data
public static class Ups {
private Notification notification;
private String transmission;
private Revoke revoke;
@Data
public static class Notification {
private String title;
private String body;
private String click_type;
private String intent;
private String url;
private Integer notify_id;
}
@Data
public static class Revoke {
private String old_task_id;
}
}
}
}
}
......@@ -13,7 +13,8 @@ import java.util.Date;
public class MetaObjectHandlerConfig implements MetaObjectHandler {
/**
* 在添加时为公共字段填充属性
* @param metaObject
*
* @param metaObject 源数据
*/
@Override
public void insertFill(MetaObject metaObject) {
......
package com.weface.controller;
import com.weface.common.utils.Model;
import com.weface.common.utils.PageUtils;
import com.weface.component.MenuService;
import com.weface.dto.UserTagFrom;
import com.weface.code.CommonResult;
import com.weface.common.validator.ValidatorUtils;
import com.weface.dto.MenuTagsForm;
import com.weface.service.MenuTagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
......@@ -12,8 +11,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Map;
import java.util.List;
/**
......@@ -23,29 +21,45 @@ import java.util.Map;
* @date 2021-11-18 16:20:52
*/
@RestController
@RequestMapping("/tags/menuTags")
@RequestMapping("/sys/menu")
public class MenuTagsController {
@Autowired
private MenuTagsService menuTagsService;
@Autowired
private MenuService menuService;
/**
* 标签列表 可模糊查询根据levelThird
*/
@PostMapping("/list")
public Model list(@RequestBody Map<String, Object> params) {
PageUtils page = menuTagsService.queryPage(params);
return Model.ok(page);
@PostMapping("/list_menu")
public CommonResult list() {
List<Object> data = menuTagsService.getTagsList();
return CommonResult.success(data);
}
/**
* 新增标签
*/
@PostMapping("/save_menu")
public CommonResult save(@RequestBody MenuTagsForm menuTagsForm) {
ValidatorUtils.validateEntity(menuTagsForm, MenuTagsForm.SaveTag.class);
return menuTagsService.saveTag(menuTagsForm);
}
/**
* 根据用户giUid先调个推拿到code后走数据库拿到数据并更新相关数据后返回
* 修改标签
*/
@PostMapping("/queryTagByGiUid")
public Model queryTagsByGiUid(@RequestBody UserTagFrom userTagFrom) {
Map<String, Object> data = menuService.getUserTags(Arrays.asList(userTagFrom.getGiUidList()), null);
return Model.ok(data);
@PostMapping("/update_menu")
public CommonResult update(@RequestBody MenuTagsForm menuTagsForm) {
ValidatorUtils.validateEntity(menuTagsForm, MenuTagsForm.UpdateTag.class);
return menuTagsService.updateTag(menuTagsForm);
}
/**
* 删除标签
*/
@PostMapping("/del_menu")
public CommonResult del(@RequestBody MenuTagsForm menuTagsForm) {
ValidatorUtils.validateEntity(menuTagsForm, MenuTagsForm.UpdateTag.class);
menuTagsService.removeById(menuTagsForm.getId());
return CommonResult.success(null);
}
}
package com.weface.controller;
import com.weface.code.CommonResult;
import com.weface.common.validator.ValidatorUtils;
import com.weface.dto.UserMenuFrom;
import com.weface.service.UserMenusService;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* @author : Administrator
* @date : 2022/2/10 11:08
*/
@RestController
@RequestMapping("/sys/tags")
public class UserMenuController {
@Autowired
private UserMenusService userMenusService;
/**
* 添加用户标签
*/
@PostMapping("/save_user_tag")
public CommonResult saveUserTag(@RequestBody UserMenuFrom userMenuFrom) {
ValidatorUtils.validateEntity(userMenuFrom, UserMenuFrom.UserMenus.class);
return userMenusService.saveUserTag(userMenuFrom);
}
/**
* 删除用户标签
*/
@PostMapping("/del_user_tag")
public CommonResult delUserTag(@RequestBody UserMenuFrom userMenuFrom){
ValidatorUtils.validateEntity(userMenuFrom, UserMenuFrom.UserMenus.class);
return userMenusService.delUserTag(userMenuFrom);
}
}
package com.weface.controller;
import com.weface.common.utils.Model;
import com.weface.code.CommonResult;
import com.weface.common.utils.PageUtils;
import com.weface.dto.UserTagFrom;
import com.weface.service.UserTagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Map;
......@@ -20,40 +17,19 @@ import java.util.Map;
* @date 2021-11-18 16:20:52
*/
@RestController
@RequestMapping("/tags/userTags")
@RequestMapping("/sys/user")
public class UserTagsController {
@Autowired
private UserTagService tUserTagService;
private UserTagService userTagService;
/**
* 查询所有用户对应标签信息
*/
@PostMapping("/list")
public Model list(@RequestBody Map<String, Object> params) {
PageUtils page = tUserTagService.getUserAndTags(params);
return Model.ok(page);
@PostMapping("/list_user")
public CommonResult list(@RequestBody Map<String, Object> params) {
PageUtils page = userTagService.getUserList(params);
return CommonResult.success(page);
}
/**
* 根据标签查询用户gid
*/
@PostMapping("/queryByTag")
public Model queryByTag(@RequestBody UserTagFrom userTagFrom) {
List<String> data = tUserTagService.getGidByTag(userTagFrom.getTags());
return Model.ok(data);
}
/**
* 根据gid查询用户标签
*/
@PostMapping("/queryByGid")
public Model queryByGid(@RequestBody UserTagFrom userTagFrom) {
String gid = userTagFrom.getGiUidList()[0];
if (StringUtils.isBlank(gid)) {
return Model.error("gid不能为空");
}
Map<String, Object> data = tUserTagService.getTagByGid(gid);
return Model.ok(data);
}
}
......@@ -4,6 +4,8 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.weface.entity.MenuTagsEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 所有标签等级划分
*
......@@ -13,4 +15,11 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MenuTagsDao extends BaseMapper<MenuTagsEntity> {
/**
* 查询索引标签信息
*
* @return 标签信息
*/
List<MenuTagsEntity> getTagsList();
}
package com.weface.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weface.entity.UserTagEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 用户ID标签关联表
......@@ -18,6 +17,14 @@ import java.util.List;
@Mapper
public interface UserTagDao extends BaseMapper<UserTagEntity> {
/**
* 查询用户标签导出
*
* @param list 用户uid
* @return 标签信息
*/
List<UserTagEntity> findUserTags(List<String> list);
/**
* 查询今天用户信息
*
......@@ -42,35 +49,10 @@ public interface UserTagDao extends BaseMapper<UserTagEntity> {
/**
* 查询用户和标签信息
*
* @param page 分页
* @param gid 银行gid
* @param <T> 分页泛型
* @param star 起始页
* @param end 每页条数
* @return 用户标签数据
*/
<T> IPage<UserTagEntity> getUserAndTags(Page<T> page, @Param("gid") String gid);
/**
* 根据标签查询用户gid
*
* @param list 标签数据
* @return 用户gid
*/
List<String> getGidByTag(List<String> list);
/**
* 根据gid查询用户标签
*
* @param gid 用户gid
* @return 用户标签数据
*/
List<UserTagEntity> getTagByGid(String gid);
/**
* 查询所有用户标签关联数据
*
* @return 用户标签数据
*/
List<UserTagEntity> selectAllUserForTags();
List<UserTagEntity> getUserList(@Param("star") Integer star, @Param("end") Integer end, @Param("param") Map<String, Object> param);
}
......@@ -2,10 +2,11 @@ package com.weface.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @CreateUser: Administrator
* @CreateTime: 2021/11/3
*/
@Data
......@@ -14,23 +15,23 @@ public class MenuTagsForm implements Serializable {
/**
* ID
*/
@NotNull(message = "id不能为空", groups = {UpdateTag.class})
private Long id;
/**
* 一级标签名称
*/
@NotBlank(message = "一级标签不能为空", groups = {SaveTag.class})
private String levelFirst;
/**
* 二级标签名称
*/
@NotBlank(message = "二级标签不能为空", groups = {SaveTag.class})
private String levelSecond;
/**
* 三级标签名称
*/
@NotBlank(message = "三级标签不能为空", groups = {SaveTag.class})
private String levelThird;
/**
* 编码
*/
private String code;
/**
* 套餐等级
*/
......@@ -39,4 +40,12 @@ public class MenuTagsForm implements Serializable {
* 是否有权重
*/
private String weight;
public interface SaveTag {
}
public interface UpdateTag {
}
}
......@@ -2,6 +2,8 @@ package com.weface.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
/**
......@@ -9,13 +11,20 @@ import java.io.Serializable;
* @CreateTime: 2021/11/17
*/
@Data
public class UserTagFrom implements Serializable {
public class UserMenuFrom implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户id
*/
@NotBlank(message = "用户id不能为空", groups = {UserMenus.class})
private String userId;
/**
* 标签ID
*/
@NotEmpty(message = "标签id不能为空", groups = {UserMenus.class})
private String[] tagsId;
public interface UserMenus {
private String[] giUidList;
private String[] tags;
private Integer page;
}
}
package com.weface.entity;
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
......@@ -27,17 +25,14 @@ public class MenuTagsEntity implements Serializable {
/**
* 一级标签名称
*/
@Excel(name = "一级标签", width = 10)
private String levelFirst;
/**
* 二级标签名称
*/
@Excel(name = "二级标签", width = 10)
private String levelSecond;
/**
* 三级标签名称
*/
@Excel(name = "三级标签", width = 10)
private String levelThird;
/**
* 编码
......@@ -52,12 +47,15 @@ public class MenuTagsEntity implements Serializable {
*/
private String weight;
/**
* 是否删除
* 是否有效 1:有效 0 无效
*/
private Integer isDel;
@TableLogic(value = "1", delval = "0")
@TableField(fill = FieldFill.INSERT)
private Integer isValid;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
*
......
package com.weface.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.weface.code.CommonResult;
import com.weface.dto.MenuTagsForm;
import com.weface.entity.MenuTagsEntity;
import com.weface.common.utils.PageUtils;
import java.util.Map;
import java.util.List;
/**
* 所有标签等级划分
......@@ -17,18 +18,24 @@ public interface MenuTagsService extends IService<MenuTagsEntity> {
/**
* 列表
*
* @param params 参数
* @return 标签分页
* @return 标签数据
*/
PageUtils queryPage(Map<String, Object> params);
List<Object> getTagsList();
/**
* 根据code和权重查询标签
* 增加标签
*
* @param code 编码
* @param weight 权重
* @return 标签信息
* @param menuTagsForm 数据
* @return 执行结果
*/
MenuTagsEntity getOneByCodeOrWeight(String code, String weight);
CommonResult saveTag(MenuTagsForm menuTagsForm);
/**
* 修改标签
*
* @param menuTagsForm 数据
* @return 执行结果
*/
CommonResult updateTag(MenuTagsForm menuTagsForm);
}
package com.weface.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.weface.code.CommonResult;
import com.weface.dto.UserMenuFrom;
import com.weface.entity.UserMenusEntity;
import java.util.List;
......@@ -20,5 +22,20 @@ public interface UserMenusService extends IService<UserMenusEntity> {
*/
void batchInsert(List<UserMenusEntity> list);
/**
* 保存用户标签
*
* @param userMenuFrom 标签信息
* @return 执行结果
*/
CommonResult saveUserTag(UserMenuFrom userMenuFrom);
/**
* 删除用户标签
*
* @param userMenuFrom 标签信息
* @return 执行结果
*/
CommonResult delUserTag(UserMenuFrom userMenuFrom);
}
......@@ -15,6 +15,14 @@ import java.util.Map;
*/
public interface UserTagService extends IService<UserTagEntity> {
/**
* 查询用户标签导出
*
* @param list 用户uid
* @return 标签信息
*/
List<UserTagEntity> findUserTags(List<String> list);
/**
* 查询当天的数据
*
......@@ -45,32 +53,7 @@ public interface UserTagService extends IService<UserTagEntity> {
* @param params 參數
* @return 分頁信息
*/
PageUtils getUserAndTags(Map<String, Object> params);
/**
* 根据标签查询用户gid
*
* @param tags 标签数组
* @return 用户gid
*/
List<String> getGidByTag(String[] tags);
/**
* 根据gid查询用户标签
*
* @param gid 用户gid数组
* @return 用户信息和标签信息
*/
Map<String, Object> getTagByGid(String gid);
/**
* 获取所有用户的标签信息 导出
*
* @return 标签信息
*/
List<UserTagEntity> getAllImport();
PageUtils getUserList(Map<String, Object> params);
}
package com.weface.serviceimpl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weface.code.CommonResult;
import com.weface.common.utils.BeanUtils;
import com.weface.dao.MenuTagsDao;
import com.weface.dto.MenuTagsForm;
import com.weface.entity.MenuTagsEntity;
import com.weface.service.MenuTagsService;
import com.weface.common.utils.PageUtils;
import com.weface.common.utils.Query;
import org.apache.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Administrator
*/
@Slf4j
@Transactional
@Service("menuTagsService")
public class MenuTagsServiceImpl extends ServiceImpl<MenuTagsDao, MenuTagsEntity> implements MenuTagsService {
/**
* 列表
*
* @param params 参数
* @return 标签
*/
private static final String CODE = "kk";
@Override
public PageUtils queryPage(Map<String, Object> params) {
String levelThird = (String) params.get("levelThird");
IPage<MenuTagsEntity> page = this.page(
new Query<MenuTagsEntity>().getPage(params),
new QueryWrapper<MenuTagsEntity>().lambda().like(StringUtils.isNotBlank(levelThird), MenuTagsEntity::getLevelThird, levelThird)
);
return new PageUtils(page);
}
/**
* 根据code和权重查询标签
*
* @param code 编码
* @param weight 权重
* @return 标签信息
*/
public List<Object> getTagsList() {
List<MenuTagsEntity> list = this.baseMapper.getTagsList();
List<Object> firstChild = new ArrayList<>();
Set<String> level_first = list.stream().map(MenuTagsEntity::getLevelFirst).collect(Collectors.toSet());
for (String first : level_first) {
List<Object> secondChild = new ArrayList<>();
Set<String> level_second = list.stream().filter(x -> first.equals(x.getLevelFirst())).map(MenuTagsEntity::getLevelSecond).collect(Collectors.toSet());
for (String second : level_second) {
Map<String, Object> second_map = new HashMap<>();
List<Map<String, Object>> level_third = list.stream()
.filter(x -> second.equals(x.getLevelSecond()) && first.equals(x.getLevelFirst()))
.sorted(Comparator.comparing(MenuTagsEntity::getCreateTime).reversed())
.map(x -> {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("level", "3");
hashMap.put("menu_id", String.valueOf(x.getId()));
hashMap.put("label", x.getLevelThird() + "," + x.getCode());
return hashMap;
}).collect(Collectors.toList());
second_map.put("level", "2");
second_map.put("label", second);
second_map.put("children", level_third);
secondChild.add(second_map);
}
Map<String, Object> first_map = new HashMap<>(level_first.size());
first_map.put("level", "1");
first_map.put("label", first);
first_map.put("children", secondChild);
firstChild.add(first_map);
}
return firstChild;
}
@Override
public MenuTagsEntity getOneByCodeOrWeight(String code, String weight) {
List<MenuTagsEntity> list = this.list(new QueryWrapper<MenuTagsEntity>()
.lambda().eq(MenuTagsEntity::getCode, code)
.eq(StringUtils.isNotBlank(weight), MenuTagsEntity::getWeight, weight));
if (list != null && list.size() > 0) {
return list.get(0);
} else {
return null;
public CommonResult saveTag(MenuTagsForm menuTagsForm) {
try {
MenuTagsEntity menuTagsEntity = new MenuTagsEntity();
BeanUtil.copyProperties(menuTagsForm, menuTagsEntity, BeanUtils.getNullPropertyNames(menuTagsForm));
Snowflake snowflake = IdUtil.getSnowflake(1, 1);
menuTagsEntity.setId(snowflake.nextId());
String tagCode = "";
boolean flag = false;
while (!flag) {
tagCode = CODE + RandomUtil.randomString(6);
int count = this.count(new QueryWrapper<MenuTagsEntity>().lambda().eq(MenuTagsEntity::getCode, tagCode));
if (count == 0) {
flag = true;
}
}
menuTagsEntity.setCode(tagCode);
menuTagsEntity.setUpdateTime(new Date());
this.save(menuTagsEntity);
return CommonResult.success(tagCode);
} catch (Exception e) {
e.printStackTrace();
log.error("执行新增标签错误{}", e.getMessage());
}
return CommonResult.failed();
}
@Override
public CommonResult updateTag(MenuTagsForm menuTagsForm) {
try {
Long id = menuTagsForm.getId();
MenuTagsEntity byId = this.getById(id);
if (byId == null) {
return CommonResult.failed();
}
BeanUtil.copyProperties(menuTagsForm, byId, BeanUtils.getNullPropertyNames(menuTagsForm));
byId.setUpdateTime(new Date());
this.updateById(byId);
return CommonResult.success();
} catch (Exception e) {
e.printStackTrace();
log.error("执行更新标签错误{}", e.getMessage());
}
return CommonResult.failed();
}
}
\ No newline at end of file
package com.weface.serviceimpl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weface.code.CommonResult;
import com.weface.dao.UserMenusDao;
import com.weface.dto.UserMenuFrom;
import com.weface.entity.UserMenusEntity;
import com.weface.service.UserMenusService;
import org.apache.commons.collections4.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service("userMenusService")
@Transactional
public class UserMenusServiceImpl extends ServiceImpl<UserMenusDao, UserMenusEntity> implements UserMenusService {
......@@ -24,7 +34,7 @@ public class UserMenusServiceImpl extends ServiceImpl<UserMenusDao, UserMenusEnt
*/
@Override
public void batchInsert(List<UserMenusEntity> userMenusList) {
if (CollectionUtils.isNotEmpty(userMenusList)) {
if (CollUtil.isNotEmpty(userMenusList)) {
List<String> deleteUid = getDeleteUid(userMenusList);
//批量插入前全删
List<Long> ids = this.baseMapper.findIdByUserId(deleteUid);
......@@ -48,13 +58,64 @@ public class UserMenusServiceImpl extends ServiceImpl<UserMenusDao, UserMenusEnt
sum += this.baseMapper.batchInsert(userMenusEntities);
}
if (sum > 0) {
log.warn("新增成功记录==" + sum + "==条");
log.warn("新增成功记录=={}==条", sum);
} else {
log.error("新增失败");
}
}
}
@Override
public CommonResult saveUserTag(UserMenuFrom userMenuFrom) {
try {
String userId = userMenuFrom.getUserId();
String[] tagsId = userMenuFrom.getTagsId();
List<UserMenusEntity> list = this.list(new QueryWrapper<UserMenusEntity>().eq("user_id", userId).in("tags_id", Arrays.asList(tagsId)));
List<String> saveTags = Arrays.asList(tagsId);
if (CollUtil.isNotEmpty(list)) {
List<String> collect = list.stream().map(x -> String.valueOf(x.getTagsId())).collect(Collectors.toList());
saveTags = saveTags.stream().filter(item -> !collect.contains(item)).collect(Collectors.toList());
// removeByIds(collect);
}
if (CollUtil.isEmpty(saveTags)) {
return CommonResult.failed("用户标签已存在");
}
List<UserMenusEntity> userMenusEntities = new ArrayList<>(tagsId.length);
Snowflake snowflake = IdUtil.getSnowflake(1, 1);
for (String aLong : saveTags) {
UserMenusEntity userMenusEntity = new UserMenusEntity();
userMenusEntity.setId(snowflake.nextId());
userMenusEntity.setUserId(userId);
userMenusEntity.setTagsId(Convert.toLong(aLong));
userMenusEntity.setCreateTime(new Date());
userMenusEntity.setIsValid(1);
userMenusEntities.add(userMenusEntity);
}
int i = this.baseMapper.batchInsert(userMenusEntities);
if (i > 0) {
return CommonResult.success();
}
} catch (Exception e) {
e.printStackTrace();
log.error("保存用户标签信息失败{}", e.getMessage());
}
return CommonResult.failed();
}
@Override
public CommonResult delUserTag(UserMenuFrom userMenuFrom) {
try {
String userId = userMenuFrom.getUserId();
String[] tagsId = userMenuFrom.getTagsId();
this.remove(new LambdaQueryWrapper<UserMenusEntity>().eq(UserMenusEntity::getUserId, userId).in(UserMenusEntity::getTagsId, Arrays.asList(tagsId)));
return CommonResult.success();
} catch (Exception e) {
e.printStackTrace();
log.error("删除用户标签失败!{}", e.getMessage());
}
return CommonResult.failed();
}
/**
* 查询删除的uid
*
......
package com.weface.serviceimpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weface.common.utils.Constant;
import com.weface.common.utils.PageUtils;
import com.weface.common.utils.RedisUtil;
import com.weface.dao.UserTagDao;
import com.weface.dto.MenuTagsForm;
import com.weface.entity.MenuTagsEntity;
import com.weface.entity.UserTagEntity;
import com.weface.service.UserTagService;
import com.weface.common.utils.PageUtils;
import com.weface.common.utils.Query;
import org.springframework.beans.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
......@@ -21,6 +27,11 @@ import java.util.*;
@Service("tUserTagService")
public class UserTagServiceImpl extends ServiceImpl<UserTagDao, UserTagEntity> implements UserTagService {
@Override
public List<UserTagEntity> findUserTags(List<String> list) {
return this.baseMapper.findUserTags(list);
}
@Override
public List<UserTagEntity> findUserByTodayAndIdBefore(Integer id) {
return this.baseMapper.findUserByTodayAndIdBefore(id);
......@@ -37,45 +48,37 @@ public class UserTagServiceImpl extends ServiceImpl<UserTagDao, UserTagEntity> i
}
@Override
public PageUtils getUserAndTags(Map<String, Object> params) {
IPage<Object> page = new Query<>().getPage(params);
String gid = (String) params.get("gid");
IPage<UserTagEntity> userAndTagsByUid = this.baseMapper.getUserAndTags(new Page<UserTagEntity>(page.getCurrent(), page.getSize()), gid);
userAndTagsByUid.setTotal(userAndTagsByUid.getRecords().size());
return new PageUtils(userAndTagsByUid);
public PageUtils getUserList(Map<String, Object> params) {
//分页参数
int page = 1;
int limit = 10;
if (params.get(Constant.PAGE) != null) {
page = Convert.toInt(params.get(Constant.PAGE));
}
@Override
public List<String> getGidByTag(String[] tags) {
return this.baseMapper.getGidByTag(Arrays.asList(tags));
if (params.get(Constant.LIMIT) != null) {
limit = Convert.toInt(params.get(Constant.LIMIT));
}
@Override
public Map<String, Object> getTagByGid(String gid) {
List<UserTagEntity> userByUid = this.baseMapper.getTagByGid(gid);
List<Map<String, Object>> list = new ArrayList<>(userByUid.size());
for (UserTagEntity tUserTagEntity : userByUid) {
Map<String, Object> map = new HashMap<>(2);
List<MenuTagsForm> objects = new ArrayList<>();
tUserTagEntity.getList().forEach(item -> {
MenuTagsForm menuTagsForm = new MenuTagsForm();
BeanUtils.copyProperties(item, menuTagsForm);
objects.add(menuTagsForm);
});
map.put("userId", tUserTagEntity.getGid());
map.put("tags", objects);
list.add(map);
int star = (page - 1) * limit;
List<UserTagEntity> list = this.baseMapper.getUserList(star, limit, params);
String count = RedisUtil.StringOps.get("tags:user:count");
if (StringUtils.isBlank(count)) {
count = String.valueOf(this.count());
RedisUtil.StringOps.setEx("tags:user:count", count, 60, TimeUnit.MINUTES);
}
Map<String, Object> map = new HashMap<>(2);
map.put("error_code", 0);
map.put("userTag", list);
return map;
List<Object> maps = new ArrayList<>();
list.forEach(x -> {
Map<String, Object> map = BeanUtil.beanToMap(x, true, true);
List<MenuTagsEntity> tag = x.getList();
if (CollUtil.isNotEmpty(tag)) {
map.put("list", tag.stream().map(y ->
{
Map<String, Object> map1 = BeanUtil.beanToMap(y, true, true);
map1.put("id", String.valueOf(map1.get("id")));
return map1;
}).collect(Collectors.toList()));
}
@Override
public List<UserTagEntity> getAllImport() {
return this.baseMapper.selectAllUserForTags();
maps.add(map);
});
return new PageUtils(maps, Integer.parseInt(count), limit, page);
}
}
\ No newline at end of file
......@@ -4,18 +4,16 @@ import cn.hutool.core.collection.CollUtil;
import com.weface.common.utils.RedisUtil;
import com.weface.component.MenuService;
import com.weface.entity.MenuTagsEntity;
import com.weface.entity.UserTagEntity;
import com.weface.entity.UserMenusEntity;
import com.weface.entity.UserTagEntity;
import com.weface.service.MenuTagsService;
import com.weface.service.UserTagService;
import com.weface.service.UserMenusService;
import com.weface.service.UserTagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
......@@ -55,7 +53,7 @@ public class UserTagsTask {
/**
* 更新用户标签
*/
@Scheduled(cron = "0 0 23 * * ?")
// @Scheduled(cron = "0 0 23 * * ?")
public void updateUserTags() {
try {
//获取每次处理的id起始值
......@@ -177,7 +175,7 @@ public class UserTagsTask {
} else {
list = gid.subList(finalI * limit, (finalI + 1) * limit);
}
if (CollectionUtils.isNotEmpty(list)) {
if (CollUtil.isNotEmpty(list)) {
//获取个像数据
Map<String, Object> android = menuService.getUserTags(list, tag);
if (android != null) {
......
......@@ -15,7 +15,7 @@ spring:
name: service-web
# 环境 dev|test|prod
profiles:
active: prod
active: dev
# jackson时间格式化
jackson:
time-zone: GMT+8
......@@ -58,7 +58,8 @@ mybatis-plus:
gexiang:
redis:
hostname: 172.21.6.6
# hostname: 172.21.6.6
hostname: 127.0.0.1
database: 0
port: 6379
maxTotal: 1000
......
......@@ -12,10 +12,13 @@
<result property="code" column="code"/>
<result property="menuGrade" column="menu_grade"/>
<result property="weight" column="weight"/>
<result property="isDel" column="is_del"/>
<result property="isValid" column="is_valid"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
</resultMap>
<select id="getTagsList" resultMap="menuTagsMap">
SELECT id,level_first,level_second,level_third,`code`,create_time FROM tb_menu_tags WHERE is_valid = 1
</select>
</mapper>
\ No newline at end of file
......@@ -3,7 +3,7 @@
<mapper namespace="com.weface.dao.UserTagDao">
<!-- 可根据自己的需求,是否要使用 -->
<!-- 可根据自己的需求,是否要使用-->
<resultMap type="com.weface.entity.UserTagEntity" id="userTagMap">
<result property="id" column="id"/>
<result property="uid" column="uid"/>
......@@ -21,6 +21,23 @@
</collection>
</resultMap>
<!-- 导出用户标签信息-->
<select id="findUserTags" resultMap="userTagMap" parameterType="java.util.List">
SELECT
um.user_id AS uid,
mt.level_third AS level_third,
mt.id AS tagId
FROM
( SELECT user_id, tags_id FROM tb_user_menus WHERE user_id IN
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item}
</foreach>
AND is_valid = 1 ) um LEFT JOIN tb_menu_tags mt ON um.tags_id = mt.id
ORDER BY
um.user_id,
mt.id
</select>
<!-- 查询id之前且当天更新的用户 AND id &lt; #{id}-->
<select id="findUserByTodayAndIdBefore" resultMap="userTagMap">
SELECT uid, gid
......@@ -33,7 +50,7 @@
<!-- 查询id之后的用户信息-->
<select id="findUserByIdAfter" resultMap="userTagMap">
SELECT id,uid, gid
SELECT id, uid, gid
FROM t_user_tag
WHERE gid IS NOT NULL
AND id > #{id} LIMIT #{limit}
......@@ -49,8 +66,8 @@
ORDER BY save_date LIMIT #{star}, #{end}
</select>
<!-- 将公共片段抽取:只针对个别业务-->
<sql id="common">
<!-- 查询用户信息根据gid-->
<select id="getUserList" resultMap="userTagMap">
SELECT ut.uid,
ut.gid,
mt.id AS tagId,
......@@ -60,46 +77,24 @@
mt.`code`,
mt.menu_grade,
mt.weight
FROM t_user_tag ut
LEFT JOIN tb_user_menus um ON ut.uid = um.user_id
LEFT JOIN tb_menu_tags mt ON um.tags_id = mt.id
WHERE mt.level_first = "Android"
AND um.is_valid = 1
</sql>
<!-- 查询用户信息根据gid-->
<select id="getUserAndTags" resultMap="userTagMap">
<include refid="common"/>
<if test="gid !=null and gid != ''">
AND ut.gid LIKE CONCAT(CONCAT('%',#{gid}),'%')
FROM (SELECT * FROM t_user_tag
<where>
<if test="param.uid != null and param.uid != ''">
uid LIKE CONCAT(CONCAT('%',#{param.uid}),'%')
</if>
</select>
<!-- 根据标签查询用户gid-->
<select id="getGidByTag" resultType="string">
SELECT DISTINCT
ut.gid
FROM
t_user_tag ut
<if test="param.gid != null and param.gid != ''">
AND gid LIKE CONCAT(CONCAT('%',#{param.gid}),'%')
</if>
<if test="param.level_third != null and param.level_third != ''">
AND uid IN (SELECT um.user_id FROM tb_user_menus um LEFT JOIN tb_menu_tags mt ON um.tags_id = mt.id WHERE mt.level_third = #{param.level_third} AND um.is_valid = 1 GROUP BY um.user_id)
</if>
</where>
LIMIT #{star}, #{end}) ut
LEFT JOIN tb_user_menus um ON ut.uid = um.user_id
LEFT JOIN tb_menu_tags mt ON um.tags_id = mt.id
WHERE
mt.level_first = "Android" AND um.is_valid = 1
AND mt.level_third IN
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- 根据gid查询用户标签-->
<select id="getTagByGid" resultMap="userTagMap">
<include refid="common"/>
AND ut.gid =#{gid}
</select>
<!-- 查询所有用户标签管理数据-->
<select id="selectAllUserForTags" resultMap="userTagMap">
<include refid="common"/>
WHERE um.is_valid = 1 OR um.is_valid IS NULL
ORDER BY ut.uid,
mt.id
</select>
</mapper>
\ No newline at end of file
......@@ -2,31 +2,45 @@ package com.weface;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.weface.common.utils.RedisUtil;
import com.weface.component.GeTuiService;
import com.weface.component.MenuService;
import com.weface.component.MessageTemplate;
import com.weface.config.GeTuiApp;
import com.weface.dto.InformForm;
import com.weface.entity.MenuTagsEntity;
import com.weface.entity.UserTagEntity;
import com.weface.entity.UserMenusEntity;
import com.weface.entity.UserTagEntity;
import com.weface.service.MenuTagsService;
import com.weface.service.UserTagService;
import com.weface.service.UserMenusService;
import org.apache.commons.collections4.CollectionUtils;
import com.weface.service.UserTagService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@SpringBootTest
......@@ -151,4 +165,230 @@ class PushMessageApplicationTests {
System.out.println(s);
}
@Test
void testPush() {
//获取标签列表
List<MenuTagsEntity> tags = menuTagsService.list();
List<String> list = Collections.singletonList("d7e78cfa76e1c61699925ec9bb960d53");
Map<String, Object> userTags = menuService.getUserTags(list, tags);
System.out.println(userTags);
}
@Test
void testExportExcel() throws IOException {
//大数据写入excel
SXSSFWorkbook sxssfWorkbook = null;
//读取excel
XSSFWorkbook workbook;
//输出流
FileOutputStream fos = null;
//读取流
FileInputStream fis = null;
try {
//写入
sxssfWorkbook = new SXSSFWorkbook();
sxssfWorkbook.setCompressTempFiles(true);// 打开压缩功能 防止占用过多磁盘
Sheet sheet = sxssfWorkbook.createSheet("存钱罐用户标签统计");
//读取
fis = new FileInputStream("C:\\Users\\Administrator\\Desktop\\用户画像编码表(1).xlsx");
workbook = new XSSFWorkbook(fis);
XSSFSheet sheetAt = workbook.getSheetAt(5);
int limit = 10000;
int rowNum = sheetAt.getPhysicalNumberOfRows();
int size = rowNum % limit == 0 ? (rowNum / limit) : (rowNum / limit + 1);
for (int i = 0; i < size; i++) {
List<String> list;
if (i == size - 1) {
list = getCellValue(sheetAt, i * limit + 1, rowNum % limit);
} else {
list = getCellValue(sheetAt, i * limit + 1, limit);
}
List<UserTagEntity> userTags = userTagService.findUserTags(list);
int x = 1;
for (UserTagEntity userTag : userTags) {
String uid = userTag.getUid();
List<MenuTagsEntity> tags = userTag.getList();
Row row = sheet.createRow(x);
x++;
Cell cell0 = row.createCell(0);
cell0.setCellValue(uid);
int j = 1;
for (MenuTagsEntity menuTagsEntity : tags) {
Cell cell = row.createCell(j);
j++;
cell.setCellValue(menuTagsEntity.getLevelThird());
}
}
}
fos = new FileOutputStream("C:/Users/Administrator/Desktop/tags.xlsx");
sxssfWorkbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
if (sxssfWorkbook != null) {
sxssfWorkbook.dispose();
}
}
}
/**
* @param sheetAt 表格
* @param star 处理起始行
* @param limit 当前需处理多少行
* @return 数据
*/
private List<String> getCellValue(XSSFSheet sheetAt, int star, int limit) {
List<String> list = new ArrayList<>();
for (int i = 0; i < limit; i++) {
XSSFRow row = sheetAt.getRow(star);
if (row == null) {
continue;
}
XSSFCell cell = row.getCell(0);
star++;
String value = cell.getStringCellValue();
list.add(value);
}
return list;
}
@Test
void getAllTags() {
List<MenuTagsEntity> list = menuTagsService.list();
Set<String> level_first = list.stream().map(MenuTagsEntity::getLevelFirst).collect(Collectors.toSet());
Map<String, Object> first_map = new HashMap<>();
for (String first : level_first) {
Set<String> level_second = list.stream().filter(x -> first.equals(x.getLevelFirst())).map(MenuTagsEntity::getLevelSecond).collect(Collectors.toSet());
Map<String, Object> second_map = new HashMap<>();
for (String second : level_second) {
List<MenuTagsEntity> level_third = list.stream().filter(x -> second.equals(x.getLevelSecond()) && first.equals(x.getLevelFirst())).collect(Collectors.toList());
second_map.put(second, level_third);
}
first_map.put(first, second_map);
}
System.out.println(first_map);
}
@Test
void testRandom() {
String token = "54_qYwZpVbWrJDkflE1ha61B4SPwdhNVoCE6g_YG9zL0PL2ki6pZYsNKK__l2fMfmjRyt3C_EIiTq2Hnnla5MK8bGLckSUXUN14_A2UKMhF9xsVHQswPd6MnmVxV1YkSAyFVLEpF76kuCbBmps7GZOfAFAWPE";
// String token = "54_hksRqu53_0Jmw_lopjrJh4Ofzqzb_289qRkfZXxIVhBhk4vjSFH-20sbf6LUg8X1Go4tkVoISnFTSWiyKKUB1Pw8-KKNM8W6GsSpGsj85_fTtm5Uus7ncmkQCS_LxTAybYsUfsU6VaBm6hnHKJSeAAAUTC";
RedisUtil.StringOps.setEx("kksh_wechat:mini_program_token:10011", token, 5400, TimeUnit.SECONDS);
// String appId = "wx0c0e88fde84cc81c";
// String secret = "45aae2597122419a74297d5987965013";
// String code = "ce863cb4acfa518fc6893686d3e9480a0fd5b4b4ba99dd3d68d5ac4e50775943";
// String userPhone = getUserPhone("10011", code);
// System.out.println(userPhone);
}
private static Map<String, String> getAppId(String programType) {
String appId;
String secret;
if ("10011".equals(programType)) {
appId = "wx93e88ce737b22930";
secret = "968ece96a90fb21095005c9d26893f4a";
} else {
return null;
}
Map<String, String> map = new HashMap<>();
map.put("appId", appId);
map.put("secret", secret);
return map;
}
public static String getUserPhone(String programType, String code) {
String token = getWeChatToken(programType);
//参数错误 获取token失败
if (token == null || token.equals("")) {
return "17";
}
String phone = null;
boolean flag = false;
while (!flag) {
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
String format = String.format(url, token);
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", code);
String body = HttpRequest.post(format).body(jsonObject.toString()).execute().body();
if (JSONUtil.isJson(body)) {
JSONObject json = JSONUtil.parseObj(body);
if (json.containsKey("errcode")) {
Integer errCode = json.getInt("errcode");
if (errCode == 0) {
phone = json.getJSONObject("phone_info").getStr("phoneNumber");
flag = true;
} else if (errCode == 42001 || errCode == 40014 || errCode == 41001) {
token = getWeChatToken(getAppId(programType));
RedisUtil.StringOps.setEx("kksh_wechat:mini_program_token:" + programType, token, 5400, TimeUnit.SECONDS);
flag = false;
} else {
phone = String.valueOf(json.getInt("errcode"));
flag = true;
}
} else {
flag = true;
}
} else {
flag = true;
}
}
return phone;
}
/**
* 获取微信小程序token
*
* @return token
*/
private static String getWeChatToken(String programType) {
String token = RedisUtil.StringOps.get("kksh_wechat:mini_program_token:" + programType);
if (StringUtils.isBlank(token)) {
Map<String, String> map = getAppId(programType);
token = getWeChatToken(map);
if (StringUtils.isBlank(token)) {
RedisUtil.StringOps.setEx("kksh_wechat:mini_program_token:" + programType, token, 5400, TimeUnit.SECONDS);
}
}
return token;
}
/**
* 获取小程序token
*
* @param map 应用信息
* @return token
*/
private static String getWeChatToken(Map<String, String> map) {
if (map == null) {
return null;
}
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=%s&appid=%s&secret=%s";
String grant_type = "client_credential";
String auth_url = String.format(url, grant_type, map.get("appId"), map.get("secret"));
String body = HttpRequest.get(auth_url).execute().body();
if (JSONUtil.isJson(body)) {
JSONObject json = JSONUtil.parseObj(body);
if (json.containsKey("access_token")) {
return json.getStr("access_token");
} else {
System.out.println(body);
}
} else {
System.out.println(body);
}
return null;
}
}
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