optimize the code

This commit is contained in:
Cauchy
2023-10-09 13:27:13 +08:00
parent 7c25318835
commit 0453bead38
4 changed files with 177 additions and 209 deletions

View File

@@ -2,21 +2,16 @@ package com.peanut.modules.book.controller;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peanut.modules.book.entity.*;
import com.peanut.modules.book.service.*;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
@@ -56,21 +51,9 @@ public class BuyOrderController {
@Autowired
private TransactionDetailsService transactionDetailsService;
@Autowired
private AuthorService authorService;
@Autowired
private UserEbookBuyService userEbookBuyService;
@Autowired
private BookService bookService;
@Autowired
private BookShelfService bookShelfService;
@Autowired
private UserRecordService userRecordService;
@Autowired
private UserFollowUpService userFollowUpService;
@Autowired
private PayWechatOrderService payWechatOrderService;
@Autowired
private PayZfbOrderService payZfbOrderService;
/**
* 订单状态 - 待支付
@@ -85,19 +68,19 @@ public class BuyOrderController {
*/
private static final String ORDER_STATUS_TO_BE_RECEIVED = "2";
/**
* 支付方式 - 支付宝
* 支付方式 - 支付宝 - 支付宝支付
*/
private static final String PAYMENT_METHOD_ALI_PAY = "1";
/**
* 支付方式
* 支付方式 - 微信支付
*/
private static final String PAYMENT_METHOD_WECHAT_PAY = "2";
/**
* 支付方式
* 支付方式 - IOS 内购
*/
private static final String PAYMENT_METHOD_IOS = "3";
/**
* 支付方式
* 支付方式 - 虚拟币支付
*/
private static final String PAYMENT_METHOD_VIRTUAL = "4";
/**
@@ -143,149 +126,75 @@ public class BuyOrderController {
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{orderId}")
public R info(@PathVariable("orderId") Integer orderId) {
BuyOrderEntity buyOrder = buyOrderService.getById(orderId);
return R.ok().put("buyOrder", buyOrder);
}
/**
* 下单
*
* @param buyOrder 订单
* @return R
*/
@RequestMapping("/buySave")
@Transactional
public R buySave(@RequestBody BuyOrderEntity buyOrder) {
BigDecimal realMoney;
// 根据订单获取订单详情
// 获取订单详情
List<BuyOrderDetailEntity> products = buyOrder.getProducts();
// ?
// 订单总金额
BigDecimal totalPrice = new BigDecimal(0);
List<BuyOrderDetailEntity> list = new ArrayList<>();
// 遍历商品 查询价格
// 遍历商品总价计算
for (BuyOrderDetailEntity buyOrderDetail : products) {
BuyOrderDetailEntity buyOrderDetailEntity = new BuyOrderDetailEntity();
Integer productId = buyOrderDetail.getProductId();
ShopProductEntity product = shopProductService.getById(productId);
BigDecimal activityPrice = product.getActivityPrice();
// 实际执行价格
BigDecimal price;
if (activityPrice == null || activityPrice.equals(BigDecimal.ZERO)) {
price = product.getPrice();
} else {
price = product.getActivityPrice();
}
int quantity = buyOrderDetail.getQuantity();
totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(quantity)));
if (product.getProductStock() - quantity < 0) {
ShopProductEntity product = shopProductService.getById(productId);
BigDecimal price = getRealPrice(product);
if (!handleStock(buyOrderDetail, product)) {
return R.error(500, "库存不足");
}
// 更新商品库存
product.setProductStock(product.getProductStock() - quantity);
product.setSumSales(product.getSumSales() + quantity);
shopProductService.updateById(product);
BeanUtils.copyProperties(buyOrderDetail, buyOrderDetailEntity);
buyOrderDetailEntity.setProductName(product.getProductName());
buyOrderDetailEntity.setProductPrice(product.getPrice());
buyOrderDetailEntity.setAddressId(buyOrder.getAddressId());
buyOrderDetailEntity.setProductUrl(product.getProductImages());
buyOrderDetailEntity.setOrderStatus(ORDER_STATUS_TO_BE_PAID);
list.add(buyOrderDetailEntity);
totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(quantity)));
buyOrderDetail.setProductName(product.getProductName());
buyOrderDetail.setProductPrice(product.getPrice());
buyOrderDetail.setAddressId(buyOrder.getAddressId());
buyOrderDetail.setProductUrl(product.getProductImages());
buyOrderDetail.setOrderStatus(ORDER_STATUS_TO_BE_PAID);
}
Integer couponId = buyOrder.getCouponId();
totalPrice = totalPrice.subtract(useCouponAmount(buyOrder));
totalPrice = totalPrice.add(getShoppingAmount(buyOrder));
String orderSn = IdWorker.getTimeId().substring(0, 32);
buyOrder.setOrderSn(orderSn);
buyOrder.setPaymentDate(new Date());
buyOrderService.save(buyOrder);
if (couponId != null) {
CouponHistoryEntity couponHistory = couponHistoryService.getById(couponId);
CouponEntity coupon = couponService.getById(couponHistory.getCouponId());
BigDecimal amount = coupon.getCouponAmount();
totalPrice = totalPrice.subtract(amount);
}
if (buyOrder.getShippingMoney() != null) {
totalPrice = totalPrice.add(buyOrder.getShippingMoney());
}
// 减去优惠券金额
realMoney = buyOrder.getRealMoney();
if (totalPrice.compareTo(realMoney) == 0) {
//特定格式的时间ID
String timeId = IdWorker.getTimeId().substring(0, 32);
buyOrder.setOrderSn(timeId);
if (PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) {
buyOrder.setOrderStatus(ORDER_STATUS_TO_BE_SHIPPED);
}
buyOrder.setPaymentDate(new Date());
buyOrderService.save(buyOrder);
for (BuyOrderDetailEntity buyOrderDetailEntity : list) {
buyOrderDetailEntity.setOrderId(buyOrder.getOrderId());
buyOrderDetailEntity.setUserId(buyOrder.getUserId());
// 判断结算状态
String buyType = buyOrder.getBuyType();
if (buyType.equals(BUY_TYPE_CART)) {
// 更改购物车 状态
List<OrderCartEntity> orderCartList = orderCartService.getBaseMapper().selectList(new QueryWrapper<OrderCartEntity>()
.eq("user_id", buyOrder.getUserId()).eq("product_id", buyOrderDetailEntity.getProductId()));
if (orderCartList.size() > 0) {
List<Integer> collect = orderCartList.stream().map(orderCartEntity -> {
Integer cartId = orderCartEntity.getCartId();
return cartId;
}).collect(Collectors.toList());
orderCartService.removeByIds(collect);
}
}
}
buyOrderDetailService.saveBatch(list);
if (couponId != null) {
//更改优惠券状态
CouponHistoryEntity one = couponHistoryService.getById(couponId);
one.setUseStatus(1);
one.setUseTime(new Date());
one.setOrderId(Long.valueOf(buyOrder.getOrderId()));
one.setOrderSn(buyOrder.getOrderSn());
couponHistoryService.updateById(one);
}
if ("4".equals(buyOrder.getPaymentMethod())) {
MyUserEntity user = this.myUserService.getById(buyOrder.getUserId());
if (user.getPeanutCoin().compareTo(realMoney) >= 0) {
user.setPeanutCoin(user.getPeanutCoin().subtract(realMoney));
this.myUserService.updateById(user);
// 添加消费信息
TransactionDetailsEntity transactionDetailsEntity = new TransactionDetailsEntity();
transactionDetailsEntity.setRemark("购买健康超市用品!订单编号为《 " + buyOrder.getOrderSn() + "");
transactionDetailsEntity.setUserId(user.getId());
transactionDetailsEntity.setUserName(user.getNickname());
transactionDetailsEntity.setChangeAmount(realMoney.negate());
transactionDetailsEntity.setUserBalance(user.getPeanutCoin());
transactionDetailsEntity.setTel(user.getTel());
transactionDetailsEntity.setOrderType("购买健康超市用品!");
transactionDetailsService.save(transactionDetailsEntity);
//购买成功后,添加书到个人表中
List<Integer> pros = products.stream().map(BuyOrderDetailEntity::getProductId).collect(Collectors.toList());
for (Integer s : pros) {
List<Integer> collect = shopProudictBookService.getBaseMapper().selectList(new LambdaQueryWrapper<ShopProudictBookEntity>()
.eq(ShopProudictBookEntity::getProudictId, s)
.eq(ShopProudictBookEntity::getDelFlag, 0)).stream().map(ShopProudictBookEntity::getBookId).collect(Collectors.toList());
userEbookBuyService.addBookForUser(buyOrder.getUserId(), collect);
}
} else {
return R.error("余额不足!");
}
for (BuyOrderDetailEntity buyOrderDetail : products) {
buyOrderDetail.setOrderId(buyOrder.getOrderId());
buyOrderDetail.setUserId(buyOrder.getUserId());
if (BUY_TYPE_CART.equals(buyOrder.getBuyType())) {
handleBuyCart(buyOrder, buyOrderDetail);
}
}
return R.ok().put("orderSn", buyOrder.getOrderSn()).put("money", realMoney);
buyOrderDetailService.saveBatch(products);
if (PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) {
buyOrder.setOrderStatus(ORDER_STATUS_TO_BE_SHIPPED);
MyUserEntity user = this.myUserService.getById(buyOrder.getUserId());
if (usePeanutCoin(user, totalPrice)) {
recordTransaction(buyOrder, user, totalPrice);
addEbookToUser(products, buyOrder);
} else {
return R.error(500, "花生币余额不足!");
}
}
Map<String, Object> result = new HashMap<>();
result.put("orderSn", buyOrder.getOrderSn());
result.put("money", totalPrice);
return R.ok(result);
}
@@ -293,10 +202,8 @@ public class BuyOrderController {
* 修改
*/
@RequestMapping("/update")
// @RequiresPermissions("book:buyorder:update")
public R update(@RequestBody BuyOrderEntity buyOrder) {
buyOrderService.updateById(buyOrder);
return R.ok();
}
@@ -304,10 +211,8 @@ public class BuyOrderController {
* 删除
*/
@RequestMapping("/delete")
// @RequiresPermissions("book:buyorder:delete")
public R delete(@RequestBody Integer[] orderIds) {
buyOrderService.removeByIds(Arrays.asList(orderIds));
return R.ok();
}
@@ -315,10 +220,8 @@ public class BuyOrderController {
* 列表
*/
@RequestMapping("/appUserGetlist")
// @RequiresPermissions("book:buyorder:list")
public R appUserGetlist(@RequestParam Map<String, Object> params) {
PageUtils page = buyOrderService.queryPage1(params);
return R.ok().put("page", page);
}
@@ -327,82 +230,46 @@ public class BuyOrderController {
* app 端 取消订单
*/
@RequestMapping("/appDelete")
// @RequiresPermissions("book:buyorder:delete")
@Transactional
public R appDelete(@RequestParam("orderId") Integer orderId) {
//1. 判断订单状态
BuyOrderEntity byId = buyOrderService.getById(orderId);
if (byId != null) {
//2. 判断当前订单是否存在优惠券 进行 回显
Integer couponId = byId.getCouponId();
if (couponId != null) {
CouponHistoryEntity byId1 = couponHistoryService.getById(couponId);
byId1.setUseStatus(0);
couponHistoryService.updateById(byId1);
}
// 库存回滚
List<BuyOrderDetailEntity> buyOrderDetailEntities = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>()
.eq("order_id", byId.getOrderId()));
for (BuyOrderDetailEntity buyOrderDetailEntity : buyOrderDetailEntities) {
Integer productId = buyOrderDetailEntity.getProductId();
ShopProductEntity product = shopProductService.getById(productId);
product.setProductStock(product.getProductStock() + buyOrderDetailEntity.getQuantity());
shopProductService.updateById(product);
}
// //3. 恢复当前订单 的 购物车商品
//
// List<BuyOrderDetailEntity> products = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>()
// .eq("order_id", orderId));
//
// for (BuyOrderDetailEntity product : products) {
//
// Integer productId = product.getProductId();
//
// OrderCartEntity byId1 = orderCartService.getDeteleOrderCarts(byId.getUserId(),productId);
//
// byId1.setDelFlag(0);
//
// orderCartService.updateById(byId1);
//
// }
buyOrderService.removeById(orderId);
}
return R.ok();
}
@RequestMapping("/randomOrderCode")
@Transactional
public R randomOrderCode(@RequestBody BuyOrderEntity buyOrder) {
// String re= String.valueOf(buyOrderService.randomOrderCode(buyOrder));
// buyOrderService.save(re);
return R.ok();
}
/**
* 充值专用订单生成接口
*/
@RequestMapping("/rechargeSave")
@Transactional
public R rechargeSave(@RequestBody BuyOrderEntity buyOrder) {
String timeId = IdWorker.getTimeId().substring(0, 32);
buyOrder.setOrderSn(timeId);
buyOrderService.save(buyOrder);
@@ -423,9 +290,6 @@ public class BuyOrderController {
} else {
orderDetail = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>()
.eq("order_id", orderId));
//TODO 根据shipping_sn快递单号分组订单下无快递单号我的订单同时无法显示暂时注释
//.groupBy("shipping_sn")
}
for (BuyOrderDetailEntity buyOrderDetailEntity : orderDetail) {
@@ -433,20 +297,13 @@ public class BuyOrderController {
if (prod != null) {
buyOrderDetailEntity.setImage(prod.getProductImages());
}
}
List<BuyOrderDetailEntity> resultOrder = new ArrayList<BuyOrderDetailEntity>();
Set<String> sn_no = new HashSet<String>();
for (BuyOrderDetailEntity buyOrderDetailEntity : orderDetail) {
resultOrder.add(buyOrderDetailEntity);
sn_no.add(buyOrderDetailEntity.getShippingSn());
}
UserRecordEntity userRecordEntity = userRecordService.getBaseMapper().selectOne(new QueryWrapper<UserRecordEntity>()
@@ -454,18 +311,12 @@ public class BuyOrderController {
.eq("userid", buyOrder.getUserId())
.eq("orderdid", buyOrder.getOrderId())
.last("LIMIT 1"));
Integer id = null;
if (userRecordEntity != null) {
id = userRecordEntity.getId();
}
buyOrder.setProducts(resultOrder);
Date createDate = buyOrder.getCreateTime();
return R.ok().put("buyOrder", buyOrder).put("CreateTime", createDate).put("userRecordid", id);
}
@@ -474,15 +325,11 @@ public class BuyOrderController {
*/
@RequestMapping("/getTransPrice/{area}")
public R getTransPrice(@PathVariable String area, @RequestParam Map<String, Object> productMap) {
Map<String, Object> params = new HashMap<>();
params.put("kdCode", "YD");
params.put("area", area);
int price = this.buyOrderService.getProductGoodsType(params, productMap);
return R.ok().put("price", price);
}
@@ -523,7 +370,6 @@ public class BuyOrderController {
return R.ok().put("rntStr", jsonList);
}
/**
* 检查可合并的订单信息
*
@@ -535,7 +381,6 @@ public class BuyOrderController {
return R.ok().put("page", page);
}
/**
* 检查传来的orderId 是否有可合并的其他订单信息
*
@@ -548,7 +393,6 @@ public class BuyOrderController {
return R.ok().put("list", list);
}
/**
* 批量发货功能
*
@@ -564,7 +408,6 @@ public class BuyOrderController {
}
/**
* 后台取消订单接口
*/
@@ -572,7 +415,6 @@ public class BuyOrderController {
public R cancelFMS(@RequestParam Map<String, Object> params) {
buyOrderService.cancelFMS(params.get("orderSn").toString(), params.get("shipperCode").toString(),
params.get("expNo").toString());
// return R.ok()
return R.ok().put("paramsTEXT", params);
}
@@ -590,4 +432,129 @@ public class BuyOrderController {
return R.ok().put("page", page);
}
/**
* 获取商品实际价格
*
* @param product 商品信息
* @return 商品实际价格
*/
private BigDecimal getRealPrice(ShopProductEntity product) {
BigDecimal activityPrice = product.getActivityPrice();
return (activityPrice == null || activityPrice.equals(BigDecimal.ZERO)) ? product.getPrice() : activityPrice;
}
/**
* 处理商品库存
*
* @param buyOrderDetail
* @param product
* @return
*/
private boolean handleStock(BuyOrderDetailEntity buyOrderDetail, ShopProductEntity product) {
int quantity = buyOrderDetail.getQuantity();
if (product.getProductStock() - quantity < 0) {
return false;
}
product.setProductStock(product.getProductStock() - quantity);
product.setSumSales(product.getSumSales() + quantity);
shopProductService.updateById(product);
return true;
}
/**
* 使用优惠券
*
* @param buyOrder
* @return
*/
private BigDecimal useCouponAmount(BuyOrderEntity buyOrder) {
Integer couponId = buyOrder.getCouponId();
if (couponId != null) {
CouponHistoryEntity couponHistory = couponHistoryService.getById(couponId);
couponHistory.setUseStatus(1);
couponHistory.setUseTime(new Date());
couponHistory.setOrderId(Long.valueOf(buyOrder.getOrderId()));
couponHistory.setOrderSn(buyOrder.getOrderSn());
CouponEntity coupon = couponService.getById(couponHistory.getCouponId());
return coupon.getCouponAmount();
}
return BigDecimal.ZERO;
}
/**
* 计算运费
*
* @param buyOrder
* @return
*/
private BigDecimal getShoppingAmount(BuyOrderEntity buyOrder) {
return buyOrder.getOrderMoney() == null ? BigDecimal.ZERO : buyOrder.getShippingMoney();
}
/**
* 使用虚拟币支付
*
* @param user
* @param totalPrice
* @return
*/
private boolean usePeanutCoin(MyUserEntity user, BigDecimal totalPrice) {
if (user.getPeanutCoin().compareTo(totalPrice) >= 0) {
user.setPeanutCoin(user.getPeanutCoin().subtract(totalPrice));
this.myUserService.updateById(user);
return true;
}
return false;
}
/**
* 交易记录
*
* @param buyOrder
* @param user
* @param totalPrice
*/
private void recordTransaction(BuyOrderEntity buyOrder, MyUserEntity user, BigDecimal totalPrice) {
TransactionDetailsEntity transactionDetailsEntity = new TransactionDetailsEntity();
transactionDetailsEntity.setRemark("订单编号为 - " + buyOrder.getOrderSn());
transactionDetailsEntity.setUserId(user.getId());
transactionDetailsEntity.setUserName(user.getNickname());
transactionDetailsEntity.setChangeAmount(totalPrice.negate());
transactionDetailsEntity.setUserBalance(user.getPeanutCoin());
transactionDetailsEntity.setTel(user.getTel());
transactionDetailsEntity.setOrderType("购买商品");
transactionDetailsService.save(transactionDetailsEntity);
}
/**
* 给用户添加电子书
*
* @param products
* @param buyOrder
*/
private void addEbookToUser(List<BuyOrderDetailEntity> products, BuyOrderEntity buyOrder) {
List<Integer> productIds = products.stream().map(BuyOrderDetailEntity::getProductId).collect(Collectors.toList());
for (Integer productId : productIds) {
List<Integer> collect = shopProudictBookService.getBaseMapper().selectList(new LambdaQueryWrapper<ShopProudictBookEntity>()
.eq(ShopProudictBookEntity::getProudictId, productId)
.eq(ShopProudictBookEntity::getDelFlag, 0)).stream().map(ShopProudictBookEntity::getBookId).collect(Collectors.toList());
userEbookBuyService.addBookForUser(buyOrder.getUserId(), collect);
}
}
/**
* 购物车
*
* @param buyOrder
* @param buyOrderDetail
*/
private void handleBuyCart(BuyOrderEntity buyOrder, BuyOrderDetailEntity buyOrderDetail) {
List<OrderCartEntity> orderCartList = orderCartService.getBaseMapper().selectList(new QueryWrapper<OrderCartEntity>()
.eq("user_id", buyOrder.getUserId()).eq("product_id", buyOrderDetail.getProductId()));
if (orderCartList.size() > 0) {
List<Integer> collect = orderCartList.stream().map(OrderCartEntity::getCartId).collect(Collectors.toList());
orderCartService.removeByIds(collect);
}
}
}

View File

@@ -284,6 +284,7 @@ public class WeChatPayController {
System.out.println("============result========================" + b);
if (wechatEntity.getTotalAmount().compareTo(realMoney) == 0) {
buyOrderService.updateOrderStatus(order.getUserId(), order.getOrderSn(), "0");
}
}
if ("point".equals(order.getOrderType())) {

View File

@@ -31,12 +31,12 @@ import java.util.Base64;
public static final String apiV3Key = "4aYFklzaULeGlr7oJPZ6rHWKcxjihZUF"; // apiV3秘钥
//商户私钥路径
public static final String privateKeyUrl = "/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem";
//public static final String privateKeyUrl = "C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/apiclient_key.pem";
//public static final String privateKeyUrl = "/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem";
public static final String privateKeyUrl = "C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/apiclient_key.pem";
//平台证书路径
public static final String wechatPayCertificateUrl = "/usr/local/hs/peanut_book/target/classes/cent/wechatpay_7B5676E3CDF56680D0414A009CE501C844DBE2D6.pem";
//public static final String wechatPayCertificateUrl = "C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/wechatpay_7B5676E3CDF56680D0414A009CE501C844DBE2D6.pem";
//public static final String wechatPayCertificateUrl = "/usr/local/hs/peanut_book/target/classes/cent/wechatpay_7B5676E3CDF56680D0414A009CE501C844DBE2D6.pem";
public static final String wechatPayCertificateUrl = "C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/wechatpay_7B5676E3CDF56680D0414A009CE501C844DBE2D6.pem";
//第一步申请完证书后在API证书哪里点击管理证书就能看到
public static final String mchSerialNo = "679AECB2F7AC4183033F713828892BA640E4EEE3"; // 商户证书序列号

View File

@@ -16,8 +16,8 @@ wxpay.notifyUrl: http://59.110.212.44:9200/pb/pay/payNotify
wxpay.refundNotifyUrl: http://pjm6m9.natappfree.cc/pay/refundNotify
# ???? /usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem
#wxpay.keyPemPath:C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/apiclient_key.pem
wxpay.keyPemPath:/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem
wxpay.keyPemPath:C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/apiclient_key.pem
#wxpay.keyPemPath:/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem
#???????
wxpay.serialNo: 679AECB2F7AC4183033F713828892BA640E4EEE3
#???????