完成Bean改造

This commit is contained in:
2019-05-30 21:17:08 +08:00
parent 707ee18ba0
commit 9b5d2ec4e5
39 changed files with 949 additions and 405 deletions
@@ -34,7 +34,7 @@ public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Book API")
.title("BookVO API")
.description("Bill接口")
.termsOfServiceUrl("http://fairy8.cn")
.contact(new Contact("Alawn","fairy8.cn","alawn.cn@gmail.com"))
@@ -93,7 +93,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/druid/**").permitAll()
.antMatchers("/test/**").permitAll() // 测试用
.antMatchers("/druid/**").permitAll() // 阿里Druid
.antMatchers("/swagger*").permitAll()
.antMatchers( HttpMethod.GET, "/","/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
// .antMatchers("/resources/**").permitAll()
@@ -170,5 +171,4 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// // 使用自定义身份验证组件
// auth.authenticationProvider(new CustomAuthenticationProvider(userDetailsService));
// }
}
@@ -1,6 +1,6 @@
package net.alawn.bill.controller;
import net.alawn.bill.entity.dto.AddUser;
import net.alawn.bill.entity.dto.NewUser;
import net.alawn.bill.security.JwtAuthenticationRequest;
import net.alawn.bill.security.JwtAuthenticationResponse;
import net.alawn.bill.service.AuthService;
@@ -52,7 +52,7 @@ public class AuthController {
}
@RequestMapping(value = "/auth/register", method = RequestMethod.POST)
public AddUser register(@RequestBody AddUser addedUser) throws AuthenticationException, HttpRequestMethodNotSupportedException {
public NewUser register(@RequestBody NewUser addedUser) throws AuthenticationException, HttpRequestMethodNotSupportedException {
return authService.register(addedUser);
}
}
@@ -1,9 +1,9 @@
package net.alawn.bill.controller;
import lombok.extern.slf4j.Slf4j;
import net.alawn.bill.entity.dto.AddMerchant;
import net.alawn.bill.entity.dto.AddPost;
import net.alawn.bill.entity.dto.AddTitle;
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;
@@ -12,7 +12,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.List;
@@ -50,12 +49,12 @@ public class BasicController {
@RequestMapping(value = "/posts",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Post> addPost(@RequestBody AddPost addPost, Principal principal) throws URISyntaxException {
public ResponseEntity<Post> addPost(@RequestBody NewPost newPost, Principal principal) throws URISyntaxException {
AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = authUser.getId();
/** 登记 Post */
Post post = addPost.build();
Post post = newPost.build();
post.setUserId(userId);
postRepo.save(post);
postRepo.flush();
@@ -91,9 +90,9 @@ public class BasicController {
@RequestMapping(value = "/merchants",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Merchant> addMerchant(@RequestBody AddMerchant addMerchant) throws URISyntaxException {
public ResponseEntity<Merchant> addMerchant(@RequestBody NewMerchant newMerchant) throws URISyntaxException {
/** 登记 Post */
Merchant merchant = merchantRepo.save(addMerchant.build());
Merchant merchant = merchantRepo.save(newMerchant.build());
merchantRepo.flush();
return ResponseEntity.ok(merchant);
}
@@ -121,9 +120,9 @@ public class BasicController {
@RequestMapping(value = "/titles",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Title> addTitle(@RequestBody AddTitle addTitle) {
public ResponseEntity<Title> addTitle(@RequestBody NewTitle newTitle) {
/** 登记 Title */
Title title = titleRepo.save(addTitle.build());
Title title = titleRepo.save(newTitle.build());
titleRepo.flush();
return ResponseEntity.ok(title);
}
@@ -1,9 +1,9 @@
package net.alawn.bill.controller;
import net.alawn.bill.entity.dto.AddBill;
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.Item;
import net.alawn.bill.enums.State;
import net.alawn.bill.entity.po.User;
import net.alawn.bill.repository.BookRepo;
import net.alawn.bill.repository.ItemRepo;
import net.alawn.bill.repository.UserRepo;
@@ -13,10 +13,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
@@ -26,7 +23,8 @@ import java.util.stream.Collectors;
*/
@RequestMapping(value = "/bills")
@Slf4j
@RequestMapping(value = "/bill")
@RestController
public class BillController {
@@ -39,24 +37,34 @@ public class BillController {
@Autowired
UserRepo userRepo;
@RequestMapping(value = "/",method = RequestMethod.POST)
public ResponseEntity<Book> addBook(@RequestBody AddBill addBill, Principal principal){
@RequestMapping(value = "/books",method = RequestMethod.POST)
public ResponseEntity<Book> newBook(@RequestBody NewBill newBill){
AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = authUser.getId();
/** 登记 book */
Book book = bookRepo.save(new Book(userId, addBill.getPostId(), State.APPLIED,new Date(),null));
log.info("newBill:" + newBill);
/** DTO -> PO 转换 */
List<Item> items = addBill.getBillItems()
.stream()
.map(bill -> new Item(book.getId(),bill.getDating(),bill.getTitleId(),bill.getMerchantId(),bill.getAmount()))
.collect(Collectors.toList());
Book book = newBill.toBook();
/** 登记 item */
itemRepo.saveAll(items);
book.setUser(new User(userId));
log.info("book:" + book);
bookRepo.save(book);
log.info("book:" + book);
bookRepo.flush();
itemRepo.flush();
bookRepo.sumAmount(book.getId());
return ResponseEntity.ok(book);
}
@RequestMapping(value = "/books",method = RequestMethod.GET)
public ResponseEntity<List<Book>> fetchBooks(){
AuthUser authUser = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = authUser.getId();
List<Book> books = bookRepo.findByUserId(userId);
return ResponseEntity.ok(books);
}
}
@@ -0,0 +1,147 @@
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<Detail> details = new HashSet() ;
// List<Detail> 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<Main> 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<Main> 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<List<Main>> mains(){
List<Main> result = mainRepo.findAll();
log.info("result.size:" + result.size());
return ResponseEntity.ok(result);
}
@RequestMapping(value = "/details",method = RequestMethod.GET)
public ResponseEntity<List<Detail>> details(){
List<Detail> result = detailRepo.findAll();
log.info("result.size:" + result.size());
// log.info("result:" + JSON.toJSONString(result,true));
log.info("result:" + result);
return ResponseEntity.ok(result);
}
}
@@ -1,17 +0,0 @@
package net.alawn.bill.entity.dto;
import lombok.Data;
import java.util.List;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 10:47 2019-05-23
*/
@Data
public class AddBill {
private long postId;
List<BillItem> billItems;
}
@@ -13,8 +13,8 @@ import java.util.Date;
@Data
public class BillItem {
private Date dating;
private long titleId;
private long merchantId;
private BigDecimal amount;
private Date dating ;
private long titleId ;
private long merchantId ;
private BigDecimal amount ;
}
@@ -0,0 +1,48 @@
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<BillItem> billItems ;
public Book toBook() {
Book book = new Book();
book.setApplyDate(new Date());
book.setPost(new Post(postId));
book.setState(State.APPLIED);
// List<Item> 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<Item> 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;
}
}
@@ -9,7 +9,7 @@ import net.alawn.bill.entity.po.Merchant;
* @Date: Create in 15:21 2019-05-23
*/
@Data
public class AddMerchant {
public class NewMerchant {
private String abbr;
private String name;
@@ -10,7 +10,7 @@ import net.alawn.bill.entity.po.Post;
*/
@Data
public class AddPost {
public class NewPost {
private String address ;
private String contact ;
private String mobile ;
@@ -12,7 +12,7 @@ import java.util.List;
*/
@Data
public class AddTitle {
public class NewTitle {
private String name;
private String abbr;
private String taxNo;
@@ -6,7 +6,7 @@ import net.alawn.bill.entity.po.User;
@Value
@Builder
public class AddUser {
public class NewUser {
private String username;
private String password;
@@ -1,6 +1,8 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
@@ -14,7 +16,9 @@ import java.io.Serializable;
@ToString(exclude = {"user"})
@NoArgsConstructor
@AllArgsConstructor
public class Authority{
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class Authority implements Serializable{
@EmbeddedId
private AuthorityId id;
@@ -1,13 +1,16 @@
package net.alawn.bill.entity.po;
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.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import java.util.Date;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.*;
/**
* @Author: Alawn
@@ -22,14 +25,40 @@ import java.util.Date;
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Book extends Base{
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class Book extends EntityId {
@JsonIgnore
@ManyToOne
@NotFound(action= NotFoundAction.IGNORE)
@JoinColumn(name = "userId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
private User user;
private long userId;
private long postId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "postId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
@NotFound(action= NotFoundAction.IGNORE)
private Post post;
@OneToMany(cascade=CascadeType.ALL, mappedBy = "book", orphanRemoval = true)
@org.hibernate.annotations.ForeignKey(name = "none")
@NotFound(action= NotFoundAction.IGNORE)
private List<Item> items = new ArrayList<>();
@Enumerated(EnumType.STRING)
private State state;
private Date applyDate;
private Date acceptDate;
private Date applyDate ;
private Date acceptDate ;
private BigDecimal totalAmount ;
public void addItem(Item item) {
item.setBook(this);
this.items.add(item);
}
public void removeItem(Item item) {
item.setBook(null);
items.remove(item);
}
}
@@ -0,0 +1,97 @@
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;
}
}
@@ -1,16 +1,14 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.experimental.Accessors;
import net.alawn.bill.security.AuthUser;
import org.springframework.data.annotation.*;
import org.springframework.data.annotation.Version;
import org.springframework.data.annotation.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.persistence.*;
import javax.persistence.Id;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@@ -20,15 +18,14 @@ import java.util.Date;
@Data
@MappedSuperclass
@Accessors(chain = true)
@EntityListeners(AuditingEntityListener.class)
public class Base implements Serializable {
private static final long serialVersionUID = 1L;
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
public class EntityId implements Serializable {
protected static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
protected Long id;
// @Temporal(TemporalType.TIMESTAMP)
// @CreationTimestamp
@@ -61,5 +58,15 @@ public class Base implements Serializable {
protected Long version;
// @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;
// }
}
@@ -1,9 +1,13 @@
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 org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
@@ -15,14 +19,46 @@ import java.util.Date;
@Entity
@Table(name = "t_bill_items")
@Data
@ToString(callSuper = true)
@ToString(exclude = {"book"})
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Item extends Base{
private long bookId;
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class Item extends EntityId {
public Item(Book book)
{ this.book = book; }
/** OK */
@JsonIgnore
@ManyToOne(fetch= FetchType.LAZY,cascade = CascadeType.MERGE,optional = false)
@JoinColumn(name = "bookId",referencedColumnName = "id",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
private Book book;
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="titleId",foreignKey = @ForeignKey(name = "none",value = ConstraintMode.NO_CONSTRAINT))
@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)
private Merchant merchant;
private Date dating;
private long titleId;
private long merchantId;
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);
}
@Override
public int hashCode() {
return 31;
}
}
@@ -0,0 +1,88 @@
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<Detail> details = new ArrayList<>();
// @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
// private Set<Authority> 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);
}
}
@@ -1,5 +1,6 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import javax.persistence.Entity;
@@ -17,7 +18,12 @@ import javax.persistence.Table;
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Merchant extends Base{
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
public class Merchant extends EntityId {
public Merchant(long id) {
this.id = id;
}
private String abbr;
private String name;
}
@@ -1,9 +1,11 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.Accessors;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@@ -17,10 +19,18 @@ import javax.persistence.Table;
@Table(name = "t_bill_posts")
@Data
@ToString(callSuper = true)
@Accessors(chain = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Post extends Base{
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class Post extends EntityId {
public Post(long id) {
this.id = id;
}
@JsonIgnore
private long userId ;
private String address ;
@@ -1,6 +1,8 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
@@ -17,10 +19,15 @@ import javax.persistence.*;
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Title extends Base{
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class Title extends EntityId {
private String name;
private String abbr;
@Column(length = 18)
private String taxNo;
public Title(long id) {
this.id = id;
}
}
@@ -1,18 +1,15 @@
package net.alawn.bill.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author Alawn
@@ -32,7 +29,13 @@ import java.util.stream.Collectors;
@AllArgsConstructor
@ToString(exclude = {"authorities"})
@Slf4j
public class User extends Base {
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" },ignoreUnknown = true)
@DynamicUpdate
public class User extends EntityId {
public User(long id) {
this.id = id;
}
/** 用户名称 */
private String username;
@@ -62,6 +65,7 @@ public class User extends Base {
@Builder.Default
private boolean enabled = true;
// public UserDetails toUserDetails() {
// log.info("toUserDetails.authorities:" + authorities);
// log.info("toUserDetails.authorities:" + mapToGrantedAuthorities(authorities));
@@ -0,0 +1,9 @@
package net.alawn.bill.entity.vo;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 10:01 2019-05-29
*/
public class BookVO {
}
@@ -0,0 +1,9 @@
package net.alawn.bill.entity.vo;
/**
* @Author: Alawn
* @Description:
* @Date: Create in 10:02 2019-05-29
*/
public class ItemVO {
}
@@ -2,7 +2,12 @@ package net.alawn.bill.repository;
import net.alawn.bill.entity.po.Book;
import org.springframework.data.jpa.repository.JpaRepository;
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
@@ -10,7 +15,13 @@ import org.springframework.stereotype.Repository;
* @Date: Create in 11:14 2019-05-23
*/
@Transactional
@Repository
public interface BookRepo extends JpaRepository<Book, Long> {
List<Book> findByUserId(long userId);
@Modifying
@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);
}
@@ -0,0 +1,17 @@
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<Detail, Long> {
}
@@ -4,6 +4,8 @@ import net.alawn.bill.entity.po.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
/**
* @Author: Alawn
* @Description:
@@ -0,0 +1,19 @@
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<Main, Long> {
List<Main> findByPost(Post post);
}
@@ -1,5 +1,6 @@
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;
@@ -13,6 +14,7 @@ import org.springframework.stereotype.Service;
* @Description:
* @Date: Create in 16:46 2019-05-20
*/
@Slf4j
@Service("authUserDetailsService")
public class AuthUserDetailsServiceImpl implements UserDetailsService {
@@ -24,6 +26,8 @@ public class AuthUserDetailsServiceImpl implements UserDetailsService {
User user = userRepo.findByUsername(name);
log.info("loadUserByUsername:" + user);
if (user == null) {
throw new UsernameNotFoundException("UsernameNotFoundException");
} else {
@@ -1,6 +1,6 @@
package net.alawn.bill.service;
import net.alawn.bill.entity.dto.AddUser;
import net.alawn.bill.entity.dto.NewUser;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
@@ -10,7 +10,7 @@ import org.springframework.web.HttpRequestMethodNotSupportedException;
* @Date: Create in 15:58 2019-05-20
*/
public interface AuthService {
AddUser register(AddUser userDTO) throws HttpRequestMethodNotSupportedException, AuthenticationException;
NewUser register(NewUser userDTO) throws HttpRequestMethodNotSupportedException, AuthenticationException;
String login(String username, String password);
String refresh(String oldToken);
}
@@ -1,6 +1,6 @@
package net.alawn.bill.service.impl;
import net.alawn.bill.entity.dto.AddUser;
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;
@@ -61,7 +61,7 @@ public class AuthServiceImpl implements AuthService {
// }
@Override
public AddUser register(AddUser userDTO) throws AuthenticationException {
public NewUser register(NewUser userDTO) throws AuthenticationException {
final String username = userDTO.getUsername();
if(userRepo.findByUsername(username) != null) {
@@ -110,7 +110,7 @@ public class AuthServiceImpl implements AuthService {
return null;
}
private void authenticateUser(AddUser userDTO) {
private void authenticateUser(NewUser userDTO) {
UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDTO.getUsername(), userDTO.getPassword());
// 进行安全认证
final Authentication authentication = authenticationManager.authenticate(upToken);
+78
View File
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<jmxConfigurator />
<property name="logBase" value="/tmp/logs"/>
<property name="appName" value="bill"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%red(%d{yyyy-MM-dd HH:mm:ss.SSS}) %green([%thread]) %yellow([%X{TRACE_ID}]) %highlight(%-5level) %boldMagenta(%logger{36}) [%line] - %cyan(%msg%n)</pattern>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logBase}/${appName}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logBase}/${appName}-%d{yyyy-MM-dd}.log.%i</fileNamePattern>
<MaxHistory>30</MaxHistory>
<TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<MaxFileSize>100MB</MaxFileSize>
</TimeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%X{TRACE_ID}] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE-error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logBase}/${appName}.err</file>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logBase}/${appName}-error-%d{yyyy-MM-dd}.log.%i</fileNamePattern>
<MaxHistory>30</MaxHistory>
<TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<MaxFileSize>50MB</MaxFileSize>
</TimeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%X{TRACE_ID}] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="druid" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${logBase}/${appName}-druid.log</File>
<encoder>
<pattern>%d [%level] [%thread] %logger{15}:%line %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logBase}/${appName}-druid.log.%d{yyyy-MM-dd}</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<appender name="druid-queue" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>512</queueSize>
<appender-ref ref="druid"/>
</appender>
<logger name="druid.sql.DataSource" level="WARN" additivity="false">
<appender-ref ref="druid-queue"/>
</logger>
<logger name="druid.sql.Connection" level="WARN" additivity="false">
<appender-ref ref="druid-queue"/>
</logger>
<logger name="druid.sql.Statement" level="DEBUG" additivity="false">
<appender-ref ref="druid-queue"/>
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
<appender-ref ref="FILE-error" />
</root>
</configuration>
+1 -1
View File
@@ -53,7 +53,7 @@ export const getPost = (id) => {
export const newBill = (bill) => {
return HttpRequest.request({
url: 'bills/',
url: 'bill/books',
method: 'post',
data: bill
})
+5
View File
@@ -25,6 +25,11 @@ export default new Router({
path: '/bill',
name: 'Bill',
component: () => import(/* webpackChunkName: "merchant" */ '../views/Bill.vue')
},
{
path: '/gird',
name: 'Gird',
component: () => import(/* webpackChunkName: "merchant" */ '../views/Gird.vue')
}
]
})
+27 -4
View File
@@ -288,7 +288,7 @@
<script>
import {
addPost,
newPost,
fetchPosts,
getPost,
fetchTitles,
@@ -411,13 +411,36 @@ export default {
},
onSubmit(formName) {
this.$refs[formName].validate(valid => {
var _this = this;
if (valid) {
console.info("bill:" + JSON.stringify(this.bill));
newBill(this.bill).then(function(response) {
newBill(this.bill).then(response=> {
this.$message({ message: "提交成功", type: "success" });
// this.disabled = true;
console.info("response:" + response);
})
.catch(function(error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
_this.$message({ message: 'status:' + error.response.status + ',message:' + error.response.data.message, type: 'error' });
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
// _this.$message.error(error.request);
console.log(error.request);
_this.$message.error('未知错误');
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error", error.message);
_this.$message.error(error.response.message);
}
console.log(error.config);
});
this.disabled = true;
this.$message({ message: "提交成功", type: "success" });
} else {
console.log("error submit!!");
return false;
+185 -294
View File
@@ -1,202 +1,49 @@
<template>
<div class="main">
<div class="group">
<!-- <el-form ref="form" :model="form" :rules="rules" label-width="80px"> -->
<!-- <el-form ref="form" :model="form" label-width="800px"> -->
<el-form ref="billForm" :model="bill" :rules="rules" label-width="80px">
<el-form-item label="邮寄地址" prop="postContact">
<!--邮寄地址-->
<el-autocomplete
class="posts"
popper-class="my-autocomplete"
v-model="bill.postContact"
:fetch-suggestions="querySearchAsyncPosts"
placeholder="请输选择邮寄地址"
@select="handleSelectPosts" :disabled="disabled">
<i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClickPosts"></i>
<template slot-scope="{ item }">
<div class="name">{{ item.contact }}</div>
<span class="subtitle">{{ item.address }}</span>
<span class="subtitle">;</span>
<span class="subtitle">{{ item.mobile }}</span>
<span class="subtitle">;</span>
</template>
</el-autocomplete>
</el-form-item>
<div class="gTable">
<!--增删改查-->
<!--明细-->
<!-- <el-form-item label="明细" prop="username"> -->
<!--分割线-->
<!-- <span><el-divider></el-divider></span> -->
<el-table :data="bill.billItems" height="400px" style="width: 100%">
<el-table-column prop="dating" label="日期" width="100" ></el-table-column>
<el-table-column prop="titleAbbr" label="抬头" width="150">
<template slot-scope="scope">
<el-popover trigger="hover" placement="top">
<p>税号: {{ scope.row.taxNo }}</p>
<p>抬头: {{ scope.row.titleName }}</p>
<div slot="reference" class="name-wrapper">
<el-tag size="medium">{{ scope.row.titleAbbr }}</el-tag>
</div>
</el-popover>
</template>
</el-table-column>
<el-table-column prop="merchantAbbr" label="餐饮商户" width="150" ></el-table-column>
<el-table-column prop="amount" label="金额" width="80" ></el-table-column>
<el-table-column align="right" >
<template slot="header" slot-scope="scope">
<!-- <el-button class="itemBtn" type="primary" size="medium" @click="clearFocusRow();isAddShow = true;resetForm('addForm');" :disabled="disabled">添加</el-button> -->
<el-button class="itemBtn" type="primary" size="small" @click="clearFocusRow();isAddShow = true;resetForm('addForm');" :disabled="disabled">添加</el-button>
</template>
<template slot-scope="scope">
<el-button-group>
<!-- type="success" -->
<el-button
size="mini"
icon="el-icon-edit"
@click="handleEdit(scope.$index, scope.row)" :disabled="disabled">编辑</el-button>
<!-- type="danger" -->
<el-button
size="mini"
icon="el-icon-delete"
@click.native.prevent="handleDelete(scope.$index,bill.billItems)" :disabled="disabled">删除</el-button>
</el-button-group>
</template>
</el-table-column>
</el-table>
<!-- </el-form-item> -->
</div>
<el-form-item label-width="2px">
<el-button class="submit" type="primary" @click="onSubmit('billForm')" :disabled="disabled">提交</el-button>
</el-form-item>
</el-form>
<div class="gTable">
<el-table :data="book" height="400px" style="width: 100%">
<el-table-column prop="applyDate" label="申请日期" width="150"></el-table-column>
<el-table-column prop="totalAmount" label="总金额" width="100"></el-table-column>
<el-table-column prop="post.contact" label="快递地址" width="100">
<template slot-scope="scope">
<el-popover trigger="hover" placement="right">
<p>手机: {{ scope.row.post.mobile }}</p>
<p>地址: {{ scope.row.post.address }}</p>
<div slot="reference" class="name-wrapper">
<el-tag size="medium">{{ scope.row.post.contact }}</el-tag>
</div>
</el-popover>
</template>
</el-table-column>
<!-- <el-table-column prop="titleAbbr" label="抬头" width="150">
<template slot-scope="scope">
<el-popover trigger="hover" placement="top">
<p>税号: {{ scope.row.taxNo }}</p>
<p>抬头: {{ scope.row.titleName }}</p>
<div slot="reference" class="name-wrapper">
<el-tag size="medium">{{ scope.row.titleAbbr }}</el-tag>
</div>
</el-popover>
</template>
</el-table-column>-->
<!-- <el-table-column prop="amount" label="金额" width="80"></el-table-column> -->
</el-table>
<!-- </el-form-item> -->
</div>
<!--增加-->
<div width="600px">
<el-dialog title="增加" :visible.sync="isAddShow" width="700px" >
<el-form ref="addForm" :model="focusRow" :rules="rules" label-width="80px">
<el-row>
<el-col :span="24">
<!--抬头-->
<el-form-item label="抬头简称" prop="titleAbbr">
<el-autocomplete class="titles" popper-class="my-autocomplete" v-model="focusRow.titleAbbr" :fetch-suggestions="querySearchAsyncTitles" placeholder="请输选择抬头" @select="handleSelectTitles" >
<i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClickTitles" ></i>
<template slot-scope="{ item }">
<div class="name">{{ item.abbr }}</div>
<span class="subtitle">{{ item.name }}</span>
<span class="subtitle">{{ item.taxNo }}</span>
</template>
</el-autocomplete>
</el-form-item>
</el-col>
</el-row>
<!--商户-->
<el-row>
<el-col :span="24">
<el-form-item label="开票商家" prop="merchantAbbr">
<el-autocomplete class="merchants" v-model="focusRow.merchantAbbr" :fetch-suggestions="querySearchAsyncMerchant" placeholder="请选择餐饮商户" @select="handleSelectMerchant">
<i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClickTitles" ></i>
<template slot-scope="{ item }">
<div class="name">{{ item.abbr }}</div>
<span class="subtitle">{{ item.name }}</span>
</template>
</el-autocomplete>
</el-form-item>
</el-col>
</el-row>
<!--日期 & 金额-->
<el-row>
<el-col :span="12">
<!--开票日期-->
<el-form-item label="开票日期" prop="dating">
<el-date-picker type="date" placeholder="选择日期" v-model="focusRow.dating" style="width: 100%;" value-format="yyyy-MM-dd"> </el-date-picker>
</el-form-item>
</el-col>
<el-col :span="1">
<!--金额-->
<el-form-item label="开票金额" prop="amount">
<el-input-number v-model="focusRow.amount" :precision="2" :step="100" controls-position="right" :min="0" :max="5000"></el-input-number>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="addItem('addForm')" :disabled="disabled">确 定</el-button>
<el-button @click="resetForm('addForm')">重置</el-button>
</div>
</el-dialog>
</div>
<!--编辑-->
<div width="600px">
<el-dialog title="编辑" :visible.sync="isEditShow" width="700px" >
<el-form ref="editForm" :model="focusRow" :rules="rules" label-width="80px">
<el-row>
<el-col :span="24">
<!--抬头-->
<el-form-item label="抬头简称" prop="titleAbbr">
<el-autocomplete class="titles" popper-class="my-autocomplete" v-model="focusRow.titleAbbr" :fetch-suggestions="querySearchAsyncTitles" placeholder="请输选择抬头" @select="handleSelectTitles" >
<i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClickTitles" ></i>
<template slot-scope="{ item }">
<div class="name">{{ item.abbr }}</div>
<span class="subtitle">{{ item.name }}</span>
<span class="subtitle">{{ item.taxNo }}</span>
</template>
</el-autocomplete>
</el-form-item>
</el-col>
</el-row>
<!--商户-->
<el-row>
<el-col :span="24">
<el-form-item label="开票商家" prop="merchantAbbr">
<el-autocomplete class="merchants" v-model="focusRow.merchantAbbr" :fetch-suggestions="querySearchAsyncMerchant" placeholder="请选择餐饮商户" @select="handleSelectMerchant">
<i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClickTitles" ></i>
<template slot-scope="{ item }">
<div class="name">{{ item.abbr }}</div>
<span class="subtitle">{{ item.name }}</span>
</template>
</el-autocomplete>
</el-form-item>
</el-col>
</el-row>
<!--日期 & 金额-->
<el-row>
<el-col :span="12">
<!--开票日期-->
<el-form-item label="开票日期" prop="dating">
<el-date-picker type="date" placeholder="选择日期" v-model="focusRow.dating" style="width: 100%;" value-format="yyyy-MM-dd"> </el-date-picker>
</el-form-item>
</el-col>
<el-col :span="1">
<!--金额-->
<el-form-item label="开票金额" prop="amount">
<el-input-number v-model="focusRow.amount" :precision="2" :step="100" controls-position="right" :min="0" :max="5000"></el-input-number>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="updateItem('editForm')" :disabled="disabled">确 定</el-button>
<!-- <el-button type="primary" @click="updateItem()" >确 定</el-button> -->
<el-button @click="resetForm('editForm')">重置</el-button>
</div>
</el-dialog>
</div>
</div>
</template>
<script>
import { addPost, fetchPosts, getPost, fetchTitles, fetchMerchants, newBill } from "../api/basic.js";
import {
newPost,
fetchPosts,
getPost,
fetchTitles,
fetchMerchants,
newBill
} from "../api/basic.js";
export default {
name: "Bill",
name: "Gird",
data() {
return {
isAddShow: false,
@@ -209,38 +56,71 @@ export default {
disabled: false,
// focusRow: { index: null,dating: "2019-05-28", titleId: null, titleAbbr: "上海沐融",titleName:"",taxNo:"",merchantId: null, merchantAbbr: "华容月",amount: 0.0 },
focusRow: {},
bill: {
postId: "",
// postAddress: "",
postContact : "",
// postMobile : "",
postId: "",
// postAddress: "",
billItems: [
// { dating: "2019-05-28", titleId: null, titleAbbr: "上海沐融",titleName:"",taxNo: "" ,merchantId: null, merchantAbbr: "华容月",amount: 0.0 },
// { dating: "2019-05-28", titleId: null, titleAbbr: "上海沐融",titleName:"",taxNo: "" ,merchantId: null, merchantAbbr: "华容月",amount: 0.0 },
// { dating: "2019-05-28", titleId: null, titleAbbr: "上海沐融",merchantId: null, merchantAbbr: "华容月",amount: 0.0 },
// { dating: "2019-05-28", titleId: null, titleAbbr: "上海沐融",merchantId: null, merchantAbbr: "华容月",amount: 0.0 },
// { dating: "2019-05-28", titleId: null, titleAbbr: "上海沐融",merchantId: null, merchantAbbr: "华容月",amount: 0.0 },
],
},
book: [
{
id: 592,
post: {
id: 32,
address: "世博馆路52号鲁能国际B座11楼",
contact: "赵磊",
mobile: "18017581610"
},
items: [
{
id: 593,
title: {
id: 25,
name: "北京沐融信息科技股份有限公司",
abbr: "沐融北京总公司",
taxNo: "91110108071711408C"
},
merchant: {
id: 22,
abbr: "汇京粹",
name: "汇京粹(上海)餐饮管理有限公司"
},
dating: "2019-05-07T00:00:00.000+0000",
amount: 500.0
},
{
id: 594,
title: {
id: 24,
name: "北京沐融信息科技股份有限公司上海分公司",
abbr: "沐融上海分公司",
taxNo: "91310107MA1G07F91W"
},
merchant: {
id: 23,
abbr: "花蓉月",
name: "上海花蓉月餐饮有限公司"
},
dating: "2019-05-16T00:00:00.000+0000",
amount: 200.0
}
],
state: "APPLIED",
applyDate: "2019-05-30T13:02:11.000+0000",
acceptDate: null,
totalAmount: 700.0
}
],
rules: {
postContact: [
{ required: true, message: "请选择邮寄地址",trigger: "change"},
{ required: true, message: "请选择邮寄地址", trigger: "change" }
// { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
],
merchantAbbr: [
{ required: true, message: "请选择餐饮商户", trigger: "change"},
{ required: true, message: "请选择餐饮商户", trigger: "change" }
],
titleAbbr: [
{ required: true, message: "请选择抬头", trigger: "change" },
],
dating: [
{ required: true, message: "选择日期", trigger: "blur" },
{ required: true, message: "请选择抬头", trigger: "change" }
],
dating: [{ required: true, message: "选择日期", trigger: "blur" }],
amount: [
{ required: true, message: "请输入金额", trigger: "blur" },
{ type: 'number', message: '金额必须为数字值'}
{ type: "number", message: "金额必须为数字值" }
]
}
};
@@ -254,42 +134,50 @@ export default {
/** 在表格中添加明细 */
addItem(formName) {
var oriForm = formName;
this.$refs[formName].validate((valid) => {
if (valid) {
console.info('addItem');
console.info('focusRow:' + JSON.stringify(this.focusRow));
console.info('this.bill.billItems:' + JSON.stringify(this.bill.billItems));
this.bill.billItems.splice(0,0,this.focusRow);
console.info('this.bill.billItems:' + JSON.stringify(this.bill.billItems));
this.clearFocusRow();
console.info('focusRow:' + JSON.stringify(this.focusRow));
this.isAddShow = false;
// this.resetForm(oriForm);
} else {
console.log('error submit!!');
return false;
}
});
this.$refs[formName].validate(valid => {
if (valid) {
console.info("addItem");
console.info("focusRow:" + JSON.stringify(this.focusRow));
console.info(
"this.bill.newItems:" + JSON.stringify(this.bill.newItems)
);
this.bill.newItems.splice(0, 0, this.focusRow);
console.info(
"this.bill.newItems:" + JSON.stringify(this.bill.newItems)
);
this.clearFocusRow();
console.info("focusRow:" + JSON.stringify(this.focusRow));
this.isAddShow = false;
// this.resetForm(oriForm);
} else {
console.log("error submit!!");
return false;
}
});
},
/** 在表格中添加明细 */
updateItem(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
console.info('index:' + index);
console.info('updateItem');
console.info('focusRow:' + JSON.stringify(this.focusRow));
console.info('this.bill.billItems:' + JSON.stringify(this.bill.billItems));
var index = this.focusRow.index;
this.bill.billItems.splice(index,1,this.focusRow);
console.info('this.bill.billItems:' + JSON.stringify(this.bill.billItems));
this.clearFocusRow();
console.info('focusRow:' + JSON.stringify(this.focusRow));
this.isEditShow = false;
} else {
console.log('error submit!!');
return false;
}
});
this.$refs[formName].validate(valid => {
if (valid) {
console.info("index:" + index);
console.info("updateItem");
console.info("focusRow:" + JSON.stringify(this.focusRow));
console.info(
"this.bill.newItems:" + JSON.stringify(this.bill.newItems)
);
var index = this.focusRow.index;
this.bill.newItems.splice(index, 1, this.focusRow);
console.info(
"this.bill.newItems:" + JSON.stringify(this.bill.newItems)
);
this.clearFocusRow();
console.info("focusRow:" + JSON.stringify(this.focusRow));
this.isEditShow = false;
} else {
console.log("error submit!!");
return false;
}
});
},
/** 表格-编辑一行 */
handleEdit(index, row) {
@@ -303,19 +191,19 @@ export default {
row.splice(index, 1);
},
onSubmit(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
console.info("bill:" + JSON.stringify(this.bill));
newBill(this.bill).then(function(response){
console.info("response:" + response)
})
this.disabled = true;
this.$message({ message: "提交成功", type: "success" });
} else {
console.log('error submit!!');
return false;
}
});
this.$refs[formName].validate(valid => {
if (valid) {
console.info("bill:" + JSON.stringify(this.bill));
newBill(this.bill).then(function(response) {
console.info("response:" + response);
});
this.disabled = true;
this.$message({ message: "提交成功", type: "success" });
} else {
console.log("error submit!!");
return false;
}
});
},
reset(formName) {
// this.$refs[formName].resetFields();
@@ -331,14 +219,14 @@ export default {
/** AutoComplete Posts 处理*/
querySearchAsyncPosts(queryString, cb) {
var list = [{}];
fetchPosts().then(function(response){
for(let i of response.data){
i.value = i.contact; //将想要展示的数据作为value
// i.value = i.contact; //将想要展示的数据作为value
fetchPosts().then(function(response) {
for (let i of response.data) {
i.value = i.contact; //将想要展示的数据作为value
// i.value = i.contact; //将想要展示的数据作为value
}
list = response.data;
cb(list);
})
});
// var posts = this.posts;
// console.error("posts:" + posts);
@@ -354,12 +242,12 @@ export default {
};
},
loadPosts() {
console.error('loadPosts');
console.error("loadPosts");
},
handleSelectPosts(item) {
this.bill.postId = item.id;
console.log('postId:' + this.bill.postId );
console.log('postContact:' + this.bill.postContact );
console.log("postId:" + this.bill.postId);
console.log("postContact:" + this.bill.postContact);
},
handleIconClickPosts(ev) {
console.log(ev);
@@ -368,14 +256,14 @@ export default {
/** AutoComplete Titles 处理*/
querySearchAsyncTitles(queryString, cb) {
var list = [{}];
fetchTitles().then(function(response){
console.info(response)
for(let i of response.data){
i.value = i.abbr; // 将想要展示的数据作为value
fetchTitles().then(function(response) {
console.info(response);
for (let i of response.data) {
i.value = i.abbr; // 将想要展示的数据作为value
}
list = response.data;
cb(list);
})
});
},
createFilterTitles(queryString) {
return titles => {
@@ -385,15 +273,15 @@ export default {
};
},
loadTitles() {
console.error('loadTitles');
console.error("loadTitles");
},
handleSelectTitles(item) {
this.focusRow.titleId = item.id;
this.focusRow.titleName = item.name;
this.focusRow.taxNo = item.taxNo;
console.log('titleId:' + this.focusRow.titleId );
console.log('titleAbbr:' + this.focusRow.titleAbbr );
console.log('titleName:' + this.focusRow.titleName );
console.log("titleId:" + this.focusRow.titleId);
console.log("titleAbbr:" + this.focusRow.titleAbbr);
console.log("titleName:" + this.focusRow.titleName);
},
handleIconClickTitles(ev) {
console.log(ev);
@@ -401,39 +289,40 @@ export default {
/** AutoComplete Merchant 处理*/
querySearchAsyncMerchant(queryString, cb) {
var list = [{}];
fetchMerchants().then(function(response){
for(let i of response.data){
i.value = i.abbr; // 将想要展示的数据作为value
fetchMerchants().then(function(response) {
for (let i of response.data) {
i.value = i.abbr; // 将想要展示的数据作为value
}
list = response.data;
cb(list);
})
});
},
createFilterMerchant(queryString) {
return merchants => {
return (
merchants.contact.toLowerCase().indexOf(queryString.toLowerCase()) === 0
merchants.contact.toLowerCase().indexOf(queryString.toLowerCase()) ===
0
);
};
},
handleSelectMerchant(item) {
this.focusRow.merchantId = item.id;
this.focusRow.merchantsAbbr = item.abbr;
console.log('merchantId:' + this.focusRow.merchantId );
console.log('merchantsAbbr:' + this.focusRow.merchantsAbbr );
console.log('merchantsName:' + item.name );
console.log("merchantId:" + this.focusRow.merchantId);
console.log("merchantsAbbr:" + this.focusRow.merchantsAbbr);
console.log("merchantsName:" + item.name);
},
handleIconClickMerchant(ev) {
console.log(ev);
},
loadMerchant() {
console.error('loadTitles');
console.error("loadTitles");
},
/** 清理当前缓存 */
clearFocusRow() {
this.focusRow = {}
console.info('clearFocusRow');
},
this.focusRow = {};
console.info("clearFocusRow");
}
},
mounted() {
// this.posts = this.loadPosts();
@@ -444,7 +333,7 @@ export default {
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.subtitle{
.subtitle {
font-size: 12px;
color: #b4b4b4;
}
@@ -464,10 +353,10 @@ a {
color: #42b983;
}
.el-form-item{
.el-form-item {
/* width: 200px; */
/* margin: 10px; */
float:inherit ;
float: inherit;
padding: 20px;
}
.group {
@@ -487,7 +376,7 @@ a {
right: 0;
bottom: 0;
}
.gTable{
.gTable {
/* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
/* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04); */
text-align: left;
@@ -506,7 +395,7 @@ a {
}
.itemBtn {
width: 100px;
float:right;
float: right;
}
.el-form {
/* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04); */
@@ -519,7 +408,9 @@ a {
text-align: left;
/* width: 800px; */
}
.posts,.titles,.merchants{
.posts,
.titles,
.merchants {
width: 487px;
}
.el-form-item {
+3
View File
@@ -50,8 +50,11 @@ export default {
var token = "Bearer " + res.data.token;
console.log("token:" + token);
window.localStorage.setItem("token", token);
this.disabled = true;
this.$message({ message: "登录成功", type: "success" });
this.$router.push({ path: 'Bill' })
})
.catch(function(error) {
// _this.$message({ message: error.response.statusText, type: 'error' });
+2 -2
View File
@@ -20,7 +20,7 @@
</template>
<script>
import { addMerchant, fetchMerchants, getMerchant } from "../api/basic.js";
import { newMerchant, fetchMerchants, getMerchant } from "../api/basic.js";
export default {
name: "Merchant",
data() {
@@ -36,7 +36,7 @@ export default {
console.log("submit!");
console.log("merc:" + this.merc.name);
// MerchantAddAction(JSON.stringify(this.merc))
addMerchant(this.merc).then(res => {
newMerchant(this.merc).then(res => {
var merchantId = res.data.id;
console.log("res.data.code" + res.data.code);
this.$message({ message: "恭喜你,这是一条成功消息", type: "success" });