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

Commenting important notes

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