diff --git a/.gitignore b/.gitignore
index d47f94d..b325f90 100644
--- a/.gitignore
+++ b/.gitignore
@@ -768,3 +768,21 @@ dmypy.json
# Pyre type checker
.pyre/
+
+# vue发布目录
+static/
+
+yarn.lock
+*.iml
+*.ipr
+nohup.out
+*tar.gz*
+*.bk
+package-lock.json
+package-lock.json
+.classpath
+.factorypath
+.project
+.settings/
+*static/
+.gitkeep
diff --git a/deploy.sh b/deploy.sh
index 9e0da4f..8a00226 100755
--- a/deploy.sh
+++ b/deploy.sh
@@ -1,5 +1,8 @@
#!/usr/bin/env sh
-
+#mvn clean package
cd target
-scp bill-1.0.0-SNAPSHOT.jar gc:/tmp
-ssh gc "sudo cp /tmp/bill-1.0.0-SNAPSHOT.jar /home/bill/service ; sudo . /home/bill/service/run.sh"
+scp bill-1.0.0-SNAPSHOT.jar me:~/bill-service
+#ssh me "sh ~/bill-service/run.sh"
+#scp bill-1.0.0-SNAPSHOT.jar gc:/tmp
+#ssh gc "sudo cp /tmp/bill-1.0.0-SNAPSHOT.jar /home/bill/service ; sudo sh /home/bill/service/run.sh"
+
diff --git a/pom.xml b/pom.xml
index 00130ac..baea5dc 100644
--- a/pom.xml
+++ b/pom.xml
@@ -12,6 +12,25 @@
1.0.0-SNAPSHOT
bill
+
+
+ dev
+
+ dev
+
+
+
+ true
+
+
+
+ prod
+
+ prod
+
+
+
+
UTF-8
1.8
@@ -27,14 +46,32 @@
2.6
4.12
0.10.5
+ 0.10.5
+ 1.3.0.Final
+
+ org.mapstruct
+ mapstruct-processor
+ ${mapstruct.version}
+
+
+ org.mapstruct
+ mapstruct-jdk8
+ ${mapstruct.version}
+
+
+ cn.hutool
+ hutool-all
+ 4.5.13
+
+
-
+
commons-codec
commons-codec
1.9
@@ -110,11 +147,23 @@
io.springfox
springfox-swagger2
${swagger2.version}
+
+
+ org.mapstruct
+ mapstruct
+
+
io.springfox
springfox-swagger-ui
${swagger2.version}
+
+
+ org.mapstruct
+ mapstruct
+
+
org.springframework.boot
@@ -160,18 +209,18 @@
org.springframework.boot
spring-boot-starter-web
${springboot.version}
-
-
-
-
-
-
-
-
- org.mybatis.spring.boot
- mybatis-spring-boot-starter
- ${mybatis-spring-boot-starter.version}
+
+
+
+
+
+
+
+
+
+
+
org.projectlombok
lombok
@@ -195,6 +244,35 @@
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.5.1
+
+ 1.8
+ 1.8
+
+
+ org.mapstruct
+ mapstruct-processor
+ ${mapstruct.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+
+
+
+
+
+
+
+
+
+
+
+
org.apache.maven.plugins
maven-surefire-plugin
@@ -207,9 +285,9 @@
- org.springframework.boot
- spring-boot-maven-plugin
-
+ org.springframework.boot
+ spring-boot-maven-plugin
+
diff --git a/run.sh b/run.sh
index c71e418..753c743 100755
--- a/run.sh
+++ b/run.sh
@@ -1,11 +1,17 @@
#!/usr/bin/env sh
pid=`ps -ef | grep bill| grep java | awk '{print $2}'`
-if [ $pid ]; then
+if [ -n "$pid" ]; then
echo $pid
kill -9 $pid
+else
+ echo "no running process"
fi
+
+
> nohup.out
+mvn clean package
nohup java -jar target/bill-1.0.0-SNAPSHOT.jar 2>/dev/null &
+tail -f nohup.out
diff --git a/src/main/java/net/alawn/bill/Application.java b/src/main/java/net/alawn/bill/Application.java
index cb8d778..e12e793 100644
--- a/src/main/java/net/alawn/bill/Application.java
+++ b/src/main/java/net/alawn/bill/Application.java
@@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author Alawn
@@ -11,7 +12,14 @@ import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
+//@EnableSpringConfigured
+//@EnableAutoConfiguration
@ServletComponentScan(basePackages = {"net.alawn.bill.config"})
+//@ComponentScan(basePackages = {"net.alawn.bill.service.mapper","net.alawn.bill.controller","net.alawn.bill.config","net.alawn.bill.security"})
+//@MapperScan("net.alawn.bill.service.mapper")
+//@ComponentScan(basePackages = {"net.alawn.bill.service.mapper","net.alawn.bill.controller","net.alawn.bill.config","net.alawn.bill.security"})
+//@ComponentScan(basePackages = {"net.alawn.bill.mapper"})
+@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
diff --git a/src/main/java/net/alawn/bill/annotation/Query.java b/src/main/java/net/alawn/bill/annotation/Query.java
new file mode 100644
index 0000000..caa3492
--- /dev/null
+++ b/src/main/java/net/alawn/bill/annotation/Query.java
@@ -0,0 +1,63 @@
+package net.alawn.bill.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * @author Alawn
+ * @date 2019-6-4 13:52:30
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Query {
+
+ /** Dong ZhaoYang 2017/8/7 基本对象的属性名 */
+ String propName() default "";
+ /** Dong ZhaoYang 2017/8/7 查询方式 */
+ Type type() default Type.EQUAL;
+
+ /**
+ * 连接查询的属性名,如User类中的dept
+ * @return
+ */
+ String joinName() default "";
+
+ /**
+ * 默认左连接
+ * @return
+ */
+ Join join() default Join.LEFT;
+
+ enum Type {
+ EQUAL
+ /** Dong ZhaoYang 2017/8/7 大于等于 */
+ , GREATER_THAN
+ /** Dong ZhaoYang 2017/8/7 小于等于 */
+ , LESS_THAN
+ /** Dong ZhaoYang 2017/8/7 中模糊查询 */
+ , INNER_LIKE
+ /** Dong ZhaoYang 2017/8/7 左模糊查询 */
+ , LEFT_LIKE
+ /** Dong ZhaoYang 2017/8/7 右模糊查询 */
+ , RIGHT_LIKE
+ /** Dong ZhaoYang 2017/8/7 小于 */
+ , LESS_THAN_NQ
+ //** jie 2019/6/4 包含 */
+ , IN
+ }
+
+ /**
+ * @author Alawn
+ * 适用于简单连接查询,复杂的请自定义该注解,或者使用sql查询
+ */
+ enum Join {
+ /** jie 2019-6-4 13:18:30 左连接 */
+ LEFT
+ /** jie 2019-6-4 13:18:30 右连接 */
+ , RIGHT
+ }
+
+}
+
diff --git a/src/main/java/net/alawn/bill/config/SwaggerConfig.java b/src/main/java/net/alawn/bill/config/SwaggerConfig.java
index cc49c52..862e7f2 100644
--- a/src/main/java/net/alawn/bill/config/SwaggerConfig.java
+++ b/src/main/java/net/alawn/bill/config/SwaggerConfig.java
@@ -17,7 +17,7 @@ import static com.google.common.collect.Lists.newArrayList;
* @author Alawn
*/
@Configuration
-@EnableSwagger2
+//@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
diff --git a/src/main/java/net/alawn/bill/config/UserIDAuditorBean.java b/src/main/java/net/alawn/bill/config/UserIDAuditorBean.java
index 42851d2..e38e857 100644
--- a/src/main/java/net/alawn/bill/config/UserIDAuditorBean.java
+++ b/src/main/java/net/alawn/bill/config/UserIDAuditorBean.java
@@ -1,6 +1,6 @@
package net.alawn.bill.config;
-import net.alawn.bill.security.AuthUser;
+import net.alawn.bill.security.JwtUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContext;
@@ -30,8 +30,8 @@ public class UserIDAuditorBean implements AuditorAware {
return Optional.empty();
}
Object principal = ctx.getAuthentication().getPrincipal();
- if (principal.getClass().isAssignableFrom(AuthUser.class)) {
- return Optional.ofNullable(((AuthUser) principal).getUsername());
+ if (principal.getClass().isAssignableFrom(JwtUser.class)) {
+ return Optional.ofNullable(((JwtUser) principal).getUsername());
} else {
return Optional.empty();
diff --git a/src/main/java/net/alawn/bill/config/WebSecurityConfig.java b/src/main/java/net/alawn/bill/config/WebSecurityConfig.java
index a9311a7..49f109a 100644
--- a/src/main/java/net/alawn/bill/config/WebSecurityConfig.java
+++ b/src/main/java/net/alawn/bill/config/WebSecurityConfig.java
@@ -3,7 +3,6 @@ package net.alawn.bill.config;
import lombok.extern.slf4j.Slf4j;
import net.alawn.bill.security.JwtAuthenticationEntryPoint;
import net.alawn.bill.security.JwtAuthenticationTokenFilter;
-import net.alawn.bill.util.AesEncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
@@ -43,7 +42,7 @@ import java.util.Arrays;
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- @Qualifier("authUserDetailsService")
+ @Qualifier("jwtUserDetailsService")
@Autowired
private UserDetailsService userDetailsService;
@@ -103,9 +102,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/swagger*").permitAll()
.antMatchers( HttpMethod.GET, "/","/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
// .antMatchers("/resources/**").permitAll()
+ .antMatchers(HttpMethod.POST,"/api/users").permitAll()
.antMatchers("/auth/**").permitAll()
- .antMatchers("/bill/**").authenticated()
- .antMatchers("/basic/**/*").authenticated()
+ .antMatchers("/api/**").authenticated()
+// .antMatchers("/basic/**/*").authenticated()
// .antMatchers("/auth/**").permitAll().anyRequest().authenticated()
.and()
.formLogin().loginPage("/").permitAll()
@@ -160,7 +160,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public String encode(CharSequence charSequence) {
log.info("encode password:" + charSequence.toString());
-// String password = AesEncryptUtil.decrypt(charSequence.toString());
+// String password = AesEncryptUtils.decrypt(charSequence.toString());
// return DigestUtils.md5DigestAsHex(password.getBytes());
return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
}
@@ -169,7 +169,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public boolean matches(CharSequence charSequence, String s) {
log.info("matches passwordRaw :" + charSequence.toString());
log.info("matches passwordDb:" + charSequence.toString());
-// String password = AesEncryptUtil.decrypt(charSequence.toString());
+// String password = AesEncryptUtils.decrypt(charSequence.toString());
// String encode = DigestUtils.md5DigestAsHex(password.getBytes());
String encode = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
boolean res = s.equals( encode );
diff --git a/src/main/java/net/alawn/bill/controller/AuthController.java b/src/main/java/net/alawn/bill/controller/AuthController.java
index 2df7822..88fd4a2 100644
--- a/src/main/java/net/alawn/bill/controller/AuthController.java
+++ b/src/main/java/net/alawn/bill/controller/AuthController.java
@@ -1,18 +1,18 @@
package net.alawn.bill.controller;
import lombok.extern.slf4j.Slf4j;
-import net.alawn.bill.entity.dto.NewUser;
-import net.alawn.bill.security.AuthUser;
+import net.alawn.bill.entity.po.User;
import net.alawn.bill.security.JwtAuthenticationRequest;
import net.alawn.bill.security.JwtAuthenticationResponse;
import net.alawn.bill.security.JwtTokenUtil;
import net.alawn.bill.service.AuthService;
+import net.alawn.bill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.validation.annotation.Validated;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
@@ -36,6 +36,9 @@ public class AuthController {
@Autowired
private JwtTokenUtil jwtTokenUtil;
+ @Autowired
+ private UserService userService;
+
@RequestMapping(value = "/auth", method = RequestMethod.POST)
public ResponseEntity> createAuthenticationToken(
@RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {
@@ -58,14 +61,16 @@ public class AuthController {
}
@RequestMapping(value = "/auth/register", method = RequestMethod.POST)
- public NewUser register(@RequestBody NewUser addedUser) throws AuthenticationException, HttpRequestMethodNotSupportedException {
- return authService.register(addedUser);
+// @PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_CREATE')")
+ public ResponseEntity register(@Validated @RequestBody User addedUser) throws AuthenticationException, HttpRequestMethodNotSupportedException {
+// return authService.register(addedUser);
+ return new ResponseEntity(userService.create(addedUser), HttpStatus.CREATED);
}
@RequestMapping(value = "/auth/valid", method = RequestMethod.POST)
public boolean valid(@RequestParam String token) throws AuthenticationException, HttpRequestMethodNotSupportedException {
log.info("token:" + token);
-// AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+// JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
boolean rs = jwtTokenUtil.isTokenExpired(token);
return !rs;
}
diff --git a/src/main/java/net/alawn/bill/controller/BasicController.java b/src/main/java/net/alawn/bill/controller/BasicController.java
deleted file mode 100644
index f87f6c4..0000000
--- a/src/main/java/net/alawn/bill/controller/BasicController.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package net.alawn.bill.controller;
-
-import lombok.extern.slf4j.Slf4j;
-import net.alawn.bill.entity.dto.NewMerchant;
-import net.alawn.bill.entity.dto.NewPost;
-import net.alawn.bill.entity.dto.NewTitle;
-import net.alawn.bill.entity.po.*;
-import net.alawn.bill.repository.*;
-import net.alawn.bill.security.AuthUser;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.bind.annotation.*;
-
-import java.net.URISyntaxException;
-import java.security.Principal;
-import java.util.List;
-import java.util.Optional;
-
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 09:59 2019-05-23
- */
-
-@Slf4j
-@RequestMapping(value = "/basic")
-@RestController
-public class BasicController {
-
- @Autowired
- BookRepo bookRepo;
-
- @Autowired
- ItemRepo itemRepo;
-
- @Autowired
- UserRepo userRepo;
-
- @Autowired
- PostRepo postRepo;
-
- @Autowired
- MerchantRepo merchantRepo;
-
- @Autowired
- TitleRepo titleRepo;
-
- @RequestMapping(value = "/posts",method = RequestMethod.POST)
- @ResponseBody
- public ResponseEntity addPost(@RequestBody NewPost newPost) {
- AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- long userId = authUser.getId();
-
- /** 登记 Post */
- Post post = newPost.build();
- post.setUserId(userId);
- postRepo.save(post);
- postRepo.flush();
- return ResponseEntity.ok(post);
- }
-
- @RequestMapping(value = "/posts",method = RequestMethod.GET)
- @ResponseBody
- public ResponseEntity> fetchPosts() {
- AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- long userId = authUser.getId();
-
- List posts = postRepo.findByUserId(userId);
- return ResponseEntity.ok(posts);
- }
-
- @RequestMapping(value = "/posts/{id}",method = RequestMethod.GET)
- @ResponseBody
- public ResponseEntity getPost(@PathVariable long id){
- log.info("post id:" + id);
-
- /** 登记 Post */
- Optional post = postRepo.findById(id);
-
- if(post.isPresent()) {
- return ResponseEntity.ok(post.get());
- }
- else{
- return ResponseEntity.noContent().build();
- }
- }
-
-
- @RequestMapping(value = "/merchants",method = RequestMethod.POST)
- @ResponseBody
- public ResponseEntity addMerchant(@RequestBody NewMerchant newMerchant) {
- /** 登记 Post */
- Merchant merchant = merchantRepo.save(newMerchant.build());
- merchantRepo.flush();
- return ResponseEntity.ok(merchant);
- }
-
- @RequestMapping(value = "/merchants",method = RequestMethod.GET)
- @ResponseBody
- public ResponseEntity> fetchMerchants() {
- List merchants = merchantRepo.findAll();
- return ResponseEntity.ok(merchants);
- }
-
-
- @RequestMapping(value = "/merchants/{id}",method = RequestMethod.GET)
- @ResponseBody
- public ResponseEntity getMerchant(@PathVariable long id){
- /** 登记 Post */
- Optional merchant = merchantRepo.findById(id);
- if(merchant.isPresent()){
- return ResponseEntity.ok(merchant.get());
- }
- else{
- return ResponseEntity.noContent().build();
- }
- }
-
- @RequestMapping(value = "/titles",method = RequestMethod.POST)
- @ResponseBody
- public ResponseEntity addTitle(@RequestBody NewTitle newTitle) {
- /** 登记 Title */
- Title title = titleRepo.save(newTitle.build());
- titleRepo.flush();
- return ResponseEntity.ok(title);
- }
-
- @RequestMapping(value = "/titles",method = RequestMethod.GET)
- @ResponseBody
- public ResponseEntity> addTitle() {
- List titles = titleRepo.findAll();
- return ResponseEntity.ok(titles);
- }
-
- @RequestMapping(value = "/titles/{id}",method = RequestMethod.GET)
- @ResponseBody
- public ResponseEntity getTitle(@PathVariable long id){
- /** 登记 Title */
- Optional title = titleRepo.findById(id);
- if(title.isPresent()) {
- return ResponseEntity.ok(title.get());
- }
- else{
- return ResponseEntity.noContent().build();
- }
- }
-}
diff --git a/src/main/java/net/alawn/bill/controller/BillController.java b/src/main/java/net/alawn/bill/controller/BillController.java
index 29cf968..fe2108a 100644
--- a/src/main/java/net/alawn/bill/controller/BillController.java
+++ b/src/main/java/net/alawn/bill/controller/BillController.java
@@ -1,85 +1,133 @@
package net.alawn.bill.controller;
import lombok.extern.slf4j.Slf4j;
-import net.alawn.bill.entity.dto.NewBill;
-import net.alawn.bill.entity.po.Book;
-import net.alawn.bill.entity.po.User;
+import net.alawn.bill.entity.po.*;
+import net.alawn.bill.enums.State;
+import net.alawn.bill.exception.CommonException;
+import net.alawn.bill.exception.RespMsg;
import net.alawn.bill.repository.BookRepo;
import net.alawn.bill.repository.ItemRepo;
-import net.alawn.bill.repository.UserRepo;
-import net.alawn.bill.security.AuthUser;
+import net.alawn.bill.security.JwtUser;
+import net.alawn.bill.service.dto.NewBill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
-import java.math.BigDecimal;
import java.util.List;
-
/**
* @Author: Alawn
* @Description:
* @Date: Create in 09:59 2019-05-23
*/
-
@Slf4j
-@RequestMapping(value = "/bill")
+@RequestMapping(value = "/api")
@RestController
public class BillController {
final static double feeRate = 0.08;
@Autowired
BookRepo bookRepo;
-
@Autowired
ItemRepo itemRepo;
- @Autowired
- UserRepo userRepo;
-
- @RequestMapping(value = "/books",method = RequestMethod.POST)
+ @RequestMapping(value = "/bill/books",method = RequestMethod.POST)
@Transactional(rollbackFor=Exception.class)
- public ResponseEntity newBook(@RequestBody NewBill newBill){
- AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- long userId = authUser.getId();
+// public ResponseEntity newBook(@RequestBody NewBill newBill){
+ public ResponseEntity create(@Validated({Book.Update.class, Title.Update.class, Post.Update.class, Merchant.Update.class}) @RequestBody NewBill resources){
+ JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+ long userId = jwtUser.getId();
- log.info("newBill:" + newBill);
- Book book = newBill.toBook();
+ Book book = resources.toBook();
- book.setUser(new User(userId));
+ log.info("Bill:" + book);
+
+// book.setUser(User.builder().id(userId).build());
+ User user = new User();
+ user.setId(userId);
+ book.setUser(user);
+
+ log.info("bookRepo.saveAndFlush");
/** 入库 */
- bookRepo.save(book);
- bookRepo.flush();
- /** 更新总金额 */
- bookRepo.sumAmount(book.getId());
+ bookRepo.saveAndFlush(book);
+
+ log.info("refreshFee");
+
+ /** 计算明细费率 */
+ itemRepo.refreshFee(book.getId());
+
+ /** 计算总金额 */
+// bookRepo.refreshTotalize(book.getId());
+ bookRepo.refreshTotalizedAmount(book.getId());
+
+ /** 计算总费率 */
+ bookRepo.refreshTotalizedFee(book.getId());
+
log.info("book:" + book);
// book = bookRepo.findById(book.getId()).get();
+
book = bookRepo.findById(book.getId()).get();
+
log.info("book:" + book);
log.info("book:" + book.getTotalAmount());
- /** 费率计算 */
- book.setTotalFee(book.getTotalAmount().multiply(BigDecimal.valueOf(feeRate)));
+// /** 费率计算 */
+// book.setTotalFee(book.getTotalAmount().multiply(BigDecimal.valueOf(feeRate)));
bookRepo.save(book);
bookRepo.flush();
return ResponseEntity.ok(book);
}
- @RequestMapping(value = "/books",method = RequestMethod.GET)
+ @RequestMapping(value = "/bill/books",method = RequestMethod.GET)
public ResponseEntity> fetchBooks(){
// public ResponseEntity> fetchBooks(){
- AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- long userId = authUser.getId();
+ JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+ long userId = jwtUser.getId();
+
+ String userName = jwtUser.getUsername();
+
+ Page books = null;
// List books = bookRepo.findByUserIdOrderByCreateTimeDesc(userId);
- Page books = bookRepo.findByUserIdOrderByCreateTimeDesc(userId, PageRequest.of(0,20));
+
+ if(userName.equalsIgnoreCase("alawn"))
+ {
+ books = bookRepo.findByOrderByCreateTimeDesc(PageRequest.of(0,20));
+ }
+ else
+ {
+ books = bookRepo.findByUserIdOrderByCreateTimeDesc(userId, PageRequest.of(0,20));
+ }
// return ResponseEntity.ok(books);
return ResponseEntity.ok(books.getContent());
}
+
+ @RequestMapping(value = "/bill/books/{bookId}",method = RequestMethod.DELETE)
+ public ResponseEntity dropBook(@PathVariable long bookId){
+ JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+ long userId = jwtUser.getId();
+
+ Book book = bookRepo.findByIdAndUserId(bookId,userId);
+
+ if(book == null){
+ throw new CommonException(RespMsg.NO_ACCESS_PERMISSION);
+ }
+
+ /** 非申请状态的不得撤销 */
+ if(book.getState() != State.Applied) {
+ throw new CommonException(RespMsg.CAN_NOT_BE_DROP);
+ }
+
+ book.setState(State.Droped);
+ bookRepo.saveAndFlush(book);
+
+ return ResponseEntity.noContent().build();
+ }
}
diff --git a/src/main/java/net/alawn/bill/controller/MerchantController.java b/src/main/java/net/alawn/bill/controller/MerchantController.java
new file mode 100644
index 0000000..8173ad4
--- /dev/null
+++ b/src/main/java/net/alawn/bill/controller/MerchantController.java
@@ -0,0 +1,52 @@
+package net.alawn.bill.controller;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.entity.po.Merchant;
+import net.alawn.bill.repository.MerchantRepo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 15:25 2019-06-25
+ */
+
+@Slf4j
+@RequestMapping(value = "/api")
+@RestController
+public class MerchantController {
+
+ @Autowired
+ MerchantRepo merchantRepo;
+
+ @RequestMapping(value = "/merchants",method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity addMerchant(@RequestBody Merchant resources) {
+ return new ResponseEntity(merchantRepo.saveAndFlush(resources), HttpStatus.CREATED);
+ }
+
+ @RequestMapping(value = "/merchants",method = RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity> fetchMerchants() {
+ return ResponseEntity.ok(merchantRepo.findAllByEnabledIsTrue());
+ }
+
+
+ @RequestMapping(value = "/merchants/{id}",method = RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity getMerchant(@PathVariable long id){
+ Optional merchant = merchantRepo.findById(id);
+ if(merchant.isPresent()){
+ return ResponseEntity.ok(merchant.get());
+ }
+ else{
+ return ResponseEntity.noContent().build();
+ }
+ }
+}
diff --git a/src/main/java/net/alawn/bill/controller/PermissionController.java b/src/main/java/net/alawn/bill/controller/PermissionController.java
new file mode 100644
index 0000000..aef9e11
--- /dev/null
+++ b/src/main/java/net/alawn/bill/controller/PermissionController.java
@@ -0,0 +1,80 @@
+package net.alawn.bill.controller;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.entity.po.Permission;
+import net.alawn.bill.exception.BadRequestException;
+import net.alawn.bill.service.PermissionService;
+import net.alawn.bill.service.dto.CommonQueryCriteria;
+import net.alawn.bill.service.dto.PermissionDTO;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+/**
+ * @author Alawn
+ * @date 2018-12-03
+ */
+@Slf4j
+@RestController
+@RequestMapping("api")
+public class PermissionController {
+
+ @Autowired
+ private PermissionService permissionService;
+
+ private static final String ENTITY_NAME = "permission";
+
+ /**
+ * 返回全部的权限,新增角色时下拉选择
+ * @return
+ */
+ @GetMapping(value = "/permissions/tree")
+// @PreAuthorize("hasAnyRole('admin','permission:all','permission:create','permission:edit','roles:select','roles:all')")
+ @PreAuthorize("hasAnyAuthority('admin','permission:all')")
+ public ResponseEntity getTree(){
+ return new ResponseEntity(permissionService.getPermissionTree(permissionService.findByPid(0L)), HttpStatus.OK);
+ }
+
+// @Log("查询权限")
+ @GetMapping(value = "/permissions")
+// @PreAuthorize("hasAnyRole('admin','permission:all','permission:select')")
+ @PreAuthorize("hasAnyAuthority('admin','permission:all')")
+ public ResponseEntity getPermissions(CommonQueryCriteria criteria){
+ List permissionDTOS = permissionService.queryAll(criteria);
+ Object obj = permissionService.buildTree(permissionDTOS);
+ log.info("Object:" + obj);
+ return new ResponseEntity(obj, HttpStatus.OK);
+// return new ResponseEntity(permissionService.buildTree(permissionDTOS), HttpStatus.OK);
+ }
+
+// @Log("新增权限")
+ @PostMapping(value = "/permissions")
+ @PreAuthorize("hasAnyRole('admin','permission:all','permission:create')")
+ public ResponseEntity create(@Validated @RequestBody Permission resources){
+ if (resources.getId() != null) {
+ throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
+ }
+ return new ResponseEntity(permissionService.create(resources), HttpStatus.CREATED);
+ }
+
+// @Log("修改权限")
+ @PutMapping(value = "/permissions")
+ @PreAuthorize("hasAnyRole('admin','permission:all','permission:edit')")
+ public ResponseEntity update(@Validated(Permission.Update.class) @RequestBody Permission resources){
+ permissionService.update(resources);
+ return new ResponseEntity(HttpStatus.NO_CONTENT);
+ }
+
+// @Log("删除权限")
+ @DeleteMapping(value = "/permissions/{id}")
+ @PreAuthorize("hasAnyRole('admin','permission:all','permission:delete')")
+ public ResponseEntity delete(@PathVariable Long id){
+ permissionService.delete(id);
+ return new ResponseEntity(HttpStatus.OK);
+ }
+}
diff --git a/src/main/java/net/alawn/bill/controller/PostController.java b/src/main/java/net/alawn/bill/controller/PostController.java
new file mode 100644
index 0000000..68cf5c4
--- /dev/null
+++ b/src/main/java/net/alawn/bill/controller/PostController.java
@@ -0,0 +1,68 @@
+package net.alawn.bill.controller;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.entity.po.Post;
+import net.alawn.bill.repository.PostRepo;
+import net.alawn.bill.util.SecurityUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 15:25 2019-06-25
+ */
+
+@Slf4j
+@RequestMapping(value = "/api")
+@RestController
+public class PostController {
+ @Autowired
+ PostRepo postRepo;
+
+ @RequestMapping(value = "/posts",method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity create(@RequestBody Post post) {
+// public ResponseEntity create(@RequestBody NewPost newPost) {
+// JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+// long userId = authUser.getId();
+
+ /** 登记 Post */
+// Post post = newPost.build();
+ post.setUserId(SecurityUtils.getUserId());
+ postRepo.save(post);
+ postRepo.flush();
+ return new ResponseEntity(post, HttpStatus.CREATED);
+ }
+
+ @RequestMapping(value = "/posts",method = RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity> fetchPosts() {
+// JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+// long userId = authUser.getId();
+ List posts = postRepo.findByUserId(SecurityUtils.getUserId());
+ return ResponseEntity.ok(posts);
+ }
+
+ @RequestMapping(value = "/posts/{id}",method = RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity getPost(@PathVariable long id){
+ log.info("post id:" + id);
+
+ /** 登记 Post */
+ Optional post = postRepo.findById(id);
+
+ if(post.isPresent()) {
+ return ResponseEntity.ok(post.get());
+ }
+ else{
+ return ResponseEntity.noContent().build();
+ }
+ }
+
+}
diff --git a/src/main/java/net/alawn/bill/controller/TestController.java b/src/main/java/net/alawn/bill/controller/TestController.java
deleted file mode 100644
index 5b0d2a8..0000000
--- a/src/main/java/net/alawn/bill/controller/TestController.java
+++ /dev/null
@@ -1,147 +0,0 @@
-package net.alawn.bill.controller;
-
-import com.alibaba.fastjson.JSON;
-import lombok.extern.slf4j.Slf4j;
-import net.alawn.bill.entity.po.*;
-import net.alawn.bill.enums.State;
-import net.alawn.bill.repository.*;
-import net.alawn.bill.security.AuthUser;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.persistence.EntityManager;
-import java.math.BigDecimal;
-import java.util.*;
-
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 09:59 2019-05-23
- */
-
-@Slf4j
-@RequestMapping(value = "/test")
-@RestController
-public class TestController {
-
- @Autowired
- MainRepo mainRepo;
- @Autowired
- DetailRepo detailRepo;
- @Autowired
- UserRepo userRepo;
- @Autowired
- MerchantRepo merchantRepo;
- @Autowired
- TitleRepo titleRepo;
- @Autowired
- EntityManager entityManager;
-
- @RequestMapping(value = "/mains",method = RequestMethod.POST)
- public ResponseEntity> main(){
- User user = userRepo.findByUsername("alawn");
-
- log.info("user:" + user);
-
-
- Merchant merc = Merchant.builder().abbr("商户简称").name("商户名称").build();
- merc.setId(22l);
-
- Title title = Title.builder().abbr("北京沐融").name("北京沐融信息科技有限公司").taxNo("2019230901258").build();
- title.setId(25l);
-
- Post post = Post.builder().address("世博馆路52号").contact("alawn").mobile("18017581610").userId(user.getId()).build();
- post.setId(32l);
-
- Detail detail1 = new Detail();
- detail1.setAmount(new BigDecimal(3.00));
- detail1.setMerchant(merc);
- detail1.setTitle(title);
- detail1.setDating(new Date());
- Detail detail2 = new Detail();
- detail2.setAmount(new BigDecimal(5.00));
- detail2.setMerchant(merc);
- detail2.setTitle(title);
- detail2.setDating(new Date());
-
-// Set details = new HashSet() ;
-// List details = new ArrayList<>() ;
-// details.add(detail1);
-// details.add(detail2);
-// details.add(detail3);
-
-
- Main main = new Main();
-
- main.setApplyDate(new Date());
- main.setAcceptDate(new Date());
- main.setState(State.Applied);
- main.setUser(user);
- main.setPost(post);
- main.addDetail(detail1);
- main.addDetail(detail2);
- log.info("main.id:" + main);
- mainRepo.save(main);
- mainRepo.flush();
- main.setAcceptDate(new Date());
-
- Post post2 = Post.builder().address("世博馆路12号").contact("alawn").mobile("18017581610").userId(user.getId()).build();
- post2.setId(32l);
-// post2.setId(33l);
-
- main.setPost(post2);
- mainRepo.save(main);
- mainRepo.flush();
-
-
-// Long mainId = main.getId();
- log.info("main:" + main);
-
-// List result = mainRepo.findAll();
-//// log.info("result:" + JSON.toJSONString(result,true));
-//
-//
-// Main rs = entityManager.find(Main.class,mainId);
-// log.info("rs:" + rs);
-
-
-// log.info("details:" + details);
-// detailRepo.saveAll(details);
-// detailRepo.flush();
-
-
-// Optional main1 = mainRepo.findById(mainId);
-// log.info("is exists:" + mainRepo.existsById(mainId));
-////
-// if(main1.isPresent()) {
-// log.info("main:" + main1.get());
-// }
-// else
-// {
-// log.info("no data");
-// }
- return ResponseEntity.ok().build();
- }
-
- @RequestMapping(value = "/mains",method = RequestMethod.GET)
- public ResponseEntity> mains(){
- List result = mainRepo.findAll();
- log.info("result.size:" + result.size());
- return ResponseEntity.ok(result);
- }
-
- @RequestMapping(value = "/details",method = RequestMethod.GET)
- public ResponseEntity> details(){
- List result = detailRepo.findAll();
- log.info("result.size:" + result.size());
-// log.info("result:" + JSON.toJSONString(result,true));
- log.info("result:" + result);
- return ResponseEntity.ok(result);
- }
-
-}
diff --git a/src/main/java/net/alawn/bill/controller/TitleController.java b/src/main/java/net/alawn/bill/controller/TitleController.java
new file mode 100644
index 0000000..f154401
--- /dev/null
+++ b/src/main/java/net/alawn/bill/controller/TitleController.java
@@ -0,0 +1,52 @@
+package net.alawn.bill.controller;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.entity.po.Title;
+import net.alawn.bill.repository.TitleRepo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+import java.util.Optional;
+
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 09:59 2019-05-23
+ */
+
+@Slf4j
+@RequestMapping(value = "/api")
+@RestController
+public class TitleController {
+
+ @Autowired
+ TitleRepo titleRepo;
+
+ @RequestMapping(value = "/titles",method = RequestMethod.POST)
+ @ResponseBody
+ public ResponseEntity addTitle(@RequestBody Title resources) {
+ return ResponseEntity.ok(titleRepo.saveAndFlush(resources));
+ }
+
+ @RequestMapping(value = "/titles",method = RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity> addTitle() {
+ return ResponseEntity.ok(titleRepo.findAll());
+ }
+
+ @RequestMapping(value = "/titles/{id}",method = RequestMethod.GET)
+ @ResponseBody
+ public ResponseEntity getTitle(@PathVariable long id){
+ /** 登记 Title */
+ Optional title = titleRepo.findById(id);
+ if(title.isPresent()) {
+ return ResponseEntity.ok(title.get());
+ }
+ else{
+ return ResponseEntity.noContent().build();
+ }
+ }
+}
diff --git a/src/main/java/net/alawn/bill/controller/UserController.java b/src/main/java/net/alawn/bill/controller/UserController.java
new file mode 100644
index 0000000..0a35624
--- /dev/null
+++ b/src/main/java/net/alawn/bill/controller/UserController.java
@@ -0,0 +1,161 @@
+package net.alawn.bill.controller;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.entity.po.User;
+import net.alawn.bill.exception.BadRequestException;
+import net.alawn.bill.security.JwtUser;
+import net.alawn.bill.service.RoleService;
+import net.alawn.bill.service.UserService;
+import net.alawn.bill.service.dto.RoleSmallDTO;
+import net.alawn.bill.service.dto.UserQueryCriteria;
+import net.alawn.bill.util.AesEncryptUtils;
+import net.alawn.bill.util.SecurityUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Pageable;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Collections;
+import java.util.stream.Collectors;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 09:59 2019-05-23
+ */
+@Slf4j
+@RestController
+@RequestMapping("/api")
+public class UserController {
+ @Autowired
+ private UserService userService;
+
+ @Autowired
+ private RoleService roleService;
+
+ /**
+ * 添加用户
+ * @param resources
+ * @return
+ * @throws AuthenticationException
+ * @throws HttpRequestMethodNotSupportedException
+ */
+ @RequestMapping(value = "/users", method = RequestMethod.POST)
+// @PreAuthorize("hasAnyRole('admin','user:all','user:create')")
+ public ResponseEntity create(@Validated @RequestBody User resources) throws AuthenticationException, HttpRequestMethodNotSupportedException {
+// return authService.register(addedUser);
+ return new ResponseEntity(userService.create(resources), HttpStatus.CREATED);
+ }
+
+ /**
+ * 修改用户
+ * @param resources
+ * @return
+ */
+ @RequestMapping(value = "/users", method = RequestMethod.PUT)
+ @PreAuthorize("hasAnyRole('admin','user:all','user:edit')")
+ public ResponseEntity update(@Validated(User.Update.class) @RequestBody User resources){
+ checkLevel(resources);
+ userService.update(resources);
+ return new ResponseEntity(HttpStatus.NO_CONTENT);
+ }
+
+
+ /**
+ * 删除用户
+ * @param id
+ * @return
+ */
+ @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
+ @PreAuthorize("hasAnyRole('admin','user:all','user:delete')")
+ public ResponseEntity delete(@PathVariable Long id){
+// Integer currentLevel = Collections.min(roleService.findByUser_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
+// Integer optLevel = Collections.min(roleService.findByUser_Id(id).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
+
+// if (currentLevel > optLevel) {
+// throw new BadRequestException("角色权限不足");
+// }
+ userService.delete(id);
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+ /**
+ * 查询用户
+ * @param criteria
+ * @param pageable
+ * @return
+ */
+ @RequestMapping(value = "/users", method = RequestMethod.GET)
+// @PreAuthorize("hasAnyRole('admin','user:all','user:select')")
+ public ResponseEntity getUsers(UserQueryCriteria criteria, Pageable pageable){
+ return new ResponseEntity(userService.queryAll(criteria,pageable),HttpStatus.OK);
+// Set deptSet = new HashSet<>();
+// Set result = new HashSet<>();
+
+// if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
+// deptSet.add(criteria.getDeptId());
+// deptSet.addAll(dataScope.getDeptChildren(deptService.findByPid(criteria.getDeptId())));
+// }
+
+ // 数据权限
+// Set deptIds = dataScope.getDeptIds();
+
+ // 查询条件不为空并且数据权限不为空则取交集
+// if (!CollectionUtils.isEmpty(deptIds) && !CollectionUtils.isEmpty(deptSet)){
+//
+// // 取交集
+// result.addAll(deptSet);
+// result.retainAll(deptIds);
+//
+// // 若无交集,则代表无数据权限
+// criteria.setDeptIds(result);
+// if(result.size() == 0){
+// return new ResponseEntity(PageUtils.toPage(null,0),HttpStatus.OK);
+// } else return new ResponseEntity(userService.queryAll(criteria,pageable),HttpStatus.OK);
+// // 否则取并集
+// } else {
+// result.addAll(deptSet);
+// result.addAll(deptIds);
+// criteria.setDeptIds(result);
+// return new ResponseEntity(userService.queryAll(criteria,pageable),HttpStatus.OK);
+// }
+ }
+
+ /**
+ * 修改密码
+ * @param user
+ * @return
+ */
+ @RequestMapping(value = "/users/updatePassword",method = RequestMethod.POST)
+ public ResponseEntity updatePass(@RequestBody User user){
+ UserDetails userDetails = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+
+ String newPassword = new BCryptPasswordEncoder().encode(AesEncryptUtils.decrypt(user.getPassword()));
+ if(newPassword.equals(userDetails.getPassword())) {
+ throw new BadRequestException("新密码不能与旧密码相同");
+ }
+
+ userService.updatePass(userDetails.getUsername(),newPassword);
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+ /**
+ * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
+ * @param resources
+ */
+ private void checkLevel(User resources) {
+ Integer currentLevel = Collections.min(roleService.findByUsers_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
+ Integer optLevel = roleService.findByRoles(resources.getRoles());
+ if (currentLevel > optLevel) {
+ throw new BadRequestException("角色权限不足");
+ }
+ }
+}
diff --git a/src/main/java/net/alawn/bill/entity/dto/NewBill.java b/src/main/java/net/alawn/bill/entity/dto/NewBill.java
deleted file mode 100644
index f29f3dd..0000000
--- a/src/main/java/net/alawn/bill/entity/dto/NewBill.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package net.alawn.bill.entity.dto;
-
-import lombok.Data;
-import net.alawn.bill.entity.po.*;
-import net.alawn.bill.enums.State;
-
-import java.util.Date;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 10:47 2019-05-23
- */
-
-@Data
-public class NewBill {
-
- private long postId ;
- private List billItems ;
-
- public Book toBook() {
- Book book = new Book();
- book.setApplyDate(new Date());
- book.setPost(new Post(postId));
- book.setState(State.Applied);
-
-// List- items = new ArrayList<>();
-// for(BillItem rq: itemRQs){
-// Item item = new Item();
-// item.setDating(rq.getDating());
-// item.setAmount(rq.getAmount());
-// item.setMerchant(new Merchant(rq.getMerchantId()));
-// item.setTitle(new Title(rq.getTitleId()));
-// items.add(item);
-// }
-
- /** 使用Java8 的stram写法 */
- List
- bookItems = billItems
- .stream()
- .map(rq -> new Item(book,new Title(rq.getTitleId()),new Merchant(rq.getMerchantId()),rq.getDating(),rq.getAmount()))
- .collect(Collectors.toList());
-
- book.setItems(bookItems);
- return book;
- }
-}
diff --git a/src/main/java/net/alawn/bill/entity/dto/NewUser.java b/src/main/java/net/alawn/bill/entity/dto/NewUser.java
deleted file mode 100644
index fa7f89f..0000000
--- a/src/main/java/net/alawn/bill/entity/dto/NewUser.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package net.alawn.bill.entity.dto;
-
-import lombok.Builder;
-import lombok.Value;
-import net.alawn.bill.entity.po.User;
-
-@Value
-@Builder
-public class NewUser {
-
- private String username;
- private String fullname;
- private String password;
-
- public User build() {
- return User.builder()
- .username(username)
- .fullname(fullname)
- .password(password)
- .build();
- }
-}
diff --git a/src/main/java/net/alawn/bill/entity/po/Book.java b/src/main/java/net/alawn/bill/entity/po/Book.java
index 9082a76..271be4e 100644
--- a/src/main/java/net/alawn/bill/entity/po/Book.java
+++ b/src/main/java/net/alawn/bill/entity/po/Book.java
@@ -2,15 +2,21 @@ package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import lombok.*;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
import net.alawn.bill.enums.State;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import javax.persistence.*;
+import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
/**
* @Author: Alawn
@@ -20,14 +26,25 @@ import java.util.*;
@Entity
@Table(name="t_bill_books")
-@Data
-@ToString(callSuper = true)
-@AllArgsConstructor
-@NoArgsConstructor
-@Builder
+//@ToString(callSuper = true)
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@Data
@DynamicUpdate
-public class Book extends EntityId {
+public class Book extends EntityCommon {
+//public class Book{
+
+ @NotNull(groups = {Update.class})
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ public Long getId() {
+ return id;
+ }
+
@JsonIgnore
@ManyToOne
@NotFound(action= NotFoundAction.IGNORE)
@@ -40,6 +57,7 @@ public class Book extends EntityId {
private Post post;
@OneToMany(cascade=CascadeType.ALL, mappedBy = "book", orphanRemoval = true)
+// @OneToMany(cascade=CascadeType.ALL, mappedBy = "book", orphanRemoval = true)
@org.hibernate.annotations.ForeignKey(name = "none")
@NotFound(action= NotFoundAction.IGNORE)
private List
- items = new ArrayList<>();
@@ -50,7 +68,8 @@ public class Book extends EntityId {
private Date applyDate ;
private Date acceptDate ;
private BigDecimal totalAmount ;
- private BigDecimal fee ;
+ private BigDecimal totalFee ;
+
public void addItem(Item item) {
item.setBook(this);
@@ -62,4 +81,22 @@ public class Book extends EntityId {
items.remove(item);
}
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof Book
+ && id != null
+ && items != null
+ && id.equals(((Book) o).id);
+ }
+
+ public @interface Update {}
+ public @interface Insert {}
}
diff --git a/src/main/java/net/alawn/bill/entity/po/Detail.java b/src/main/java/net/alawn/bill/entity/po/Detail.java
deleted file mode 100644
index c134552..0000000
--- a/src/main/java/net/alawn/bill/entity/po/Detail.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package net.alawn.bill.entity.po;
-
-import com.alibaba.fastjson.JSON;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import lombok.*;
-import org.hibernate.annotations.DynamicUpdate;
-import org.hibernate.annotations.NotFound;
-import org.hibernate.annotations.NotFoundAction;
-
-import javax.persistence.*;
-import java.math.BigDecimal;
-import java.util.Date;
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 10:53 2019-05-23
- */
-@Entity
-@Table(name = "t_bill_detail")
-@Data
-@ToString(exclude = {"main"})
-//@AllArgsConstructor
-//@NoArgsConstructor
-//@Builder
-@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
-@DynamicUpdate
-public class Detail extends EntityId {
-
- public Detail (Main main) {
- this.main = main;
- }
-
- public Detail () {
- }
-
-// @NotFound(action = NotFoundAction.IGNORE)
-// @MapsId("id")
-// @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=false) // 可选属性optional=false,表示author不能为空。删除文章,不影响用户
-// @JoinColumn(name="main_id",)//设置在article表中的关联字段(外键)
-// @MapsId("id")
-// @NotFound(action = NotFoundAction.IGNORE)
-
-
- /** OK */
- @JsonIgnore
-// @ManyToOne(cascade = CascadeType.MERGE,fetch=FetchType.LAZY)
- @ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.REFRESH)
- @JoinColumn(name = "mainId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
- private Main main;
-
-
-// @ManyToOne(fetch = FetchType.LAZY)
-// @NotFound(action = NotFoundAction.IGNORE)
-//// @JoinColumn(name = "userId", referencedColumnName = "id")
-// @JoinColumn(name = "userId", referencedColumnName = "id")
-//// @MapsId("username")
-// @MapsId("id")
-// private User user;
-//
-
- private Date dating;
-
-// @OneToOne(cascade= CascadeType.REFRESH,fetch=FetchType.LAZY)
-// @NotFound(action = NotFoundAction.IGNORE)
-// @MapsId("id")
-// @ManyToOne(fetch=FetchType.LAZY)
- @OneToOne(fetch=FetchType.LAZY)
- @JoinColumn(name="titleId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))//设置在article表中的关联字段(外键)
- @NotFound(action = NotFoundAction.IGNORE)
- private Title title;
-
-// @OneToOne(cascade= CascadeType.REFRESH,fetch=FetchType.LAZY)
-// @NotFound(action = NotFoundAction.IGNORE)
-// @MapsId("id")
-// @ManyToOne(fetch=FetchType.LAZY)
- @JsonIgnore
- @OneToOne(fetch=FetchType.LAZY)
- @JoinColumn(name="merchantId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))//设置在article表中的关联字段(外键)
- @NotFound(action = NotFoundAction.IGNORE)
- private Merchant merchant;
-
- private BigDecimal amount;
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Detail )) return false;
- return id != null && id.equals(((Detail) o).id);
- }
-
- @Override
- public int hashCode() {
- return 31;
- }
-}
diff --git a/src/main/java/net/alawn/bill/entity/po/EntityId.java b/src/main/java/net/alawn/bill/entity/po/EntityCommon.java
similarity index 81%
rename from src/main/java/net/alawn/bill/entity/po/EntityId.java
rename to src/main/java/net/alawn/bill/entity/po/EntityCommon.java
index ea55996..13311e3 100644
--- a/src/main/java/net/alawn/bill/entity/po/EntityId.java
+++ b/src/main/java/net/alawn/bill/entity/po/EntityCommon.java
@@ -3,12 +3,12 @@ package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
-import org.springframework.data.annotation.Version;
import org.springframework.data.annotation.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import javax.persistence.Id;
-import javax.persistence.*;
+import javax.persistence.Column;
+import javax.persistence.EntityListeners;
+import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.util.Date;
@@ -20,12 +20,14 @@ import java.util.Date;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
-public class EntityId implements Serializable {
+public class EntityCommon implements Serializable {
protected static final long serialVersionUID = 1L;
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- protected Long id;
+// @NotNull(groups = {Update.class})
+// @Id
+// @GeneratedValue(strategy = GenerationType.AUTO)
+// protected Long id;
+
// @Temporal(TemporalType.TIMESTAMP)
// @CreationTimestamp
@@ -55,8 +57,7 @@ public class EntityId implements Serializable {
@JsonIgnore
@Version
@Column(name = "version")
- protected Long version;
-
+ protected Long version = 0l;
// @Override
// public boolean equals(Object o) {
diff --git a/src/main/java/net/alawn/bill/entity/po/Item.java b/src/main/java/net/alawn/bill/entity/po/Item.java
index 3fb1478..85f5b3f 100644
--- a/src/main/java/net/alawn/bill/entity/po/Item.java
+++ b/src/main/java/net/alawn/bill/entity/po/Item.java
@@ -9,6 +9,7 @@ import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import javax.persistence.*;
+import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
@@ -21,17 +22,21 @@ import java.util.Date;
@Table(name = "t_bill_items")
@Data
@ToString(exclude = {"book"})
-@AllArgsConstructor
@NoArgsConstructor
+@AllArgsConstructor
@Builder
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
-public class Item extends EntityId {
+public class Item extends EntityCommon {
+//public class Item {
- public Item(Book book)
- { this.book = book; }
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @NotNull(groups = {Update.class})
+ private Long id;
/** OK */
+// @JoinColumn(name = "bookId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
@JsonIgnore
@ManyToOne(fetch= FetchType.LAZY,cascade = CascadeType.MERGE,optional = false)
@JoinColumn(name = "bookId",referencedColumnName = "id",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
@@ -42,7 +47,6 @@ public class Item extends EntityId {
@NotFound(action = NotFoundAction.IGNORE)
private Title title;
-
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="merchantId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
@NotFound(action = NotFoundAction.IGNORE)
@@ -51,17 +55,25 @@ public class Item extends EntityId {
// @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date dating;
+
+ private BigDecimal fee;
+
private BigDecimal amount;
@Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Item )) return false;
- return id != null && id.equals(((Item) o).id);
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
}
@Override
- public int hashCode() {
- return 31;
+ public boolean equals(Object o) {
+ return this == o || o instanceof Item
+ && id != null
+ && id.equals(((Item) o).id);
}
+
+ public @interface Update{}
}
diff --git a/src/main/java/net/alawn/bill/entity/po/Main.java b/src/main/java/net/alawn/bill/entity/po/Main.java
deleted file mode 100644
index 881a50c..0000000
--- a/src/main/java/net/alawn/bill/entity/po/Main.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package net.alawn.bill.entity.po;
-
-import com.alibaba.fastjson.JSON;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import lombok.*;
-import net.alawn.bill.enums.State;
-import org.hibernate.annotations.DynamicUpdate;
-import org.hibernate.annotations.NotFound;
-import org.hibernate.annotations.NotFoundAction;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 10:06 2019-05-23
- */
-
-@Entity
-@Table(name="t_bill_main")
-@Data
-@AllArgsConstructor
-@NoArgsConstructor
-@Builder
-@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
-@DynamicUpdate
-//@ToString(exclude = {"details"})
-public class Main extends EntityId {
-
-// @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
-// @OneToOne(fetch=FetchType.LAZY)
-// @NotFound(action = NotFoundAction.IGNORE)
-// @MapsId("id")
- @JsonIgnore
- @ManyToOne
- @NotFound(action= NotFoundAction.IGNORE)
- @JoinColumn(name = "userId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
- private User user;
-
-// @OneToOne(mappedBy="id",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
-// @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
-// @NotFound(action = NotFoundAction.IGNORE)
-// @MapsId("id")
- @ManyToOne(fetch = FetchType.EAGER)
- @JoinColumn(name = "postId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
- @NotFound(action= NotFoundAction.IGNORE)
- private Post post;
-
-// @OneToMany( mappedBy = "main", cascade=CascadeType.ALL,fetch=FetchType.LAZY)
-// @NotFound(action = NotFoundAction.IGNORE)
-// @MapsId("id")
-
- @OneToMany(cascade=CascadeType.ALL, mappedBy = "main", orphanRemoval = true)
-// @OneToMany(cascade=CascadeType.ALL, orphanRemoval = true)
-// @JoinColumn(name = "main_id")
- @org.hibernate.annotations.ForeignKey(name = "none")
- @NotFound(action= NotFoundAction.IGNORE)
- private List details = new ArrayList<>();
-
-// @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
-// private Set authorities;
-
-
- @Enumerated(EnumType.STRING)
- private State state;
-
- private Date applyDate;
- private Date acceptDate;
-
- public String toJson() {
- return JSON.toJSONString(this.toString());
-// return JSON.toJSONString(this.toString(),true);
- }
-
- public void addDetail(Detail detail) {
- detail.setMain(this);
- this.details.add(detail);
- }
-
- public void removeDetail(Detail detail) {
- detail.setMain(null);
- details.remove(detail);
- }
-}
diff --git a/src/main/java/net/alawn/bill/entity/po/Merchant.java b/src/main/java/net/alawn/bill/entity/po/Merchant.java
index 244bbd6..73df990 100644
--- a/src/main/java/net/alawn/bill/entity/po/Merchant.java
+++ b/src/main/java/net/alawn/bill/entity/po/Merchant.java
@@ -2,9 +2,12 @@ package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
+import org.hibernate.annotations.DynamicInsert;
+import org.hibernate.annotations.DynamicUpdate;
-import javax.persistence.Entity;
-import javax.persistence.Table;
+import javax.persistence.*;
+import javax.validation.constraints.NotNull;
+import java.math.BigDecimal;
/**
* @Author: Alawn
@@ -19,11 +22,55 @@ import javax.persistence.Table;
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
-public class Merchant extends EntityId {
- public Merchant(long id) {
- this.id = id;
+@DynamicInsert
+@DynamicUpdate
+public class Merchant extends EntityCommon {
+//public class Merchant {
+
+
+// @ApiModelProperty(hidden = true)
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @NotNull(groups = {Update.class})
+ private Long id;
+
+ /**
+ * 简称
+ */
+ @Column
+ private String abbr;
+ /**
+ * 全称
+ */
+ @Column
+ private String name;
+ /**
+ * 税率
+ */
+ @Column
+ private BigDecimal feeRate;
+
+ /**
+ * 启用状态
+ */
+ @Column
+ @Builder.Default
+ private boolean enabled = true;
+
+ public @interface Update{}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
}
- private String abbr;
- private String name;
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof Merchant
+ && id != null
+ && id.equals(((Merchant) o).id);
+ }
}
diff --git a/src/main/java/net/alawn/bill/entity/po/Permission.java b/src/main/java/net/alawn/bill/entity/po/Permission.java
new file mode 100644
index 0000000..9905bf1
--- /dev/null
+++ b/src/main/java/net/alawn/bill/entity/po/Permission.java
@@ -0,0 +1,83 @@
+package net.alawn.bill.entity.po;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.*;
+import org.hibernate.annotations.DynamicUpdate;
+
+import javax.persistence.*;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+import java.util.Set;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 11:35 2019-06-12
+ */
+
+
+@Data
+@Builder
+@Entity
+@Table(name = "t_bill_permissions")
+@ToString(exclude = {"roles"})
+@NoArgsConstructor
+@AllArgsConstructor
+@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
+@DynamicUpdate
+//public class Permission{
+public class Permission extends EntityCommon {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @NotNull(groups = {Update.class})
+ protected Long id;
+
+ /**
+ * 权限
+ */
+ private String perms ;
+ /**
+ * 别名
+ * */
+ @NotBlank
+ private String alias;
+
+ /**
+ * 备注
+ * */
+ private String remark;
+
+ /**
+ * 上级类目
+ */
+ @NotNull
+ @Column(name = "pid",nullable = false)
+ private Long pid;
+
+ @JsonIgnore
+ @ManyToMany(mappedBy = "permissions")
+ private Set roles;
+
+ public @interface Update{}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+// result = prime * result + ((roles == null) ? 0 : roles.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof Permission
+ && id != null && roles != null
+ && id.equals(((Permission) o).id);
+// && roles.equals(((Permission) o).roles);
+ }
+}
+
+
diff --git a/src/main/java/net/alawn/bill/entity/po/Post.java b/src/main/java/net/alawn/bill/entity/po/Post.java
index ecdf1cc..1e7fc04 100644
--- a/src/main/java/net/alawn/bill/entity/po/Post.java
+++ b/src/main/java/net/alawn/bill/entity/po/Post.java
@@ -4,10 +4,11 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.Accessors;
+import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
-import javax.persistence.Entity;
-import javax.persistence.Table;
+import javax.persistence.*;
+import javax.validation.constraints.NotNull;
/**
* @Author: Alawn
@@ -25,15 +26,43 @@ import javax.persistence.Table;
@AllArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
-public class Post extends EntityId {
+@DynamicInsert
+//public class Post {
+public class Post extends EntityCommon {
- public Post(long id) {
- this.id = id;
- }
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @NotNull(groups = {Update.class})
+// @ApiModelProperty(hidden = true)
+ protected Long id;
+
+// public Post(long id) {
+// this.id = id;
+// }
@JsonIgnore
- private long userId ;
+ private Long userId ;
private String address ;
private String contact ;
private String mobile ;
+
+ public @interface Update{}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((userId == null) ? 0 : userId.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof Post
+ && id != null && userId != null
+ && id.equals(((Post) o).id)
+ && userId.equals(((Post) o).userId);
+ }
+
}
diff --git a/src/main/java/net/alawn/bill/entity/po/Role.java b/src/main/java/net/alawn/bill/entity/po/Role.java
new file mode 100644
index 0000000..6c93a97
--- /dev/null
+++ b/src/main/java/net/alawn/bill/entity/po/Role.java
@@ -0,0 +1,67 @@
+package net.alawn.bill.entity.po;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.*;
+import org.hibernate.annotations.DynamicUpdate;
+
+import javax.persistence.*;
+import javax.validation.constraints.NotNull;
+import java.util.Set;
+
+@Data
+@Builder
+@Entity
+@Table(name = "t_bill_roles")
+@ToString(exclude = {"users","permissions"})
+@NoArgsConstructor
+@AllArgsConstructor
+@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
+@DynamicUpdate
+public class Role extends EntityCommon {
+//public class Role{
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @NotNull(groups = {Update.class})
+ private Long id;
+
+ @Column
+ private String name;
+
+ @Column
+ private String remark;
+
+ // 数值越小,级别越大
+ @Column(name = "level")
+ private Integer level = 3;
+
+ @JsonIgnore
+ @ManyToMany(mappedBy = "roles")
+ private Set users;
+
+ @JsonIgnore
+ @ManyToMany
+ @JoinTable( name = "t_bill_roles_permissions",
+ joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")},
+ inverseJoinColumns = {@JoinColumn(name = "permission_id",referencedColumnName = "id")},
+ foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
+ private Set permissions;
+
+ public @interface Update{}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof Role
+ && id != null && users != null
+ && id.equals(((Role) o).id);
+ }
+}
diff --git a/src/main/java/net/alawn/bill/entity/po/Title.java b/src/main/java/net/alawn/bill/entity/po/Title.java
index fa365ee..c9067c8 100644
--- a/src/main/java/net/alawn/bill/entity/po/Title.java
+++ b/src/main/java/net/alawn/bill/entity/po/Title.java
@@ -2,9 +2,11 @@ package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
+import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
+import javax.validation.constraints.NotNull;
/**
* @Author: Alawn
@@ -21,13 +23,41 @@ import javax.persistence.*;
@AllArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
-public class Title extends EntityId {
+@DynamicInsert
+public class Title extends EntityCommon {
+//public class Title {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @NotNull(groups = {Update.class})
+// @ApiModelProperty(hidden = true)
+ private Long id;
+
private String name;
private String abbr;
@Column(length = 18)
private String taxNo;
- public Title(long id) {
- this.id = id;
+// public Title(long id) {
+// this.id = id;
+// }
+
+ public @interface Update{}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((taxNo == null) ? 0 : taxNo.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof Title
+ && id != null
+ && id.equals(((Title) o).id)
+ && taxNo.equals(((Title) o).taxNo);
}
}
diff --git a/src/main/java/net/alawn/bill/entity/po/User.java b/src/main/java/net/alawn/bill/entity/po/User.java
index d2d9638..c0ab584 100644
--- a/src/main/java/net/alawn/bill/entity/po/User.java
+++ b/src/main/java/net/alawn/bill/entity/po/User.java
@@ -5,9 +5,13 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
+import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
+import org.springframework.util.StringUtils;
import javax.persistence.*;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.Set;
@@ -27,28 +31,35 @@ import java.util.Set;
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
-@ToString(exclude = {"authorities"})
+@ToString(exclude = {"roles"})
@Slf4j
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
-public class User extends EntityId {
+@DynamicInsert
+//public class User {
+public class User extends EntityCommon {
- public User(long id) {
- this.id = id;
- }
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+// public User(long id) {
+// this.id = id;
+// }
/** 用户名称 */
+ @NotBlank
+ @Column(unique = true)
private String username;
/** 用户全名 */
private String fullname;
-
/** 密钥 */
- @JsonIgnore
private String password;
/** 密钥 */
+ @JsonIgnore
private String secret;
/** 密码盐 */
@@ -57,23 +68,75 @@ public class User extends EntityId {
/** token因子 */
private String tokenFactor;
+ /** 手机号码 */
+ private String phone;
+
+ /** 头像 */
+ private String avatar;
+
/** 邮箱 */
+// @NotBlank
+ @Pattern(regexp = "([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}",message = "格式错误")
private String email;
/** 上一次重置密码时间 */
private Date lastPasswordResetDate;
- @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
- private Set authorities;
-
@Builder.Default
private boolean enabled = true;
+// @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
+// private Set authorities;
+
+ @ManyToMany
+ @JoinTable(name = "t_bill_users_roles",
+ joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "id")},
+ inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "id")})
+ private Set roles;
+
+
+ /**
+ * Validated分组条件
+ */
+ public @interface Update {}
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((username == null) ? 0 : username.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || o instanceof User
+ && id != null && username != null && StringUtils.isEmpty(username) != true
+ && id.equals(((User) o).id)
+ && id.equals(((User) o).username);
+ }
+
+
+// @Override
+// public boolean equals(Object obj) {
+// if (this == obj)
+// return true;
+// if (obj == null)
+// return false;
+// if (getClass() != obj.getClass())
+// return false;
+// Student other = (Student) obj;
+// if (ID == other.ID && age == other.age && gender.equals(other.gender) && name.equals(other.name))
+// return true;
+// return false;
+// }
+
// public UserDetails toUserDetails() {
// log.info("toUserDetails.authorities:" + authorities);
// log.info("toUserDetails.authorities:" + mapToGrantedAuthorities(authorities));
-// return new AuthUser(id,username, password, email,enabled, mapToGrantedAuthorities(authorities),lastPasswordResetDate);
+// return new JwtUser(id,username, password, email,enabled, mapToGrantedAuthorities(authorities),lastPasswordResetDate);
// }
//
//// private static Set mapToGrantedAuthorities(Set authorities) {
diff --git a/src/main/java/net/alawn/bill/enums/State.java b/src/main/java/net/alawn/bill/enums/State.java
index a51e35b..2b41b70 100644
--- a/src/main/java/net/alawn/bill/enums/State.java
+++ b/src/main/java/net/alawn/bill/enums/State.java
@@ -12,7 +12,8 @@ public enum State {
Rejected ( "已受理"),
Accepted ( "已受理"),
Posted ( "已快递"),
- Finished ( "已完成");
+ Finished ( "已完成"),
+ Droped ( "已丢弃");
private String desc;
diff --git a/src/main/java/net/alawn/bill/exception/BadRequestException.java b/src/main/java/net/alawn/bill/exception/BadRequestException.java
new file mode 100644
index 0000000..3f6600a
--- /dev/null
+++ b/src/main/java/net/alawn/bill/exception/BadRequestException.java
@@ -0,0 +1,26 @@
+package net.alawn.bill.exception;
+
+import lombok.Getter;
+import org.springframework.http.HttpStatus;
+
+import static org.springframework.http.HttpStatus.BAD_REQUEST;
+
+/**
+ * @author Alawn
+ * @date 2019-06-21
+ * 统一异常处理
+ */
+@Getter
+public class BadRequestException extends RuntimeException{
+
+ private Integer status = BAD_REQUEST.value();
+
+ public BadRequestException(String msg){
+ super(msg);
+ }
+
+ public BadRequestException(HttpStatus status, String msg){
+ super(msg);
+ this.status = status.value();
+ }
+}
diff --git a/src/main/java/net/alawn/bill/exception/EntityExistException.java b/src/main/java/net/alawn/bill/exception/EntityExistException.java
new file mode 100644
index 0000000..4510135
--- /dev/null
+++ b/src/main/java/net/alawn/bill/exception/EntityExistException.java
@@ -0,0 +1,32 @@
+package net.alawn.bill.exception;
+
+import org.springframework.util.StringUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.IntStream;
+
+/**
+ * @author Alawn
+ * @date 2018-06-24
+ */
+public class EntityExistException extends RuntimeException {
+
+ public EntityExistException(Class clazz, Object... saveBodyParamsMap) {
+ super(EntityExistException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, saveBodyParamsMap)));
+ }
+
+ private static String generateMessage(String entity, Map saveBodyParams) {
+ return StringUtils.capitalize(entity) + " 已存在 " + saveBodyParams;
+ }
+
+ private static Map toMap(
+ Class keyType, Class valueType, Object... entries) {
+ if (entries.length % 2 == 1)
+ throw new IllegalArgumentException("Invalid entries");
+ return IntStream.range(0, entries.length / 2).map(i -> i * 2)
+ .collect(HashMap::new,
+ (m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])),
+ Map::putAll);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/net/alawn/bill/exception/EntityNotFoundException.java b/src/main/java/net/alawn/bill/exception/EntityNotFoundException.java
new file mode 100644
index 0000000..5690bfe
--- /dev/null
+++ b/src/main/java/net/alawn/bill/exception/EntityNotFoundException.java
@@ -0,0 +1,35 @@
+package net.alawn.bill.exception;
+
+import org.springframework.util.StringUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.IntStream;
+
+/**
+ * @author Alawn
+ * @date 2018-06-24
+ */
+public class EntityNotFoundException extends RuntimeException {
+
+ public EntityNotFoundException(Class clazz, Object... searchParamsMap) {
+ super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, searchParamsMap)));
+ }
+
+ private static String generateMessage(String entity, Map searchParams) {
+ return StringUtils.capitalize(entity) +
+ " 不存在 " +
+ searchParams;
+ }
+
+ private static Map toMap(
+ Class keyType, Class valueType, Object... entries) {
+ if (entries.length % 2 == 1)
+ throw new IllegalArgumentException("Invalid entries");
+ return IntStream.range(0, entries.length / 2).map(i -> i * 2)
+ .collect(HashMap::new,
+ (m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])),
+ Map::putAll);
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/java/net/alawn/bill/exception/RespMsg.java b/src/main/java/net/alawn/bill/exception/RespMsg.java
index 7b6b83c..de367f7 100644
--- a/src/main/java/net/alawn/bill/exception/RespMsg.java
+++ b/src/main/java/net/alawn/bill/exception/RespMsg.java
@@ -25,6 +25,7 @@ public enum RespMsg {
USER_ALREADY_EXIST ( "200018", RespMsgConstants.USER_ALREADY_EXIST ) ,
USER_NOT_EXIST_OR_PASSWORD_INCORRECT ( "200019", RespMsgConstants.USER_NOT_EXIST_OR_PASSWORD_INCORRECT ) ,
USERNAME_OR_PASSWORD_IS_EMPTY ( "200020", RespMsgConstants.USERNAME_OR_PASSWORD_IS_EMPTY ) ,
+ CAN_NOT_BE_DROP ( "200021", RespMsgConstants.CAN_NOT_BE_DROP ) ,
SUCCESS ( "000000", RespMsgConstants.SUCCESS ) ;
diff --git a/src/main/java/net/alawn/bill/exception/RespMsgConstants.java b/src/main/java/net/alawn/bill/exception/RespMsgConstants.java
index ab32be6..48cf989 100644
--- a/src/main/java/net/alawn/bill/exception/RespMsgConstants.java
+++ b/src/main/java/net/alawn/bill/exception/RespMsgConstants.java
@@ -25,5 +25,6 @@ public final class RespMsgConstants {
public final static String USER_ALREADY_EXIST = "用户已存在" ;
public final static String USER_NOT_EXIST_OR_PASSWORD_INCORRECT = "用户不存在或密码不正确" ;
public final static String USERNAME_OR_PASSWORD_IS_EMPTY = "用户名或密码不得为空" ;
+ public final static String CAN_NOT_BE_DROP = "不能撤销" ;
public final static String SUCCESS = "业务成功" ;
}
diff --git a/src/main/java/net/alawn/bill/mapper/PermissionMapper.java b/src/main/java/net/alawn/bill/mapper/PermissionMapper.java
new file mode 100644
index 0000000..71cb5f2
--- /dev/null
+++ b/src/main/java/net/alawn/bill/mapper/PermissionMapper.java
@@ -0,0 +1,18 @@
+package net.alawn.bill.mapper;
+
+import net.alawn.bill.entity.po.Permission;
+import net.alawn.bill.service.EntityMapper;
+import net.alawn.bill.service.dto.PermissionDTO;
+import org.mapstruct.Mapper;
+import org.mapstruct.ReportingPolicy;
+import org.mapstruct.factory.Mappers;
+
+/**
+ * @author Alawn
+ * @date 2018-11-23
+ */
+@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface PermissionMapper extends EntityMapper {
+ PermissionMapper INSTANCE = Mappers.getMapper( PermissionMapper.class );
+
+}
diff --git a/src/main/java/net/alawn/bill/mapper/RoleMapper.java b/src/main/java/net/alawn/bill/mapper/RoleMapper.java
new file mode 100644
index 0000000..499f16d
--- /dev/null
+++ b/src/main/java/net/alawn/bill/mapper/RoleMapper.java
@@ -0,0 +1,17 @@
+package net.alawn.bill.mapper;
+
+import net.alawn.bill.entity.po.Role;
+import net.alawn.bill.service.EntityMapper;
+import net.alawn.bill.service.dto.RoleDTO;
+import org.mapstruct.Mapper;
+import org.mapstruct.ReportingPolicy;
+import org.mapstruct.factory.Mappers;
+
+/**
+ * @author Alawn
+ * @date 2018-11-23
+ */
+@Mapper(componentModel = "spring", uses = {PermissionMapper.class, }, unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface RoleMapper extends EntityMapper {
+ RoleMapper INSTANCE = Mappers.getMapper( RoleMapper.class );
+}
diff --git a/src/main/java/net/alawn/bill/mapper/RoleSmallMapper.java b/src/main/java/net/alawn/bill/mapper/RoleSmallMapper.java
new file mode 100644
index 0000000..6ccbf13
--- /dev/null
+++ b/src/main/java/net/alawn/bill/mapper/RoleSmallMapper.java
@@ -0,0 +1,18 @@
+package net.alawn.bill.mapper;
+
+import net.alawn.bill.entity.po.Role;
+import net.alawn.bill.service.EntityMapper;
+import net.alawn.bill.service.dto.RoleSmallDTO;
+import org.mapstruct.Mapper;
+import org.mapstruct.ReportingPolicy;
+import org.mapstruct.factory.Mappers;
+
+/**
+ * @author Alawn
+ * @date 2019-06-21
+ */
+@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface RoleSmallMapper extends EntityMapper {
+ RoleSmallMapper INSTANCE = Mappers.getMapper( RoleSmallMapper.class );
+
+}
diff --git a/src/main/java/net/alawn/bill/mapper/UserMapper.java b/src/main/java/net/alawn/bill/mapper/UserMapper.java
new file mode 100644
index 0000000..94b2196
--- /dev/null
+++ b/src/main/java/net/alawn/bill/mapper/UserMapper.java
@@ -0,0 +1,20 @@
+package net.alawn.bill.mapper;
+
+import net.alawn.bill.entity.po.User;
+import net.alawn.bill.service.EntityMapper;
+import net.alawn.bill.service.dto.UserDTO;
+import org.mapstruct.Mapper;
+import org.mapstruct.ReportingPolicy;
+import org.mapstruct.factory.Mappers;
+
+//import org.mapstruct.Mapper;
+
+/**
+ * @author Alawn
+ * @date 2018-11-23
+ */
+
+@Mapper(componentModel = "spring",uses = {RoleMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
+public interface UserMapper extends EntityMapper {
+ UserMapper INSTANCE = Mappers.getMapper( UserMapper.class );
+}
diff --git a/src/main/java/net/alawn/bill/repository/BookRepo.java b/src/main/java/net/alawn/bill/repository/BookRepo.java
index 24b7056..d597040 100644
--- a/src/main/java/net/alawn/bill/repository/BookRepo.java
+++ b/src/main/java/net/alawn/bill/repository/BookRepo.java
@@ -1,14 +1,15 @@
package net.alawn.bill.repository;
import net.alawn.bill.entity.po.Book;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
-import java.util.List;
-
/**
* @Author: Alawn
* @Description:
@@ -17,11 +18,25 @@ import java.util.List;
@Transactional
@Repository
-public interface BookRepo extends JpaRepository {
+public interface BookRepo extends JpaRepository , JpaSpecificationExecutor {
- List findByUserIdOrderByCreateTimeDesc(long userId);
+// List findByUserIdOrderByCreateTimeDesc(long userId);
+//
+ Page findByUserIdOrderByCreateTimeDesc(long userId, Pageable pageable);
+
+ Page findByOrderByCreateTimeDesc(Pageable pageable);
+
+ Book findByIdAndUserId(long bookId, long userId);
@Modifying(clearAutomatically = true)
- @Query(value = "update t_bill_books set total_amount = (select sum(amount) from t_bill_items where book_id = ?1) where id = ?1",nativeQuery = true)
- void sumAmount(long bookId);
+ @Query(value = "update t_bill_books set (total_amount,total_fee) = (select ifnull(sum(amount),0),ifnull(sum(fee),0) from t_bill_items where book_id = ?1) where id = ?1",nativeQuery = true)
+ void refreshTotalize(long bookId);
+
+ @Modifying(clearAutomatically = true)
+ @Query(value = "update t_bill_books set total_fee = (select ifnull(sum(fee),0) from t_bill_items where book_id = ?1) where id = ?1",nativeQuery = true)
+ void refreshTotalizedAmount(long bookId);
+
+ @Modifying(clearAutomatically = true)
+ @Query(value = "update t_bill_books set total_amount = (select ifnull(sum(amount),0) from t_bill_items where book_id = ?1) where id = ?1",nativeQuery = true)
+ void refreshTotalizedFee(long bookId);
}
diff --git a/src/main/java/net/alawn/bill/repository/DetailRepo.java b/src/main/java/net/alawn/bill/repository/DetailRepo.java
deleted file mode 100644
index 0b10ad1..0000000
--- a/src/main/java/net/alawn/bill/repository/DetailRepo.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package net.alawn.bill.repository;
-
-import net.alawn.bill.entity.po.Detail;
-import net.alawn.bill.entity.po.Main;
-import org.springframework.data.jpa.repository.JpaRepository;
-import org.springframework.stereotype.Repository;
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 11:14 2019-05-23
- */
-
-@Repository
-public interface DetailRepo extends JpaRepository {
-
-}
diff --git a/src/main/java/net/alawn/bill/repository/ItemRepo.java b/src/main/java/net/alawn/bill/repository/ItemRepo.java
index 71fab5f..27d3ee2 100644
--- a/src/main/java/net/alawn/bill/repository/ItemRepo.java
+++ b/src/main/java/net/alawn/bill/repository/ItemRepo.java
@@ -2,9 +2,12 @@ package net.alawn.bill.repository;
import net.alawn.bill.entity.po.Item;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
-import java.math.BigDecimal;
+import javax.transaction.Transactional;
/**
* @Author: Alawn
@@ -12,7 +15,11 @@ import java.math.BigDecimal;
* @Date: Create in 11:14 2019-05-23
*/
+@Transactional
@Repository
-public interface ItemRepo extends JpaRepository
- {
+public interface ItemRepo extends JpaRepository
- , JpaSpecificationExecutor {
+ @Modifying(clearAutomatically = true)
+ @Query(value = "update t_bill_items item set item.fee = (select merc.fee_rate from t_bill_merchants merc where merc.id = item.merchant_id) * item.amount where book_id = ?1",nativeQuery = true)
+ void refreshFee(long bookId);
}
diff --git a/src/main/java/net/alawn/bill/repository/MainRepo.java b/src/main/java/net/alawn/bill/repository/MainRepo.java
deleted file mode 100644
index c50879d..0000000
--- a/src/main/java/net/alawn/bill/repository/MainRepo.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package net.alawn.bill.repository;
-
-import net.alawn.bill.entity.po.Main;
-import net.alawn.bill.entity.po.Post;
-import org.springframework.data.jpa.repository.JpaRepository;
-import org.springframework.stereotype.Repository;
-
-import java.util.List;
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 11:14 2019-05-23
- */
-
-@Repository
-public interface MainRepo extends JpaRepository {
- List findByPost(Post post);
-}
diff --git a/src/main/java/net/alawn/bill/repository/MerchantRepo.java b/src/main/java/net/alawn/bill/repository/MerchantRepo.java
index bc63f79..66219e8 100644
--- a/src/main/java/net/alawn/bill/repository/MerchantRepo.java
+++ b/src/main/java/net/alawn/bill/repository/MerchantRepo.java
@@ -1,8 +1,8 @@
package net.alawn.bill.repository;
-import net.alawn.bill.entity.po.Item;
import net.alawn.bill.entity.po.Merchant;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -14,5 +14,6 @@ import java.util.List;
*/
@Repository
-public interface MerchantRepo extends JpaRepository {
+public interface MerchantRepo extends JpaRepository , JpaSpecificationExecutor {
+ List findAllByEnabledIsTrue();
}
diff --git a/src/main/java/net/alawn/bill/repository/PermissionRepo.java b/src/main/java/net/alawn/bill/repository/PermissionRepo.java
new file mode 100644
index 0000000..6dce457
--- /dev/null
+++ b/src/main/java/net/alawn/bill/repository/PermissionRepo.java
@@ -0,0 +1,21 @@
+package net.alawn.bill.repository;
+
+import net.alawn.bill.entity.po.Permission;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 11:14 2019-05-23
+ */
+
+@Repository
+public interface PermissionRepo extends JpaRepository, JpaSpecificationExecutor {
+
+ Permission findByPerms(String perms);
+ List findByPid(Long pid);
+}
diff --git a/src/main/java/net/alawn/bill/repository/PostRepo.java b/src/main/java/net/alawn/bill/repository/PostRepo.java
index 9051f90..e412ad1 100644
--- a/src/main/java/net/alawn/bill/repository/PostRepo.java
+++ b/src/main/java/net/alawn/bill/repository/PostRepo.java
@@ -1,8 +1,8 @@
package net.alawn.bill.repository;
-import net.alawn.bill.entity.po.Item;
import net.alawn.bill.entity.po.Post;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -14,6 +14,6 @@ import java.util.List;
*/
@Repository
-public interface PostRepo extends JpaRepository {
+public interface PostRepo extends JpaRepository , JpaSpecificationExecutor {
List findByUserId(long userId);
}
diff --git a/src/main/java/net/alawn/bill/repository/RoleRepo.java b/src/main/java/net/alawn/bill/repository/RoleRepo.java
new file mode 100644
index 0000000..9072257
--- /dev/null
+++ b/src/main/java/net/alawn/bill/repository/RoleRepo.java
@@ -0,0 +1,32 @@
+package net.alawn.bill.repository;
+
+import net.alawn.bill.entity.po.Role;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.stereotype.Repository;
+
+import java.util.Set;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 11:14 2019-05-23
+ */
+
+@Repository
+public interface RoleRepo extends JpaRepository, JpaSpecificationExecutor {
+ /**
+ * findByPerms
+ * @param name
+ * @return
+ */
+ Role findByName(String name);
+
+ /**
+ * findByUser_Id
+ * @param id
+ * @return
+ */
+ Set findByUsers_Id(Long id);
+// Set findByMenuId(Long id);
+}
diff --git a/src/main/java/net/alawn/bill/repository/TitleRepo.java b/src/main/java/net/alawn/bill/repository/TitleRepo.java
index 201ef01..ad50ae5 100644
--- a/src/main/java/net/alawn/bill/repository/TitleRepo.java
+++ b/src/main/java/net/alawn/bill/repository/TitleRepo.java
@@ -1,8 +1,8 @@
package net.alawn.bill.repository;
-import net.alawn.bill.entity.po.Post;
import net.alawn.bill.entity.po.Title;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
/**
@@ -12,6 +12,6 @@ import org.springframework.stereotype.Repository;
*/
@Repository
-public interface TitleRepo extends JpaRepository {
+public interface TitleRepo extends JpaRepository , JpaSpecificationExecutor {
}
diff --git a/src/main/java/net/alawn/bill/repository/UserRepo.java b/src/main/java/net/alawn/bill/repository/UserRepo.java
index a63bd27..01d9de6 100644
--- a/src/main/java/net/alawn/bill/repository/UserRepo.java
+++ b/src/main/java/net/alawn/bill/repository/UserRepo.java
@@ -2,9 +2,48 @@ package net.alawn.bill.repository;
import net.alawn.bill.entity.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
+import java.util.Date;
+
@Repository
-public interface UserRepo extends JpaRepository {
+public interface UserRepo extends JpaRepository, JpaSpecificationExecutor {
User findByUsername(String username);
+
+ /**
+ * findByEmail
+ * @param email
+ * @return
+ */
+ User findByEmail(String email);
+
+ /**
+ * 修改密码
+ * @param username
+ * @param pass
+ */
+ @Modifying
+ @Query(value = "update t_bill_users set password = ?2 , last_password_reset_time = ?3 where username = ?1",nativeQuery = true)
+ void updatePass(String username, String pass, Date lastPasswordResetTime);
+
+ /**
+ * 修改头像
+ * @param username
+ * @param url
+ */
+ @Modifying
+ @Query(value = "update t_bill_users set avatar = ?2 where username = ?1",nativeQuery = true)
+ void updateAvatar(String username, String url);
+
+ /**
+ * 修改邮箱
+ * @param username
+ * @param email
+ */
+ @Modifying
+ @Query(value = "update t_bill_users set email = ?2 where username = ?1",nativeQuery = true)
+ void updateEmail(String username, String email);
}
diff --git a/src/main/java/net/alawn/bill/security/AuthUserDetailsServiceImpl.java b/src/main/java/net/alawn/bill/security/AuthUserDetailsServiceImpl.java
deleted file mode 100644
index cbb0e56..0000000
--- a/src/main/java/net/alawn/bill/security/AuthUserDetailsServiceImpl.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package net.alawn.bill.security;
-
-import lombok.extern.slf4j.Slf4j;
-import net.alawn.bill.entity.po.User;
-import net.alawn.bill.repository.UserRepo;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.stereotype.Service;
-
-/**
- * @Author: Alawn
- * @Description:
- * @Date: Create in 16:46 2019-05-20
- */
-@Slf4j
-@Service("authUserDetailsService")
-public class AuthUserDetailsServiceImpl implements UserDetailsService {
-
- @Autowired
- private UserRepo userRepo;
-
- @Override
- public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
-
- User user = userRepo.findByUsername(name);
-
- log.info("loadUserByUsername:" + user);
-
- if (user == null) {
- throw new UsernameNotFoundException("UsernameNotFoundException");
- } else {
- return UserFactory.createAuthUser(user);
- }
- }
-}
diff --git a/src/main/java/net/alawn/bill/security/JwtAuthenticationEntryPoint.java b/src/main/java/net/alawn/bill/security/JwtAuthenticationEntryPoint.java
index 69b478d..4d4a5a1 100644
--- a/src/main/java/net/alawn/bill/security/JwtAuthenticationEntryPoint.java
+++ b/src/main/java/net/alawn/bill/security/JwtAuthenticationEntryPoint.java
@@ -20,6 +20,7 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Se
AuthenticationException authException) throws IOException {
// This is invoked when user tries to access a secured REST resource without supplying any credentials
// We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
- response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
+// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
+ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
}
}
diff --git a/src/main/java/net/alawn/bill/security/JwtAuthenticationTokenFilter.java b/src/main/java/net/alawn/bill/security/JwtAuthenticationTokenFilter.java
index 7737bc3..1a4d2f5 100644
--- a/src/main/java/net/alawn/bill/security/JwtAuthenticationTokenFilter.java
+++ b/src/main/java/net/alawn/bill/security/JwtAuthenticationTokenFilter.java
@@ -26,7 +26,7 @@ import java.io.IOException;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
- @Qualifier("authUserDetailsService")
+ @Qualifier("jwtUserDetailsService")
@Autowired
private UserDetailsService userDetailsService;
@@ -57,11 +57,11 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
- AuthUser authUser = (AuthUser) this.userDetailsService.loadUserByUsername(username);
- logger.info("userDetails:" + authUser);
+ JwtUser jwtUser = (JwtUser) this.userDetailsService.loadUserByUsername(username);
+ logger.info("userDetails:" + jwtUser);
- if (jwtTokenUtil.validateToken(authToken, authUser)) {
- UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(authUser, null, authUser.getAuthorities());
+ if (jwtTokenUtil.validateToken(authToken, jwtUser)) {
+ UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails( request));
logger.info("authenticated user " + username + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
diff --git a/src/main/java/net/alawn/bill/security/JwtPermissionService.java b/src/main/java/net/alawn/bill/security/JwtPermissionService.java
new file mode 100644
index 0000000..1682091
--- /dev/null
+++ b/src/main/java/net/alawn/bill/security/JwtPermissionService.java
@@ -0,0 +1,40 @@
+package net.alawn.bill.security;
+
+import net.alawn.bill.entity.po.Role;
+import net.alawn.bill.repository.RoleRepo;
+import net.alawn.bill.service.dto.UserDTO;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cache.annotation.CacheConfig;
+import org.springframework.cache.annotation.Cacheable;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.stereotype.Service;
+
+import java.util.Collection;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@Service
+@CacheConfig(cacheNames = "role")
+public class JwtPermissionService {
+
+ @Autowired
+ private RoleRepo roleRepo;
+
+ /**
+ * key的名称如有修改,请同步修改 UserServiceImpl 中的 update 方法
+ * @param user
+ * @return
+ */
+ @Cacheable(key = "'loadPermissionByUser:' + #p0.username")
+ public Collection mapToGrantedAuthorities(UserDTO user) {
+
+ System.out.println("--------------------loadPermissionByUser:" + user.getUsername() + "---------------------");
+
+ Set roles = roleRepo.findByUsers_Id(user.getId());
+
+ return roles.stream().flatMap(role -> role.getPermissions().stream())
+ .map(permission -> new SimpleGrantedAuthority(permission.getPerms()))
+ .collect(Collectors.toList());
+ }
+}
diff --git a/src/main/java/net/alawn/bill/security/AuthUser.java b/src/main/java/net/alawn/bill/security/JwtUser.java
similarity index 66%
rename from src/main/java/net/alawn/bill/security/AuthUser.java
rename to src/main/java/net/alawn/bill/security/JwtUser.java
index e4ac365..ea6deb7 100644
--- a/src/main/java/net/alawn/bill/security/AuthUser.java
+++ b/src/main/java/net/alawn/bill/security/JwtUser.java
@@ -1,35 +1,45 @@
package net.alawn.bill.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import lombok.Builder;
+import lombok.Data;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Date;
+import java.util.stream.Collectors;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 16:09 2019-05-20
*/
+@Builder
+@Data
@ToString(callSuper = true)
-public class AuthUser implements UserDetails {
+public class JwtUser implements UserDetails {
private final long id;
private final String username;
private final String password;
+ private final String fullname;
+ private final String avatar;
+ private final String phone;
+ private final Date createTime;
private final boolean enabled;
+// private final Collection extends GrantedAuthority> authorities;
private final Collection extends GrantedAuthority> authorities;
private final Date lastPasswordResetDate;
- public AuthUser(long id, String username, String password, String email, boolean enabled, Collection extends GrantedAuthority> authorities, Date lastPasswordResetDate) {
- this.id = id;
- this.username = username;
- this.password = password;
- this.enabled = enabled;
- this.authorities = authorities;
- this.lastPasswordResetDate = lastPasswordResetDate;
- }
+// public JwtUser(long id, String username, String password, boolean enabled, Collection extends GrantedAuthority> authorities, Date lastPasswordResetDate) {
+// this.id = id;
+// this.username = username;
+// this.password = password;
+// this.enabled = enabled;
+// this.authorities = authorities;
+// this.lastPasswordResetDate = lastPasswordResetDate;
+// }
// 返回分配给用户的角色列表
@Override
@@ -86,5 +96,7 @@ public class AuthUser implements UserDetails {
return lastPasswordResetDate;
}
-
+ public Collection getRoles() {
+ return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
+ }
}
diff --git a/src/main/java/net/alawn/bill/security/JwtUserDetailsServiceImpl.java b/src/main/java/net/alawn/bill/security/JwtUserDetailsServiceImpl.java
new file mode 100644
index 0000000..72a64c0
--- /dev/null
+++ b/src/main/java/net/alawn/bill/security/JwtUserDetailsServiceImpl.java
@@ -0,0 +1,63 @@
+package net.alawn.bill.security;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.service.UserService;
+import net.alawn.bill.service.dto.UserDTO;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 16:46 2019-05-20
+ */
+@Slf4j
+@Service("jwtUserDetailsService")
+@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
+public class JwtUserDetailsServiceImpl implements UserDetailsService {
+
+ @Autowired
+ private UserService userService;
+
+ @Autowired
+ private JwtPermissionService permissionService;
+
+
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+
+ UserDTO user = userService.findByName(username);
+// User user = userRepo.findByUsername(name);
+
+ log.info("loadUserByUsername:" + user);
+
+ if (user == null) {
+ throw new UsernameNotFoundException("UsernameNotFoundException");
+ } else {
+ return createAuthUser(user);
+ }
+ }
+
+ private UserDetails createAuthUser(UserDTO user) {
+ log.info("mapToGrantedAuthorities" + permissionService.mapToGrantedAuthorities(user));
+
+ return JwtUser.builder()
+ .id(user.getId())
+ .authorities(permissionService.mapToGrantedAuthorities(user))
+ .enabled(user.getEnabled())
+ .lastPasswordResetDate(user.getLastPasswordResetDate())
+ .password(user.getPassword())
+ .phone(user.getPhone())
+ .fullname(user.getFullname())
+ .avatar(user.getAvatar())
+ .createTime(user.getCreateTime())
+ .username(user.getUsername())
+ .build();
+ }
+
+}
diff --git a/src/main/java/net/alawn/bill/security/UserFactory.java b/src/main/java/net/alawn/bill/security/UserFactory.java
index 9298890..41b9be0 100644
--- a/src/main/java/net/alawn/bill/security/UserFactory.java
+++ b/src/main/java/net/alawn/bill/security/UserFactory.java
@@ -5,8 +5,6 @@ import net.alawn.bill.entity.po.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import java.util.Arrays;
-import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -16,21 +14,20 @@ import java.util.stream.Collectors;
* @Date: Create in 16:45 2019-05-20
*/
public class UserFactory {
-
private UserFactory() {
}
- public static AuthUser createAuthUser(User user) {
+ public static JwtUser createAuthUser(User user) {
// user.toUserDetails();
- return new AuthUser(
- user.getId(),
- user.getUsername(),
- user.getPassword(),
- user.getEmail(),
- user.isEnabled(),
- mapToGrantedAuthorities(user.getAuthorities()),
- user.getLastPasswordResetDate()
- );
+// return new JwtUser(
+// user.getId(),
+// user.getUsername(),
+// user.getPassword(),
+// user.isEnabled(),
+//// mapToGrantedAuthorities(user.getAuthorities()),
+// user.getLastPasswordResetDate()
+// );
+ return null;
}
private static Set mapToGrantedAuthorities(Set authorities) {
diff --git a/src/main/java/net/alawn/bill/service/AuthService.java b/src/main/java/net/alawn/bill/service/AuthService.java
index f7fbcef..f761975 100644
--- a/src/main/java/net/alawn/bill/service/AuthService.java
+++ b/src/main/java/net/alawn/bill/service/AuthService.java
@@ -1,8 +1,6 @@
package net.alawn.bill.service;
-import net.alawn.bill.entity.dto.NewUser;
import org.springframework.security.core.AuthenticationException;
-import org.springframework.web.HttpRequestMethodNotSupportedException;
/**
* @Author: Alawn
@@ -10,7 +8,7 @@ import org.springframework.web.HttpRequestMethodNotSupportedException;
* @Date: Create in 15:58 2019-05-20
*/
public interface AuthService {
- NewUser register(NewUser userDTO) throws HttpRequestMethodNotSupportedException, AuthenticationException;
+// UserDTO register(UserDTO userDTO) throws HttpRequestMethodNotSupportedException, AuthenticationException;
String login(String username, String password) throws AuthenticationException;
String refresh(String oldToken);
}
diff --git a/src/main/java/net/alawn/bill/service/EntityMapper.java b/src/main/java/net/alawn/bill/service/EntityMapper.java
new file mode 100644
index 0000000..ed47247
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/EntityMapper.java
@@ -0,0 +1,38 @@
+package net.alawn.bill.service;
+
+import java.util.List;
+
+/**
+ * @author Alawn
+ * @date 2019-06-21
+ */
+public interface EntityMapper {
+
+ /**
+ * DTO转Entity
+ * @param dto
+ * @return
+ */
+ E toEntity(D dto);
+
+ /**
+ * Entity转DTO
+ * @param entity
+ * @return
+ */
+ D toDto(E entity);
+
+ /**
+ * DTO集合转Entity集合
+ * @param dtoList
+ * @return
+ */
+ List toEntity(List dtoList);
+
+ /**
+ * Entity集合转DTO集合
+ * @param entityList
+ * @return
+ */
+ List toDto(List entityList);
+}
diff --git a/src/main/java/net/alawn/bill/service/PermissionService.java b/src/main/java/net/alawn/bill/service/PermissionService.java
new file mode 100644
index 0000000..a92c7e4
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/PermissionService.java
@@ -0,0 +1,79 @@
+package net.alawn.bill.service;
+
+import net.alawn.bill.entity.po.Permission;
+import net.alawn.bill.service.dto.CommonQueryCriteria;
+import net.alawn.bill.service.dto.PermissionDTO;
+import org.springframework.cache.annotation.CacheConfig;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
+
+import java.util.List;
+
+/**
+ * @author Alawn
+ * @date 2018-12-08
+ */
+@CacheConfig(cacheNames = "permission")
+public interface PermissionService {
+
+ /**
+ * get
+ * @param id
+ * @return
+ */
+ @Cacheable(key = "#p0")
+ PermissionDTO findById(long id);
+
+ /**
+ * create
+ * @param resources
+ * @return
+ */
+ @CacheEvict(allEntries = true)
+ PermissionDTO create(Permission resources);
+
+ /**
+ * update
+ * @param resources
+ */
+ @CacheEvict(allEntries = true)
+ void update(Permission resources);
+
+ /**
+ * delete
+ * @param id
+ */
+ @CacheEvict(allEntries = true)
+ void delete(Long id);
+
+ /**
+ * permission tree
+ * @return
+ */
+ @Cacheable(key = "'tree'")
+ Object getPermissionTree(List permissions);
+
+ /**
+ * findByPid
+ * @param pid
+ * @return
+ */
+ @Cacheable(key = "'pid:'+#p0")
+ List findByPid(long pid);
+
+ /**
+ * build Tree
+ * @param permissionDTOS
+ * @return
+ */
+ @Cacheable(keyGenerator = "keyGenerator")
+ Object buildTree(List permissionDTOS);
+
+ /**
+ * queryAll
+ * @param criteria
+ * @return
+ */
+ @Cacheable(keyGenerator = "keyGenerator")
+ List queryAll(CommonQueryCriteria criteria);
+}
diff --git a/src/main/java/net/alawn/bill/service/RoleService.java b/src/main/java/net/alawn/bill/service/RoleService.java
new file mode 100644
index 0000000..1da5d2c
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/RoleService.java
@@ -0,0 +1,97 @@
+package net.alawn.bill.service;
+
+import net.alawn.bill.entity.po.Role;
+import net.alawn.bill.service.dto.CommonQueryCriteria;
+import net.alawn.bill.service.dto.RoleDTO;
+import net.alawn.bill.service.dto.RoleSmallDTO;
+import org.springframework.cache.annotation.CacheConfig;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
+import org.springframework.data.domain.Pageable;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * @author Alawn
+ * @date 2018-12-03
+ */
+@CacheConfig(cacheNames = "role")
+public interface RoleService {
+
+ /**
+ * get
+ * @param id
+ * @return
+ */
+ @Cacheable(key = "#p0")
+ RoleDTO findById(long id);
+
+ /**
+ * create
+ * @param resources
+ * @return
+ */
+ @CacheEvict(allEntries = true)
+ RoleDTO create(Role resources);
+
+ /**
+ * update
+ * @param resources
+ */
+ @CacheEvict(allEntries = true)
+ void update(Role resources);
+
+ /**
+ * delete
+ * @param id
+ */
+ @CacheEvict(allEntries = true)
+ void delete(Long id);
+
+ /**
+ * key的名称如有修改,请同步修改 UserServiceImpl 中的 update 方法
+ * findByUser_Id
+ * @param id
+ * @return
+ */
+ @Cacheable(key = "'findByUsers_Id:' + #p0")
+ List findByUsers_Id(Long id);
+
+ @Cacheable(keyGenerator = "keyGenerator")
+ Integer findByRoles(Set roles);
+
+ /**
+ * updatePermission
+ * @param resources
+ * @param roleDTO
+ */
+ @CacheEvict(allEntries = true)
+ void updatePermission(Role resources, RoleDTO roleDTO);
+
+ /**
+ * updateMenu
+ * @param resources
+ * @param roleDTO
+ */
+ @CacheEvict(allEntries = true)
+ void updateMenu(Role resources, RoleDTO roleDTO);
+
+// @CacheEvict(allEntries = true)
+// void untiedMenu(Menu menu);
+
+ /**
+ * queryAll
+ * @param pageable
+ * @return
+ */
+ Object queryAll(Pageable pageable);
+
+ /**
+ * queryAll
+ * @param pageable
+ * @param criteria
+ * @return
+ */
+ Object queryAll(CommonQueryCriteria criteria, Pageable pageable);
+}
diff --git a/src/main/java/net/alawn/bill/service/UserService.java b/src/main/java/net/alawn/bill/service/UserService.java
new file mode 100644
index 0000000..8accc9a
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/UserService.java
@@ -0,0 +1,82 @@
+package net.alawn.bill.service;
+
+import net.alawn.bill.entity.po.User;
+import net.alawn.bill.service.dto.UserDTO;
+import net.alawn.bill.service.dto.UserQueryCriteria;
+import org.springframework.cache.annotation.CacheConfig;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
+import org.springframework.data.domain.Pageable;
+
+/**
+ * @author Alawn
+ * @date 2019-06-21
+ */
+@CacheConfig(cacheNames = "user")
+public interface UserService {
+
+ /**
+ * get
+ * @param id
+ * @return
+ */
+ @Cacheable(key = "#p0")
+ UserDTO findById(long id);
+
+ /**
+ * create
+ * @param resources
+ * @return
+ */
+ @CacheEvict(allEntries = true)
+ UserDTO create(User resources);
+
+ /**
+ * update
+ * @param resources
+ */
+ @CacheEvict(allEntries = true)
+ void update(User resources);
+
+ /**
+ * delete
+ * @param id
+ */
+ @CacheEvict(allEntries = true)
+ void delete(Long id);
+
+ /**
+ * findByPerms
+ * @param userName
+ * @return
+ */
+ @Cacheable(key = "'loadUserByUsername:'+#p0")
+ UserDTO findByName(String userName);
+
+ /**
+ * 修改密码
+ * @param username
+ * @param encryptPassword
+ */
+ @CacheEvict(allEntries = true)
+ void updatePass(String username, String encryptPassword);
+
+ /**
+ * 修改头像
+ * @param username
+ * @param url
+ */
+ @CacheEvict(allEntries = true)
+ void updateAvatar(String username, String url);
+
+ /**
+ * 修改邮箱
+ * @param username
+ * @param email
+ */
+ @CacheEvict(allEntries = true)
+ void updateEmail(String username, String email);
+
+ @Cacheable(keyGenerator = "keyGenerator")
+ Object queryAll(UserQueryCriteria criteria, Pageable pageable);
+}
diff --git a/src/main/java/net/alawn/bill/entity/dto/BillItem.java b/src/main/java/net/alawn/bill/service/dto/BillItem.java
similarity index 70%
rename from src/main/java/net/alawn/bill/entity/dto/BillItem.java
rename to src/main/java/net/alawn/bill/service/dto/BillItem.java
index d573e9e..6f8743a 100644
--- a/src/main/java/net/alawn/bill/entity/dto/BillItem.java
+++ b/src/main/java/net/alawn/bill/service/dto/BillItem.java
@@ -1,4 +1,4 @@
-package net.alawn.bill.entity.dto;
+package net.alawn.bill.service.dto;
import lombok.Data;
@@ -14,7 +14,7 @@ import java.util.Date;
@Data
public class BillItem {
private Date dating ;
- private long titleId ;
- private long merchantId ;
+ private Long titleId ;
+ private Long merchantId ;
private BigDecimal amount ;
}
diff --git a/src/main/java/net/alawn/bill/service/dto/CommonQueryCriteria.java b/src/main/java/net/alawn/bill/service/dto/CommonQueryCriteria.java
new file mode 100644
index 0000000..1168003
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/CommonQueryCriteria.java
@@ -0,0 +1,14 @@
+package net.alawn.bill.service.dto;
+
+import lombok.Data;
+import net.alawn.bill.annotation.Query;
+
+/**
+ * 公共查询类
+ */
+@Data
+public class CommonQueryCriteria {
+
+ @Query(type = Query.Type.INNER_LIKE)
+ private String name;
+}
diff --git a/src/main/java/net/alawn/bill/service/dto/NewBill.java b/src/main/java/net/alawn/bill/service/dto/NewBill.java
new file mode 100644
index 0000000..8053e25
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/NewBill.java
@@ -0,0 +1,51 @@
+package net.alawn.bill.service.dto;
+
+import lombok.Data;
+import net.alawn.bill.entity.po.*;
+import net.alawn.bill.enums.State;
+
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * @Author: Alawn
+ * @Description:
+ * @Date: Create in 10:47 2019-05-23
+ */
+
+@Data
+public class NewBill {
+
+ private long postId ;
+ private List items ;
+ private boolean sendQuick ;
+
+ public Book toBook() {
+
+ Post post = Post.builder().id(postId).build();
+ Book book = Book.builder().applyDate(new Date()).post(post).state(State.Applied).build();
+// book.setApplyDate(new Date());
+// book.setPost(new Post(postId));
+// book.setState(State.Applied);
+
+// List
- items = new ArrayList<>();
+// for(BillItem rq: itemRQs){
+// Item item = new Item();
+// item.setMerchant(new Merchant(rq.getMerchantId()));
+// item.setTitle(new Title(rq.getTitleId()));
+// items.add(item);
+// }
+
+// Item.builder()
+
+// new Item(book,new Title(rq.getTitleId()),new Merchant(rq.getMerchantId()),rq.getDating(),rq.getAmount())
+ /** 使用Java8 的stram写法 */
+ List
- list = items
+ .stream()
+ .map(rq -> Item.builder().book(book).title(Title.builder().id(rq.getTitleId()).build()).amount(rq.getAmount()).dating(rq.getDating()).merchant(Merchant.builder().id(rq.getMerchantId()).build()).build())
+ .collect(Collectors.toList());
+ book.setItems(list);
+ return book;
+ }
+}
diff --git a/src/main/java/net/alawn/bill/entity/dto/NewMerchant.java b/src/main/java/net/alawn/bill/service/dto/NewMerchant.java
similarity index 90%
rename from src/main/java/net/alawn/bill/entity/dto/NewMerchant.java
rename to src/main/java/net/alawn/bill/service/dto/NewMerchant.java
index 8c71d4f..5c4467b 100644
--- a/src/main/java/net/alawn/bill/entity/dto/NewMerchant.java
+++ b/src/main/java/net/alawn/bill/service/dto/NewMerchant.java
@@ -1,4 +1,4 @@
-package net.alawn.bill.entity.dto;
+package net.alawn.bill.service.dto;
import lombok.Data;
import net.alawn.bill.entity.po.Merchant;
diff --git a/src/main/java/net/alawn/bill/entity/dto/NewPost.java b/src/main/java/net/alawn/bill/service/dto/NewPost.java
similarity index 53%
rename from src/main/java/net/alawn/bill/entity/dto/NewPost.java
rename to src/main/java/net/alawn/bill/service/dto/NewPost.java
index 7da4b58..ecfbcda 100644
--- a/src/main/java/net/alawn/bill/entity/dto/NewPost.java
+++ b/src/main/java/net/alawn/bill/service/dto/NewPost.java
@@ -1,7 +1,6 @@
-package net.alawn.bill.entity.dto;
+package net.alawn.bill.service.dto;
import lombok.Data;
-import net.alawn.bill.entity.po.Post;
/**
* @Author: Alawn
@@ -14,8 +13,4 @@ public class NewPost {
private String address ;
private String contact ;
private String mobile ;
-
- public Post build() {
- return Post.builder().address(address).contact(contact).mobile(mobile).build();
- }
}
diff --git a/src/main/java/net/alawn/bill/entity/dto/NewTitle.java b/src/main/java/net/alawn/bill/service/dto/NewTitle.java
similarity index 85%
rename from src/main/java/net/alawn/bill/entity/dto/NewTitle.java
rename to src/main/java/net/alawn/bill/service/dto/NewTitle.java
index 3b7e23c..e265209 100644
--- a/src/main/java/net/alawn/bill/entity/dto/NewTitle.java
+++ b/src/main/java/net/alawn/bill/service/dto/NewTitle.java
@@ -1,10 +1,8 @@
-package net.alawn.bill.entity.dto;
+package net.alawn.bill.service.dto;
import lombok.Data;
import net.alawn.bill.entity.po.Title;
-import java.util.List;
-
/**
* @Author: Alawn
* @Description:
diff --git a/src/main/java/net/alawn/bill/service/dto/PermissionDTO.java b/src/main/java/net/alawn/bill/service/dto/PermissionDTO.java
new file mode 100644
index 0000000..3dcafcb
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/PermissionDTO.java
@@ -0,0 +1,30 @@
+package net.alawn.bill.service.dto;
+
+import lombok.Data;
+import lombok.ToString;
+
+import java.io.Serializable;
+import java.sql.Timestamp;
+import java.util.List;
+
+/**
+ * @author Alawn
+ * @date 2019-06-21
+ */
+@Data
+@ToString
+public class PermissionDTO implements Serializable{
+
+ private Long id;
+
+ private String perms;
+
+ private Long pid;
+
+ private String alias;
+
+ private Timestamp createTime;
+
+ private List children;
+
+}
diff --git a/src/main/java/net/alawn/bill/service/dto/RoleDTO.java b/src/main/java/net/alawn/bill/service/dto/RoleDTO.java
new file mode 100644
index 0000000..4553fea
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/RoleDTO.java
@@ -0,0 +1,29 @@
+package net.alawn.bill.service.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.sql.Timestamp;
+import java.util.Set;
+
+/**
+ * @author Alawn
+ * @date 2018-11-23
+ */
+@Data
+public class RoleDTO implements Serializable {
+
+ private Long id;
+
+ private String name;
+
+ private String dataScope;
+
+ private Integer level;
+
+ private String remark;
+
+ private Set permissions;
+
+ private Timestamp createTime;
+}
diff --git a/src/main/java/net/alawn/bill/service/dto/RoleSmallDTO.java b/src/main/java/net/alawn/bill/service/dto/RoleSmallDTO.java
new file mode 100644
index 0000000..1dad989
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/RoleSmallDTO.java
@@ -0,0 +1,16 @@
+package net.alawn.bill.service.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * @author Alawn
+ * @date 2018-06-21
+ */
+@Data
+public class RoleSmallDTO implements Serializable {
+ private Long id;
+ private String name;
+ private Integer level;
+}
diff --git a/src/main/java/net/alawn/bill/service/dto/UserDTO.java b/src/main/java/net/alawn/bill/service/dto/UserDTO.java
new file mode 100644
index 0000000..44b2e73
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/UserDTO.java
@@ -0,0 +1,33 @@
+package net.alawn.bill.service.dto;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Builder;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Set;
+
+@Builder
+@Data
+public class UserDTO implements Serializable {
+
+ @ApiModelProperty(hidden = true)
+ private Long id;
+
+ private String username;
+ private String fullname;
+ private String avatar;
+ private String phone;
+ private String email;
+ private Date createTime;
+ private Date lastPasswordResetDate;
+
+ @JsonIgnore
+ private String password;
+ private Boolean enabled;
+
+ @ApiModelProperty(hidden = true)
+ private Set roles;
+}
diff --git a/src/main/java/net/alawn/bill/service/dto/UserQueryCriteria.java b/src/main/java/net/alawn/bill/service/dto/UserQueryCriteria.java
new file mode 100644
index 0000000..17cb6f3
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/dto/UserQueryCriteria.java
@@ -0,0 +1,29 @@
+package net.alawn.bill.service.dto;
+
+import lombok.Data;
+import net.alawn.bill.annotation.Query;
+
+import java.io.Serializable;
+
+/**
+ * @author Alawn
+ * @date 2019-06-21
+ */
+@Data
+public class UserQueryCriteria implements Serializable {
+ @Query
+ private Long id;
+// @Query(propName = "id", type = Query.Type.IN, joinName = "dept")
+// private Set deptIds;
+
+ @Query(type = Query.Type.INNER_LIKE)
+ private String username;
+
+ @Query(type = Query.Type.INNER_LIKE)
+ private String email;
+
+ @Query
+ private Boolean enabled;
+
+// private Long deptId;
+}
diff --git a/src/main/java/net/alawn/bill/service/impl/AuthServiceImpl.java b/src/main/java/net/alawn/bill/service/impl/AuthServiceImpl.java
index 38b9d7d..3d1738a 100644
--- a/src/main/java/net/alawn/bill/service/impl/AuthServiceImpl.java
+++ b/src/main/java/net/alawn/bill/service/impl/AuthServiceImpl.java
@@ -1,31 +1,23 @@
package net.alawn.bill.service.impl;
import lombok.extern.slf4j.Slf4j;
-import net.alawn.bill.entity.dto.NewUser;
-import net.alawn.bill.entity.po.Authority;
-import net.alawn.bill.entity.po.AuthorityId;
-import net.alawn.bill.entity.po.User;
-import net.alawn.bill.exception.CommonException;
-import net.alawn.bill.exception.RespMsg;
import net.alawn.bill.repository.AuthorityRepo;
import net.alawn.bill.repository.UserRepo;
-import net.alawn.bill.security.AuthUser;
+import net.alawn.bill.security.JwtUser;
import net.alawn.bill.security.JwtTokenUtil;
import net.alawn.bill.service.AuthService;
-import net.alawn.bill.util.AesEncryptUtil;
+import net.alawn.bill.service.dto.UserDTO;
+import net.alawn.bill.util.AesEncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
-import org.springframework.util.StringUtils;
/**
@@ -42,7 +34,7 @@ public class AuthServiceImpl implements AuthService {
@Autowired
private AuthenticationManager authenticationManager;
- @Qualifier("authUserDetailsService")
+ @Qualifier("jwtUserDetailsService")
@Autowired
private UserDetailsService userDetailsService;
@@ -59,43 +51,55 @@ public class AuthServiceImpl implements AuthService {
private AuthorityRepo authorityRepo;
+ @Autowired
+ private UserServiceImpl userService;
+
// @Autowired
// public AuthServiceImpl(AuthenticationManager authenticationManager) {
// this.authenticationManager = authenticationManager;
// }
- @Override
- public NewUser register(NewUser userDTO) throws AuthenticationException {
- log.info("AuthServiceImpl.register start");
- log.info("userDTO:" + userDTO);
- final String username = userDTO.getUsername();
-
- if(userRepo.findByUsername(username) != null) {
- throw new CommonException(RespMsg.USER_ALREADY_EXIST);
- }
-
- BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
-
-// final String rawPassword = userDTO.getPassword();
- final String password = AesEncryptUtil.decrypt(userDTO.getPassword());
-
- User user = User.builder()
- .username(username)
- .password(encoder.encode(password)).build();
-// .password(userDTO.getPassword()).build();
- User saved = userRepo.save(user);
- Authority savedAuth = authorityRepo.save(
- Authority.builder()
- .user(saved)
- .id(AuthorityId.builder()
- .userId(saved.getId())
- .authority("ROLE_USER")
- .build())
- .build());
- userRepo.flush();
- authorityRepo.flush();
- return userDTO;
- }
+// @Override
+// public UserDTO register(UserDTO userDTO) throws AuthenticationException {
+// log.info("AuthServiceImpl.register start");
+// log.info("userDTO:" + userDTO);
+// final String username = userDTO.getUsername();
+//
+// if(userRepo.findByUsername(username) != null) {
+// throw new CommonException(RespMsg.USER_ALREADY_EXIST);
+// }
+//
+// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
+//
+//// final String rawPassword = userDTO.getPassword();
+// final String password = AesEncryptUtils.decrypt(userDTO.getPassword());
+//
+// User user = User.builder()
+// .username(username)
+// .password(encoder.encode(password)).build();
+//// .password(userDTO.getPassword()).build();
+//
+//
+//
+//
+//// return ResponseEntity.ok(userService.create(user));
+//// User saved = userRepo.save(user);
+////
+////
+////
+////
+//// Authority savedAuth = authorityRepo.save(
+//// Authority.builder()
+//// .user(saved)
+//// .id(AuthorityId.builder()
+//// .userId(saved.getId())
+//// .authority("ROLE_USER")
+//// .build())
+//// .build());
+//// userRepo.flush();
+//// authorityRepo.flush();
+//// return userDTO;
+// }
@Override
@@ -108,7 +112,7 @@ public class AuthServiceImpl implements AuthService {
// }
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
- password = AesEncryptUtil.decrypt(password);
+ password = AesEncryptUtils.decrypt(password);
UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
final Authentication authentication = authenticationManager.authenticate(upToken);
@@ -128,14 +132,14 @@ public class AuthServiceImpl implements AuthService {
public String refresh(String oldToken) {
final String token = oldToken.substring(tokenHead.length());
String username = jwtTokenUtil.getUsernameFromToken(token);
- AuthUser user = (AuthUser)userDetailsService.loadUserByUsername(username);
+ JwtUser user = (JwtUser)userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())){
return jwtTokenUtil.refreshToken(token);
}
return null;
}
- private void authenticateUser(NewUser userDTO) {
+ private void authenticateUser(UserDTO userDTO) {
UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDTO.getUsername(), userDTO.getPassword());
// 进行安全认证
final Authentication authentication = authenticationManager.authenticate(upToken);
diff --git a/src/main/java/net/alawn/bill/service/impl/PermissionServiceImpl.java b/src/main/java/net/alawn/bill/service/impl/PermissionServiceImpl.java
new file mode 100644
index 0000000..320d908
--- /dev/null
+++ b/src/main/java/net/alawn/bill/service/impl/PermissionServiceImpl.java
@@ -0,0 +1,153 @@
+package net.alawn.bill.service.impl;
+
+import lombok.extern.slf4j.Slf4j;
+import net.alawn.bill.entity.po.Permission;
+import net.alawn.bill.exception.BadRequestException;
+import net.alawn.bill.exception.EntityExistException;
+import net.alawn.bill.mapper.PermissionMapper;
+import net.alawn.bill.repository.PermissionRepo;
+import net.alawn.bill.service.PermissionService;
+import net.alawn.bill.service.dto.CommonQueryCriteria;
+import net.alawn.bill.service.dto.PermissionDTO;
+import net.alawn.bill.util.QueryHelp;
+import net.alawn.bill.util.ValidationUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.*;
+
+/**
+ * @author Alawn
+ * @date 2018-12-03
+ */
+@Slf4j
+@Service
+@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
+public class PermissionServiceImpl implements PermissionService {
+
+ @Autowired
+ private PermissionRepo permissionRepo;
+
+// @Resource
+// private PermissionMapper permissionMapper;
+
+ @Override
+ public List queryAll(CommonQueryCriteria criteria) {
+// return permissionMapper.toDto(permissionRepo.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
+
+
+ List list = permissionRepo.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
+ log.info("Permission.list:" + list);
+ List dto = PermissionMapper.INSTANCE.toDto(list);
+ log.info("PermissionDTO.list:" + dto);
+ return dto;
+// return PermissionMapper.INSTANCE.toDto(list);
+// return PermissionMapper.INSTANCE.toDto(permissionRepo.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
+ }
+
+ @Override
+ public PermissionDTO findById(long id) {
+ Optional permission = permissionRepo.findById(id);
+ ValidationUtils.isNull(permission,"Permission","id",id);
+// return permissionMapper.toDto(permission.get());
+ return PermissionMapper.INSTANCE.toDto(permission.get());
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public PermissionDTO create(Permission resources) {
+ if(permissionRepo.findByPerms(resources.getPerms()) != null){
+ throw new EntityExistException(Permission.class,"name",resources.getPerms());
+ }
+// return permissionMapper.toDto(permissionRepo.save(resources));
+ return PermissionMapper.INSTANCE.toDto(permissionRepo.save(resources));
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public void update(Permission resources) {
+ Optional optionalPermission = permissionRepo.findById(resources.getId());
+ if(resources.getId().equals(resources.getPid())) {
+ throw new BadRequestException("上级不能为自己");
+ }
+ ValidationUtils.isNull(optionalPermission,"Permission","id",resources.getId());
+
+ Permission permission = optionalPermission.get();
+
+ Permission permission1 = permissionRepo.findByPerms(resources.getPerms());
+
+ if(permission1 != null && !permission1.getId().equals(permission.getId())){
+ throw new EntityExistException(Permission.class,"name",resources.getPerms());
+ }
+
+ permission.setPerms(resources.getPerms());
+ permission.setAlias(resources.getAlias());
+ permission.setPid(resources.getPid());
+ permissionRepo.save(permission);
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public void delete(Long id) {
+ List permissionList = permissionRepo.findByPid(id);
+ for (Permission permission : permissionList) {
+ permissionRepo.delete(permission);
+ }
+ permissionRepo.deleteById(id);
+ }
+
+ @Override
+ public Object getPermissionTree(List permissions) {
+ List