Commit 44bd4786 by chamberone

Merge branch 'develop' of https://zhangguoping@gitlab.dituhui.com/bsh/project/pr…

…oject.git into develop
2 parents e63bb510 962a0ba5
Showing with 1328 additions and 98 deletions
...@@ -16,15 +16,29 @@ ...@@ -16,15 +16,29 @@
package com.dituhui.pea.common; package com.dituhui.pea.common;
import com.dituhui.pea.enums.StatusCodeEnum;
/** /**
* 响应返回实体类型
*
* @param <T> 返回业务实际类型泛型定义
* @author TrevorLink * @author TrevorLink
*/ */
public class Result<T> { public class Result<T> {
/**
* 业务响应状态代码
*/
private String code; private String code;
/**
* 业务响应状态描述
*/
private String message; private String message;
/**
* 业务响应信息承载体
*/
private T result; private T result;
public static <T> Result<T> success(T result) { public static <T> Result<T> success(T result) {
...@@ -52,6 +66,14 @@ public class Result<T> { ...@@ -52,6 +66,14 @@ public class Result<T> {
return new Result<>(errorResult.getCode(), errorResult.getMessage(), null); return new Result<>(errorResult.getCode(), errorResult.getMessage(), null);
} }
public static <T> Result<T> failed(T result) {
return new Result<>(ResultEnum.COMMON_FAILED.getCode(), ResultEnum.COMMON_FAILED.getMessage(), result);
}
public static <T> Result<T> failed(StatusCodeEnum resultEnum, T result) {
return new Result<>(resultEnum.getCode(), resultEnum.getDesc(), result);
}
public Result() { public Result() {
} }
......
...@@ -13,6 +13,11 @@ public enum RedisKeyGroup { ...@@ -13,6 +13,11 @@ public enum RedisKeyGroup {
/** /**
* 认证ak对应的认证信息 * 认证ak对应的认证信息
*/ */
appKey; appKey,
/**
* 资源信息
*/
resourceKey;
} }
...@@ -6,6 +6,7 @@ import com.dituhui.pea.pojo.role.RoleResourceInfo; ...@@ -6,6 +6,7 @@ import com.dituhui.pea.pojo.role.RoleResourceInfo;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
...@@ -13,7 +14,7 @@ import java.util.List; ...@@ -13,7 +14,7 @@ import java.util.List;
* 角色信息 * 角色信息
*/ */
@Data @Data
public class RoleInfo { public class RoleInfo implements Serializable {
/** /**
* 主键 * 主键
...@@ -32,9 +33,14 @@ public class RoleInfo { ...@@ -32,9 +33,14 @@ public class RoleInfo {
private String groupId; private String groupId;
/** /**
* 备注
*/
private String notes;
/**
* 角色自定义条件 * 角色自定义条件
*/ */
@NotBlank(message = "角色条件不能为空!") // @NotBlank(message = "角色条件不能为空!")
private String extra; private String extra;
/** /**
...@@ -50,4 +56,12 @@ public class RoleInfo { ...@@ -50,4 +56,12 @@ public class RoleInfo {
private Date updatedTime; private Date updatedTime;
private List<RoleResourceInfo> resourceInfos; private List<RoleResourceInfo> resourceInfos;
/**
* 创建人
*/
private String createdBy;
/**
* 更新人
*/
private String updatedBy;
} }
...@@ -78,7 +78,7 @@ public class UserInfo { ...@@ -78,7 +78,7 @@ public class UserInfo {
/** /**
* 最后登录时间 * 最后登录时间
*/ */
//private Date lastLoginTime; private Date lastLoginTime;
/** /**
* 用户自定义条件 * 用户自定义条件
*/ */
...@@ -98,18 +98,43 @@ public class UserInfo { ...@@ -98,18 +98,43 @@ public class UserInfo {
/** /**
* 创建人 * 创建人
*/ */
//private String createdBy; private String createdBy;
/** /**
* 创建时间 * 创建时间
*/ */
// private Date createdTime; private Date createdTime;
/** /**
* 更新人 * 更新人
*/ */
//private String updatedBy; private String updatedBy;
/** /**
* 更新时间 * 更新时间
*/ */
// private Date updatedTime; private Date updatedTime;
/**
* 是否禁用 0: 否 1:是 默认0
*/
private Integer ban = 0;
/**
* 用户来源:0:bean 1:新建
*/
private Integer source;
/**
* 工程师工号
*/
private String engineerCode;
/**
* 备注
*/
private String notes;
/**
* 是否正常 0: 否 1:是 默认1
*/
private Integer status = 1;
} }
...@@ -65,7 +65,7 @@ public class UserInfoSearch extends PageRequest implements Serializable { ...@@ -65,7 +65,7 @@ public class UserInfoSearch extends PageRequest implements Serializable {
/** /**
* 最后登录时间 * 最后登录时间
*/ */
//private Date lastLoginTime; private String lastLoginTime;
/** /**
* 用户自定义条件 * 用户自定义条件
*/ */
...@@ -104,18 +104,22 @@ public class UserInfoSearch extends PageRequest implements Serializable { ...@@ -104,18 +104,22 @@ public class UserInfoSearch extends PageRequest implements Serializable {
/** /**
* 创建人 * 创建人
*/ */
//private String createdBy; private String createdBy;
/** /**
* 创建时间 * 创建时间
*/ */
// private Date createdTime; private String createdTime;
/** /**
* 更新人 * 更新人
*/ */
//private String updatedBy; private String updatedBy;
/** /**
* 更新时间 * 更新时间
*/ */
// private Date updatedTime; private String updatedTime;
/**
* 更新时间
*/
private String notes;
} }
package com.dituhui.pea.pojo.user;
import lombok.Data;
import java.io.Serializable;
@Data
public class OrgInfo implements Serializable {
/**
* 机构id
*/
private Integer id;
/**
* 机构名称
*/
private String name;
}
...@@ -27,7 +27,17 @@ public interface IRole { ...@@ -27,7 +27,17 @@ public interface IRole {
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/role/add", method = RequestMethod.POST) @RequestMapping(value = "/pea-user/role/add", method = RequestMethod.POST)
WebResult<RoleInfo> addRole(@RequestBody RoleInfo roleInfo); Result<RoleInfo> addRole(@RequestBody RoleInfo roleInfo);
/**
* 添加角色
*
* @param roleInfo 角色信息
* @return
*/
@RequestMapping(value = "/pea-user/role/delete2", method = RequestMethod.POST)
Result<RoleInfo> deleteRole2(@RequestBody RoleInfo roleInfo);
/** /**
...@@ -37,7 +47,7 @@ public interface IRole { ...@@ -37,7 +47,7 @@ public interface IRole {
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/role/update", method = RequestMethod.POST) @RequestMapping(value = "/pea-user/role/update", method = RequestMethod.POST)
WebResult<RoleInfo> updateRole(@RequestBody RoleInfo roleInfo); Result<RoleInfo> updateRole(@RequestBody RoleInfo roleInfo);
/** /**
* 删除角色 * 删除角色
...@@ -46,7 +56,7 @@ public interface IRole { ...@@ -46,7 +56,7 @@ public interface IRole {
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/role/delete", method = RequestMethod.POST) @RequestMapping(value = "/pea-user/role/delete", method = RequestMethod.POST)
WebResult<Boolean> deleteRole(@RequestParam("id") String roleId); Result<Boolean> deleteRole(@RequestBody RoleInfo roleInfo);
/** /**
* 添加用户角色 * 添加用户角色
......
// package com.dituhui.pea.user;
//
// import com.dituhui.pea.common.Result;
// import com.dituhui.pea.pojo.RoleInfo;
// import org.springframework.cloud.openfeign.FeignClient;
// import org.springframework.web.bind.annotation.RequestBody;
// import org.springframework.web.bind.annotation.RequestMapping;
// import org.springframework.web.bind.annotation.RequestMethod;
//
// /**
// * 角色相关接口
// */
// @FeignClient(value = "project-user", contextId = "role2")
// public interface IRole2 {
//
// /**
// * 添加角色
// *
// * @param roleInfo 角色信息
// * @return
// */
// @RequestMapping(value = "/pea-user/role/add2", method = RequestMethod.POST)
// Result<RoleInfo> addRole(@RequestBody RoleInfo roleInfo);
//
// }
...@@ -2,6 +2,7 @@ package com.dituhui.pea.user; ...@@ -2,6 +2,7 @@ package com.dituhui.pea.user;
import com.dituhui.pea.common.PageResult; import com.dituhui.pea.common.PageResult;
import com.dituhui.pea.pojo.*; import com.dituhui.pea.pojo.*;
import com.dituhui.pea.pojo.user.OrgInfo;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
...@@ -12,8 +13,11 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -12,8 +13,11 @@ import org.springframework.web.bind.annotation.RequestParam;
import com.dituhui.pea.common.Result; import com.dituhui.pea.common.Result;
import com.dituhui.pea.enums.ThirdPartyEnum; import com.dituhui.pea.enums.ThirdPartyEnum;
import java.util.List;
/** /**
* 用户相关接口 * 用户相关接口
*
* @author * @author
*/ */
@FeignClient(value = "project-user", contextId = "user") @FeignClient(value = "project-user", contextId = "user")
...@@ -35,7 +39,7 @@ public interface IUser { ...@@ -35,7 +39,7 @@ public interface IUser {
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/userInfo", method = RequestMethod.GET) @RequestMapping(value = "/pea-user/userInfo", method = RequestMethod.GET)
public Result<UserLoginDTO> getUserInfo(@RequestHeader(name="userId", required = true) String userId); public Result<UserLoginDTO> getUserInfo(@RequestHeader(name = "userId", required = true) String userId);
/** /**
* 刷新appkey接口<br> * 刷新appkey接口<br>
...@@ -59,6 +63,7 @@ public interface IUser { ...@@ -59,6 +63,7 @@ public interface IUser {
/** /**
* 获取用户信息 * 获取用户信息
*
* @param id 用户ID * @param id 用户ID
* @return * @return
*/ */
...@@ -96,31 +101,35 @@ public interface IUser { ...@@ -96,31 +101,35 @@ public interface IUser {
/** /**
* 添加用户 * 添加用户
*
* @param userInfo 用户信息 * @param userInfo 用户信息
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/add", method = RequestMethod.POST) @RequestMapping(value = "/pea-user/add", method = RequestMethod.POST)
WebResult<UserInfo> addUser(@RequestBody UserInfo userInfo); Result<UserInfo> addUser(@RequestBody UserInfo userInfo);
/** /**
* 更新用户 * 更新用户
*
* @param userInfo 用户信息 * @param userInfo 用户信息
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/update", method = RequestMethod.POST) @RequestMapping(value = "/pea-user/update", method = RequestMethod.POST)
WebResult<UserInfo> updateUser(@RequestBody UserInfo userInfo); Result<UserInfo> updateUser(@RequestBody UserInfo userInfo);
/** /**
* 删除用户 * 删除用户
*
* @param userId 用户ID * @param userId 用户ID
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/delete", method = RequestMethod.POST) @RequestMapping(value = "/pea-user/delete", method = RequestMethod.POST)
WebResult<Boolean> deleteUser(@RequestParam("id") String userId); Result<Boolean> deleteUser(@RequestBody UserInfoSearch search);
/** /**
* 注册用户 * 注册用户
*
* @param userInfo 用户信息 * @param userInfo 用户信息
* @return * @return
*/ */
...@@ -129,6 +138,7 @@ public interface IUser { ...@@ -129,6 +138,7 @@ public interface IUser {
/** /**
* 第三方用户注册 * 第三方用户注册
*
* @param thirdUserInfo 第三方用户信息 * @param thirdUserInfo 第三方用户信息
* @return * @return
*/ */
...@@ -138,6 +148,7 @@ public interface IUser { ...@@ -138,6 +148,7 @@ public interface IUser {
/** /**
* 用户列表 * 用户列表
*
* @param search 查询条件 * @param search 查询条件
* @return * @return
*/ */
...@@ -147,10 +158,21 @@ public interface IUser { ...@@ -147,10 +158,21 @@ public interface IUser {
/** /**
* 禁用用户 * 禁用用户
*
* @param search 查询条件 * @param search 查询条件
* @return * @return
*/ */
@RequestMapping(value = "/pea-user/ban", method = RequestMethod.GET) @RequestMapping(value = "/pea-user/ban", method = RequestMethod.POST)
Result<Boolean> ban(UserInfoSearch search); Result<Boolean> ban(@RequestBody UserInfoSearch search);
/**
* 获取用户组织
*
* @param userId 查询条件
* @return
*/
@RequestMapping(value = "/pea-user/orgs", method = RequestMethod.GET)
Result<List<OrgInfo>> orgs(String userId);
} }
package com.dituhui.pea.util;
import lombok.experimental.UtilityClass;
import org.springframework.util.Assert;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalQuery;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* 日期工具类
*
* @author liuxin
*/
@UtilityClass
public class DateUtil {
/**
* yyyy-MM-dd HH:mm:ss
*/
public static final String PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
/**
* 日期 yyyy-MM-dd格式
*/
public static final String PATTERN_DATE = "yyyy-MM-dd";
/**
* 时间格式 HH:mm:ss
*/
public static final String PATTERN_TIME = "HH:mm:ss";
/**
* java 8 时间格式化
*/
public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME);
/**
* 日期 yyyy-MM-dd格式
*/
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE);
/**
* 时间格式 HH:mm:ss
*/
public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_TIME);
/**
* 获取当前日期
*
* @return 当前日期
*/
public static Date now() {
return new Date();
}
/**
* 添加年
*
* @param date 时间
* @param yearsToAdd 添加的年数
* @return 设置后的时间
*/
public static Date plusYears(Date date, int yearsToAdd) {
return DateUtil.set(date, Calendar.YEAR, yearsToAdd);
}
/**
* 添加月
*
* @param date 时间
* @param monthsToAdd 添加的月数
* @return 设置后的时间
*/
public static Date plusMonths(Date date, int monthsToAdd) {
return DateUtil.set(date, Calendar.MONTH, monthsToAdd);
}
/**
* 添加周
*
* @param date 时间
* @param weeksToAdd 添加的周数
* @return 设置后的时间
*/
public static Date plusWeeks(Date date, int weeksToAdd) {
return DateUtil.plus(date, Period.ofWeeks(weeksToAdd));
}
/**
* 添加天
*
* @param date 时间
* @param daysToAdd 添加的天数
* @return 设置后的时间
*/
public static Date plusDays(Date date, long daysToAdd) {
return DateUtil.plus(date, Duration.ofDays(daysToAdd));
}
/**
* 添加小时
*
* @param date 时间
* @param hoursToAdd 添加的小时数
* @return 设置后的时间
*/
public static Date plusHours(Date date, long hoursToAdd) {
return DateUtil.plus(date, Duration.ofHours(hoursToAdd));
}
/**
* 添加分钟
*
* @param date 时间
* @param minutesToAdd 添加的分钟数
* @return 设置后的时间
*/
public static Date plusMinutes(Date date, long minutesToAdd) {
return DateUtil.plus(date, Duration.ofMinutes(minutesToAdd));
}
/**
* 添加秒
*
* @param date 时间
* @param secondsToAdd 添加的秒数
* @return 设置后的时间
*/
public static Date plusSeconds(Date date, long secondsToAdd) {
return DateUtil.plus(date, Duration.ofSeconds(secondsToAdd));
}
/**
* 添加毫秒
*
* @param date 时间
* @param millisToAdd 添加的毫秒数
* @return 设置后的时间
*/
public static Date plusMillis(Date date, long millisToAdd) {
return DateUtil.plus(date, Duration.ofMillis(millisToAdd));
}
/**
* 添加纳秒
*
* @param date 时间
* @param nanosToAdd 添加的纳秒数
* @return 设置后的时间
*/
public static Date plusNanos(Date date, long nanosToAdd) {
return DateUtil.plus(date, Duration.ofNanos(nanosToAdd));
}
/**
* 日期添加时间量
*
* @param date 时间
* @param amount 时间量
* @return 设置后的时间
*/
public static Date plus(Date date, TemporalAmount amount) {
Instant instant = date.toInstant();
return Date.from(instant.plus(amount));
}
/**
* 减少年
*
* @param date 时间
* @param years 减少的年数
* @return 设置后的时间
*/
public static Date minusYears(Date date, int years) {
return DateUtil.set(date, Calendar.YEAR, -years);
}
/**
* 减少月
*
* @param date 时间
* @param months 减少的月数
* @return 设置后的时间
*/
public static Date minusMonths(Date date, int months) {
return DateUtil.set(date, Calendar.MONTH, -months);
}
/**
* 减少周
*
* @param date 时间
* @param weeks 减少的周数
* @return 设置后的时间
*/
public static Date minusWeeks(Date date, int weeks) {
return DateUtil.minus(date, Period.ofWeeks(weeks));
}
/**
* 减少天
*
* @param date 时间
* @param days 减少的天数
* @return 设置后的时间
*/
public static Date minusDays(Date date, long days) {
return DateUtil.minus(date, Duration.ofDays(days));
}
/**
* 减少小时
*
* @param date 时间
* @param hours 减少的小时数
* @return 设置后的时间
*/
public static Date minusHours(Date date, long hours) {
return DateUtil.minus(date, Duration.ofHours(hours));
}
/**
* 减少分钟
*
* @param date 时间
* @param minutes 减少的分钟数
* @return 设置后的时间
*/
public static Date minusMinutes(Date date, long minutes) {
return DateUtil.minus(date, Duration.ofMinutes(minutes));
}
/**
* 减少秒
*
* @param date 时间
* @param seconds 减少的秒数
* @return 设置后的时间
*/
public static Date minusSeconds(Date date, long seconds) {
return DateUtil.minus(date, Duration.ofSeconds(seconds));
}
/**
* 减少毫秒
*
* @param date 时间
* @param millis 减少的毫秒数
* @return 设置后的时间
*/
public static Date minusMillis(Date date, long millis) {
return DateUtil.minus(date, Duration.ofMillis(millis));
}
/**
* 减少纳秒
*
* @param date 时间
* @param nanos 减少的纳秒数
* @return 设置后的时间
*/
public static Date minusNanos(Date date, long nanos) {
return DateUtil.minus(date, Duration.ofNanos(nanos));
}
/**
* 日期减少时间量
*
* @param date 时间
* @param amount 时间量
* @return 设置后的时间
*/
public static Date minus(Date date, TemporalAmount amount) {
Instant instant = date.toInstant();
return Date.from(instant.minus(amount));
}
/**
* 设置日期属性
*
* @param date 时间
* @param calendarField 更改的属性
* @param amount 更改数,-1表示减少
* @return 设置后的时间
*/
private static Date set(Date date, int calendarField, int amount) {
Assert.notNull(date, "The date must not be null");
Calendar c = Calendar.getInstance();
c.setLenient(false);
c.setTime(date);
c.add(calendarField, amount);
return c.getTime();
}
/**
* 将字符串转换为时间
*
* @param dateStr 时间字符串
* @param pattern 表达式
* @param query TemporalQuery
* @param <T> 转换目标类型
* @return 时间
*/
public static <T> T parse(String dateStr, String pattern, TemporalQuery<T> query) {
return DateTimeFormatter.ofPattern(pattern).parse(dateStr, query);
}
/**
* 时间转 Instant
*
* @param dateTime 时间
* @return Instant
*/
public static Instant toInstant(LocalDateTime dateTime) {
return dateTime.atZone(ZoneId.of("+8")).toInstant();
}
/**
* Instant 转 时间
*
* @param instant Instant
* @return Instant
*/
public static LocalDateTime toDateTime(Instant instant) {
return LocalDateTime.ofInstant(instant, ZoneId.of("+8"));
}
/**
* 转换成 date
*
* @param dateTime LocalDateTime
* @return Date
*/
public static Date toDate(LocalDateTime dateTime) {
return Date.from(DateUtil.toInstant(dateTime));
}
/**
* 转换成 date
*
* @param localDate LocalDate
* @return Date
*/
public static Date toDate(final LocalDate localDate) {
return Date.from(localDate.atStartOfDay(ZoneId.of("+8")).toInstant());
}
/**
* Converts local date time to Calendar.
*
* @param localDateTime 需要转换掉时间
* @return Calendar对象
*/
public static Calendar toCalendar(final LocalDateTime localDateTime) {
return GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.of("+8")));
}
/**
* localDateTime 转换成毫秒数
*
* @param localDateTime LocalDateTime
* @return long
*/
public static long toMilliseconds(final LocalDateTime localDateTime) {
return localDateTime.atZone(ZoneId.of("+8")).toInstant().toEpochMilli();
}
/**
* localDate 转换成毫秒数
*
* @param localDate LocalDate
* @return long
*/
public static long toMilliseconds(LocalDate localDate) {
return toMilliseconds(localDate.atStartOfDay());
}
/**
* 转换成java8 时间
*
* @param calendar 日历
* @return LocalDateTime
*/
public static LocalDateTime fromCalendar(final Calendar calendar) {
TimeZone tz = calendar.getTimeZone();
ZoneId zid = tz == null ? ZoneId.of("+8") : tz.toZoneId();
return LocalDateTime.ofInstant(calendar.toInstant(), zid);
}
/**
* 转换成java8 时间
*
* @param instant Instant
* @return LocalDateTime
*/
public static LocalDateTime fromInstant(final Instant instant) {
return LocalDateTime.ofInstant(instant, ZoneId.of("+8"));
}
/**
* 转换成java8 时间
*
* @param date Date
* @return LocalDateTime
*/
public static LocalDateTime fromDate(final Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.of("+8"));
}
/**
* 转换成java8 时间
*
* @param milliseconds 毫秒数
* @return LocalDateTime
*/
public static LocalDateTime fromMilliseconds(final long milliseconds) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneId.of("+8"));
}
/**
* 比较2个时间差,跨度比较小
*
* @param startInclusive 开始时间
* @param endExclusive 结束时间
* @return 时间间隔
*/
public static Duration between(Temporal startInclusive, Temporal endExclusive) {
return Duration.between(startInclusive, endExclusive);
}
/**
* 比较2个时间差,跨度比较大,年月日为单位
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return 时间间隔
*/
public static Period between(LocalDate startDate, LocalDate endDate) {
return Period.between(startDate, endDate);
}
/**
* 比较2个 时间差
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return 时间间隔
*/
public static Duration between(Date startDate, Date endDate) {
return Duration.between(startDate.toInstant(), endDate.toInstant());
}
/**
* 将秒数转换为日时分秒
*
* @param second 秒数
* @return 时间
*/
//CHECKSTYLE:OFF
@SuppressWarnings("checkstyle:MagicNumber")
public static String secondToTime(Long second) {
// 判断是否为空
if (second == null || second == 0L) {
return "";
}
//转换天数
long days = second / 86400;
//剩余秒数
second = second % 86400;
//转换小时
long hours = second / 3600;
//剩余秒数
second = second % 3600;
//转换分钟
long minutes = second / 60;
//剩余秒数
second = second % 60;
if (days > 0) {
return MessageFormat.format("{}天{}小时{}分{}秒", days, hours, minutes, second);
} else {
return MessageFormat.format("{}小时{}分{}秒", hours, minutes, second);
}
}
//CHECKSTYLE:ON
}
package com.dituhui.pea.util;
import java.util.UUID;
/**
* uuid生成工具
* @author guoping
*
*/
public class UUIDUtil {
public static String getUuid() {
UUID uuid = UUID.randomUUID();
String sud = uuid.toString();
sud = sud.replaceAll("-", "");
return sud;
}
public static String getUid(){
return UUID.randomUUID().toString().replace("-", "").toLowerCase();
}
public static void main(String[] args) {
System.out.println(getUuid());
}
}
...@@ -12,4 +12,4 @@ RUN sh -c 'touch /app.jar' ...@@ -12,4 +12,4 @@ RUN sh -c 'touch /app.jar'
EXPOSE 8013 EXPOSE 8013
EXPOSE 62001 EXPOSE 62001
ENTRYPOINT ["java", "-jar","-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=62001","/app.jar"] ENTRYPOINT ["java","-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=62001","-jar","/app.jar"]
...@@ -110,6 +110,11 @@ ...@@ -110,6 +110,11 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>io.sentry</groupId> <groupId>io.sentry</groupId>
<artifactId>sentry-spring-boot-starter</artifactId> <artifactId>sentry-spring-boot-starter</artifactId>
<version>6.22.0</version> <version>6.22.0</version>
...@@ -139,13 +144,15 @@ ...@@ -139,13 +144,15 @@
<plugin> <plugin>
<groupId>com.github.shalousun</groupId> <groupId>com.github.shalousun</groupId>
<artifactId>smart-doc-maven-plugin</artifactId> <artifactId>smart-doc-maven-plugin</artifactId>
<version>2.7.6</version> <version>2.7.7</version>
<configuration> <configuration>
<configFile>./src/main/resources/smart-doc.json</configFile> <configFile>./src/main/resources/smart-doc.json</configFile>
<projectName>${project.description}</projectName> <projectName>${project.description}</projectName>
<includes> <includes>
<!-- 使用了jpa的分页需要include所使用的源码包 --> <!-- 使用了jpa的分页需要include所使用的源码包 -->
<include>org.springframework.data:spring-data-commons</include> <include>org.springframework.data:spring-data-commons</include>
<include>com.alibaba.cloud:project-interface</include>
<include>com.alibaba.cloud:project-order</include>
</includes> </includes>
</configuration> </configuration>
</plugin> </plugin>
......
...@@ -5,13 +5,18 @@ import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; ...@@ -5,13 +5,18 @@ import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.Validator;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Properties;
@Configuration @Configuration
public class OrderConfig { public class OrderConfig {
...@@ -39,4 +44,26 @@ public class OrderConfig { ...@@ -39,4 +44,26 @@ public class OrderConfig {
return builder; return builder;
} }
/**
* hibernate 验证器验证规则配置, 集成spring message
*
* @param messageSource spring message resource
* @return Validator
*/
@Bean
public Validator validator(MessageSource messageSource) {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
// 设置上方配置的国际化源
factoryBean.setValidationMessageSource(messageSource);
// 设置使用 HibernateValidator 校验器
factoryBean.setProviderClass(HibernateValidator.class);
Properties properties = new Properties();
// 设置 快速异常返回
properties.setProperty("hibernate.validator.fail_fast", "true");
factoryBean.setValidationProperties(properties);
// 加载配置
factoryBean.afterPropertiesSet();
return factoryBean.getValidator();
}
} }
package com.dituhui.pea.order.controller; package com.dituhui.pea.order.controller;
import com.dituhui.pea.common.BusinessException;
import com.dituhui.pea.common.Result; import com.dituhui.pea.common.Result;
import com.dituhui.pea.order.dto.OrganizationTreeDTO; import com.dituhui.pea.order.dto.OrganizationTreeDTO;
import com.dituhui.pea.order.dto.param.BaseDistance; import com.dituhui.pea.order.dto.param.BaseDistance;
...@@ -13,6 +14,7 @@ import com.dituhui.pea.order.dto.param.OrderConfirmParam; ...@@ -13,6 +14,7 @@ import com.dituhui.pea.order.dto.param.OrderConfirmParam;
import com.dituhui.pea.order.dto.param.OrderConfirmResult; import com.dituhui.pea.order.dto.param.OrderConfirmResult;
import com.dituhui.pea.order.dto.param.OrderDTO; import com.dituhui.pea.order.dto.param.OrderDTO;
import com.dituhui.pea.order.dto.param.ValidGroup; import com.dituhui.pea.order.dto.param.ValidGroup;
import com.dituhui.pea.util.DateUtil;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
...@@ -26,10 +28,11 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -26,10 +28,11 @@ import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.time.Period;
import java.util.Date; import java.util.Date;
/** /**
* PEA 调用API * PEA 对外接口
*/ */
@RestController @RestController
@RequestMapping("/pea-order/pea") @RequestMapping("/pea-order/pea")
...@@ -108,7 +111,12 @@ public class PeaApiController { ...@@ -108,7 +111,12 @@ public class PeaApiController {
*/ */
@PostMapping("/capacity/query") @PostMapping("/capacity/query")
public Result<CapacityQueryDTO.Result> capacityQuery(@Validated @RequestBody CapacityQueryDTO.Request reqDTO) { public Result<CapacityQueryDTO.Result> capacityQuery(@Validated @RequestBody CapacityQueryDTO.Request reqDTO) {
//TODO 查询日期起止参数限制为一月 //查询日期起止参数限制为一月
Period between = Period.between(DateUtil.fromDate(reqDTO.getBeginDate()).toLocalDate(), DateUtil.fromDate(reqDTO.getEndDate()).toLocalDate());
if (between.getMonths() > 1) {
throw new BusinessException("查询日期起止参数限制为一月");
}
CapacityQueryDTO.Result result = new CapacityQueryDTO.Result(); CapacityQueryDTO.Result result = new CapacityQueryDTO.Result();
return Result.success(result); return Result.success(result);
......
/*
* Begin license text.
* Copyright (c) 2020 — 2021 Liu Xin lsy_xin@163.com
* All rights reserved
* End license text.
*/
package com.dituhui.pea.order.interceptor;
import com.dituhui.pea.common.BusinessException;
import com.dituhui.pea.common.Result;
import com.dituhui.pea.enums.StatusCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 全局异常处理基础类
*
* @author liuxin
*/
@ControllerAdvice
public class RBaseExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RBaseExceptionHandler.class);
/**
* validator 参数校验错误 处理 form data方式调用接口校验失败抛出的异常
*
* @param bindException {@link BindException}
* @return 参数校验失败信息
*/
@ExceptionHandler(value = BindException.class)
public Result<?> handler(BindException bindException) {
String message = StringUtils.collectionToCommaDelimitedString(
bindException.getAllErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList())
);
LOGGER.error("【RBaseExceptionHandler】【BindException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), message);
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), message, null);
}
/**
* Hibernate Validator参数校验异常处理 处理 json 请求体调用接口校验失败抛出的异常
*
* @param e {@link MethodArgumentNotValidException}
* @return 参数校验失败信息
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<?> handler(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
String exceptionMsg = StringUtils.collectionToCommaDelimitedString(
bindingResult.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList())
);
LOGGER.error("【RBaseExceptionHandler】【MethodArgumentNotValidException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), exceptionMsg);
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), exceptionMsg, null);
}
/**
* Spring Validator参数校验异常处理 处理单个参数校验失败抛出的异常
*
* @param ex {@link ConstraintViolationException}
* @return 参数校验失败信息
*/
@ExceptionHandler(value = ConstraintViolationException.class)
public Result<?> handler(ConstraintViolationException ex) {
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
String message = StringUtils.collectionToCommaDelimitedString(constraintViolations.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList()));
LOGGER.error("【RBaseExceptionHandler】【ConstraintViolationException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), ex.getMessage());
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), message, null);
}
/**
* Spring Validator参数校验异常处理
*
* @param ex {@link IllegalArgumentException}
* @return 参数校验失败信息
*/
@ExceptionHandler(value = IllegalArgumentException.class)
public Result<?> handler(IllegalArgumentException ex) {
LOGGER.error("【RBaseExceptionHandler】【IllegalArgumentException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), ex.getMessage());
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), ex.getMessage(), null);
}
/**
* 业务异常处理
*
* @param ex BusinessException
* @return 错误提示信息
*/
@ExceptionHandler(value = BusinessException.class)
public Result<?> handler(BusinessException ex) {
LOGGER.error("[RBaseExceptionHandler]:【BusinessException】---->{}", ex.getMessage());
return Result.failed(ex.getMessage());
}
/**
* 未知错误类型处理
*
* @param ex exception
* @return 未知错误提示信息
*/
@ExceptionHandler(value = Exception.class)
public Result<?> handler(Exception ex) {
LOGGER.error("[RBaseExceptionHandler]:【Exception】---->{}\nstackTrace:{}",
ex.getMessage(), ex.getStackTrace());
return Result.failed();
}
}
...@@ -34,10 +34,10 @@ ...@@ -34,10 +34,10 @@
<version>${druid.version}</version> <version>${druid.version}</version>
</dependency> </dependency>
<dependency> <!-- <dependency>-->
<groupId>com.alibaba.cloud</groupId> <!-- <groupId>com.alibaba.cloud</groupId>-->
<artifactId>spring-cloud-starter-alibaba-seata</artifactId> <!-- <artifactId>spring-cloud-starter-alibaba-seata</artifactId>-->
</dependency> <!-- </dependency>-->
<dependency> <dependency>
<groupId>com.alibaba.cloud</groupId> <groupId>com.alibaba.cloud</groupId>
......
...@@ -5,11 +5,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; ...@@ -5,11 +5,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages = "com.dituhui.pea") @ComponentScan(basePackages = "com.dituhui.pea")
@EnableFeignClients(basePackages = {"com.dituhui.pea.order"}) @EnableFeignClients(basePackages = {"com.dituhui.pea.order"})
@EnableJpaAuditing @EnableJpaAuditing
@EnableTransactionManagement
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -15,6 +15,7 @@ import com.dituhui.pea.user.service.RoleService; ...@@ -15,6 +15,7 @@ import com.dituhui.pea.user.service.RoleService;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -33,25 +34,32 @@ public class RoleController implements IRole { ...@@ -33,25 +34,32 @@ public class RoleController implements IRole {
RoleService roleService; RoleService roleService;
@Override @Override
public WebResult<RoleInfo> addRole(@Validated RoleInfo roleInfo) { public Result<RoleInfo> addRole(@Validated RoleInfo roleInfo) {
roleInfo = roleService.addRole(roleInfo); return roleService.addRole(roleInfo);
return WebResult.ok(roleInfo);
} }
@Override @Override
public WebResult<RoleInfo> updateRole(@Validated RoleInfo roleInfo) { public Result<RoleInfo> deleteRole2(@Validated RoleInfo roleInfo) {
roleInfo = roleService.deleteRole2(roleInfo);
return Result.success(roleInfo);
}
@Override
public Result<RoleInfo> updateRole(@Validated RoleInfo roleInfo) {
roleInfo = roleService.updateRole(roleInfo); roleInfo = roleService.updateRole(roleInfo);
return WebResult.ok(roleInfo); return Result.success(roleInfo);
} }
@Override @Override
public WebResult<Boolean> deleteRole(String roleId) { public Result<Boolean> deleteRole(RoleInfo roleInfo) {
if (StringUtils.isBlank(roleId)) { if (StringUtils.isBlank(roleInfo.getId())) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, false);
} }
roleService.deleteRole(roleId); roleService.deleteRole(roleInfo.getId());
return WebResult.ok(); return Result.success(true);
} }
@Override @Override
......
...@@ -3,6 +3,8 @@ package com.dituhui.pea.user.controller; ...@@ -3,6 +3,8 @@ package com.dituhui.pea.user.controller;
import com.dituhui.pea.common.PageResult; import com.dituhui.pea.common.PageResult;
import com.dituhui.pea.pojo.*; import com.dituhui.pea.pojo.*;
import com.dituhui.pea.pojo.user.OrgInfo;
import com.dituhui.pea.user.dao.UserOrgDao;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
...@@ -16,6 +18,8 @@ import com.dituhui.pea.user.service.UserService; ...@@ -16,6 +18,8 @@ import com.dituhui.pea.user.service.UserService;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import java.util.List;
/** /**
* 用户控制层 * 用户控制层
*/ */
...@@ -84,39 +88,38 @@ public class UserController implements IUser { ...@@ -84,39 +88,38 @@ public class UserController implements IUser {
} }
@Override @Override
public WebResult<UserInfo> addUser(UserInfo userInfo) { public Result<UserInfo> addUser(UserInfo userInfo) {
if (ObjectUtil.isNull(userInfo)) { if (ObjectUtil.isNull(userInfo)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, null);
} }
if (StringUtils.isBlank(userInfo.getAccount())) { if (StringUtils.isBlank(userInfo.getAccount())) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, null);
} }
if (StringUtils.isBlank(userInfo.getPassword())) { // if (StringUtils.isBlank(userInfo.getPassword())) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); // return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, null);
} // }
userInfo = userService.saveUser(userInfo); return userService.saveUser(userInfo);
return WebResult.ok(userInfo);
} }
@Override @Override
public WebResult<UserInfo> updateUser(UserInfo userInfo) { public Result<UserInfo> updateUser(UserInfo userInfo) {
if (userInfo == null) { if (userInfo == null) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, null);
} }
if (StringUtils.isBlank(userInfo.getId())) { if (StringUtils.isBlank(userInfo.getId())) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, null);
} }
userInfo = userService.updateUser(userInfo); return userService.updateUser(userInfo);
return WebResult.ok(userInfo);
} }
@Override @Override
public WebResult<Boolean> deleteUser(String userId) { public Result<Boolean> deleteUser(UserInfoSearch search) {
String userId = search.getId();
if (StringUtils.isBlank(userId)) { if (StringUtils.isBlank(userId)) {
return WebResult.failed(StatusCodeEnum.COMMON_PARAM_EMPTY); return Result.failed(StatusCodeEnum.COMMON_PARAM_EMPTY, null);
} }
userService.deleteUser(userId); userService.deleteUser(userId);
return WebResult.ok(); return Result.success(true);
} }
@Override @Override
...@@ -157,4 +160,10 @@ public class UserController implements IUser { ...@@ -157,4 +160,10 @@ public class UserController implements IUser {
return Result.success(true); return Result.success(true);
} }
@Override
public Result<List<OrgInfo>> orgs(String userId) {
List<OrgInfo> orgInfos = userService.orgs(userId);
return Result.success(orgInfos);
}
} }
// package com.dituhui.pea.user.controller2;
//
// import com.dituhui.pea.common.PageResult;
// import com.dituhui.pea.common.Result;
// import com.dituhui.pea.enums.StatusCodeEnum;
// import com.dituhui.pea.pojo.PageRequest;
// import com.dituhui.pea.pojo.ResourceInfo;
// import com.dituhui.pea.pojo.RoleInfo;
// import com.dituhui.pea.pojo.WebResult;
// import com.dituhui.pea.user.IRole;
// import com.dituhui.pea.user.IRole2;
// import com.dituhui.pea.user.service.RoleService;
// import com.dituhui.pea.user.service.RoleService2;
// import org.apache.commons.lang.StringUtils;
// 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.RequestBody;
// import org.springframework.web.bind.annotation.RequestMapping;
// import org.springframework.web.bind.annotation.RequestMethod;
// import org.springframework.web.bind.annotation.RestController;
//
// import java.util.List;
//
// /**
// * 角色控制层
// */
// @RestController
// @RefreshScope
// public class RoleController2 implements IRole2 {
//
//
// @Autowired
// RoleService2 roleService;
//
// /**
// * 添加角色
// *
// * @param roleInfo 角色信息
// * @return
// */
// @RequestMapping(value = "/pea-user/role/add2", method = RequestMethod.POST)
// public Result<RoleInfo> addRole(@RequestBody RoleInfo roleInfo) {
// return roleService.addRole(roleInfo);
// }
//
// }
...@@ -10,13 +10,13 @@ import java.util.List; ...@@ -10,13 +10,13 @@ import java.util.List;
/** /**
* 资源表 用户对某种具体权限或者功能的描述(Resource)表数据库访问层 * 资源表 用户对某种具体权限或者功能的描述(Resource)表数据库访问层
*
*/ */
public interface ResourceDao extends JpaRepository<ResourceEntity, String>, public interface ResourceDao extends JpaRepository<ResourceEntity, String>,
JpaSpecificationExecutor<ResourceEntity>, CrudRepository<ResourceEntity, String> { JpaSpecificationExecutor<ResourceEntity>, CrudRepository<ResourceEntity, String> {
/** /**
* 根据IDs查询多个资源 * 根据IDs查询多个资源
*
* @param ids 资源ID集合 * @param ids 资源ID集合
* @return * @return
*/ */
...@@ -31,5 +31,5 @@ public interface ResourceDao extends JpaRepository<ResourceEntity, String>, ...@@ -31,5 +31,5 @@ public interface ResourceDao extends JpaRepository<ResourceEntity, String>,
List<ResourceEntity> findByParentId(String parentId); List<ResourceEntity> findByParentId(String parentId);
List<ResourceEntity> findByTypeNot(Integer type);
} }
// package com.dituhui.pea.user.dao;
//
//
// import com.dituhui.pea.user.entity.RoleEntity2;
// import org.springframework.data.jpa.repository.JpaRepository;
// import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
// import org.springframework.data.repository.CrudRepository;
//
// /**
// * 角色表(Role)表数据库访问层
// *
// */
// public interface RoleDao2 extends JpaRepository<RoleEntity2, String>,
// JpaSpecificationExecutor<RoleEntity2>, CrudRepository<RoleEntity2, String> {
//
// }
...@@ -5,6 +5,8 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -5,6 +5,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import java.util.List;
/** /**
* 用户组织关联表 * 用户组织关联表
*/ */
...@@ -17,7 +19,7 @@ public interface UserOrgDao extends JpaRepository<UserOrgEntity, String>, JpaSpe ...@@ -17,7 +19,7 @@ public interface UserOrgDao extends JpaRepository<UserOrgEntity, String>, JpaSpe
* @param id * @param id
* @return * @return
*/ */
UserOrgEntity findByUserId(String id); List<UserOrgEntity> findByUserId(String userId);
void deleteByUserId(String userId); void deleteByUserId(String userId);
} }
...@@ -27,7 +27,7 @@ public class RoleEntity implements Serializable { ...@@ -27,7 +27,7 @@ public class RoleEntity implements Serializable {
@Id @Id
@GeneratedValue(generator = "uuid") @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "ID", unique = true, nullable = false, length = 32) @Column(name = "ID", unique = true, nullable = false, length = 60)
private String id; private String id;
/** /**
* 名称 * 名称
...@@ -44,7 +44,7 @@ public class RoleEntity implements Serializable { ...@@ -44,7 +44,7 @@ public class RoleEntity implements Serializable {
* 角色自定义条件 * 角色自定义条件
*/ */
@Column(name = "extra") @Column(name = "extra")
@NotBlank(message = "角色自定义条件不能为空!") // @NotBlank(message = "角色自定义条件不能为空!")
private String extra; private String extra;
/** /**
* 创建人 * 创建人
...@@ -69,4 +69,10 @@ public class RoleEntity implements Serializable { ...@@ -69,4 +69,10 @@ public class RoleEntity implements Serializable {
@LastModifiedDate @LastModifiedDate
private Date updatedTime; private Date updatedTime;
/**
* 备注
*/
@Column(name = "notes")
private String notes;
} }
// 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.NotBlank;
// import java.io.Serializable;
// import java.util.Date;
//
// /**
// * 角色表(RoleEntity)实体类
// *
// */
// @Data
// @Entity
// @Table(name ="sys_role")
// @EntityListeners(AuditingEntityListener.class)
// public class RoleEntity2 implements Serializable {
// private static final long serialVersionUID = -71423293716769828L;
// /**
// * 主键
// */
// @Id
// @GeneratedValue(generator = "uuid")
// @GenericGenerator(name = "uuid", strategy = "uuid")
// @Column(name = "ID", unique = true, nullable = false, length = 60)
// private String id;
// /**
// * 名称
// */
// @Column(name = "name")
// @NotBlank(message = "角色名称不能为空!")
// private String name;
// /**
// * 角色组id
// */
// @Column(name = "group_id")
// private String groupId;
// /**
// * 角色自定义条件
// */
// @Column(name = "extra")
// @NotBlank(message = "角色自定义条件不能为空!")
// private String extra;
// /**
// * 创建人
// */
// @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;
//
// /**
// * 备注
// */
// @Column(name = "notes")
// private String notes;
//
// }
...@@ -120,6 +120,12 @@ public class UserEntity implements Serializable { ...@@ -120,6 +120,12 @@ public class UserEntity implements Serializable {
private Integer ban = 0; private Integer ban = 0;
/** /**
* 是否正常 0: 否 1:是 默认1
*/
@Column(name = "status")
private Integer status = 1;
/**
* 用户来源:0:bean 1:新建 * 用户来源:0:bean 1:新建
*/ */
@Column(name = "source") @Column(name = "source")
...@@ -130,4 +136,10 @@ public class UserEntity implements Serializable { ...@@ -130,4 +136,10 @@ public class UserEntity implements Serializable {
*/ */
@Column(name = "engineer_code") @Column(name = "engineer_code")
private String engineerCode; private String engineerCode;
/**
* 备注
*/
@Column(name = "notes")
private String notes;
} }
...@@ -3,27 +3,37 @@ package com.dituhui.pea.user.service; ...@@ -3,27 +3,37 @@ package com.dituhui.pea.user.service;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dituhui.pea.common.PageResult; import com.dituhui.pea.common.PageResult;
import com.dituhui.pea.common.Result;
import com.dituhui.pea.enums.RedisKeyGroup;
import com.dituhui.pea.enums.StatusCodeEnum; import com.dituhui.pea.enums.StatusCodeEnum;
import com.dituhui.pea.exception.BusinessException; import com.dituhui.pea.exception.BusinessException;
import com.dituhui.pea.pojo.PageRequest; import com.dituhui.pea.pojo.PageRequest;
import com.dituhui.pea.pojo.ResourceInfo; import com.dituhui.pea.pojo.ResourceInfo;
import com.dituhui.pea.pojo.RoleInfo; import com.dituhui.pea.pojo.RoleInfo;
import com.dituhui.pea.pojo.role.RoleResourceInfo; import com.dituhui.pea.pojo.role.RoleResourceInfo;
import com.dituhui.pea.user.commom.RedisService;
import com.dituhui.pea.user.dao.*; import com.dituhui.pea.user.dao.*;
import com.dituhui.pea.user.entity.*; import com.dituhui.pea.user.entity.*;
import com.dituhui.pea.util.UUIDUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.ArrayList; import java.time.LocalDateTime;
import java.util.Arrays; import java.util.*;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
...@@ -32,6 +42,7 @@ import java.util.stream.Collectors; ...@@ -32,6 +42,7 @@ import java.util.stream.Collectors;
* @author zl * @author zl
*/ */
@Service @Service
@Slf4j
public class RoleService { public class RoleService {
@Autowired @Autowired
...@@ -49,32 +60,62 @@ public class RoleService { ...@@ -49,32 +60,62 @@ public class RoleService {
@Autowired @Autowired
RoleResourceDao roleResourceDao; RoleResourceDao roleResourceDao;
@Autowired
RedisService redisService;
// @Autowired
// private DataSourceTransactionManager dataSourceTransactionManager;
/**
* 失效时间ms
*/
private static final int LIVE_TIME_MILLIS = 360000;
@Transactional
public Result<RoleInfo> addRole(RoleInfo roleInfo) {
// String name = roleInfo.getName();
// String createdBy = roleInfo.getCreatedBy();
// String notes = roleInfo.getNotes();
// RoleEntity roleEntity = new RoleEntity();
// roleEntity.setName(name);
// roleEntity.setCreatedBy(createdBy);
// roleEntity.setCreatedTime(LocalDateTime.now());
// roleEntity.setNotes(notes);
@Transactional(rollbackFor = Exception.class)
public RoleInfo addRole(RoleInfo roleInfo) {
RoleEntity roleEntity = BeanUtil.copyProperties(roleInfo, RoleEntity.class); RoleEntity roleEntity = BeanUtil.copyProperties(roleInfo, RoleEntity.class);
// RoleEntity roleEntity = assembleRole(roleInfo);
log.info("新增角色入参:" + JSONObject.toJSONString(roleEntity));
roleEntity = roleDao.save(roleEntity); roleEntity = roleDao.save(roleEntity);
// roleInfo = BeanUtil.copyProperties(roleEntity, RoleInfo.class);
roleInfo.setId(roleEntity.getId());
List<RoleResourceInfo> resourceInfos = roleInfo.getResourceInfos(); List<RoleResourceInfo> resourceInfos = roleInfo.getResourceInfos();
if (CollectionUtils.isNotEmpty(resourceInfos)) { if (CollectionUtils.isNotEmpty(resourceInfos)) {
for (RoleResourceInfo resourceInfo : resourceInfos) { for (RoleResourceInfo resourceInfo : resourceInfos) {
RoleResourceEntity roleResourceEntity = assembleRoleResource(roleEntity.getId(), resourceInfo.getResourceId()); RoleResourceEntity roleResourceEntity = assembleRoleResource(roleInfo.getId(), resourceInfo.getResourceId());
roleResourceDao.save(roleResourceEntity); roleResourceDao.save(roleResourceEntity);
} }
} }
roleInfo = BeanUtil.copyProperties(roleEntity, RoleInfo.class); log.info("新增角色信息:" + JSONObject.toJSONString(roleInfo));
return roleInfo; return Result.success(roleInfo);
} }
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public RoleInfo updateRole(RoleInfo roleInfo) { public RoleInfo updateRole(RoleInfo roleInfo) {
RoleEntity entity = roleDao.findById(roleInfo.getId()).orElse(null);
if (ObjectUtil.isEmpty(entity)) {
// return Result.failed(StatusCodeEnum.ROLE_DOES_NOT_EXIST, null);
return roleInfo;
}
RoleEntity roleEntity = BeanUtil.copyProperties(roleInfo, RoleEntity.class); RoleEntity roleEntity = BeanUtil.copyProperties(roleInfo, RoleEntity.class);
roleEntity.setCreatedBy(entity.getCreatedBy());
roleEntity.setCreatedTime(entity.getCreatedTime());
roleEntity = roleDao.save(roleEntity); roleEntity = roleDao.save(roleEntity);
List<RoleResourceInfo> resourceInfos = roleInfo.getResourceInfos(); List<RoleResourceInfo> resourceInfos = roleInfo.getResourceInfos();
if (CollectionUtils.isNotEmpty(resourceInfos)) { if (CollectionUtils.isNotEmpty(resourceInfos)) {
for (RoleResourceInfo resourceInfo : resourceInfos) {
// 先清除 // 先清除
roleResourceDao.deleteByRoleId(roleEntity.getId()); roleResourceDao.deleteByRoleId(roleEntity.getId());
for (RoleResourceInfo resourceInfo : resourceInfos) {
RoleResourceEntity roleResourceEntity = assembleRoleResource(roleEntity.getId(), resourceInfo.getResourceId()); RoleResourceEntity roleResourceEntity = assembleRoleResource(roleEntity.getId(), resourceInfo.getResourceId());
roleResourceDao.save(roleResourceEntity); roleResourceDao.save(roleResourceEntity);
} }
...@@ -98,6 +139,34 @@ public class RoleService { ...@@ -98,6 +139,34 @@ public class RoleService {
roleResourceDao.deleteByRoleId(roleId); roleResourceDao.deleteByRoleId(roleId);
} }
@Transactional(rollbackFor = Exception.class)
public RoleInfo deleteRole2(RoleInfo roleInfo) {
String name = roleInfo.getName();
String createdBy = roleInfo.getCreatedBy();
String notes = roleInfo.getNotes();
RoleEntity roleEntity = new RoleEntity();
roleEntity.setName(name);
roleEntity.setCreatedBy(createdBy);
roleEntity.setCreatedTime(new Date());
roleEntity.setNotes(notes);
// RoleEntity roleEntity = assembleRole(roleInfo);
log.info("新增角色入参:" + JSONObject.toJSONString(roleEntity));
roleEntity = roleDao.save(roleEntity);
// roleInfo = BeanUtil.copyProperties(roleEntity, RoleInfo.class);
roleInfo.setId(roleEntity.getId());
List<RoleResourceInfo> resourceInfos = roleInfo.getResourceInfos();
if (CollectionUtils.isNotEmpty(resourceInfos)) {
for (RoleResourceInfo resourceInfo : resourceInfos) {
RoleResourceEntity roleResourceEntity = assembleRoleResource(roleInfo.getId(), resourceInfo.getResourceId());
roleResourceDao.save(roleResourceEntity);
}
}
log.info("新增角色信息:" + JSONObject.toJSONString(roleInfo));
return roleInfo;
}
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void addUserRole(String roleId, String userId) { public void addUserRole(String roleId, String userId) {
// 查询角色是否存在 // 查询角色是否存在
...@@ -226,6 +295,16 @@ public class RoleService { ...@@ -226,6 +295,16 @@ public class RoleService {
} }
private RoleEntity assembleRole(RoleInfo roleInfo) {
RoleEntity roleEntity = new RoleEntity();
roleEntity.setName(roleInfo.getName());
roleEntity.setCreatedBy(roleInfo.getCreatedBy());
roleEntity.setCreatedTime(new Date());
roleEntity.setNotes(roleInfo.getNotes());
return roleEntity;
}
public PageResult<RoleInfo> listRole(PageRequest pageRequest) { public PageResult<RoleInfo> listRole(PageRequest pageRequest) {
Sort sort = Sort.by(Sort.Order.desc("createdTime")); Sort sort = Sort.by(Sort.Order.desc("createdTime"));
Pageable pageable = org.springframework.data.domain.PageRequest.of(pageRequest.getPage() - 1, pageRequest.getSize(), sort); Pageable pageable = org.springframework.data.domain.PageRequest.of(pageRequest.getPage() - 1, pageRequest.getSize(), sort);
...@@ -263,7 +342,27 @@ public class RoleService { ...@@ -263,7 +342,27 @@ public class RoleService {
} }
public List<ResourceInfo> allResource() { public List<ResourceInfo> allResource() {
List<ResourceEntity> all = resourceDao.findAll(); String redisValue = redisService.get(RedisKeyGroup.resourceKey.name());
return all.stream().map(entity -> BeanUtil.copyProperties(entity, ResourceInfo.class)).collect(Collectors.toList()); if (StringUtils.isNotBlank(redisValue)) {
return JSONObject.parseObject(redisValue, List.class);
}
List<ResourceEntity> all = resourceDao.findByTypeNot(3);
List<ResourceInfo> collect = all.stream().filter(resourceEntity -> StringUtils.isBlank(resourceEntity.getParentId())).map(entity -> BeanUtil.copyProperties(entity, ResourceInfo.class)).collect(Collectors.toList());
for (ResourceInfo entity : collect) {
List<ResourceInfo> twoResource = all.stream().filter(resourceEntity -> StringUtils.isNotBlank(resourceEntity.getParentId())
&& resourceEntity.getParentId().equals(entity.getId()))
.map(e -> BeanUtil.copyProperties(e, ResourceInfo.class)).collect(Collectors.toList());
for (ResourceInfo twoEntity : twoResource) {
List<ResourceInfo> threeResource = all.stream().filter(resourceEntity -> StringUtils.isNotBlank(resourceEntity.getParentId())
&& resourceEntity.getParentId().equals(twoEntity.getId()))
.map(e -> BeanUtil.copyProperties(e, ResourceInfo.class)).collect(Collectors.toList());
twoEntity.setChildren(threeResource);
}
entity.setChildren(twoResource);
}
long timestamp = System.currentTimeMillis() + LIVE_TIME_MILLIS;
redisService.set(RedisKeyGroup.resourceKey.name(), JSONObject.toJSONString(collect), timestamp / 1000);
return collect;
} }
} }
// package com.dituhui.pea.user.service;
//
// import cn.hutool.core.bean.BeanUtil;
// import com.alibaba.fastjson.JSONObject;
// import com.dituhui.pea.common.Result;
// import com.dituhui.pea.pojo.RoleInfo;
// import com.dituhui.pea.pojo.role.RoleResourceInfo;
// import com.dituhui.pea.user.dao.RoleDao;
// import com.dituhui.pea.user.dao.RoleDao2;
// import com.dituhui.pea.user.dao.RoleResourceDao;
// import com.dituhui.pea.user.entity.RoleEntity;
// import com.dituhui.pea.user.entity.RoleEntity2;
// import com.dituhui.pea.user.entity.RoleResourceEntity;
// import lombok.extern.slf4j.Slf4j;
// import org.apache.commons.collections.CollectionUtils;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.stereotype.Service;
// import org.springframework.transaction.annotation.Transactional;
//
// import java.util.List;
//
// @Service
// @Slf4j
// public class RoleService2 {
//
// @Autowired
// RoleDao2 roleDao;
// @Autowired
// RoleResourceDao roleResourceDao;
//
// @Transactional
// public Result<RoleInfo> addRole(RoleInfo roleInfo) {
// RoleEntity2 roleEntity = BeanUtil.copyProperties(roleInfo, RoleEntity2.class);
// // RoleEntity roleEntity = assembleRole(roleInfo);
// log.info("新增角色入参:" + JSONObject.toJSONString(roleEntity));
// roleEntity = roleDao.save(roleEntity);
// // roleInfo = BeanUtil.copyProperties(roleEntity, RoleInfo.class);
// roleInfo.setId(roleEntity.getId());
// List<RoleResourceInfo> resourceInfos = roleInfo.getResourceInfos();
// if (CollectionUtils.isNotEmpty(resourceInfos)) {
// for (RoleResourceInfo resourceInfo : resourceInfos) {
// RoleResourceEntity roleResourceEntity = assembleRoleResource(roleInfo.getId(), resourceInfo.getResourceId());
// roleResourceDao.save(roleResourceEntity);
// }
// }
// log.info("新增角色信息:" + JSONObject.toJSONString(roleInfo));
// return Result.success(roleInfo);
// }
//
//
// private RoleResourceEntity assembleRoleResource(String roleId, String resourceId) {
// RoleResourceEntity roleResourceEntity = new RoleResourceEntity();
// roleResourceEntity.setRoleId(roleId);
// roleResourceEntity.setResourceId(resourceId);
// return roleResourceEntity;
// }
//
//
// }
...@@ -13,16 +13,16 @@ import javax.persistence.criteria.Predicate; ...@@ -13,16 +13,16 @@ import javax.persistence.criteria.Predicate;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.dituhui.pea.common.PageResult; import com.dituhui.pea.common.PageResult;
import com.dituhui.pea.pojo.*; import com.dituhui.pea.pojo.*;
import com.dituhui.pea.pojo.user.OrgInfo;
import com.dituhui.pea.user.dao.*; import com.dituhui.pea.user.dao.*;
import com.dituhui.pea.user.entity.*; import com.dituhui.pea.user.entity.*;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl; import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers; import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -63,6 +63,8 @@ public class UserService { ...@@ -63,6 +63,8 @@ public class UserService {
*/ */
private static final int LIVE_TIME_MILLIS = 7200000; private static final int LIVE_TIME_MILLIS = 7200000;
private static final Gson gson = new Gson(); private static final Gson gson = new Gson();
private static final java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
;
@Autowired @Autowired
UserDao userDao; UserDao userDao;
...@@ -285,16 +287,22 @@ public class UserService { ...@@ -285,16 +287,22 @@ public class UserService {
* @return * @return
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public UserInfo saveUser(UserInfo userInfo) { public Result<UserInfo> saveUser(UserInfo userInfo) {
// 校验用户信息 // 校验用户信息
checkAccount(userInfo); Result<UserInfo> checkAccount = checkAccount(userInfo);
if (null != checkAccount) {
return checkAccount;
}
UserEntity userEntity = BeanUtil.copyProperties(userInfo, UserEntity.class); UserEntity userEntity = BeanUtil.copyProperties(userInfo, UserEntity.class);
// 密码MD5加密 // 密码MD5加密
userEntity.setPassword(SecureUtil.md5(userInfo.getPassword())); userEntity.setPassword(SecureUtil.md5(userEntity.getPhone().substring(userEntity.getPhone().length() - 6)));
// 保存用户信息 // 保存用户信息
userEntity = userDao.save(userEntity); userEntity = userDao.save(userEntity);
userInfo.setId(userEntity.getId());
savaUserRoleAndOrgInfo(userInfo); savaUserRoleAndOrgInfo(userInfo);
return BeanUtil.copyProperties(userEntity, UserInfo.class); UserInfo info = BeanUtil.copyProperties(userEntity, UserInfo.class);
info.setPassword(null);
return Result.success(info);
} }
/** /**
...@@ -424,19 +432,23 @@ public class UserService { ...@@ -424,19 +432,23 @@ public class UserService {
* @return * @return
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public UserInfo updateUser(UserInfo userInfo) { public Result<UserInfo> updateUser(UserInfo userInfo) {
// 校验用户信息 // 校验用户信息
checkAccount(userInfo); Result<UserInfo> checkAccount = checkAccount(userInfo);
if (null != checkAccount) {
return checkAccount;
}
// 查询用户信息是否存在 // 查询用户信息是否存在
UserEntity userEntity = userDao.findById(userInfo.getId()).orElse(null); UserEntity userEntity = userDao.findById(userInfo.getId()).orElse(null);
if (ObjectUtil.isNull(userEntity)) { if (ObjectUtil.isNull(userEntity)) {
throw new BusinessException(StatusCodeEnum.USER_DOES_NOT_EXIST); return Result.failed(StatusCodeEnum.USER_DOES_NOT_EXIST, null);
} }
assembleUpdateUserInfo(userInfo, userEntity); assembleUpdateUserInfo(userInfo, userEntity);
userEntity = userDao.save(userEntity); userEntity = userDao.save(userEntity);
savaUserRoleAndOrgInfo(userInfo); savaUserRoleAndOrgInfo(userInfo);
userInfo = BeanUtil.copyProperties(userEntity, UserInfo.class); userInfo = BeanUtil.copyProperties(userEntity, UserInfo.class);
return userInfo; userInfo.setPassword(null);
return Result.success(userInfo);
} }
/** /**
...@@ -460,11 +472,17 @@ public class UserService { ...@@ -460,11 +472,17 @@ public class UserService {
userRoleDao.save(userRoleEntity); userRoleDao.save(userRoleEntity);
} }
} }
if (MapUtils.isNotEmpty(userRoleMap)) {
for (String roleId : userRoleMap.keySet()) {
UserRoleEntity userRoleEntity = userRoleMap.get(roleId);
userRoleDao.deleteById(userRoleEntity.getId());
}
}
} }
//处理用户机构关联信息 //处理用户机构关联信息
if (CollectionUtils.isNotEmpty(userInfo.getOrgIds()) && null != userInfo.getOrgIds()) { if (CollectionUtils.isNotEmpty(userInfo.getOrgIds()) && null != userInfo.getOrgIds()) {
for (Integer orgId : userInfo.getOrgIds()) {
userOrgDao.deleteByUserId(userInfo.getId()); userOrgDao.deleteByUserId(userInfo.getId());
for (Integer orgId : userInfo.getOrgIds()) {
UserOrgEntity userOrgEntity = new UserOrgEntity(); UserOrgEntity userOrgEntity = new UserOrgEntity();
userOrgEntity.setUserId(userInfo.getId()); userOrgEntity.setUserId(userInfo.getId());
userOrgEntity.setOrgId(orgId); userOrgEntity.setOrgId(orgId);
...@@ -515,33 +533,39 @@ public class UserService { ...@@ -515,33 +533,39 @@ public class UserService {
* *
* @param userInfo 用户信息 * @param userInfo 用户信息
*/ */
private void checkAccount(UserInfo userInfo) { private Result<UserInfo> checkAccount(UserInfo userInfo) {
// 校验账号 // 校验账号
if (StringUtils.isNotBlank(userInfo.getAccount())) { if (StringUtils.isNotBlank(userInfo.getAccount())) {
if (checkAccount(userInfo.getAccount(), userInfo.getId())) { if (checkAccount(userInfo.getAccount(), userInfo.getId())) {
throw new BusinessException(StatusCodeEnum.ACCOUNT_EXISTS); return Result.failed(StatusCodeEnum.ACCOUNT_EXISTS, null);
// throw new BusinessException(StatusCodeEnum.ACCOUNT_EXISTS);
} }
} }
// 校验手机号 // 校验手机号
if (StringUtils.isNotBlank(userInfo.getPhone())) { if (StringUtils.isNotBlank(userInfo.getPhone())) {
// 校验手机格式是否正确 // 校验手机格式是否正确
if (!Validator.isMobile(userInfo.getPhone())) { if (!Validator.isMobile(userInfo.getPhone())) {
throw new BusinessException(StatusCodeEnum.COMMON_PARAM_ERROR); return Result.failed(StatusCodeEnum.COMMON_PARAM_ERROR, null);
// throw new BusinessException(StatusCodeEnum.COMMON_PARAM_ERROR);
} }
if (checkPhone(userInfo.getPhone(), userInfo.getId())) { if (checkPhone(userInfo.getPhone(), userInfo.getId())) {
throw new BusinessException(StatusCodeEnum.MOBILE_NUMBER_EXISTS); return Result.failed(StatusCodeEnum.MOBILE_NUMBER_EXISTS, null);
// throw new BusinessException(StatusCodeEnum.MOBILE_NUMBER_EXISTS);
} }
} }
// 校验邮箱 // 校验邮箱
if (StringUtils.isNotBlank(userInfo.getEmail())) { if (StringUtils.isNotBlank(userInfo.getEmail())) {
// 校验邮箱格式是否正确 // 校验邮箱格式是否正确
if (!Validator.isEmail(userInfo.getEmail())) { if (!Validator.isEmail(userInfo.getEmail())) {
throw new BusinessException(StatusCodeEnum.COMMON_PARAM_ERROR); return Result.failed(StatusCodeEnum.COMMON_PARAM_ERROR, null);
// throw new BusinessException(StatusCodeEnum.COMMON_PARAM_ERROR);
} }
if (checkEmail(userInfo.getEmail(), userInfo.getId())) { if (checkEmail(userInfo.getEmail(), userInfo.getId())) {
throw new BusinessException(StatusCodeEnum.EMAIL_EXISTS); return Result.failed(StatusCodeEnum.EMAIL_EXISTS, null);
// throw new BusinessException(StatusCodeEnum.EMAIL_EXISTS);
} }
} }
return null;
} }
/** /**
...@@ -680,7 +704,7 @@ public class UserService { ...@@ -680,7 +704,7 @@ public class UserService {
querySql.append("and su.source =" + search.getSource() + " "); querySql.append("and su.source =" + search.getSource() + " ");
} }
if (null != search.getOrgId()) { if (null != search.getOrgId()) {
querySql.append("and suo.org_id =" + search.getOrgId() + " "); querySql.append("and suo.org_id ='" + search.getOrgId() + "'");
} }
if (null != search.getQueryString()) { if (null != search.getQueryString()) {
querySql.append("and (su.engineer_code LIKE '%" + search.getQueryString() + "%' or su.nickname like '%" + search.getQueryString() + "%' or su.phone like '%" + search.getQueryString() + "%' or su.email like '%" + search.getQueryString() + "%' )"); querySql.append("and (su.engineer_code LIKE '%" + search.getQueryString() + "%' or su.nickname like '%" + search.getQueryString() + "%' or su.phone like '%" + search.getQueryString() + "%' or su.email like '%" + search.getQueryString() + "%' )");
...@@ -726,6 +750,13 @@ public class UserService { ...@@ -726,6 +750,13 @@ public class UserService {
search.setPhone(map.containsKey("phone") && ObjectUtil.isNotEmpty(map.get("phone")) ? map.get("phone").toString() : null); search.setPhone(map.containsKey("phone") && ObjectUtil.isNotEmpty(map.get("phone")) ? map.get("phone").toString() : null);
search.setEngineerCode(map.containsKey("engineer_code") && ObjectUtil.isNotEmpty(map.get("engineer_code")) ? map.get("engineer_code").toString() : null); search.setEngineerCode(map.containsKey("engineer_code") && ObjectUtil.isNotEmpty(map.get("engineer_code")) ? map.get("engineer_code").toString() : null);
search.setRoleName(map.containsKey("roleName") && ObjectUtil.isNotEmpty(map.get("roleName")) ? map.get("roleName").toString() : null); search.setRoleName(map.containsKey("roleName") && ObjectUtil.isNotEmpty(map.get("roleName")) ? map.get("roleName").toString() : null);
search.setBan(map.containsKey("ban") && ObjectUtil.isNotEmpty(map.get("ban")) ? Integer.parseInt(map.get("ban").toString()) : null);
search.setCreatedBy(map.containsKey("CREATED_BY") && ObjectUtil.isNotEmpty(map.get("CREATED_BY")) ? map.get("CREATED_BY").toString() : null);
search.setUpdatedBy(map.containsKey("UPDATED_BY") && ObjectUtil.isNotEmpty(map.get("UPDATED_BY")) ? map.get("UPDATED_BY").toString() : null);
search.setNotes(map.containsKey("notes") && ObjectUtil.isNotEmpty(map.get("notes")) ? map.get("notes").toString() : null);
search.setCreatedTime(map.containsKey("CREATED_TIME") && ObjectUtil.isNotEmpty(map.get("CREATED_TIME")) ? formatter.format(map.get("CREATED_TIME")) : null);
search.setUpdatedTime(map.containsKey("UPDATED_TIME") && ObjectUtil.isNotEmpty(map.get("UPDATED_TIME")) ? formatter.format(map.get("UPDATED_TIME")) : null);
search.setLastLoginTime(map.containsKey("LAST_LOGIN_TIME") && ObjectUtil.isNotEmpty(map.get("LAST_LOGIN_TIME")) ? formatter.format(map.get("LAST_LOGIN_TIME")) : null);
return search; return search;
} }
...@@ -742,4 +773,18 @@ public class UserService { ...@@ -742,4 +773,18 @@ public class UserService {
userDao.save(byId); userDao.save(byId);
} }
} }
public List<OrgInfo> orgs(String userId) {
List<OrgInfo> orgInfos = new ArrayList<>();
List<UserOrgEntity> byUserId = userOrgDao.findByUserId(userId);
if (CollectionUtils.isEmpty(byUserId)) {
return orgInfos;
}
byUserId.forEach(e -> {
OrgInfo orgInfo = new OrgInfo();
orgInfo.setId(e.getOrgId());
orgInfos.add(orgInfo);
});
return orgInfos;
}
} }
...@@ -42,11 +42,11 @@ spring: ...@@ -42,11 +42,11 @@ spring:
seata: #seata:
application-id: ${spring.application.name} # application-id: ${spring.application.name}
tx-service-group: ${spring.application.name}-group # tx-service-group: ${spring.application.name}-group
service: # service:
vgroup-mapping: # vgroup-mapping:
project-user-group: default # project-user-group: default
grouplist: # grouplist:
default: seata-server:8091 # default: seata-server:8091
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!