提交 9a5594d1 authored 作者: Whispa's avatar Whispa

commit

上级 b7b0a674
...@@ -54,6 +54,12 @@ ...@@ -54,6 +54,12 @@
<artifactId>unirest-java</artifactId> <artifactId>unirest-java</artifactId>
<version>1.4.9</version> <version>1.4.9</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.hashids/hashids -->
<dependency>
<groupId>org.hashids</groupId>
<artifactId>hashids</artifactId>
<version>1.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
......
...@@ -23,6 +23,7 @@ import com.google.firebase.FirebaseOptions; ...@@ -23,6 +23,7 @@ import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken; import com.google.firebase.auth.FirebaseToken;
import org.hashids.Hashids;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
...@@ -184,12 +185,18 @@ public class AuthController { ...@@ -184,12 +185,18 @@ public class AuthController {
if ( !optional.isPresent() ) { if ( !optional.isPresent() ) {
String userid = IdUtil.createIdbyUUID(); String userid = IdUtil.createIdbyUUID();
user.setPassword(encoder.encode(user.getFirebaseUid())); user.setPassword(encoder.encode(user.getFirebaseUid()));
user.setUserId(userid); user.setUserId(userid);
fillUserNecessayInfo(user); fillUserNecessayInfo(user);
userRepository.save(user); user = userRepository.save(user);
//赠送用户优惠券 //赠送用户优惠券
List<TbCfCoupon> couponVailList = couponRepository.findAllByCouponVaild(1); List<TbCfCoupon> couponVailList = couponRepository.findAllByCouponVaild(1);
//获取当前时间的时分秒 //获取当前时间的时分秒
...@@ -220,6 +227,17 @@ public class AuthController { ...@@ -220,6 +227,17 @@ public class AuthController {
user.setPassword(encoder.encode(user.getFirebaseUid()));// Assign user from database to the user we have to return back to request user.setPassword(encoder.encode(user.getFirebaseUid()));// Assign user from database to the user we have to return back to request
} }
if( user.getCode() == null){
Hashids hashids = new Hashids("big father is daddy", 6);
Long codeCount = user.getCodeCount();
if( codeCount == null){
codeCount = userRepository.count();
}
user.setCode(hashids.encode(codeCount));
}
user.setLastLoginTime(new Date()); user.setLastLoginTime(new Date());
userRepository.save(user); userRepository.save(user);
//注册成功 创建token //注册成功 创建token
......
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
@RestController
@RequestMapping("/discover/bonus")
public class BonusController {
private final BonusRepository repository;
private final ItemRepository itemRepository;
private final UserRepository userRepository;
private final PostRepository postRepository;
private final NetworkRepository networkRepository;
private final EntityManager entityManager;
public BonusController(BonusRepository repository, ItemRepository itemRepository, UserRepository userRepository, PostRepository postRepository, NetworkRepository networkRepository, EntityManager entityManager) {
this.repository = repository;
this.itemRepository = itemRepository;
this.userRepository = userRepository;
this.postRepository = postRepository;
this.networkRepository = networkRepository;
this.entityManager = entityManager;
}
@GetMapping(value = "/listBonus")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<Bonus> getList(@RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAll(PageRequest.of(pageNo, pageSize)).toList();
}
@GetMapping(value = "/list/bonus/{userId}")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<Bonus> getListByUser(@PathVariable("userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAllByUserInfo_UserIdOrderByIdDesc(id, PageRequest.of(pageNo, pageSize)).toList();
}
@GetMapping(value = "/list/bonus/{userId}/currentMonth")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public Map<String, Object> getListByUserAndCurrentMonth(@PathVariable("userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
int year = localDate.getYear();
Optional<TbCfUserInfo> byId = userRepository.findById(id);
if (!byId.isPresent()) return null;
Query nativeQuery = entityManager.createNativeQuery("select IFNULL(sum(b.amount),0) as data FROM bonus b where b.user_info_user_id=:user and month (b.create_date) = :month and year(b.create_date) = :year ");
nativeQuery.setParameter("user", id);
nativeQuery.setParameter("month", month);
nativeQuery.setParameter("year", year);
List<Bonus> bonuses = repository.findAllByUser_IdAndCreateDateMonthAndCreateDateYear(byId.get(), month, year, PageRequest.of(pageNo, pageSize)).toList();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("total", nativeQuery.getSingleResult());
hashMap.put("list", bonuses);
return hashMap;
}
@GetMapping(value = "/list/bonus/{userId}/prevMonth")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public Map<String, Object> getListByUserAndPreviousMonth(@PathVariable("userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue() - 1;
int year = localDate.getYear();
Optional<TbCfUserInfo> byId = userRepository.findById(id);
if (!byId.isPresent()) return null;
Query nativeQuery = entityManager.createNativeQuery("select IFNULL(sum(b.amount),0) as data FROM bonus b where b.user_info_user_id=:user and month (b.create_date) = :month and year(b.create_date) = :year ");
nativeQuery.setParameter("user", id);
nativeQuery.setParameter("month", month);
nativeQuery.setParameter("year", year);
List<Bonus> bonuses = repository.findAllByUser_IdAndCreateDateMonthAndCreateDateYear(byId.get(), month, year, PageRequest.of(pageNo, pageSize)).toList();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("total", nativeQuery.getSingleResult());
hashMap.put("list", bonuses);
return hashMap;
}
@GetMapping(value = "/list/bonus/{userId}/today")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public Map<String, Object> getListByUserAndToday(@PathVariable("userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int dayOfYear = localDate.getDayOfYear();
int year = localDate.getYear();
Optional<TbCfUserInfo> byId = userRepository.findById(id);
if (!byId.isPresent()) return null;
Query nativeQuery = entityManager.createNativeQuery("select IFNULL(sum(b.amount),0) as data FROM bonus b where b.user_info_user_id=:user and dayofyear(b.create_date) = :day and year(b.create_date) = :year ");
nativeQuery.setParameter("user", id);
nativeQuery.setParameter("day", dayOfYear);
nativeQuery.setParameter("year", year);
List<Bonus> bonuses = repository.findAllByUser_IdAndCreateDate(byId.get(), dayOfYear, year, PageRequest.of(pageNo, pageSize)).toList();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("total", nativeQuery.getSingleResult());
hashMap.put("list", bonuses);
return hashMap;
}
@PostMapping(value = "/saveBonus")
public Bonus saveBonus(@ModelAttribute("Bonus") Bonus bonus) {
String itemId = bonus.getProduct();
boolean exists = itemRepository.existsByItemName(itemId);
Item byItemName = itemRepository.findByItemName(itemId);
Post post = bonus.getPost();
if (exists) {
bonus.setItem(byItemName);
} else return null;
String sharer = bonus.getSharer();
double amount = bonus.getAmount();
bonus.setAmount(amount * 5 / 100);
bonus.setItem(byItemName);
bonus.setPercentage(5);
if (sharer != null && userRepository.existsByCode(sharer)) {
Optional<TbCfUserInfo> byId = userRepository.findByCode(sharer);
if (byId.isPresent()) {
Bonus bonus1 = new Bonus();
bonus1.setItem(byItemName);
bonus1.setPost(post);
bonus1.setUserInfo(byId.get());
bonus1.setAmount(amount * 10 / 100);
bonus1.setPercentage(10.0);
repository.save(bonus1);
}
}
return repository.save(bonus);
}
@PostMapping(value = "/saveNetworkMarketing")
public Bonus saveNetworkMarketing(@ModelAttribute("Bonus") Bonus bonus) {
Optional<String> userIdOptional = bonus.userId();
double amount = bonus.getAmount();
if (userIdOptional.isPresent()) {
Optional<TbCfUserInfo> optionalUser = userRepository.findById(userIdOptional.get());
if (optionalUser.isPresent()) {
TbCfUserInfo user = optionalUser.get();
Post post = bonus.getPost();
Optional<Post> postOptional = post == null ? Optional.empty() : postRepository.findById(post.getId());
String productSharer = bonus.getProductSharer();
Optional<TbCfUserInfo> sharer = Optional.empty();
if( productSharer != null){
sharer = userRepository.findByCode(productSharer);
}
if (user.invited()) {
bonus.setAmount(amount * 10 / 100);
bonus.setUserInfo(user);
bonus.setPercentage(10);
bonus = repository.save(bonus);
}
TbCfUserInfo bonusInc = runBonusInc(user, amount, 5,false,bonus.getOrderId());
runBonusInc(sharer.orElseGet(() -> postOptional.isPresent() ? postOptional.get().getUser() : bonusInc), amount, 5,postOptional.isPresent() || sharer.isPresent(),bonus.getOrderId());
//runBonusInc(bonusInc, amount, 0);
}
}
return bonus;
}
private TbCfUserInfo runBonusInc(TbCfUserInfo user, double amount, int percent,boolean direct,String orderId) {
if (user == null) return null;
Optional<Network> userCode = networkRepository.findByNetworkInfoCode(user.getCode());
if (userCode.isPresent()) {
TbCfUserInfo me = userCode.get().getUserInfo();
Bonus bonus = new Bonus();
bonus.setUserInfo(direct ? user : me);
bonus.setAmount(amount * percent / 100);
bonus.setPercentage(percent);
bonus.setOrderId(orderId);
if (me.invited()) repository.save(bonus);
return me;
}
return null;
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.Comment;
import com.example.afrishop_v3.repository.CommentRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/discover/comment")
public class CommentController {
private final CommentRepository repository;
private final AuthenticationUser user;
public CommentController(CommentRepository repository, AuthenticationUser user) {
this.repository = repository;
this.user = user;
}
@GetMapping(value = "/commentsByPostId/{postId}")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<Comment> getList(@PathVariable(value = "postId") long id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAllByPostId(id, PageRequest.of(pageNo, pageSize)).toList();
}
@PostMapping(value ="/saveComment")
public Comment saveProduct(@ModelAttribute("Comment") Comment comment){
comment.setUserInfo(user.user());
return repository.save(comment);
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.CommentLike;
import com.example.afrishop_v3.repository.CommentLikeRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/discover/comment/like")
public class CommentLikeController {
private final CommentLikeRepository repository;
public CommentLikeController(CommentLikeRepository repository) {
this.repository = repository;
}
@PostMapping(value ="/saveCommentLike/{liked}")
public CommentLike saveReply(@PathVariable("liked") boolean liked, @ModelAttribute("CommentLike") CommentLike like){
if( liked )
return repository.save(like);
else{
repository.removeByComment_Id(like.commentId());
return null;
}
}
@GetMapping(value = "/CommentsLikesByCommentId/{commentId}")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<CommentLike> getList(@PathVariable(value = "commentId") long id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAllByCommentId(id, PageRequest.of(pageNo, pageSize)).toList();
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.Following;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.FollowRepository;
import com.example.afrishop_v3.repository.UserRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/discover/follow")
public class FollowingController {
private final FollowRepository repository;
private final UserRepository userRepository;
public FollowingController(FollowRepository repository, UserRepository userRepository) {
this.repository = repository;
this.userRepository = userRepository;
}
@GetMapping("listFollowers/{userId}")
public List<TbCfUserInfo> getList(@PathVariable("userId") String id){
return repository.findAllByFollowedInfoUserId(id).stream().map(Following::getFollowerInfo).collect(Collectors.toList());
}
@GetMapping("listFollowing/{userId}")
public List<TbCfUserInfo> getListFollowing(@PathVariable("userId") String id){
return repository.findAllByFollowerInfoUserId(id).stream().map(Following::getFollowedInfo).collect(Collectors.toList());
}
@GetMapping("follow/user/{follower}/{followed}/{status}")
public Following followingStatus(@PathVariable("follower") String follower, @PathVariable("followed") String followed, @PathVariable("status") boolean status){
Following following = new Following();
Optional<TbCfUserInfo> optionalUser = userRepository.findById(followed);
Optional<TbCfUserInfo> optionalUser0 = userRepository.findById(follower);
optionalUser.ifPresent(following::setFollowedInfo);
optionalUser0.ifPresent(following::setFollowerInfo);
if( status ) {
if(!repository.existsByFollowedInfoUserIdAndFollowerInfoUserId(followed,follower))
repository.save(following);
}else
repository.removeByFollowed_IdAndFollower_Id(followed,follower);
return following;
}
@GetMapping("follow/status/{follower}/{followed}")
public boolean followStatus(@PathVariable("follower") String follower, @PathVariable("followed") String followed){
return repository.existsByFollowedInfoUserIdAndFollowerInfoUserId(followed,follower);
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.Hashtag;
import com.example.afrishop_v3.repository.HashtagRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class HashtagController {
private final HashtagRepository repository;
public HashtagController(HashtagRepository repository) {
this.repository = repository;
}
@GetMapping(value = "/listHashtags")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<Hashtag> getList(@RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAll(PageRequest.of(pageNo, pageSize)).toList();
}
@GetMapping(value = "/searchHashtags/{query}")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<Hashtag> getSearch(@PathVariable(value = "query") String query, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAllByNameContaining(query, PageRequest.of(pageNo, pageSize)).toList();
}
@PostMapping(value = "/saveHashTag")
public Hashtag saveProduct(@ModelAttribute("Hashtag") Hashtag hashtag) {
return repository.save(hashtag);
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.InvitationRequest;
import com.example.afrishop_v3.repository.InvitationRequestRepository;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/discover/invitation")
public class InvitationRequestController {
private final InvitationRequestRepository repository;
public InvitationRequestController(InvitationRequestRepository repository) {
this.repository = repository;
}
@PostMapping(value ="/saveInvitationRequest")
public InvitationRequest saveProduct(@ModelAttribute("InvitationRequest") InvitationRequest request){
if( repository.existsByUserInfo_UserId(request.userId())){
return repository.findByUserInfo_UserId(request.userId());
}else
return repository.save(request);
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.PostLike;
import com.example.afrishop_v3.repository.LikeRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/discover/like")
public class LikeController {
private final LikeRepository repository;
public LikeController(LikeRepository repository) {
this.repository = repository;
}
@GetMapping(value = "/likesByPostId/{postId}")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<PostLike> getList(@PathVariable(value = "postId") long id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
return repository.findAllByPostId(id, PageRequest.of(pageNo, pageSize)).toList();
}
@PostMapping(value = "/saveLike/{status}")
public String saveProduct(@PathVariable(value = "status") boolean status, @ModelAttribute("PostLike") PostLike like) {
if (status) {
if( !repository.existsByUserInfo_UserIdAndPost_Id(like.getUserId(),like.getPostId())) repository.save(like);
}else repository.removeByUser_IdAndPost_Id(like.getUserId(), like.getPostId());
return "delete";
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.models.Network;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.NetworkRepository;
import com.example.afrishop_v3.repository.UserRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@RestController
public class NetworkController {
private final NetworkRepository repository;
private final UserRepository userRepository;
private final EntityManager manager;
public NetworkController(NetworkRepository repository, UserRepository userRepository, EntityManager manager) {
this.repository = repository;
this.userRepository = userRepository;
this.manager = manager;
}
@PostMapping(value = "/saveNetwork")
public Network saveNetwork(@ModelAttribute("Network") Network network) {
if( network.getNetworkId() == null || network.getUserId() == null){
return null;
}
if (repository.existsByUserInfo_UserIdAndNetworkInfo_UserId(network.getUserId(), network.getNetworkId()))
return repository.findByUserInfo_UserIdAndNetworkInfo_UserId(network.getUserId(), network.getNetworkId());
else return repository.save(network);
}
@PostMapping(value = "/saveNetwork2")
public Network saveNetwork2(@ModelAttribute("Network") Network network) {
if( network.getCode() == null || network.getUserId() == null){
return null;
}
if (repository.existsByUserInfo_CodeAndNetworkInfo_UserId(network.getCode(), network.getNetworkId()))
return repository.findByUserInfo_CodeAndNetworkInfo_UserId(network.getCode(), network.getNetworkId());
else if ( userRepository.existsByCode(network.getCode())){
Optional<TbCfUserInfo> byCode = userRepository.findByCode(network.getCode());
if( byCode.isPresent() ) {
network.setUserInfo(byCode.get());
return repository.save(network);
}
}
return null;
}
@GetMapping(value = "/networksByUserId/{userId}")
//@PreAuthorize("hasAuthority('ADMIN_USER') or hasAuthority('STANDARD_USER')")
public List<TbCfUserInfo> getList(@PathVariable(value = "userId") String id, @RequestParam(value = "pageNo") Integer pageNo, @RequestParam(value = "pageSize") Integer pageSize) {
List<TbCfUserInfo> collect = repository.findAllByUserInfo_UserIdOrderByIdDesc(id, PageRequest.of(pageNo, pageSize)).toList().stream().map(Network::getNetworkInfo).collect(Collectors.toList());
for (TbCfUserInfo user : collect){
Query nativeQuery = manager.createNativeQuery("select IFNULL(sum(b.amount),0) as data FROM bonus b where b.user_info_user_id=:me and b.user_id IN (SELECT x.user_info_user_id FROM network x WHERE x.network_info_user_id=:id) ");
nativeQuery.setParameter("id",user.getUserId());
nativeQuery.setParameter("me",id);
user.networkAmount = (double) nativeQuery.getSingleResult();
}
return collect;
}
}
...@@ -17,7 +17,7 @@ import org.springframework.web.bind.annotation.*; ...@@ -17,7 +17,7 @@ import org.springframework.web.bind.annotation.*;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
...@@ -34,13 +34,15 @@ public class OrderController { ...@@ -34,13 +34,15 @@ public class OrderController {
private final TbCfCartRecordRRepository cartRepository; private final TbCfCartRecordRRepository cartRepository;
private final TbCfCouponRepository couponRepository; private final TbCfCouponRepository couponRepository;
private final TbCfStationItemRepository itemRepository; private final TbCfStationItemRepository itemRepository;
private final TbCfItemCommentRepository commentRepository;
private final AuthenticationUser user; private final AuthenticationUser user;
public OrderController(TbCfOrderRepository repository, TbCfCartRecordRRepository cartRepository, TbCfCouponRepository couponRepository, TbCfStationItemRepository itemRepository, AuthenticationUser user) { public OrderController(TbCfOrderRepository repository, TbCfCartRecordRRepository cartRepository, TbCfCouponRepository couponRepository, TbCfStationItemRepository itemRepository, TbCfItemCommentRepository commentRepository, AuthenticationUser user) {
this.repository = repository; this.repository = repository;
this.cartRepository = cartRepository; this.cartRepository = cartRepository;
this.couponRepository = couponRepository; this.couponRepository = couponRepository;
this.itemRepository = itemRepository; this.itemRepository = itemRepository;
this.commentRepository = commentRepository;
this.user = user; this.user = user;
} }
...@@ -253,6 +255,38 @@ public class OrderController { ...@@ -253,6 +255,38 @@ public class OrderController {
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(), ""); return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(), "");
} }
@PostMapping("/add/comment")
public Result addComment(@RequestBody TbCfItemComment comment) {
TbCfUserInfo user = this.user.user();
String userId = user.getUserId();
String itemId = comment.getItemId();
boolean exists = commentRepository.existsByUserUserIdAndItemId(userId, itemId);
if( exists ){
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Already reviewed this product!");
}
comment.setItemId(itemId);
comment.setUser(user);
comment.setId(IdUtil.createIdbyUUID());
comment.setDelFlag(0);
comment.setLikeNum(0L);
comment.setCreateTime(new Date());
comment.setUpdateTime(new Date());
comment.setType(0);
if (!StringUtils.isBlank(comment.getUrls())) {
comment.setType(1);
}
TbCfItemComment save = commentRepository.save(comment);
return new Result<>(save,"Comment on success!");
}
private Sort sort(String order) { private Sort sort(String order) {
String col = "orderTime"; String col = "orderTime";
return Sort.by("desc".equals(order) ? desc(col) : asc(col)); return Sort.by("desc".equals(order) ? desc(col) : asc(col));
......
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.models.TbCfItemComment;
import com.example.afrishop_v3.repository.TbCfItemCommentRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("shopify")
public class ShopifyController {
private final TbCfItemCommentRepository repository;
public ShopifyController(TbCfItemCommentRepository repository) {
this.repository = repository;
}
@GetMapping("/querycomments")
public Result queryComments(@RequestParam(value = "itemId") String itemId,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
@RequestParam(value = "userId", required = false) String userId) {
Page<TbCfItemComment> list = repository.findAllByItemId(itemId, PageRequest.of(pageNum, pageSize));
List<TbCfItemComment> content = list.getContent();
for (TbCfItemComment item : content){
//if(StringUtils.isNotBlank(userId)) item.setLike(repository.existsByUserIdAndItemId(userId,itemId));
}
return new Result<>(list);
}
}
...@@ -27,22 +27,26 @@ public class UploadController { ...@@ -27,22 +27,26 @@ public class UploadController {
@PostMapping("/uploadFile") @PostMapping("/uploadFile")
public Result uploadFile(@RequestBody String strImg) throws Exception { public Result uploadFile(@RequestBody String strImg) throws Exception {
Result<String> result = new Result<>(); Result<String> result = new Result<>();
String url = sendFile(strImg,api);
result.setData(url).setMessage(ResultCodeEnum.SUCCESS.getDesc());
return result;
}
static String sendFile(String strImg,String api){
try { try {
if (!StringUtils.isBlank(strImg)) { if (!StringUtils.isBlank(strImg)) {
Map<String,Object> map = new HashMap<>(); Map<String,Object> map = new HashMap<>();
map.put("file", strImg); map.put("file", strImg);
String url = HttpClientUtil.sendPostWithBodyParameter(api, map); String url = HttpClientUtil.sendPostWithBodyParameter(api, map);
url = url.substring(1, url.length() - 1); return url.substring(1, url.length() - 1);
result.setData(url).setMessage(ResultCodeEnum.SUCCESS.getDesc());
} else { } else {
result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode()); return null;
result.setMessage("The parameter cannot be null");
} }
} catch (Exception e) { } catch (Exception e) {
result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode()); return null;
result.setMessage("Upload failed");
} }
return result;
} }
//@ApiOperation("删除文件") //@ApiOperation("删除文件")
......
...@@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory; ...@@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Date; import java.util.Date;
import java.util.Optional;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
...@@ -150,4 +151,11 @@ public class UserController { ...@@ -150,4 +151,11 @@ public class UserController {
return new Result<>(save); return new Result<>(save);
} }
@GetMapping("userById/{id}")
public Result userById(@PathVariable("id") String id){
Optional<TbCfUserInfo> byId = repository.findById(id);
return byId.map(userInfo -> new Result<>(userInfo, "Success")).orElseGet(() -> new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Not found !"));
}
} }
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import java.util.Date;
import java.util.Optional;
@Entity
@Getter
@Setter
public class Bonus extends Model {
@ManyToOne()
private TbCfUserInfo userInfo;
@ManyToOne()
private Post post;
@ManyToOne()
private Item item;
private double amount;
private String orderId;
private String account;
private String accountName;
private String names;
private String email;
@Transient
private String productSharer;
private boolean status = false;
public boolean isWithdraw = false;
@Transient
private String product;
@Transient
private String sharer;
private double percentage;
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderId() {
return orderId;
}
public String getProduct() {
return product;
}
public String getSharer() {
return sharer;
}
public Post getPost() {
return post;
}
public String getProductSharer() {
return productSharer;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
private void withDrawChange(){
this.isWithdraw = true;
}
public void reverseAmount(){
this.withDrawChange();
amount *= -1;
}
public String getUserId(){
return userInfo == null ? null : userInfo.getUserId();
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public void setPost(Post post) {
this.post = post;
}
public void setUserInfo(TbCfUserInfo userInfo) {
this.userInfo = userInfo;
}
public Optional<String> userId(){
return userInfo == null ? Optional.empty() : Optional.ofNullable(userInfo.getUserId());
}
public void setItem(Item item) {
this.item = item;
}
public Date getDate(){
return createDate;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Formula;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.util.Date;
@Entity
@Getter
@Setter
public class Comment extends Model {
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL)
private Post post;
@ManyToOne()
private TbCfUserInfo userInfo;
private String content;
@JsonProperty
public Date date(){
return createDate;
}
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM comment_like c WHERE c.comment_id=id)")
private int likes;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM reply c WHERE c.comment_id=id)")
private int replies;
public void setUserInfo(TbCfUserInfo userInfo) {
this.userInfo = userInfo;
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class CommentLike extends Model {
@ManyToOne
private Comment comment;
@ManyToOne
private TbCfUserInfo userInfo;
public Long commentId(){
return comment != null ? comment.id : null;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@Setter
public class Content extends Model {
@JsonBackReference
@ManyToOne(cascade = CascadeType.ALL)
private Post post;
private String content;
private String thumbnail;
private long size;
private boolean isImage;
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public void setImage(boolean image) {
isImage = image;
}
public void setPost(Post post) {
this.post = post;
}
public void setContent(String content) {
this.content = content;
}
public void setSize(long size) {
this.size = size;
}
@OneToMany(mappedBy = "content")
public List<ContentTag> tagList = new ArrayList<>();
public String getThumbnail() {
return thumbnail;
}
public boolean isImage() {
return isImage;
}
public long getSize() {
return size;
}
public String getContent() {
return content;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class ContentTag extends Model {
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL)
private Content content;
@ManyToOne()
private Tag tag;
private double x;
private double y;
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void setContent(Content content) {
this.content = content;
}
public void setTag(Tag tag) {
this.tag = tag;
}
public Tag getTag() {
return tag;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class Following extends Model {
@ManyToOne()
private TbCfUserInfo followerInfo;
@ManyToOne()
private TbCfUserInfo followedInfo;
public TbCfUserInfo getFollowedInfo() {
return followedInfo;
}
public TbCfUserInfo getFollowerInfo() {
return followerInfo;
}
public void setFollowedInfo(TbCfUserInfo followedInfo) {
this.followedInfo = followedInfo;
}
public void setFollowerInfo(TbCfUserInfo followerInfo) {
this.followerInfo = followerInfo;
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Formula;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
@Getter
@Setter
public class Hashtag extends Model{
@Column(unique = true)
private String name;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM post_hashtag c WHERE c.hashtag_id=id)")
private int count;
public String getName() {
return name;
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class InvitationRequest extends Model {
@ManyToOne
private TbCfUserInfo userInfo;
private boolean status;
public String userId(){
return userInfo == null ? null : userInfo.getUserId();
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
@Getter
@Setter
public class Item extends Model {
protected String itemName;
@Column(unique = true)
protected String itemId;
protected String itemImg;
protected double discountPrice;
protected int itemCount;
protected String itemSku;
public String getItemId() {
return itemId;
}
}
package com.example.afrishop_v3.models;
import java.util.List;
public class JsonTag {
public List<Position> list;
private boolean image;
public boolean isImage() {
return image;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.Date;
@MappedSuperclass
abstract class Model {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty
protected Long id;
@JsonIgnore
Date createDate = new Date();
public Long getId() {
return id;
}
@JsonIgnore
public String createdBy;
@JsonIgnore
public Date updateDate = new Date();
@JsonIgnore
public String updatedBy;
@Version
private int version;
@JsonIgnore
public boolean archived;
@JsonIgnore
public String archivedBy;
@JsonIgnore
public Date archivedDate = new Date();
public void clearId(){
id = null;
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
@Entity
@Getter
@Setter
public class Network extends Model {
@ManyToOne()
private TbCfUserInfo userInfo;
@ManyToOne()
private TbCfUserInfo networkInfo;
@Transient
private String code;
public String getUserId(){
return userInfo != null ? userInfo.getUserId() : null;
}
public void setUserInfo(TbCfUserInfo userInfo) {
this.userInfo = userInfo;
}
public String getCode() {
return code;
}
public TbCfUserInfo getUserInfo() {
return userInfo;
}
public String getNetworkId(){
return userInfo != null ? userInfo.getUserId() : null;
}
public TbCfUserInfo getNetworkInfo() {
return networkInfo;
}
}
package com.example.afrishop_v3.models;
public class Position extends Tag {
private double x;
private double y;
public double getY() {
return y;
}
public double getX() {
return x;
}
public Tag getTag(){
Tag tag = new Tag();
tag.tagName = tagName;
tag.setItem(item);
return tag;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Formula;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Entity
@Getter
@Setter
@Table(name = "post_data")
public class Post extends Model {
@ManyToOne()
private TbCfUserInfo userInfo;
private String title;
@Transient
private String tags;
@Transient
private String hashtags;
private String description;
private String category;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM post_like c WHERE c.post_id=id)")
private int likes;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM comment c WHERE c.post_id=id)")
private int comments;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM visit c WHERE c.post_id=id)")
private int visits;
@Transient
public boolean liked = false;
@OneToMany(mappedBy = "post")
public List<Content> contentList = new ArrayList<>();
@JsonIgnore
@OneToMany(mappedBy = "post")
public List<PostHashtag> hashtagList = new ArrayList<>();
public String getTags() {
return tags;
}
public TbCfUserInfo getUser() {
return userInfo;
}
public String getHashtags() {
return hashtags;
}
public void setUser(TbCfUserInfo user) {
this.userInfo = user;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@JsonProperty
public Date date() {
return createDate;
}
@JsonProperty
public List<Hashtag> hashtags() {
return hashtagList.stream().map(PostHashtag::getHashtag).collect(Collectors.toList());
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class PostHashtag extends Model {
@ManyToOne
private Post post;
@ManyToOne
private Hashtag hashtag;
public void setPost(Post post) {
this.post = post;
}
public void setHashtag(Hashtag hashtag) {
this.hashtag = hashtag;
}
public Hashtag getHashtag() {
return hashtag;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class PostLike extends Model {
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL)
private Post post;
@ManyToOne()
private TbCfUserInfo userInfo;
public Long getPostId() {
return post == null ? null : post.id;
}
public String getUserId() {
return userInfo == null ? null : userInfo.getUserId();
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class Reply extends Model {
@ManyToOne
private Comment comment;
@ManyToOne
private TbCfUserInfo userInfo;
private String content;
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Formula;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class Tag extends Model {
@ManyToOne()
protected Item item;
protected String tagName;
@Formula(value = "(SELECT IFNULL(COUNT(p.id),0) FROM content_tag p WHERE p.tag_id=id)")
protected int posts;
public String getTagName() {
return tagName;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* 实体
* 表名 tb_cf_item_comment
*
* @author lipengjun
* @date 2020-01-09 10:17:03
*/
@Entity
@Data
public class TbCfItemComment{
/**
* 商品评论ID
*/
@Id
private String id;
/**
* 评论人
*/
@ManyToOne
@JsonIgnore
@JoinColumn(columnDefinition = "user_id",name = "user_id")
private TbCfUserInfo user;
/**
* 订单ID
*/
private String orderId;
/**
* 商品ID
*/
private String itemId;
/**
* 类型 0: 只有文本内容 1:带图片
*/
private Integer type;
/**
* 图片或视频的url
*/
private String urls;
/**
* 商品评分
*/
private Integer itemScore;
/**
* 服务评分
*/
private Integer serviceScore;
/**
* 物流评分
*/
private Integer logisticsScore;
/**
* 价格评分
*/
private Integer priceScore;
/**
* 商品评论
*/
private String itemReview;
/**
* 点赞人数
*/
private Long likeNum;
/**
* 删除标志 0:正常 1:已删除
*/
private Integer delFlag;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
@Transient
private String userName;
@Transient
private String avatar;
private String orderNo;
private String itemName;
@Transient
private boolean isLike;
public boolean isLike() {
return isLike;
}
public void setLike(boolean like) {
isLike = like;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
/**
* 设置:商品评论ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取:商品评论ID
*/
public String getId() {
return id;
}
/**
* 设置:评论人
*/
public void setUser(TbCfUserInfo user) {
this.user = user;
}
@PostLoad
public void catchName(){
this.userName = user == null ? "" : user.display();
this.avatar = user == null ? "" : user.getAvatar();
}
/**
* 获取:评论人
*/
public String getUserId() {
return user != null ? user.getUserId() : null;
}
/**
* 设置:订单ID
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* 获取:订单ID
*/
public String getOrderId() {
return orderId;
}
/**
* 设置:商品ID
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
* 获取:商品ID
*/
public String getItemId() {
return itemId;
}
/**
* 设置:类型 0: 只有文本内容 1:带图片
*/
public void setType(Integer type) {
this.type = type;
}
/**
* 获取:类型 0: 只有文本内容 1:带图片
*/
public Integer getType() {
return type;
}
/**
* 设置:图片或视频的url
*/
public void setUrls(String urls) {
this.urls = urls;
}
/**
* 获取:图片或视频的url
*/
public String getUrls() {
return urls;
}
/**
* 设置:商品评分
*/
public void setItemScore(Integer itemScore) {
this.itemScore = itemScore;
}
/**
* 获取:商品评分
*/
public Integer getItemScore() {
return itemScore;
}
/**
* 设置:服务评分
*/
public void setServiceScore(Integer serviceScore) {
this.serviceScore = serviceScore;
}
/**
* 获取:服务评分
*/
public Integer getServiceScore() {
return serviceScore;
}
/**
* 设置:物流评分
*/
public void setLogisticsScore(Integer logisticsScore) {
this.logisticsScore = logisticsScore;
}
/**
* 获取:物流评分
*/
public Integer getLogisticsScore() {
return logisticsScore;
}
/**
* 设置:价格评分
*/
public void setPriceScore(Integer priceScore) {
this.priceScore = priceScore;
}
/**
* 获取:价格评分
*/
public Integer getPriceScore() {
return priceScore;
}
/**
* 设置:商品评论
*/
public void setItemReview(String itemReview) {
this.itemReview = itemReview;
}
/**
* 获取:商品评论
*/
public String getItemReview() {
return itemReview;
}
/**
* 设置:点赞人数
*/
public void setLikeNum(Long likeNum) {
this.likeNum = likeNum;
}
/**
* 获取:点赞人数
*/
public Long getLikeNum() {
return likeNum;
}
/**
* 设置:删除标志 0:正常 1:已删除
*/
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
/**
* 获取:删除标志 0:正常 1:已删除
*/
public Integer getDelFlag() {
return delFlag;
}
/**
* 设置:创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:创建时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置:更新时间
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* 获取:更新时间
*/
public Date getUpdateTime() {
return updateTime;
}
}
...@@ -122,10 +122,8 @@ public class TbCfStationItem { ...@@ -122,10 +122,8 @@ public class TbCfStationItem {
*/ */
private String itemDescritionId; private String itemDescritionId;
private String template;
@ManyToOne @ManyToOne
@JoinColumn(columnDefinition = "template") @JoinColumn(columnDefinition = "template",name = "template")
private TbCfExpressTemplate express; private TbCfExpressTemplate express;
@Formula(value = "(SELECT IFNULL(CEILING(SUM((a.item_score+a.service_score+a.logistics_score+a.price_score)/4)/COUNT(a.item_id)),5) FROM tb_cf_item_comment a WHERE a.item_id=item_id)") @Formula(value = "(SELECT IFNULL(CEILING(SUM((a.item_score+a.service_score+a.logistics_score+a.price_score)/4)/COUNT(a.item_id)),5) FROM tb_cf_item_comment a WHERE a.item_id=item_id)")
...@@ -467,11 +465,4 @@ public class TbCfStationItem { ...@@ -467,11 +465,4 @@ public class TbCfStationItem {
return itemDescritionId; return itemDescritionId;
} }
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
} }
package com.example.afrishop_v3.models; package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import javax.persistence.Entity; import javax.persistence.*;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
...@@ -99,7 +100,8 @@ public class TbCfUserInfo { ...@@ -99,7 +100,8 @@ public class TbCfUserInfo {
* 默认地址id * 默认地址id
*/ */
@ManyToOne @ManyToOne
@JoinColumn(columnDefinition = "default_address_id") @JoinColumn(columnDefinition = "default_address_id",name = "default_address_id")
@NotFound(action = NotFoundAction.IGNORE)
private TbCfAddress address; private TbCfAddress address;
/** /**
* 发出邀请的用户 * 发出邀请的用户
...@@ -136,6 +138,44 @@ public class TbCfUserInfo { ...@@ -136,6 +138,44 @@ public class TbCfUserInfo {
private int sentCount; private int sentCount;
private String slogan;
private String fcm;
@Column(unique = true)
private String code;
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true)
private Long codeCount;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM following c WHERE c.followed_info_user_id=user_id)")
private int followers;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM post_data c WHERE c.id IN (SELECT l.post_id FROM post_like l WHERE l.user_info_user_id=user_id))")
private int likes;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM following c WHERE c.follower_info_user_id=user_id)")
private int following;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM post_data c WHERE c.user_info_user_id=user_id)")
private int posts;
@Formula(value = "(SELECT IFNULL(SUM(c.amount),0.0) FROM bonus c WHERE c.user_info_user_id=user_id and c.is_withdraw=false)")
private double bonus;
@Formula(value = "(SELECT IFNULL(SUM(c.amount),0.0) FROM bonus c WHERE c.user_info_user_id=user_id and c.is_withdraw=true)")
private double withdraw;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM visit c INNER JOIN post_data p ON p.id=c.post_id WHERE p.user_info_user_id=user_id)")
private int visits;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM network c WHERE c.user_info_user_id=user_id)")
private int networks;
@Formula(value = "(SELECT IFNULL(COUNT(c.id),0) FROM network c WHERE c.network_info_user_id=user_id)")
private int invitation;
@Transient
@JsonProperty
public double networkAmount;
public void setCodeSentTime(Date codeSentTime) { public void setCodeSentTime(Date codeSentTime) {
this.codeSentTime = codeSentTime; this.codeSentTime = codeSentTime;
} }
...@@ -144,6 +184,15 @@ public class TbCfUserInfo { ...@@ -144,6 +184,15 @@ public class TbCfUserInfo {
return codeSentTime; return codeSentTime;
} }
public String getCode() {
return code;
}
@JsonProperty
public boolean invited(){
return invitation > 0;
}
public int getSentCount() { public int getSentCount() {
return sentCount; return sentCount;
} }
...@@ -152,6 +201,13 @@ public class TbCfUserInfo { ...@@ -152,6 +201,13 @@ public class TbCfUserInfo {
this.verificationCode = verificationCode; this.verificationCode = verificationCode;
} }
public void setCode(String code) {
this.code = code;
}
public Long getCodeCount() {
return codeCount;
}
public String getVerificationCode() { public String getVerificationCode() {
return verificationCode; return verificationCode;
...@@ -261,6 +317,9 @@ public class TbCfUserInfo { ...@@ -261,6 +317,9 @@ public class TbCfUserInfo {
return nick; return nick;
} }
public String display(){
return getNick() != null ? getNick() : getEmail() != null ? getEmail() : getPhone();
}
/** /**
* 设置:电话号码 * 设置:电话号码
*/ */
......
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
@Entity
@Getter
@Setter
public class Visit extends Model {
@ManyToOne(cascade = CascadeType.ALL)
private Post post;
public void setPost(Post post) {
this.post = post;
}
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Bonus;
import com.example.afrishop_v3.models.TbCfUserInfo;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface BonusRepository extends JpaRepository<Bonus,Long> {
Page<Bonus> findAllByUserInfo_UserIdOrderByIdDesc(String id, Pageable pageable);
@Query(value = "select a from #{#entityName} a WHERE month(a.createDate) = :month and year(a.createDate) = :year and a.userInfo=:id order by a.id desc")
Page<Bonus> findAllByUser_IdAndCreateDateMonthAndCreateDateYear(TbCfUserInfo id, int month, int year, Pageable pageable);
@Query(value = "select a from #{#entityName} a WHERE dayofyear(a.createDate) = :day and year(a.createDate) = :year and a.userInfo=:id order by a.id desc")
Page<Bonus> findAllByUser_IdAndCreateDate(TbCfUserInfo id, int day, int year, Pageable pageable);
Page<Bonus> findAllByUserInfo_UserIdAndWithdraw(String id, boolean withdraw, Pageable pageable);
@Query(value = "delete from bonus WHERE post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByPost_Id(@Param("post") Long post_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.CommentLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface CommentLikeRepository extends PagingAndSortingRepository<CommentLike,Long> {
Page<CommentLike> findAllByCommentId(long id, Pageable pageable);
@Query(value = "delete from comment_like WHERE comment_id=:comment",nativeQuery = true)
@Modifying
@Transactional
void removeByComment_Id(@Param("comment") Long comment_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface CommentRepository extends PagingAndSortingRepository<Comment, Long> {
Page<Comment> findAllByPostId(long id, Pageable pageable);
@Query(value = "delete from comment WHERE post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByPost_Id(@Param("post") Long post_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Content;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface ContentRepository extends PagingAndSortingRepository<Content, Long> {
@Query(value = "delete from content WHERE post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByPost_Id(@Param("post") Long post_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Following;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface FollowRepository extends CrudRepository<Following,Long> {
List<Following> findAllByFollowedInfoUserId(String followedInfo_userId);
List<Following> findAllByFollowerInfoUserId(String followerInfo_userId);
boolean existsByFollowedInfoUserIdAndFollowerInfoUserId(String followedInfo_userId, String followerInfo_userId);
@Query(value = "delete from following WHERE followed_info_user_id=:id1 and follower_info_user_id=:id2",nativeQuery = true)
@Modifying
@Transactional
void removeByFollowed_IdAndFollower_Id(@Param("id1") String followed_id, @Param("id2") String follower_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Hashtag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Optional;
public interface HashtagRepository extends PagingAndSortingRepository<Hashtag,Long> {
boolean existsByName(String name);
Optional<Hashtag> findByName(String name);
Page<Hashtag> findAllByNameContaining(String name, Pageable pageable);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.InvitationRequest;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface InvitationRequestRepository extends PagingAndSortingRepository<InvitationRequest, Long> {
boolean existsByUserInfo_UserId(String userInfo_userId);
InvitationRequest findByUserInfo_UserId(String userInfo_userId);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Item;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ItemRepository extends PagingAndSortingRepository<Item, Long> {
boolean existsByItemId(String itemId);
boolean existsByItemName(String string);
Item findByItemId(String itemId);
Item findByItemName(String string);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.PostLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface LikeRepository extends PagingAndSortingRepository<PostLike, Long> {
Page<PostLike> findAllByPostId(long id, Pageable pageable);
@Query(value = "delete from post_like WHERE user_info_user_id=:userId and post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByUser_IdAndPost_Id(@Param("userId") String user_id, @Param("post") Long post_id);
@Query(value = "delete from post_like WHERE post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByPost_Id(@Param("post") Long post_id);
boolean existsByUserInfo_UserIdAndPost_Id(String user_id, Long post_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Network;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Optional;
public interface NetworkRepository extends PagingAndSortingRepository<Network,Long> {
boolean existsByUserInfo_UserIdAndNetworkInfo_UserId(String userInfo_userId, String networkInfo_userId);
boolean existsByUserInfo_CodeAndNetworkInfo_UserId(String userInfo_code, String networkInfo_userId);
Network findByUserInfo_UserIdAndNetworkInfo_UserId(String user, String network);
Network findByUserInfo_CodeAndNetworkInfo_UserId(String userInfo_code, String networkInfo_userId);
Optional<Network> findByNetworkInfoCode(String user_code);
Page<Network> findAllByUserInfo_UserIdOrderByIdDesc(String userInfo_userId, Pageable pageable);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.PostHashtag;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PostHashtagRepository extends PagingAndSortingRepository<PostHashtag,Long> {
boolean existsByHashtagNameAndPostId(String name, long post);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Hashtag;
import com.example.afrishop_v3.models.Post;
import com.example.afrishop_v3.models.TbCfUserInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {
Page<Post> findAllByUserInfoUserIdOrderByIdDesc(String tUser_userId, Pageable pageable);
Page<Post> findAllByDescriptionContainingOrTitleContainingOrUserInfoNickContaining(String query, String query1, String query2, Pageable pageable);
//@Query(value = "select a from #{#entityName} a WHERE EXISTS(SELECT f.follower FROM Following f WHERE f.follower=:me and f.followed=a.user)")
//Page<Post> findAllByOrderByIdDesc(@Param("me") User user, Pageable pageable);
@Query(value = "select a from #{#entityName} a WHERE a IN (SELECT x.post FROM PostLike x WHERE x.userInfo=:me) order by a.id desc")
Page<Post> findAllByOrderByIdDesc(@Param("me") TbCfUserInfo user, Pageable pageable);
@Query(value = "select a from #{#entityName} a WHERE a IN (SELECT x.post FROM PostHashtag x WHERE x.hashtag=:tag) order by a.id desc")
Page<Post> findAllByOrderByIdDesc(@Param("tag") Hashtag hashtag, Pageable pageable);
Page<Post> findAllByOrderByIdDesc(Pageable pageable);
//@Query(value = "select a from #{#entityName} a WHERE NOT EXISTS(SELECT f.follower FROM Following f WHERE f.follower=:me and f.followed=a.user)")
//Page<Post> _findAllByOrderByIdDesc(@Param("me") User user,Pageable pageable);
//Page<Post> _findAllByOrderByIdDesc(Pageable pageable);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.ContentTag;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface PostTagRepository extends CrudRepository<ContentTag, Long> {
@Query(value = "delete ct from content_tag ct INNER JOIN content c ON c.id = ct.content_id WHERE c.post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByPost_Id(@Param("post") Long post_id);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Reply;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ReplyRepository extends PagingAndSortingRepository<Reply,Long> {
Page<Reply> findAllByCommentId(long id, Pageable pageable);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TagRepository extends PagingAndSortingRepository<Tag, Long> {
boolean existsByTagName(String string);
Tag findByTagName(String string);
Page<Tag> findAllByTagNameContaining(String string, Pageable pageable);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfItemComment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfItemCommentRepository extends PagingAndSortingRepository<TbCfItemComment,String> {
boolean existsByUserUserIdAndItemId(String userId, String itemId);
Page<TbCfItemComment> findAllByItemId(String itemId, Pageable pageable);
}
...@@ -9,4 +9,6 @@ public interface UserRepository extends PagingAndSortingRepository<TbCfUserInfo, ...@@ -9,4 +9,6 @@ public interface UserRepository extends PagingAndSortingRepository<TbCfUserInfo,
Optional<TbCfUserInfo> findByAccount(String s); Optional<TbCfUserInfo> findByAccount(String s);
Optional<TbCfUserInfo> findByFirebaseUid(String s); Optional<TbCfUserInfo> findByFirebaseUid(String s);
Optional<TbCfUserInfo> findFirstByEmail(String s); Optional<TbCfUserInfo> findFirstByEmail(String s);
Optional<TbCfUserInfo> findByCode(String s);
boolean existsByCode(String code);
} }
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.Visit;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface VisitRepository extends CrudRepository<Visit,Long> {
@Query(value = "delete from visit WHERE post_id=:post",nativeQuery = true)
@Modifying
@Transactional
void removeByPost_Id(@Param("post") Long post_id);
}
...@@ -21,47 +21,47 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic ...@@ -21,47 +21,47 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableGlobalMethodSecurity( @EnableGlobalMethodSecurity(
// securedEnabled = true, // securedEnabled = true,
// jsr250Enabled = true, // jsr250Enabled = true,
prePostEnabled = true) prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
UserDetailsServiceImpl userDetailsService; UserDetailsServiceImpl userDetailsService;
@Autowired @Autowired
private AuthEntryPointJwt unauthorizedHandler; private AuthEntryPointJwt unauthorizedHandler;
@Bean @Bean
public AuthTokenFilter authenticationJwtTokenFilter() { public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter(); return new AuthTokenFilter();
} }
@Override @Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
} }
@Bean @Bean
@Override @Override
public AuthenticationManager authenticationManagerBean() throws Exception { public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean(); return super.authenticationManagerBean();
} }
@Bean @Bean
public PasswordEncoder passwordEncoder() { public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); return new BCryptPasswordEncoder(12);
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable() http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**","/itemStation/**","/startPage/**","/home/**","/spider/**","/store/**").permitAll() .authorizeRequests().antMatchers("/api/auth/**", "/itemStation/**", "/startPage/**", "/home/**", "/spider/**", "/store/**", "/shopify/**").permitAll()
.antMatchers("/api/test/**").permitAll() .antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated(); .anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
} }
} }
server.servlet.context-path=/zion server.servlet.context-path=/zion
spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:165.22.82.105}:3306/chinafrica?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC spring.datasource.url=jdbc:mysql://${MYSQL_HOST:165.22.82.105}:3306/chinafrica?useUnicode=true&connectionCollation=utf8_general_ci&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root spring.datasource.username=root
spring.datasource.password=clement123 spring.datasource.password=clement123
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.connectionInitSql: SET NAMES 'utf8mb4' spring.datasource.connectionInitSql: SET NAMES 'utf8mb4'
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect #spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
security.oauth2.resource.filter-order=3 security.oauth2.resource.filter-order=3
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论