提交 420a90b7 authored 作者: Whispa's avatar Whispa

Commenting important notes

上级 f5a8d595
......@@ -56,6 +56,9 @@ public class CartController extends Controller {
return new Result<>(ResultCodeEnum.SUCCESS.getCode(), "Item quantity updated");
}
logger.warn("Cart record not found !");
return new Result<>(ResultCodeEnum.SERVICE_ERROR.getCode(), "Failed");
}
......@@ -102,15 +105,19 @@ public class CartController extends Controller {
price = skuOptional.get().getSkuPrice();
}
//Go for reptile products
if (targetUrl != null && itemSkuId == null){
try {
JSONObject detail = spiderService.getItemDetail(targetUrl);
if( !detail.containsKey("originalPriceList"))
if( !detail.containsKey("originalPriceList")) {
logger.warn("No price detected from reptile products");
return skuNotFound;
}
JSONArray priceList = detail.getJSONArray("originalPriceList");
if( priceList.isEmpty() ){
logger.warn("No price detected from reptile products");
return skuNotFound;
}else
price = BigDecimal.valueOf(priceList.getJSONObject(0).getDouble("price"));
......
......@@ -19,6 +19,7 @@ public class CommentLikeController {
@PostMapping(value ="/saveCommentLike/{liked}")
public CommentLike saveCommentLike(@PathVariable("liked") boolean liked, @ModelAttribute("CommentLike") CommentLike like){
//Like status for determine whether to like or dislike
if( liked )
return repository.save(like);
else{
......
......@@ -4,6 +4,8 @@ import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
......@@ -27,6 +29,7 @@ public class ItemController {
private final TbCfItemCollectionRepository collectionRepository;
private final TbCfItemParamRepository itemParamRepository;
private final TbCfRecommendRepository recommendRepository;
private static Logger logger = LoggerFactory.getLogger(ItemController.class);
public ItemController(TbCfStationItemRepository repository, TbCfGoodstwotypeRepository goodstwotypeRepository, TbCfGoodstypeRepository goodstypeRepository, TbCfDescripitonRepository descriptionRepository, TbCfCategoryRepository categoryRepository, TbCfItemSkuRepository skuRepository, TbCfItemDescRepository descRepository, TbCfItemCollectionRepository collectionRepository, TbCfItemParamRepository itemParamRepository, TbCfRecommendRepository recommendRepository) {
this.repository = repository;
......@@ -91,7 +94,7 @@ public class ItemController {
try {
List<SearchModel> list = repository.searchAllItems(name, pageNum * pageSize, pageSize);
Long count = repository.countAllBySearchItems(name);
Long totalPage = 0L;
long totalPage;
if (count % pageSize == 0) {
totalPage = count / pageSize;
} else {
......@@ -126,7 +129,7 @@ public class ItemController {
Page<TbCfStationItem> recommendItems = repository.getRecommendItems(itemId, stationItem.getItemDescritionId(), stationItem.getItemCategorytwo(), stationItem.getItemCategory(), PageRequest.of(pageNum, pageSize));
return new Result<>(recommendItems);
}
}else logger.warn("Recommended item not found");
return new Result<>(new ArrayList<>(), ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(), "Item id is invalid or not found");
}
......@@ -187,7 +190,7 @@ public class ItemController {
@RequestParam(value = "userId", required = false) String userId) {
Optional<TbCfStationItem> itemOptional = repository.findById(itemId);
//Check if item is available
if (!itemOptional.isPresent())
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(), "Item Id is not found");
......
......@@ -8,6 +8,8 @@ import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.TbCfItemCommentRepository;
import com.example.afrishop_v3.repository.TbCfItemLikeRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
......@@ -18,6 +20,7 @@ public class ItemLikeController {
private final TbCfItemLikeRepository repository;
private final TbCfItemCommentRepository commentRepository;
private final AuthenticationUser user;
private static Logger logger = LoggerFactory.getLogger(ItemLikeController.class);
public ItemLikeController(TbCfItemLikeRepository repository, TbCfItemCommentRepository commentRepository, AuthenticationUser user) {
this.repository = repository;
......@@ -31,8 +34,11 @@ public class ItemLikeController {
try {
Optional<TbCfItemComment> commentOptional = commentRepository.findById(commentId);
//Check if comment exists
if( !commentOptional.isPresent() )
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Item comment not found !");
if( !commentOptional.isPresent() ) {
logger.warn("Item Comment not found !");
logger.warn(commentId);
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Item comment not found !");
}
TbCfUserInfo user = this.user.user();
String userId = user.getUserId();
//Check if comment is already liked
......@@ -51,6 +57,8 @@ public class ItemLikeController {
repository.save(itemLike);
}catch (Exception e){
System.out.println(e.getMessage());
logger.debug(e.getMessage());
logger.warn(e.toString());
}
return new Result<>(true,"Comment liked");
......
......@@ -4,6 +4,8 @@ package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.models.PostLike;
import com.example.afrishop_v3.repository.LikeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
......@@ -13,6 +15,7 @@ import java.util.List;
@RequestMapping("/discover/like")
public class LikeController {
private final LikeRepository repository;
private static Logger logger = LoggerFactory.getLogger(LikeController.class);
public LikeController(LikeRepository repository) {
this.repository = repository;
......@@ -28,8 +31,12 @@ public class LikeController {
//Like a post
@PostMapping(value = "/saveLike/{status}")
public Result saveProduct(@PathVariable(value = "status") boolean status, @ModelAttribute("PostLike") PostLike like) {
//status is true if mean to like post
//status if false if mean to be disliked
if (status) {
//check existence before deleting
if( !repository.existsByUserInfo_UserIdAndPost_Id(like.getUserId(),like.getPostId())) repository.save(like);
else logger.info("Not found");
}else repository.removeByUser_IdAndPost_Id(like.getUserId(), like.getPostId());
return new Result();
}
......
......@@ -9,6 +9,8 @@ import com.example.afrishop_v3.repository.TbCfExpressTemplateRepository;
import com.example.afrishop_v3.repository.TbCfPlatformOrderRepository;
import com.example.afrishop_v3.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -39,6 +41,7 @@ public class LogisticsController {
private final TbCfPlatformOrderRepository repository;
private final TbCfExpressTemplateRepository expressTemplateRepository;
private static Logger logger = LoggerFactory.getLogger(LogisticsController.class);
public LogisticsController(TbCfPlatformOrderRepository repository, TbCfExpressTemplateRepository expressTemplateRepository) {
this.repository = repository;
......@@ -47,7 +50,7 @@ public class LogisticsController {
@GetMapping("/getOrderLogistics/{orderDetailId}")
public Result getOrderLogistics(@PathVariable("orderDetailId") String orderDetailId) {
Result result = new Result();
Result<JSONObject> result = new Result<>();
try {
/**
* {
......@@ -86,6 +89,8 @@ public class LogisticsController {
if (StringUtils.isBlank(data)) {
result.setCode(ResultCodeEnum.QUERY_ERROR.getCode());
result.setMessage("No logistics information");
logger.info("No logistics information");
logger.info(orderDetailId);
return result;
}
}
......@@ -100,6 +105,6 @@ public class LogisticsController {
@GetMapping("/freeShippingThreshold")
public Result freeShippingThreshold(){
return new Result(expressTemplateRepository.findFirstByIsDefault(1));
return new Result<>(expressTemplateRepository.findFirstByIsDefault(1));
}
}
......@@ -65,6 +65,8 @@ public class OrderController extends Controller {
this.user = user;
}
//Simulate cart object for payNow process
private TbCfCartRecordR getCart(TbCfStationItem item, String itemSku, Integer itemNum, BigDecimal price, TbCfItemSkus itemSkuObj) {
TbCfCartRecordR record = new TbCfCartRecordR();
......@@ -76,7 +78,7 @@ public class OrderController extends Controller {
record.setCartRecordId(IdUtil.createIdbyUUID());
record.setItemSku(itemSku);
record.setItemSkuId(itemSkuObj.getId());
record.setItemCount( itemSkuObj.getSkuCount() == null ? 0 : itemSkuObj.getSkuCount());
record.setItemCount(itemSkuObj.getSkuCount() == null ? 0 : itemSkuObj.getSkuCount());
record.setTemplate(item.getExpress());
record.setItemTitle(item.getItemName());
record.setItemPrice(price);
......@@ -90,6 +92,8 @@ public class OrderController extends Controller {
public Result convert(@RequestParam("price") BigDecimal price, @RequestParam("currency") String currency) {
TbCfExchange exchangeEntity = exchangeRepository.findByExchangeCurrency(currency.toUpperCase());
if (exchangeEntity == null) {
logger.warn("Currency not found");
logger.warn(currency);
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(), "Currency Not Found");
}
BigDecimal rate = exchangeEntity.getExchangeRate();
......@@ -139,10 +143,11 @@ public class OrderController extends Controller {
//Check whether the inventory is greater than the purchased quantity before placing an order
boolean anyMatch = list.stream().anyMatch(TbCfCartRecordR::isOutOfStock);
if( anyMatch ) return new Result<>(code, "Items run out of stock");
if (anyMatch) return new Result<>(code, "Items run out of stock");
order.setCouponId(toitableId);
//Check coupon availability
if (toitableId != null && !toitableId.isEmpty()) {
Optional<TbCfToicoupon> couponOptional = toicouponRepository.findById(toitableId);
......@@ -154,7 +159,7 @@ public class OrderController extends Controller {
}
order.setOpen(open);
order.setCouponMap(map);
order.getItemOrderListFromCartList(list, itemRepository,activityRepository);
order.getItemOrderListFromCartList(list, itemRepository, activityRepository);
return new Result<>(order);
}
......@@ -180,7 +185,7 @@ public class OrderController extends Controller {
////Check whether the inventory is greater than the purchased quantity before placing an order
boolean anyMatch = allByUserId.stream().anyMatch(TbCfCartRecordR::isOutOfStock);
if( anyMatch ) return new Result<>(code, "Items run out of stock");
if (anyMatch) return new Result<>(code, "Items run out of stock");
TbCfOrder order = new TbCfOrder();
order.setCouponMap(couponMap);
......@@ -201,7 +206,7 @@ public class OrderController extends Controller {
}
order.setOpen(open);
order.getItemOrderListFromCartList(allByUserId, itemRepository,activityRepository);
order.getItemOrderListFromCartList(allByUserId, itemRepository, activityRepository);
return new Result<>(order);
......@@ -224,7 +229,7 @@ public class OrderController extends Controller {
@RequestParam(value = "itemSkuId", required = false) String itemSkuId,
@RequestParam(value = "orderSource", required = false) Integer orderSource,
@RequestParam(value = "open", required = false) boolean open
) throws IOException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException, ParseException {
) throws ParseException {
TbCfUserInfo user = this.user.user();
String userId = user.getUserId();
......@@ -291,7 +296,7 @@ public class OrderController extends Controller {
//Check whether the inventory is greater than the purchased quantity before placing an order
boolean anyMatch = allByUserId.stream().anyMatch(TbCfCartRecordR::isOutOfStock);
if( anyMatch ) return new Result<>(v_code, "Items run out of stock");
if (anyMatch) return new Result<>(v_code, "Items run out of stock");
String addressId = tbCfOrder.getDeliveryAddressId();
......@@ -336,22 +341,21 @@ public class OrderController extends Controller {
tbCfToicoupon = couponOptional.get();
TbCfCoupon coupon = tbCfToicoupon.getCoupon();
order.setCoupon(coupon);
}
} else logger.warn("Invalid Coupon " + toitableId);
}
order.setUserId(userId);
if (orderSource==null){
if (orderSource == null) {
order.setOrderSource(1);
}else {
} else {
order.setOrderSource(orderSource);
}
order.setOpen(open);
order.getItemOrderListFromCartList(allByUserId, itemRepository,activityRepository);
order.getItemOrderListFromCartList(allByUserId, itemRepository, activityRepository);
TbCfOrder save = repository.save(order);
......@@ -366,12 +370,13 @@ public class OrderController extends Controller {
List<String> collect = allByUserId.stream().map(TbCfCartRecordR::getCartRecordId).collect(Collectors.toList());
//Convert to array
String[] strings = collect.toArray(new String[]{});
if (payNow) {
//Automatically remove the shelf when the stock is insufficient
cartRepository.updateItemShelf_(itemId,itemNum);
cartRepository.updateItemShelf_(itemId, itemNum);
//Inventory reduction for pay now item
cartRepository.updateItemQuantity_(itemId, itemNum);
cartRepository.updateSkuQuantity_(itemSkuId, itemNum);
......@@ -478,6 +483,8 @@ public class OrderController extends Controller {
System.out.println(orderId);
logger.warn("Order deleted");
repository.save(order);
return new Result();
......@@ -499,6 +506,7 @@ public class OrderController extends Controller {
boolean exists = commentRepository.existsByUserUserIdAndItemId(userId, itemId);
if (exists) {
//Product reviewed condition
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Already reviewed this product!");
}
......@@ -519,7 +527,7 @@ public class OrderController extends Controller {
}
private Sort sort(String order) {
String col = "orderTime";
String col = "orderTime";//Sort by order tim
return Sort.by("desc".equals(order) ? desc(col) : asc(col));
}
......@@ -527,7 +535,6 @@ public class OrderController extends Controller {
@GetMapping("/details/{orderId}")
public Result getOrderDetails(@PathVariable("orderId") String orderId) {
Optional<TbCfOrder> optionalTbCfOrder = repository.findById(orderId);
String minutes = "160";
Date current = new Date();
if (!optionalTbCfOrder.isPresent()) {
......
......@@ -11,6 +11,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.util.Base64;
import com.google.api.client.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
......@@ -43,6 +45,7 @@ public class PostController {
private final ComplainRepository complainRepository;
private final PostHashtagRepository postHashtagRepository;
private final AuthenticationUser user;
private static Logger logger = LoggerFactory.getLogger(PostController.class);
public PostController(PostRepository repository, LikeRepository likeRepository, CommentRepository commentRepository, PostTagRepository postTagRepository, ContentRepository contentRepository, UserRepository userRepository, VisitRepository visitRepository, BonusRepository bonusRepository, HashtagRepository hashtagRepository, TbCfStationItemRepository itemRepository, TagRepository tagRepository, ComplainRepository complainRepository, PostHashtagRepository postHashtagRepository, AuthenticationUser user) {
......@@ -79,8 +82,10 @@ public class PostController {
Optional<Hashtag> byName = hashtagRepository.findFirstByName(tag);
if (!byName.isPresent()) return new ArrayList<>();
if (!byName.isPresent()){
logger.info("Hashtag not found");
return new ArrayList<>();
}
//return found result
return repository.findAllByOrderByCreateDateDesc(byName.get(), PageRequest.of(pageNo, pageSize)).toList();
}
......@@ -90,7 +95,7 @@ public class PostController {
Optional<TbCfUserInfo> byId = userRepository.findById(id);
if (!byId.isPresent()) return new ArrayList<>();
List<Post> postList = repository.findAllByOrderByCreateDateDesc(byId.get(), PageRequest.of(pageNo, pageSize)).toList();
return id == null ? postList : postList(postList, id);
return postList(postList, id);
}
......@@ -117,12 +122,14 @@ public class PostController {
TbCfUserInfo user = this.user.user();
if(complainRepository.existsByUserInfoAndPost(user,complain.getPost())){
//Complain already exists
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Already complained");
}
String userId = complain.userId();
if( userId == null ){
//return if user not found
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"User not found");
}
......@@ -132,6 +139,8 @@ public class PostController {
TbCfUserInfo info = byId.get();
if( "8AD1dO".equals(info.getCode()) || "xdEmqd".equals(info.getCode()) || "MdjDn0".equals(info.getCode())){
del(complain.postId());
logger.warn("Post automatically deleted by :");
logger.warn(info.display());
return new Result<>(complain);
}
}
......@@ -153,6 +162,7 @@ public class PostController {
Post post = optional.get();
List<PostHashtag> hashtagList = new ArrayList<>(post.hashtagList);
List<Content> contentList = new ArrayList<>(post.contentList);
//Declare new post to be copied to
Post nPost = new Post();
nPost.setUser(byId.get());
nPost.setTitle(post.getTitle());
......@@ -160,12 +170,14 @@ public class PostController {
nPost.setCategory(post.getCategory());
nPost = repository.save(nPost);
Post finalNPost = nPost;
//Copy hashtags
hashtagList.forEach(f -> {
PostHashtag hashtag = new PostHashtag();
hashtag.setPost(finalNPost);
hashtag.setHashtag(f.getHashtag());
postHashtagRepository.save(hashtag);
});
//Copy post contents
contentList.forEach(f -> {
List<ContentTag> tagList = new ArrayList<>(f.contentTags);
Content content = new Content();
......@@ -219,7 +231,7 @@ public class PostController {
@Transactional //manage transaction for many queries
public String del(@PathVariable("postId") String id) {
try {
//Delete all chained information to the post
likeRepository.removeByPost_Id(id);
commentRepository.removeByPost_Id(id);
postTagRepository.removeByPost_Id(id);
......@@ -236,8 +248,7 @@ public class PostController {
@Transactional()
@PostMapping("/upload")
public List<String> handleFileUpload(@RequestParam("files") MultipartFile[] files, @RequestParam("thumbs") MultipartFile[] thumbs, @ModelAttribute("Post") Post ePost,
RedirectAttributes redirectAttributes) throws IOException {
public List<String> handleFileUpload(@RequestParam("files") MultipartFile[] files, @RequestParam("thumbs") MultipartFile[] thumbs, @ModelAttribute("Post") Post ePost) {
Post post = new Post();
TbCfUserInfo user = this.user.user();
post.setUser(user);
......@@ -256,11 +267,12 @@ public class PostController {
// Path store = storageService.store(file);
// String string = MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
// "serveFile", store.getFileName().toString()).build().toUri().toString();
String string = null;
String string;
try {
string = OssUtil.upload(file,"discover");
} catch (Exception e) {
System.out.println(e.getMessage());
logger.debug(e.getMessage());
continue;
}
thumbList.add(string);
......@@ -275,11 +287,11 @@ public class PostController {
// Path store = storageService.store(file);
// String string = MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
// "serveFile", store.getFileName().toString()).build().toUri().toString();
String string = null;
String string;
try {
string = OssUtil.upload(file,"discover");
} catch (Exception e) {
System.out.println(e.getMessage());
logger.warn(e.getMessage());
continue;
}
list.add(string);
......@@ -305,6 +317,7 @@ public class PostController {
});
} catch (JsonProcessingException e) {
System.out.println(e.getMessage());
logger.warn(e.getMessage());
}
if (hashtags != null) {
......@@ -351,6 +364,8 @@ public class PostController {
item = itemOptional.get();
} else {
//item = itemRepository.save(item);
logger.warn("Product not found");
logger.warn(item.getItemId());
}
tag.setStationItem(item);
......@@ -358,6 +373,8 @@ public class PostController {
ContentTag contentTag = new ContentTag();
if (!tagRepository.existsByTagName(tag.getTagName())) {
// tagRepository.save(tag);
logger.warn("Tag Not found");
logger.warn(tag.getTagName());
} else {
tag = tagRepository.findByTagName(tag.getTagName());
}
......@@ -373,12 +390,14 @@ public class PostController {
}
}catch (Exception e){
System.out.println(e.getMessage());
logger.warn(e.getMessage());
}
//redirectAttributes.addFlashAttribute();
try {
repository.save(post);
}catch (Exception e){
logger.warn(e.getMessage());
System.out.println(e.getMessage());
}
......
......@@ -22,6 +22,7 @@ public class ProblemController {
@GetMapping
public Result getProblemList(@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
//Assign defaults if no parameters sent
pageNum = pageNum == null ? 1 : pageNum;
pageSize = pageSize == null ? 10 : pageSize;
return new Result<>(repository.findAll(PageRequest.of(pageNum, pageSize)));
......@@ -35,7 +36,7 @@ public class ProblemController {
TbCfProblem problem = new TbCfProblem();
problem.setQuestion(clause.getQuestion());
problem.setAnswer(shippingClause);
return new Result(problem);
return new Result<>(problem);
}
}
......@@ -27,21 +27,21 @@ public class SearchController {
@PostMapping("/save")
public Result save(@RequestBody TbCfSearch tbCfSearch) {
//NotNull body is required
if (tbCfSearch == null)
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Empty body !");
String searchKeywords = tbCfSearch.getSearchKeywords();
//Keyword is also required
if (searchKeywords == null || searchKeywords.trim().isEmpty())
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Empty search keyword !");
//Remove trailing spaces
searchKeywords = searchKeywords.trim();
String userId = user.userId();
Optional<TbCfSearch> optional = repository.findFirstBySearchKeywordsAndUserId(searchKeywords, userId);
//Replace db object if found
tbCfSearch = optional.orElse(tbCfSearch);
......
......@@ -7,6 +7,8 @@ import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.TbCfItemCommentRepository;
import com.example.afrishop_v3.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -21,6 +23,7 @@ import java.util.Optional;
public class ShopifyController {
private final TbCfItemCommentRepository repository;
private final UserRepository userRepository;
private static Logger logger = LoggerFactory.getLogger(ShopifyController.class);
public ShopifyController(TbCfItemCommentRepository repository, UserRepository userRepository) {
this.repository = repository;
......@@ -42,7 +45,7 @@ public class ShopifyController {
page.getContent().forEach(v-> v.getItemComment().setLike(v.getCommented() != null && v.getCommented() > 0));
Page<TbCfItemComment> map = page.map(CommentCount::getItemComment);
return new Result<>(map);
}
}else logger.info("User id not found");
}
Page<TbCfItemComment> list = repository.findAllByItemId(itemId, request);
......
......@@ -4,6 +4,8 @@ import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -25,6 +27,7 @@ public class TbCfHomePageEntityController extends Controller {
private final UserRepository userRepository;
private final VisitRepository visitRepository;
private final PostRepository postRepository;
private static Logger logger = LoggerFactory.getLogger(UploadController.class);
public TbCfHomePageEntityController(TbCfHomePageRepository repository, TbCfSortRepository sortRepository, TbCfClassificationRepository classificationRepository, TbCfStoreRepository storeRepository, TbCfPosterRepository posterRepository, TbCfColumnRepository columnRepository, UserRepository userRepository, VisitRepository visitRepository, PostRepository postRepository) {
this.repository = repository;
......@@ -73,9 +76,11 @@ public class TbCfHomePageEntityController extends Controller {
if (byId.isPresent()) {
Post post = byId.get();
visitPost(post);
//Retrieve all post related information this is important to increase community performance while serializing json
post.retrieveAll = true;
return post;
}
logger.info("Post not found");
return null;
}
......@@ -83,6 +88,7 @@ public class TbCfHomePageEntityController extends Controller {
@GetMapping("/home/clientWithFcm")
public Result getClientList( @RequestParam(value = "pageNo",required = false,defaultValue = "20") Integer pageNo, @RequestParam(value = "pageSize",required = false,defaultValue = "20") Integer pageSize){
List<TbCfUserInfo> allByFcmIsNotNull = userRepository.findAllByFcmIsNotNullOrderByLastLoginTimeDesc(PageRequest.of(pageNo, pageSize));
//Map list to Small map to minimize amount of json serialized information
return new Result<>(allByFcmIsNotNull.stream().map(TbCfUserInfo::smallMap).collect(Collectors.toList()));
}
......@@ -130,7 +136,7 @@ public class TbCfHomePageEntityController extends Controller {
}
list.add(moduleMap);
}
Map map = new HashMap();
Map<String,Object> map = new HashMap<>();
List<TbCfColumn> hotColumnList = columnRepository.findAllByColumnType(4);
map.put("hot_title", hotColumnList);
list.add(map);
......
......@@ -5,6 +5,8 @@ import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.util.HttpClientUtil;
import com.example.afrishop_v3.util.OssUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
......@@ -23,6 +25,7 @@ public class UploadController {
@Value("${upload.api}")
private String api;
private static Logger logger = LoggerFactory.getLogger(UploadController.class);
@PostMapping("/uploadFile")
public Result uploadFile(@RequestBody String strImg) throws Exception {
......@@ -33,7 +36,7 @@ public class UploadController {
return result;
}
static String sendFile(String strImg,String api){
private static String sendFile(String strImg,String api){
try {
if (!StringUtils.isBlank(strImg)) {
......@@ -42,9 +45,11 @@ public class UploadController {
String url = HttpClientUtil.sendPostWithBodyParameter(api, map);
return url.substring(1, url.length() - 1);
} else {
logger.info("Null Image");
return null;
}
} catch (Exception e) {
logger.info(e.getMessage());
return null;
}
}
......
......@@ -130,6 +130,7 @@ public class UserController extends Controller {
Integer sentCount = user.getSentCount();
if( sentCount == null ){
//Set count if not available
user.setSentCount(-1);
sentCount = -1;
}
......@@ -181,6 +182,7 @@ public class UserController extends Controller {
public Result updatePassword(@RequestBody ResetBody body){
if( body == null || body.getNewPassword() == null || body.getOldPassword() == null || body.getOldPassword().isEmpty() || body.getNewPassword().isEmpty()){
//Validate reset password body
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Empty body");
}
......@@ -191,6 +193,7 @@ public class UserController extends Controller {
boolean matches = encoder.matches(body.getOldPassword(), user.getPassword());
if( !matches ){
//Valid old password is required
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Old password does not match");
}
......@@ -198,6 +201,7 @@ public class UserController extends Controller {
boolean matches1 = encoder.matches(body.getNewPassword(), user.getPassword());
if( matches1 ){
//Can't match old password
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Can’t change to the same password as last time");
}
......@@ -212,14 +216,16 @@ public class UserController extends Controller {
@PutMapping
public Result updateUser(@RequestBody TbCfUserInfo info) {
TbCfUserInfo user = this.user.user();
//return if body is null
if (info == null) return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Empty body");
if(StringUtils.isNotBlank(info.getAvatar()) ){
//set avatar image url
user.setAvatar(info.getAvatar());
}
if( info.getBirthday() != null ){
//only supported format received
user.setBirthday(info.getBirthday());
}
......@@ -253,6 +259,7 @@ public class UserController extends Controller {
if( byId.isPresent() && byId.get().hasFcm() ){
TbCfUserInfo userInfo = byId.get();
sendNotification(userInfo.getFcm(),title,content);
logger.info("Notification sent to "+userInfo.display());
return new Result();
}
......@@ -268,9 +275,9 @@ public class UserController extends Controller {
}
@PostMapping(value = "/edit/slogan")
public Result editSlogan(@RequestBody TbCfUserInfo tbCfUserInfo) {
//decode user from token
TbCfUserInfo user = this.user.user();
//Check not null
if( user != null && tbCfUserInfo != null){
user.setSlogan(tbCfUserInfo.getSlogan());
repository.save(user);
......@@ -312,9 +319,9 @@ public class UserController extends Controller {
@DeleteMapping("/delCollection")
public Result delCollection(@RequestBody String[] collectionIds) {
//Check if body is not null
if( collectionIds == null ) return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Empty body");
//Check if body is not empty
if( collectionIds.length == 0 ) return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Empty body");
String userId = user.userId();
......
......@@ -39,12 +39,12 @@ public class WithdrawController {
}
Optional<TbCfUserInfo> byId = withdraw.getUserId() == null ? Optional.empty() : userRepository.findById(withdraw.getUserId());
//Check Id availability
if( !byId.isPresent() ){
code = 0;
message = "Service Error";
}
//Check balance
if( byId.isPresent() && byId.get().ogWallet() < withdraw.getAmount().doubleValue() ){
code = 0;
message = "Insufficient balance";
......
......@@ -287,7 +287,7 @@ public class TbCfStationItem {
return itemImg;
}
//Get first image from many separated by comma
public String catchSingleImage(){
String itemImg = getItemImg();
String[] strings = itemImg != null ? itemImg.split(";") : new String[]{};
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论