Commit a9172314 by 丁伟峰

Merge remote-tracking branch 'origin/develop' into develop

2 parents f66f8cf9 7d168256
Showing with 346 additions and 931 deletions
......@@ -105,7 +105,6 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
......@@ -116,7 +115,7 @@
<dependency>
<groupId>org.optaplanner</groupId>
<artifactId>optaplanner-persistence-jackson</artifactId>
<version>9.38.0.Final</version>
<version>${version.org.optaplanner}</version>
<scope>compile</scope>
</dependency>
......@@ -130,7 +129,6 @@
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.0</version>
</dependency>
......
......@@ -49,7 +49,7 @@ public class BatchServiceImpl implements BatchService {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");
// 将当前时间转换为字符串
String result = LocalTime.now().format(formatter);
return day.replaceAll("-","") + "-" + result;
return day.replaceAll("-", "") + "-" + result;
}
......@@ -94,17 +94,37 @@ public class BatchServiceImpl implements BatchService {
" order by a.engineer_code asc";
int engCount = jdbcTemplate.update(sqlEngineer, batchNo, groupId);
// 未派过的工单
String sqlOrder = "INSERT INTO dispatch_order (group_id, batch_no, order_id , x, y, expect_time_begin, expect_time_end, tags, priority , skills , take_time )\n" +
" select a.org_group_id, ? , a.order_id, a.x, a.y , \n" +
" a.expect_time_begin, a.expect_time_end, a.tags, a.priority , concat(a.brand, a.type, a.skill) skills , b.take_time \n" +
" from order_request a left join product_category b on (a.brand=b.brand and a.type=b.type and a.skill=b.skill )\n" +
" where a.org_group_id=? and status='OPEN' and appointment_status='NOT_ASSIGNED' and appointment_method like 'AUTO%' \n" +
" and expect_time_begin between ? and ? \n" +
" where a.org_group_id=? and a.status='OPEN' " +
" and a.dt = ? " +
" and appointment_status ='NOT_ASSIGNED' and appointment_method like 'AUTO%' \n" +
" order by a.expect_time_begin asc ";
int orderCount = jdbcTemplate.update(sqlOrder, batchNo, groupId, batchDay + " 00:00:00", batchDay + " 23:59:59");
int orderCount = jdbcTemplate.update(sqlOrder, batchNo, groupId, batchDay );
// 已派过PRE状态还可以再次派
String sqlOrderPre = "INSERT INTO dispatch_order (group_id, batch_no, order_id , x, y, expect_time_begin, expect_time_end, tags, priority , skills , take_time )\n" +
" select a.org_group_id, ?, a.order_id, a.x, a.y , \n" +
" a.expect_time_begin, a.expect_time_end, a.tags, a.priority , concat(a.brand, a.type, a.skill) skills , b.take_time \n" +
" from order_request a " +
" left join product_category b on (a.brand=b.brand and a.type=b.type and a.skill=b.skill )\n" +
" left join order_appointment o on (a.order_id =o.order_id)\n" +
" where a.org_group_id=? and a.status='OPEN' \n" +
" and a.dt = ? " +
" and a.appointment_status = 'ASSIGNED' and appointment_method like 'AUTO%' \n" +
" and o.pre_status ='PRE' \n" +
" order by a.expect_time_begin asc ";
int orderCountPre = jdbcTemplate.update(sqlOrderPre, batchNo, groupId, batchDay );
log.info("准备批次数据 order1 :{}", orderCount);
log.info("准备批次数据 order2 :{}", orderCountPre);
jdbcTemplate.update("update dispatch_batch set engineer_num=? , order_num=?, status='RUNNING' where group_id=? and batch_no=?", engCount, orderCount, groupId, batchNo);
jdbcTemplate.update("update dispatch_batch set engineer_num=? , order_num=?, start_time=?, end_time=null, status='RUNNING' where group_id=? and batch_no=?",
engCount, orderCount+orderCountPre, LocalDateTime.now(), groupId, batchNo);
log.info("准备批次数据完成, groupId:{}, day:{}, batchNo:{}", groupId, batchDay, batchNo);
......
......@@ -12,6 +12,8 @@ import com.dituhui.pea.dispatch.pojo.DispatchSolution;
import com.dituhui.pea.dispatch.service.ExtractService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.util.FileUtil;
import org.drools.util.FileUtils;
import org.optaplanner.core.api.score.ScoreExplanation;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.api.solver.SolutionManager;
......@@ -19,12 +21,15 @@ import org.optaplanner.core.api.solver.SolutionUpdatePolicy;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.config.solver.SolverConfig;
import org.optaplanner.persistence.jackson.impl.domain.solution.JacksonSolutionFileIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalDateTime;
......@@ -130,8 +135,20 @@ public class ExtractServiceImpl implements ExtractService {
});
Object[] paramBatch= {groupId, batchNo};
jdbcTemplate.update(" update dispatch_batch set status='DONE' where group_id=? and batch_no=? ", paramBatch);
JacksonSolutionFileIO<DispatchSolution> exporter = new JacksonSolutionFileIO<DispatchSolution>(DispatchSolution.class);
String fileName = String.format("dispatchSolution-%s-%s.json", groupId, batchNo);
File tempFile = new File(fileName);
exporter.write(solution, tempFile);
String dispatchResultJson = "{}";
try {
dispatchResultJson = FileUtil.readAsString(tempFile);
} catch (IOException e) {
log.error("json算法结果回写 error , groupId:{}, batchNo:{} ", groupId, batchNo, e);
}
Object[] paramBatch = {LocalDateTime.now(), dispatchResultJson, groupId, batchNo};
jdbcTemplate.update(" update dispatch_batch set status='DONE', end_time=? , ext=? where group_id=? and batch_no=? ", paramBatch);
log.info("算法结果回写dispatch完成, groupId:{}, batchNo:{}", groupId, batchNo);
......
......@@ -6,6 +6,7 @@ import com.dituhui.pea.dispatch.constraint.DispatchConstraintProvider;
import com.dituhui.pea.dispatch.dao.DispatchEngineerRepository;
import com.dituhui.pea.dispatch.dao.DispatchOrderRepository;
import com.dituhui.pea.dispatch.dao.OrgGroupRepository;
import com.dituhui.pea.dispatch.entity.DispatchOrder;
import com.dituhui.pea.dispatch.entity.OrgGroup;
import com.dituhui.pea.dispatch.pojo.*;
import com.dituhui.pea.dispatch.service.ExtractService;
......@@ -87,7 +88,11 @@ public class SolveServiceImpl implements SolveService {
// customerlist
ArrayList<Customer> customerList = new ArrayList<>();
dispatchOrderRepo.findByGroupIdAndBatchNo(groupId, batchNo).forEach(order -> {
List<DispatchOrder> dispatchOrderList = dispatchOrderRepo.findByGroupIdAndBatchNo(groupId, batchNo);
log.info("组织问题对象, dispatchorder-list, groupId:{}, batchNo:{}, dispatchorder-size:{}", groupId, batchNo, dispatchOrderList.size());
dispatchOrderList.forEach(order -> {
Location location = new Location(order.getId(), order.getOrderId(), "工单", Double.parseDouble(order.getX()), Double.parseDouble(order.getY()));
LocalDateTime ldt1 = dateToLocalDateTime(order.getExpectTimeBegin());
......@@ -101,6 +106,18 @@ public class SolveServiceImpl implements SolveService {
end = ldt2.getMinute();
}
// 40分钟兜低(技能未能正确匹配原因)
if (null == order.getTakeTime()) {
order.setTakeTime(40);
}
if (null == order.getTags()) {
order.setTags("");
}
if (null == order.getPriority()) {
order.setPriority(0);
}
Customer customer = new Customer(order.getId(), order.getOrderId(), location, start, end,
order.getSkills(), order.getTakeTime());
......@@ -178,8 +195,6 @@ public class SolveServiceImpl implements SolveService {
JacksonSolutionFileIO<DispatchSolution> exporter = new JacksonSolutionFileIO<DispatchSolution>(
DispatchSolution.class);
// Set the output file.
String fileName = String.format("dispatchSolution-%s-%s.json", groupId, batchNo);
exporter.write(solution, new File(fileName));
......
......@@ -18,11 +18,6 @@ public class UserAuthInfo implements Serializable {
private String userId;
/**
* 团队id
*/
private String teamId;
/**
* 用户名称
*/
private String userName;
......@@ -37,9 +32,8 @@ public class UserAuthInfo implements Serializable {
*/
private String role;
public UserAuthInfo(String userId, String teamId, String userName, String password, String role) {
public UserAuthInfo(String userId, String userName, String password, String role) {
this.userId = userId;
this.teamId = teamId;
this.userName = userName;
this.password = password;
this.role = role;
......
......@@ -97,14 +97,5 @@ public class UserInfo {
* 更新时间
*/
private Date updatedTime;
/**
* 团队ID
*/
private String teamId;
/**
* 团队信息
*/
private TeamInfo teamInfo;
}
......@@ -78,6 +78,12 @@
</dependency>
<dependency>
<groupId>org.gavaghan</groupId>
<artifactId>geodesy</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
......@@ -102,12 +108,6 @@
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>project-dispatch</artifactId>
<version>2021.0.5.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
......
package com.dituhui.pea.order.common;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
public class Distance {
public long calculateDistance(double lat1, double lnt1, double lat2, double lnt2) {
GlobalCoordinates source = new GlobalCoordinates(lat1, lnt1);
GlobalCoordinates target = new GlobalCoordinates(lat2, lnt2);
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.WGS84, source, target);
return Math.round(geoCurve.getEllipsoidalDistance());
}
}
package com.dituhui.pea.order.common;
import com.dituhui.pea.order.dao.EngineerBusinessMPDao;
import com.dituhui.pea.order.dao.OrderAppointmentMPDao;
import com.dituhui.pea.order.dao.OrderRequestMPDao;
import com.dituhui.pea.order.dao.SkillInfoMPDao;
import com.dituhui.pea.order.entity.EngineerBusiness;
import com.dituhui.pea.order.entity.OrderAppointment;
import com.dituhui.pea.order.entity.OrderRequest;
import com.dituhui.pea.order.entity.SkillInfo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class OrderAssignCheck {
private String orderId;
private String engineerCode;
@Autowired
OrderRequestMPDao orderRequestMPDao;
@Autowired
OrderAppointmentMPDao orderAppointmentMPDao;
@Autowired
SkillInfoMPDao skillInfoMPDao;
@Autowired
EngineerBusinessMPDao engineerBusinessMPDao;
public OrderAssignCheck(String orderId, String engineerCode) {
this.orderId = orderId;
this.engineerCode = engineerCode;
}
@Data
public class Result {
private Boolean canAssign;
private String message;
private int minuteAddition;
private int distanceAddition;
private LocalDateTime start;
private LocalDateTime end;
public Result(boolean canAssign, String message, int minuteAddition, int distanceAddition, LocalDateTime start, LocalDateTime end){
this.canAssign = canAssign;
this.message = message;
this.minuteAddition = minuteAddition;
this.distanceAddition = distanceAddition;
this.start = start;
this.end = end;
}
}
public Result orderAssignCheck() {
OrderRequest order = orderRequestMPDao.getByOrderId(this.orderId);
double curX = Double.parseDouble(order.getX());
double curY = Double.parseDouble(order.getY());
// 获取技能需要的时长(分钟)
SkillInfo skillInfo = skillInfoMPDao.getByBrandAndTypeAndSkill(order.getBrand(), order.getType(), order.getSkill());
int takeTime = skillInfo.getTakeTime();
// 获取客户期望时间段
int start = this.timestamp2Point(order.getExpectTimeBegin());
int end = this.timestamp2Point(order.getExpectTimeEnd());
// 获取技术员的已分配订单的时间段, 根据时间段排序
List<OrderSegment> orderSegments = getEngineerOrderSegments(engineerCode, order.getDt());
// 转化为SegmentInsertion需要的时间段
List<SegmentInsertion.Segment> segments = this.orderSegment2Segment(orderSegments);
int index = SegmentInsertion.insertSegment(takeTime, start, end, segments);
if (index == -1) {
return new Result(false, "没有连续可插入空间(没计算时间)", 0, 0, null, null);
}
// 计算距离 & 时间
if(index == 0) {
// 第一订单为出发地
EngineerBusiness b = engineerBusinessMPDao.getByEngineerCode(engineerCode);
OrderSegment post = orderSegments.get(1);
OrderSegment pre = new OrderSegment(480, post.getStart(), Double.parseDouble(b.getX()), Double.parseDouble(b.getY()));
return this.getResult(curX, curY, pre, post, takeTime, order.getDt());
}
else if(index == orderSegments.size()) {
// 最后一个订单出发
OrderSegment pre = orderSegments.get(index);
// 为当前订单
OrderSegment post = new OrderSegment(start, end, Double.parseDouble(order.getX()), Double.parseDouble(order.getY()));
} else {
OrderSegment pre = orderSegments.get(index);
OrderSegment post = orderSegments.get(index+1);
return this.getResult(curX, curY, pre, post, takeTime, order.getDt());
}
return null;
}
private List<OrderSegment> getEngineerOrderSegments(String engineerCode, LocalDate dt) {
List<OrderSegment> orderSegments = new ArrayList<>();
List<OrderAppointment> appointments = orderAppointmentMPDao.selectByEngineerCodeAndDt(engineerCode, dt);
List<String> orderIds = new ArrayList<>();
for (OrderAppointment o: appointments) {
// 过滤掉已经取消的订单
if(o.getStatus().equals("NOT_ASSIGNED") || o.getStatus().equals("CANCELED")) {
continue;
}
orderIds.add(o.getOrderId());
}
Map<String, List<OrderAppointment>> m = appointments.stream().collect(Collectors.groupingBy(OrderAppointment::getOrderId));
List<OrderRequest> orderRequests = orderRequestMPDao.selectByOrderIds(orderIds);
for(OrderRequest o: orderRequests) {
List<OrderAppointment> tmp = m.getOrDefault(o.getOrderId(), new ArrayList<>());
if(tmp.isEmpty()) {
continue;
}
OrderAppointment oa = tmp.get(0);
OrderSegment seg = new OrderSegment();
seg.setOrderId(o.getOrderId());
seg.setX(Double.parseDouble(o.getX()));
seg.setY(Double.parseDouble(o.getY()));
seg.setStart(this.timestamp2Point(oa.getExpectStartTime()));
seg.setEnd(this.timestamp2Point(oa.getExpectEndTime()));
orderSegments.add(seg);
}
return orderSegments.stream().sorted(Comparator.comparing(OrderSegment::getStart)).collect(Collectors.toList());
}
private List<SegmentInsertion.Segment> orderSegment2Segment(List<OrderSegment> orderSegments) {
List<SegmentInsertion.Segment> segments = new ArrayList<>();
for (OrderSegment s: orderSegments) {
segments.add(new SegmentInsertion.Segment(s.getOrderId(), s.getStart(), s.getEnd()));
}
return segments;
}
private Result getResult(double curX, double curY, OrderSegment pre, OrderSegment post, int takeTime, LocalDate dt) {
Pair preCurPair = this.getDistanceAndDuration(pre.getX(), pre.getY(), curX, curY);
Pair postCurPair = this.getDistanceAndDuration(post.getX(), post.getY(), curX, curY);
Pair prePostPair = this.getDistanceAndDuration(post.getX(), post.getY(), pre.getX(), pre.getY());
// 判断增加时间+距离后,时间是否重叠了
int distance = post.getStart() - postCurPair.getDuration() - (pre.getEnd() + preCurPair.getDuration());
if(distance < takeTime) {
// 不支持插入
return new Result(false, "增加时间路程后,不支持插入", 0, 0, null, null);
}
// 插入点(时间点)
int startInsert = pre.getEnd() + preCurPair.getDuration();
int endInsert = startInsert + takeTime;
LocalDateTime startDateTime = this.point2LocalDateTime(startInsert, dt);
LocalDateTime endDateTime = this.point2LocalDateTime(endInsert, dt);
int minuteAddition = preCurPair.getDuration() + postCurPair.getDuration() - prePostPair.getDuration();
int distanceAddition = preCurPair.getDistance() + postCurPair.getDistance() - prePostPair.getDistance();
return new Result(true, "success", minuteAddition, distanceAddition, startDateTime, endDateTime);
}
private int timestamp2Point(Timestamp t) {
LocalDateTime dt = t.toLocalDateTime();
return dt.getHour() * 60 + dt.getMinute();
}
private LocalTime point2LocalTime(int point) {
int hour = point / 60;
int minute = point % 60;
return LocalTime.of(hour, minute, 0);
}
private LocalDateTime point2LocalDateTime(int point, LocalDate dt) {
return LocalDateTime.of(dt, this.point2LocalTime(point));
}
private Pair getDistanceAndDuration(double x1, double y1, double x2, double y2){
Distance cal= new Distance();
long distance = Math.round(cal.calculateDistance(x1, y1, x2, y2) * 1.4); // 单位为米
long duration = distance / (19 * 1000 / 60); // 时间为分钟,假设电动车速度为19km/h
return new Pair((int)distance, (int)duration);
}
}
@Data
class OrderSegment{
private String orderId;
private int start;
private int end;
private double x;
private double y;
public OrderSegment(){
}
public OrderSegment(int start, int end, double x, double y){
this.start = start;
this.end = end;
this.x = x;
this.y = y;
}
}
@Data
class Pair{
private int distance;
private int duration;
public Pair(int distance, int duration){
this.distance = distance;
this.duration = duration;
}
}
......@@ -13,6 +13,7 @@
<properties>
<druid.version>1.1.10</druid.version>
<mysql.version>8.0.28</mysql.version>
</properties>
<dependencies>
......@@ -93,10 +94,10 @@
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- temp -->
......
package com.dituhui.pea.user.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dituhui.pea.enums.StatusCodeEnum;
import com.dituhui.pea.pojo.RoleInfo;
import com.dituhui.pea.pojo.UserInfo;
import com.dituhui.pea.user.ITeam;
import com.dituhui.pea.user.entity.TeamEntity;
import com.dituhui.pea.user.service.TeamService;
import com.dituhui.pea.pojo.WebResult;
import com.dituhui.pea.pojo.TeamInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
*
* 团队控制层
* @author zl
* @since 2020-12-09 15:42:00
*
*/
@RestController
@RefreshScope
public class TeamController implements ITeam {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
TeamService teamService;
@Override
public WebResult<TeamInfo> queryById(String teamId) {
if (StringUtils.isBlank(teamId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
TeamInfo teamInfo = teamService.queryTeamById(teamId);
return WebResult.ok(teamInfo);
}
@Override
public WebResult<TeamInfo> queryByAppKey(String ak) {
if (StringUtils.isBlank(ak)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
TeamInfo teamInfo = teamService.queryTeamByAppKey(ak);
return WebResult.ok(teamInfo);
}
@Override
public WebResult<TeamInfo> addTeam(@Validated TeamInfo teamInfo) {
TeamEntity teamEntity = BeanUtil.copyProperties(teamInfo, TeamEntity.class);
teamInfo = teamService.saveTeam(teamEntity);
return WebResult.ok(teamInfo);
}
@Override
public WebResult<TeamInfo> updateTeam(TeamInfo teamInfo) {
if (ObjectUtil.isNull(teamInfo)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
if (StringUtils.isBlank(teamInfo.getId())){
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
teamInfo = teamService.updateTeam(teamInfo);
return WebResult.ok(teamInfo);
}
@Override
public WebResult<Boolean> deleteTeam(String teamId) {
if (StringUtils.isBlank(teamId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
teamService.deleteTeam(teamId);
return WebResult.ok();
}
@Override
public WebResult<Boolean> addTeamUser(String teamId, String userId) {
if (StringUtils.isBlank(teamId) && StringUtils.isBlank(userId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
teamService.saveTeamUser(teamId, userId);
return WebResult.ok();
}
@Override
public WebResult<Boolean> deleteTeamUser(String teamId, String userId) {
if (StringUtils.isBlank(teamId) && StringUtils.isBlank(userId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
teamService.deleteTeamUser(teamId,userId);
return WebResult.ok();
}
@Override
public WebResult<List<UserInfo>> getTeamUser(String teamId) {
if (StringUtils.isBlank(teamId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
List<UserInfo> teamUserList = teamService.getTeamUserList(teamId);
return WebResult.ok(teamUserList);
}
@Override
public WebResult<List<RoleInfo>> getTeamRole(String teamId) {
if (StringUtils.isBlank(teamId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
List<RoleInfo> teamRoleList = teamService.getTeamRoleList(teamId);
return WebResult.ok(teamRoleList);
}
}
......@@ -8,9 +8,7 @@ import com.dituhui.pea.enums.ThirdPartyEnum;
import com.dituhui.pea.pojo.*;
import com.dituhui.pea.user.IUser;
import com.dituhui.pea.user.commom.RedisService;
import com.dituhui.pea.user.service.TeamService;
import com.dituhui.pea.user.service.UserService;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -30,25 +28,13 @@ public class UserController implements IUser {
private UserService userService;
@Autowired
TeamService teamService;
@Autowired
private CurrentUser currentUser;
@Autowired
private RedisService redisService;
@Override
public WebResult<UserInfo> getCurrentUserInfo(String userToken, Boolean needTeamInfo) {
UserAuthInfo userInfoCache = getUserAuthInfoFromToken(userToken);
String userId = userInfoCache.getUserId();
String teamId = userInfoCache.getTeamId();
UserInfo userInfo = userService.queryUserById(userId);
if (BooleanUtils.isTrue(needTeamInfo)) {
TeamInfo teamInfo = teamService.queryTeamById(teamId);
userInfo.setTeamInfo(teamInfo);
userInfo.setTeamId(teamId);
}
return WebResult.ok(userInfo);
}
......@@ -78,8 +64,6 @@ public class UserController implements IUser {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
UserInfo userInfo = userService.queryTeamByAccount(account);
// 补充团队信息
fillTemInfo(userInfo);
return WebResult.ok(userInfo);
}
......@@ -91,32 +75,15 @@ public class UserController implements IUser {
}
UserInfo userInfo = userService.queryUserByPhone(phone);
System.out.println("queryUserByPhone UserInfo ["+userInfo+"]");
// 补充团队信息
fillTemInfo(userInfo);
System.out.println("queryUserByPhone fillTemInfo UserInfo ["+userInfo+"]");
return WebResult.ok(userInfo);
}
/**
* 补充团队信息
*
* @param userInfo
*/
private void fillTemInfo(UserInfo userInfo) {
if (StringUtils.isNotEmpty(userInfo.getTeamId())) {
TeamInfo teamInfo = teamService.queryTeamById(userInfo.getTeamId());
userInfo.setTeamInfo(teamInfo);
}
}
@Override
public WebResult<UserInfo> queryUserByThirdParty(String id, ThirdPartyEnum type) {
if (StringUtils.isBlank(id)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY);
}
UserInfo userInfo = userService.queryUserByThirdParty(id, type);
// 补充团队信息
fillTemInfo(userInfo);
return WebResult.ok(userInfo);
}
......@@ -159,16 +126,12 @@ public class UserController implements IUser {
@Override
public WebResult<UserInfo> register(@Validated UserInfo userInfo) {
userInfo = userService.register(userInfo);
// 补充团队信息
fillTemInfo(userInfo);
return WebResult.ok(userInfo);
}
@Override
public WebResult<UserInfo> thirdRegister(ThirdUserInfo thirdUserInfo) {
UserInfo userInfo = userService.thirdRegister(thirdUserInfo);
// 补充团队信息
fillTemInfo(userInfo);
return WebResult.ok(userInfo);
}
......
......@@ -6,8 +6,6 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* 角色表(Role)表数据库访问层
*
......@@ -17,22 +15,4 @@ import java.util.List;
public interface RoleDao extends JpaRepository<RoleEntity, String>,
JpaSpecificationExecutor<RoleEntity>, CrudRepository<RoleEntity, String> {
/**
* 根据团队ID查询
* @param teamId 团队ID
* @return
*/
List<RoleEntity> findByTeamId(String teamId);
/**
* 根据角色ID和团队ID查询
* @param id 角色ID
* @param teamId 团队ID
* @return
*/
RoleEntity findByIdAndTeamId(String id, String teamId);
}
package com.dituhui.pea.user.dao;
import com.dituhui.pea.user.entity.TeamEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
/**
* 团队表(Team)表数据库访问层
*
* @author zl
* @since 2020-12-09 15:34:36
*/
public interface TeamDao extends JpaRepository<TeamEntity, String>,
JpaSpecificationExecutor<TeamEntity>, CrudRepository<TeamEntity, String> {
/**
* 查询团队信息
*
* @param ak 团队ak
* @return
*/
TeamEntity findByAppKey(String ak);
}
package com.dituhui.pea.user.dao;
import com.dituhui.pea.user.entity.UserEntity;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
import com.dituhui.pea.user.entity.UserEntity;
/**
* 用户表(User)表数据库访问层
......@@ -47,20 +47,6 @@ public interface UserDao extends JpaRepository<UserEntity, String>,
List<UserEntity> findByWechatMiniProgram(String wechatMiniProgram);
/**
* 根据qq查询
* @param qq
* @return
*/
List<UserEntity> findByQq(String qq);
/**
* 根据微博查询
* @param weibo 微博
* @return
*/
Optional<UserEntity> findByWeibo(String weibo);
/**
* 根据账号查询
* @param account 账号
* @return
......
package com.dituhui.pea.user.dao;
import com.dituhui.pea.user.entity.UserTeamEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* 用户所属团队表(UserTeam)表数据库访问层
*
* @author zl
* @since 2020-12-09 15:34:53
*/
public interface UserTeamDao extends JpaRepository<UserTeamEntity, String>,
JpaSpecificationExecutor<UserTeamEntity>, CrudRepository<UserTeamEntity, String> {
/**
* 根据用户ID查询
* @param userId 用户ID
* @return
*/
UserTeamEntity findByUserId(String userId);
/**
* 根据用户ID查询
*
* @param userId 用户ID
* @param status 状态
* @return
*/
List<UserTeamEntity> findAllByUserIdAndStatusOrderByCreatedByDesc(String userId, int status);
/**
* 根据团队Id和用户ID查询
* @param userId 用户ID
* @param teamId 团队ID
* @return
*/
UserTeamEntity findByUserIdAndTeamId(String userId, String teamId);
/**
* 根据用户ID删除
* @param userId 用户ID
*/
void deleteByUserId(String userId);
/**
* 根据团队ID查询
* @param teamId 团队ID
* @return
*/
List<UserTeamEntity> findByTeamId(String teamId);
/**
* 根据teamId删除
* @param teamId 团队Id
*/
void deleteByTeamId(String teamId);
/**
* 根据团队和用户删除
* @param teamId 团队ID
* @param userId 用户ID
*/
void deleteByTeamIdAndUserId(String teamId, String userId);
}
......@@ -14,12 +14,10 @@ import java.util.Date;
/**
* 资源表 用户对某种具体权限或者功能的描述(ResourceEntity)实体类
*
* @author zl
* @since 2020-12-09 15:13:43
*/
@Data
@Entity
@Table(name ="resource")
@Table(name = "sys_resource")
@EntityListeners(AuditingEntityListener.class)
public class ResourceEntity implements Serializable {
private static final long serialVersionUID = 157258775707540233L;
......@@ -43,11 +41,10 @@ public class ResourceEntity implements Serializable {
@Column(name = "extra")
private String extra;
/**
* 团队id
* 资源类型1菜单2功能点3所属组织
*/
@Column(name = "team_id")
@NotBlank(message = "团队名称不能为空!")
private String teamId;
@Column(name = "type")
private Integer type;
/**
* 描述
*/
......
......@@ -14,12 +14,10 @@ import java.util.Date;
/**
* 角色表(RoleEntity)实体类
*
* @author zl
* @since 2020-12-09 15:13:27
*/
@Data
@Entity
@Table(name ="role")
@Table(name ="sys_role")
@EntityListeners(AuditingEntityListener.class)
public class RoleEntity implements Serializable {
private static final long serialVersionUID = -71423293715769828L;
......@@ -38,12 +36,6 @@ public class RoleEntity implements Serializable {
@NotBlank(message = "角色名称不能为空!")
private String name;
/**
* 团队id
*/
@Column(name = "team_id")
@NotBlank(message = "团队Id不能为空!")
private String teamId;
/**
* 角色组id
*/
@Column(name = "group_id")
......
......@@ -10,12 +10,10 @@ import java.util.Date;
/**
* 角色组表(RoleGroupEntity)实体类
*
* @author zl
* @since 2020-12-09 15:13:18
*/
@Data
@Entity
@Table(name ="role_group")
@Table(name ="sys_role_group")
public class RoleGroupEntity implements Serializable {
private static final long serialVersionUID = -66824982136301845L;
/**
......@@ -37,11 +35,6 @@ public class RoleGroupEntity implements Serializable {
@Column(name = "description")
private String description;
/**
* 团队id
*/
@Column(name = "team_id")
private String teamId;
/**
* 创建人
*/
@Column(name = "CREATED_BY")
......
......@@ -10,12 +10,10 @@ import java.util.Date;
/**
* 角色资源表(RoleResourceEntity)实体类
*
* @author zl
* @since 2020-12-09 15:13:05
*/
@Data
@Entity
@Table(name ="role_resource")
@Table(name ="sys_role_resource")
public class RoleResourceEntity implements Serializable {
private static final long serialVersionUID = -10273487455832697L;
/**
......
package com.dituhui.pea.user.entity;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
/**
* 团队表(TeamEntity)实体类
*
* @author zl
* @since 2020-12-09 15:16:29
*/
@Data
@Entity
@Table(name ="team")
@EntityListeners(AuditingEntityListener.class)
public class TeamEntity implements Serializable {
private static final long serialVersionUID = 959077359004482022L;
/**
* 主键
*/
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "ID", unique = true, nullable = false, length = 32)
private String id;
/**
* 名称
*/
@Column(name = "name")
@NotNull(message = "团队名称不能为空!")
private String name;
/**
* 到期时间
*/
@Column(name = "expire_date")
@NotNull(message = "团队到期时间不能为空!")
private Date expireDate;
/**
* 是否签约
*/
@Column(name = "contract")
@NotNull(message = "团队签约状态不能为空!")
private Integer contract;
/**
* ak
*/
@Column(name = "app_key")
@NotNull(message = "团队ak不能为空!")
private String appKey;
/**
* 密钥
*/
@NotNull(message = "团队secret不能为空!")
@Column(name = "secret")
private String secret;
/**
* 公司图标
*/
@Column(name = "logo")
private String logo;
/**
* 所属行业
*/
@Column(name = "business")
private String business;
/**
* 所属省
*/
@Column(name = "province")
private String province;
/**
* 所属市
*/
@Column(name = "city")
private String city;
/**
* 所属区县
*/
@Column(name = "county")
private String county;
/**
* 人数
*/
@Column(name = "size")
private String size;
/**
* 公司地址
*/
@Column(name = "address")
private String address;
/**
* 营业执照
*/
@Column(name = "charter")
private String charter;
/**
* 团队自定义条件
*/
@Column(name = "extra")
private String extra;
/**
* 创始人用户id
*/
@Column(name = "admin_id")
private String adminId;
/**
* 创建人
*/
@Column(name = "CREATED_BY")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "CREATED_TIME")
@CreatedDate
private Date createdTime;
/**
* 更新人
*/
@Column(name = "UPDATED_BY")
private String updatedBy;
/**
* 更新时间
*/
@Column(name = "UPDATED_TIME")
@LastModifiedDate
private Date updatedTime;
}
......@@ -13,12 +13,10 @@ import java.util.Date;
/**
* 用户表(UserEntity)实体类
*
* @author zl
* @since 2020-12-09 15:11:38
*/
@Data
@Entity
@Table(name ="user")
@Table(name ="sys_user")
@EntityListeners(AuditingEntityListener.class)
public class UserEntity implements Serializable {
private static final long serialVersionUID = 595672857439664430L;
......@@ -84,16 +82,6 @@ public class UserEntity implements Serializable {
@Column(name = "LAST_LOGIN_TIME")
private Date lastLoginTime;
/**
* 微博唯一识别id
*/
@Column(name = "weibo")
private String weibo;
/**
* qq唯一识别id
*/
@Column(name = "qq")
private String qq;
/**
* 微信小程序识别id
*/
@Column(name = "wechat_mini_program")
......
......@@ -14,12 +14,10 @@ import java.util.Date;
/**
* 用户角色关系表(UserRoleEntity)实体类
*
* @author zl
* @since 2020-12-09 15:12:06
*/
@Data
@Entity
@Table(name ="user_role")
@Table(name ="sys_user_role")
@EntityListeners(AuditingEntityListener.class)
public class UserRoleEntity implements Serializable {
private static final long serialVersionUID = -30812324643312481L;
......@@ -44,12 +42,6 @@ public class UserRoleEntity implements Serializable {
@NotBlank(message = "角色ID不能为空")
private String roleId;
/**
* 团队id
*/
@Column(name = "team_id")
@NotBlank(message = "团队ID不能为空")
private String teamId;
/**
* 创建人
*/
@Column(name = "CREATED_BY")
......
package com.dituhui.pea.user.entity;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
/**
* 用户所属团队表(UserTeamEntity)实体类
*
* @author zl
* @since 2020-12-09 15:12:19
*/
@Data
@Entity
@Table(name ="user_team")
@EntityListeners(AuditingEntityListener.class)
public class UserTeamEntity implements Serializable {
private static final long serialVersionUID = 544874589204245131L;
/**
* 主键
*/
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "ID", unique = true, nullable = false, length = 32)
private String id;
/**
* 用户id
*/
@Column(name = "user_id")
@NotNull(message = "用户ID为空")
private String userId;
/**
* 团队id
*/
@Column(name = "team_id")
@NotNull(message = "团队ID为空")
private String teamId;
/**
* 状态
*/
@Column(name = "status")
@NotNull(message = "用户状态为空")
private Integer status;
/**
* 创建人
*/
@Column(name = "CREATED_BY")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "CREATED_TIME")
@CreatedDate
private Date createdTime;
/**
* 更新人
*/
@Column(name = "UPDATED_BY")
private String updatedBy;
/**
* 更新时间
*/
@Column(name = "UPDATED_TIME")
@LastModifiedDate
private Date updatedTime;
}
package com.dituhui.pea.user.factory;
import com.dituhui.pea.user.entity.UserEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* QqThirdStrategy
*
* @author zhouyun
* 2021/5/21 15:08
* <p>Company: 成都地图慧科技有限公司</p>
*/
@Component("QQ")
public class QqThirdStrategy extends AbstractThirdStrategy {
@Override
public UserEntity getUser(String id) {
List<UserEntity> allUserEntityList = userDao.findByQq(id);
if (CollectionUtils.isEmpty(allUserEntityList)) {
return null;
}
// 如果存在多个qq用户 默认取第一个
return allUserEntityList.get(0);
}
}
package com.dituhui.pea.user.factory;
import com.dituhui.pea.user.entity.UserEntity;
import org.springframework.stereotype.Component;
/**
* WeiboThirdStrategy
*
* @author zhouyun
* 2021/5/21 15:09
* <p>Company: 成都地图慧科技有限公司</p>
*/
@Component("WEIBO")
public class WeiboThirdStrategy extends AbstractThirdStrategy{
@Override
public UserEntity getUser(String id) {
return userDao.findByWeibo(id).orElse(null);
}
}
......@@ -79,7 +79,7 @@ public class RoleService {
throw new BusinessException(StatusCodeEnum.ROLE_RESOURCE_EMPTY);
}
// 保存用户角色关系
UserRoleEntity userRoleEntity = assembleUserRoleEntity(roleId, userId, roleEntity.getTeamId());
UserRoleEntity userRoleEntity = assembleUserRoleEntity(roleId, userId);
userRoleDao.save(userRoleEntity);
}
......@@ -173,11 +173,10 @@ public class RoleService {
}
private UserRoleEntity assembleUserRoleEntity(String roleId, String userId, String teamId) {
private UserRoleEntity assembleUserRoleEntity(String roleId, String userId) {
UserRoleEntity userRoleEntity = new UserRoleEntity();
userRoleEntity.setRoleId(roleId);
userRoleEntity.setUserId(userId);
userRoleEntity.setTeamId(teamId);
return userRoleEntity;
}
......
package com.dituhui.pea.user.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.dituhui.pea.constants.TeamConstant;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dituhui.pea.enums.StatusCodeEnum;
import com.dituhui.pea.enums.TeamContractEnum;
import com.dituhui.pea.enums.ThirdPartyEnum;
import com.dituhui.pea.enums.UserStatusEnum;
import com.dituhui.pea.exception.BusinessException;
import com.dituhui.pea.pojo.ThirdUserInfo;
import com.dituhui.pea.pojo.UserInfo;
import com.dituhui.pea.user.constant.TextConstant;
import com.dituhui.pea.user.dao.TeamDao;
import com.dituhui.pea.user.dao.UserDao;
import com.dituhui.pea.user.dao.UserTeamDao;
import com.dituhui.pea.user.entity.TeamEntity;
import com.dituhui.pea.user.entity.UserEntity;
import com.dituhui.pea.user.entity.UserTeamEntity;
import com.dituhui.pea.user.factory.ThirdStrategy;
import com.dituhui.pea.user.factory.ThirdStrategyFactory;
import com.dituhui.pea.user.utils.TextHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.persistence.criteria.*;
import java.util.Date;
import java.util.List;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
/**
* 用户业务层
......@@ -43,20 +37,12 @@ import java.util.List;
@Service
public class UserService {
@Autowired
UserDao userDao;
@Autowired
TeamDao teamDao;
@Autowired
UserTeamDao userTeamDao;
@Autowired
ThirdStrategyFactory thirdStrategyFactory;
public String getUserName(String userId) {
return "Jown Snow " + userId;
}
......@@ -74,8 +60,6 @@ public class UserService {
throw new BusinessException(StatusCodeEnum.USER_DOES_NOT_EXIST);
}
UserInfo user = BeanUtil.copyProperties(userEntity, UserInfo.class);
// 设置用户信息对应的默认团队
user.setTeamId(queryTeamByUserId(user.getId()));
return user;
}
......@@ -91,8 +75,6 @@ public class UserService {
throw new BusinessException(StatusCodeEnum.USER_DOES_NOT_EXIST);
}
UserInfo user = BeanUtil.copyProperties(userEntity, UserInfo.class);
// 设置用户信息对应的默认团队
user.setTeamId(queryTeamByUserId(user.getId()));
return user;
}
......@@ -118,28 +100,10 @@ public class UserService {
throw new BusinessException(StatusCodeEnum.USER_DOES_NOT_EXIST);
}
UserInfo user = BeanUtil.copyProperties(userEntity, UserInfo.class);
// 设置用户信息对应的默认团队
user.setTeamId(queryTeamByUserId(user.getId()));
return user;
}
/**
* 查询用户默认团队id
*
* @param userId 用户id
* @return
*/
private String queryTeamByUserId(String userId) {
List<UserTeamEntity> userTeamEntityList = userTeamDao.findAllByUserIdAndStatusOrderByCreatedByDesc(userId,
UserStatusEnum.NORMAL.getStatus());
if (CollectionUtils.isEmpty(userTeamEntityList)) {
throw new BusinessException(StatusCodeEnum.TEAM_DOES_NOT_EXIST);
}
return userTeamEntityList.get(0).getTeamId();
}
/**
* 查询用户信息
* @param id 用户ID
* @return
......@@ -166,16 +130,6 @@ public class UserService {
userEntity.setPassword(SecureUtil.md5(userInfo.getPassword()));
// 保存用户信息
userEntity = userDao.save(userEntity);
// 保存用户和团队的关系
String teamId = userInfo.getTeamId();
if (StringUtils.isNotBlank(teamId)) {
TeamEntity teamEntity = teamDao.findById(teamId).orElse(null);
if (ObjectUtil.isNull(teamEntity)) {
throw new BusinessException(StatusCodeEnum.TEAM_DOES_NOT_EXIST);
}
UserTeamEntity userTeamEntity = assembleUserTeamEntity(userEntity, teamEntity);
userTeamDao.save(userTeamEntity);
}
return BeanUtil.copyProperties(userEntity, UserInfo.class);
}
......@@ -204,14 +158,7 @@ public class UserService {
userEntity.setPassword(SecureUtil.md5(userInfo.getPassword()));
// 保存用户信息
userEntity = userDao.save(userEntity);
// 保存团队信息
TeamEntity teamEntity = assembleTeamEntity(userEntity);
teamEntity = teamDao.save(teamEntity);
// 保存用户团队关系表
UserTeamEntity userTeamEntity = assembleUserTeamEntity(userEntity, teamEntity);
userTeamDao.save(userTeamEntity);
userInfo.setId(userEntity.getId());
userInfo.setTeamId(teamEntity.getId());
return userInfo;
}
......@@ -225,15 +172,9 @@ public class UserService {
userEntity.setCreatedTime(new Date());
ThirdPartyEnum thirdPartyEnum = ThirdPartyEnum.valueOf(thirdUserInfo.getThirdType());
switch (thirdPartyEnum) {
case QQ:
userEntity.setQq(thirdUserInfo.getThirdId());
break;
case WECHAT:
userEntity.setWechat(thirdUserInfo.getThirdId());
break;
case WEIBO:
userEntity.setWeibo(thirdUserInfo.getThirdId());
break;
case WECHAT_MINI_PROGRAM:
userEntity.setWechatMiniProgram(thirdUserInfo.getThirdId());
userEntity.setPhone(thirdUserInfo.getPhone());
......@@ -252,15 +193,7 @@ public class UserService {
userEntity = userDao.save(userEntity);
// 对象转换
UserInfo userInfo = BeanUtil.copyProperties(userEntity, UserInfo.class);
// 保存团队信息
TeamEntity teamEntity = assembleTeamEntity(userEntity);
teamEntity = teamDao.save(teamEntity);
// 保存用户团队关系表
UserTeamEntity userTeamEntity = assembleUserTeamEntity(userEntity, teamEntity);
userTeamDao.save(userTeamEntity);
userInfo.setId(userEntity.getId());
userInfo.setTeamId(teamEntity.getId());
return userInfo;
}
......@@ -276,15 +209,9 @@ public class UserService {
return null;
}
switch (thirdPartyEnum) {
case QQ:
userEntity.setQq(thirdId);
break;
case WECHAT:
userEntity.setWechat(thirdId);
break;
case WEIBO:
userEntity.setWeibo(thirdId);
break;
case WECHAT_MINI_PROGRAM:
userEntity.setWechatMiniProgram(thirdId);
default:
......@@ -292,8 +219,6 @@ public class UserService {
userEntity = userDao.save(userEntity);
// 对象转换
UserInfo userInfo = BeanUtil.copyProperties(userEntity, UserInfo.class);
UserTeamEntity userTeamEntity = userTeamDao.findByUserId(userInfo.getId());
userInfo.setTeamId(userTeamEntity.getTeamId());
return userInfo;
}
......@@ -343,20 +268,6 @@ public class UserService {
if (ObjectUtil.isNull(userEntity)) {
throw new BusinessException(StatusCodeEnum.USER_DOES_NOT_EXIST);
}
// 查询团队是否存在
if (StringUtils.isNotBlank(userInfo.getTeamId())) {
TeamEntity teamEntity = teamDao.findById(userInfo.getTeamId()).orElse(null);
if (ObjectUtil.isNull(teamEntity)) {
throw new BusinessException(StatusCodeEnum.TEAM_DOES_NOT_EXIST);
}
// 查询用户团队关系表 没有记录就添加
UserTeamEntity userTeamEntity =
userTeamDao.findByUserIdAndTeamId(userInfo.getId(), userInfo.getTeamId());
if (ObjectUtil.isNull(userTeamEntity)) {
userTeamEntity = assembleUserTeamEntity(userEntity, teamEntity);
userTeamDao.save(userTeamEntity);
}
}
assembleUpdateUserInfo(userInfo, userEntity);
userEntity = userDao.save(userEntity);
userInfo = BeanUtil.copyProperties(userEntity, UserInfo.class);
......@@ -376,46 +287,10 @@ public class UserService {
if (ObjectUtil.isNull(userEntity)) {
throw new BusinessException(StatusCodeEnum.USER_DOES_NOT_EXIST);
}
// 删除用户和团队的关系
userTeamDao.deleteByUserId(userId);
// 删除用户
userDao.deleteById(userId);
}
/**
* 组装用户团队关系表
* @param userEntity 用户信息
* @param teamEntity 团队信息
* @return
*/
private UserTeamEntity assembleUserTeamEntity(UserEntity userEntity, TeamEntity teamEntity) {
UserTeamEntity userTeamEntity = new UserTeamEntity();
userTeamEntity.setUserId(userEntity.getId());
userTeamEntity.setTeamId(teamEntity.getId());
userTeamEntity.setStatus(UserStatusEnum.NORMAL.getStatus());
return userTeamEntity;
}
/**
* 组装团队信息
* @param userEntity 用户信息
* @return
*/
private TeamEntity assembleTeamEntity(UserEntity userEntity) {
// 创建团队
TeamEntity teamEntity = new TeamEntity();
teamEntity.setName(userEntity.getNickname() + TeamConstant.TEAM_NAME_SUFFIX);
teamEntity.setAdminId(userEntity.getId());
// 新建团队默认有一周时间的试用期
teamEntity.setExpireDate(DateUtil.offsetDay(new Date(), 7));
teamEntity.setContract(TeamContractEnum.NO_CONTRACT.getStatus());
teamEntity.setAppKey(IdUtil.simpleUUID());
teamEntity.setSecret(IdUtil.simpleUUID());
return teamEntity;
}
/**
* 校验 [账号 手机号] 是否存在
* @param phone 手机号
......
......@@ -109,16 +109,4 @@ public class TextHelper {
return str.matches(regex);
}
/**
* 执行正则表达式
*
* @param pat 表达式
* @param str 待验证字符串
* @return 返回true, 否则为false
*/
private static boolean match(String pat, String str) {
Pattern pattern = Pattern.compile(pat);
Matcher match = pattern.matcher(str);
return match.find();
}
}
......@@ -15,16 +15,15 @@ spring:
file-extension: yaml
config:
import:
- optional:nacos:project-user.yaml?group=project&refreshEnabled=true
- optional:nacos:datasource-config.yaml?group=project&refreshEnabled=true
- optional:nacos:redis-config.yaml?group=project&refreshEnabled=true
main:
allow-bean-definition-overriding: true
datasource:
url: jdbc:postgresql://project-pg:8432/project
driver-class-name: org.postgresql.Driver
username: 'postgres'
password: 'postgres'
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.10.0.54:3306/saas_aftersale_test?serverTimezone=Asia/Shanghai
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
redis:
database: 0
host: redis
......
......@@ -50,7 +50,6 @@
{
"timestamp": "@timestamp",
"userId": "%X{userId:-}",
"teamId": "%X{teamId:-}",
"severity": "%level",
"service": "${springAppName:-}",
"trace": "%X{traceId:-}",
......
package com.dituhui.pea.user;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TeamControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenQueryTeamSuccess() throws Exception {
String result = mockMvc.perform(
get("/v1/team/get").param("id", "40288ac9764ba85101764baef86f0000")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk()).andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenAddTeamSuccess() throws Exception {
String content = "{\"name\":\"测试团队001\",\"business\":\"001团队\",\"province\":\"四川省\",\"city\":\"成都市\",\"county\":\"高新区\",\"size\":1000,\"address\":\"新川科技园成都超图大厦\",\"expireDate\":\"2020-12-23 00:00:00\"}";
String result = mockMvc.perform(post("/v1/team/add").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenUpdateTeamSuccess() throws Exception {
String content = "{\"id\":\"40288ac9768e57d101768e5808610000\",\"name\":\"测试团队002\",\"business\":\"002团队\",\"province\":\"四川省\",\"city\":\"成都市\",\"county\":\"高新区\",\"size\":1000,\"address\":\"新川科技园成都超图大厦\"}";
String result = mockMvc.perform(post("/v1/team/update").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenDeleteTeamSuccess() throws Exception {
String result = mockMvc.perform(post("/v1/team/delete").param("id", "40288ac9768e540101768e5437aa0000")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenAddTeamUserSuccess() throws Exception {
String result = mockMvc.perform(post("/v1/team/addUser").param("id","40288ac9768e57d101768e5808610000")
.param("userId", "9a29b842388148eda91eede9e11dddbb")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenDeleteTeamUserSuccess() throws Exception {
String result = mockMvc.perform(post("/v1/team/deleteUser").param("id","40288ac9768e57d101768e5808610000")
.param("userId", "9a29b842388148eda91eede9e11dddbb")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenGetTeamUserSuccess() throws Exception {
String result = mockMvc.perform(get("/v1/team/getUsers").param("teamId", "40288ac97673e23f017673e26ed90001")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk()).andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test
public void whenGetTeamRoleSuccess() throws Exception {
String result = mockMvc.perform(get("/v1/team/getRoles").param("teamId", "40288ac97673e23f017673e26ed90001")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk()).andExpect(jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!