Files
nuttyreading-server/src/main/java/com/peanut/modules/book/controller/BuyOrderController.java
2026-04-30 23:08:14 +08:00

1404 lines
61 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.peanut.modules.book.controller;
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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.alibaba.fastjson.JSONObject;
import com.peanut.common.utils.DateUtils;
import com.peanut.common.utils.PageUtils;
import com.peanut.common.utils.R;
import com.peanut.common.utils.ShiroUtils;
import com.peanut.config.Constants;
import com.peanut.config.DelayQueueConfig;
import com.peanut.modules.book.service.*;
import com.peanut.modules.book.service.BuyOrderService;
import com.peanut.modules.book.service.CityService;
import com.peanut.modules.book.service.CountyService;
import com.peanut.modules.book.service.ExpressOrderService;
import com.peanut.modules.book.service.MyUserService;
import com.peanut.modules.book.service.ProvinceService;
import com.peanut.modules.book.service.TransactionDetailsService;
import com.peanut.modules.book.service.UserAddressService;
import com.peanut.modules.book.to.UserOrderDto;
import com.peanut.modules.book.vo.UserAddressVo;
import com.peanut.modules.book.vo.request.BuyOrderListRequestVo;
import com.peanut.modules.book.vo.request.ModifyOrderAddressRequestVo;
import com.peanut.modules.book.vo.request.ProductRequestVo;
import com.peanut.modules.book.vo.request.ProductTransportVo;
import com.peanut.modules.book.vo.response.BuyOrderResponseVo;
import com.peanut.modules.book.vo.response.OrderAddressResponseVo;
import com.peanut.modules.common.dao.UserCourseBuyDao;
import com.peanut.modules.common.entity.*;
import com.peanut.modules.common.service.*;
import com.peanut.modules.master.service.CourseCatalogueService;
import com.peanut.modules.pay.alipay.service.AliPayService;
import com.peanut.modules.pay.weChatPay.dto.WeChatRefundInfo;
import com.peanut.modules.pay.weChatPay.dto.WechatPaymentInfo;
import com.peanut.modules.pay.weChatPay.service.WxpayService;
import com.peanut.modules.sys.entity.SysConfigEntity;
import com.peanut.modules.sys.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
/**
* 订单表
*
* @author yl
* @email yl328572838@163.com
* @date 2022-08-29 15:27:44
*/
@Slf4j
@RestController
@RequestMapping("book/buyOrder")
public class BuyOrderController {
@Autowired
private BuyOrderService buyOrderService;
@Autowired
private ShopProductService shopProductService;
@Autowired
private UserVipService userVipService;
@Autowired
private BuyOrderDetailService buyOrderDetailService;
@Autowired
private OrderCartService orderCartService;
@Autowired
private MyUserService myUserService;
@Autowired
private TransactionDetailsService transactionDetailsService;
@Autowired
private UserEbookBuyService userEbookBuyService;
@Autowired
private WxpayService wxpayService;
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private ShopProductBookService shopProductBookService;
@Autowired
private ExpressOrderService expressOrderService;
@Autowired
private UserAddressService userAddressService;
@Autowired
private ExpressFeeService expressFeeService;
@Autowired
private SysConfigService sysConfigService;
@Autowired
private BuyOrderProductService buyOrderProductService;
@Autowired
private ProvinceService provinceService;
@Autowired
private CityService cityService;
@Autowired
private CountyService countyService;
@Autowired
private UserCourseBuyDao userCourseBuyDao;
@Autowired
private JfTransactionDetailsService jfTransactionDetailsService;
@Autowired
private CouponService couponService;
@Autowired
private CouponHistoryService couponHistoryService;
@Autowired
private UserCourseBuyLogService userCourseBuyLogService;
@Autowired
private CourseCatalogueService courseCatalogueService;
@Autowired
private BuyOrderRefundService buyOrderRefundService;
@Autowired
private BuyOrderRefundLogService buyOrderRefundLogService;
@Autowired
private AliPayService aliPayService;
@RequestMapping(value = "/decomposeShipment", method = RequestMethod.POST)
public R decomposeShipment(@RequestBody BuyOrderListRequestVo requestVo) {
Map<String, Object> result = buyOrderService.decomposeShipment(requestVo);
return R.ok().put("result", result);
}
// TODO 新版本上线后废弃
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params) throws Exception {
PageUtils page = buyOrderService.list(params);
return R.ok().put("page", page);
}
/**
* 订单列表
*
* @param requestVo request value object
* @return R
*/
@RequestMapping(path = "/orderList", method = RequestMethod.POST)
public R orderList(@RequestBody BuyOrderListRequestVo requestVo) {
Page<BuyOrder> buyOrderPage = buyOrderService.orderList(requestVo);
return R.ok().put("result", buyOrderPage);
}
//导出名医精彩订单
@RequestMapping("/exportMingyijingcaiOrder")
public void exportMingyijingcaiOrder(HttpServletResponse response, @RequestBody BuyOrderListRequestVo requestVo) {
requestVo.setOrderStatus("3");
requestVo.setPageIndex(1);
requestVo.setPageSize(100000);
R r = orderList(requestVo);
if ("0".equals(r.get("code").toString())){
Page<BuyOrder> buyOrderPage = (Page<BuyOrder>) r.get("result");
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("名医精彩订单");
Row titleRow = sheet.createRow(0);//日期,姓名,电话,付款方式,金额
titleRow.createCell(0).setCellValue("序号");
titleRow.createCell(1).setCellValue("订单时间");
titleRow.createCell(2).setCellValue("订单编号");
titleRow.createCell(3).setCellValue("商品名");
titleRow.createCell(4).setCellValue("姓名");
titleRow.createCell(5).setCellValue("联系方式");
titleRow.createCell(6).setCellValue("用户邮箱");
titleRow.createCell(7).setCellValue("付款方式");
titleRow.createCell(8).setCellValue("订单金额");
titleRow.createCell(9).setCellValue("实付金额");
titleRow.createCell(10).setCellValue("积分抵扣");
//序号默认为1
int cell = 1;
//遍历
for (BuyOrder buyOrder : buyOrderPage.getRecords()) {
Row row = sheet.createRow(cell);
row.createCell(0).setCellValue(cell);
row.createCell(1).setCellValue(DateUtils.format(buyOrder.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
row.createCell(2).setCellValue(buyOrder.getOrderSn());
if ("relearn".equals(buyOrder.getOrderType())){
row.createCell(3).setCellValue(buyOrder.getRemark());
}else {
row.createCell(3).setCellValue(buyOrder.getProductList().get(0).getProduct().getProductName());
}
row.createCell(4).setCellValue(buyOrder.getUser().getName());
row.createCell(5).setCellValue(buyOrder.getUser().getTel());
row.createCell(6).setCellValue(buyOrder.getUser().getEmail());
String payMethod = "";
if ("1".equals(buyOrder.getPaymentMethod())){
payMethod = "微信";
}else if ("2".equals(buyOrder.getPaymentMethod())){
payMethod = "支付宝";
}else if ("3".equals(buyOrder.getPaymentMethod())){
payMethod = "IOS内购";
}else if ("4".equals(buyOrder.getPaymentMethod())){
payMethod = "虚拟币";
}
row.createCell(7).setCellValue(payMethod);
row.createCell(8).setCellValue(buyOrder.getOrderMoney().toString());
row.createCell(9).setCellValue(buyOrder.getRealMoney().toString());
row.createCell(10).setCellValue(buyOrder.getJfDeduction().toString());
//序号自增
cell++;
}
String fileName = "名医精彩订单.xlsx";
OutputStream outputStream =null;
try {
//文件名编码格式
fileName = URLEncoder.encode(fileName,"UTF-8");
//设置ContentType请求信息格式
response.setContentType("application/vnd.ms-excel");
//设置标头
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
outputStream = response.getOutputStream();
wb.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取用户订单列表
* @param userOrderDto
* @return
*/
@RequestMapping("/getUserOrderList")
public R getUserOrderList(@RequestBody UserOrderDto userOrderDto){
Page<BuyOrder> userOrderList = buyOrderService.getUserOrderList(userOrderDto);
return R.ok().put("page",userOrderList);
}
/**
* 获取用户订单各个状态的数量
* @param map
* @return
*/
@RequestMapping("/getUserOrderStatusNum")
public R getUserOrderStatusNum(@RequestBody Map<String,Object> map){
Integer userId = Integer.valueOf(map.get("userId").toString());
List<BuyOrder> userOrderStatusNum = buyOrderService.getUserOrderStatusNum(userId);
Map<String, Integer> m = new HashMap<>();
for (BuyOrder b : userOrderStatusNum){
m.put(b.getOrderStatus().toString(),b.getStatusNum());
}
return R.ok().put("map",m);
}
//获取商品vip折扣金额
@RequestMapping("/getVipDiscountAmount")
public R getVipDiscountAmount(@RequestBody BuyOrder buyOrder){
BigDecimal b = new BigDecimal(0);
if (userVipService.isVip()){
List<BuyOrderProduct> buyOrderProductList = buyOrder.getProductList();
for (BuyOrderProduct buyOrderProduct : buyOrderProductList) {
BigDecimal pvda = shopProductService.getVipDiscountAmount(shopProductService.getById(buyOrderProduct.getProductId()));
b = b.add(pvda.multiply(new BigDecimal(buyOrderProduct.getQuantity())));
}
}
return R.ok().put("discountAmount",b);
}
//获取商品活动折扣金额
@RequestMapping("/getDistrictAmount")
public R getDistrictAmount(@RequestBody BuyOrder buyOrder){
BigDecimal total = new BigDecimal(0);
List<BuyOrderProduct> buyOrderProductList = buyOrder.getProductList();
for (BuyOrderProduct buyOrderProduct : buyOrderProductList) {
ShopProduct shopProduct = shopProductService.getById(buyOrderProduct.getProductId());
if (userVipService.isVip()){
BigDecimal pvda = shopProductService.getVipDiscountAmount(shopProductService.getById(buyOrderProduct.getProductId()));
if (pvda.compareTo(BigDecimal.ZERO)>0){
continue;
}
}
if (shopProduct.getActivityPrice().compareTo(BigDecimal.ZERO)>0){
total = total.add((shopProduct.getPrice().subtract(shopProduct.getActivityPrice())).multiply(new BigDecimal(buyOrderProduct.getQuantity())));
}
}
return R.ok().put("districtAmount",total);
}
//
@RequestMapping("/getShopProductListByIds")
public R getShopProductListByIds(@RequestBody Map<String,Object> params){
String[] productIds = params.get("productIds").toString().split(",");
LambdaQueryWrapper<ShopProduct> wrapper = new LambdaQueryWrapper();
wrapper.select(ShopProduct::getProductId,ShopProduct::getProductName,ShopProduct::getProductImages,ShopProduct::getPrice,ShopProduct::getActivityPrice,ShopProduct::getIsVipPrice,ShopProduct::getGoodsType);
wrapper.in(ShopProduct::getProductId,Arrays.asList(productIds));
List<ShopProduct> shopProductList = shopProductService.list(wrapper);
for (ShopProduct shopProduct:shopProductList){
if (userVipService.isVip()&&shopProduct.getIsVipPrice()==1){
shopProduct.setVipPrice(shopProductService.getVipPrice(shopProduct));
}
}
return R.ok().put("shopProductList",shopProductList);
}
/**
* 订单详情
*
* @param orderSn 订单号
* @return R
*/
@RequestMapping(path = "/orderDetail", method = RequestMethod.GET)
public R orderDetail(@RequestParam("orderSn") String orderSn) {
BuyOrderResponseVo buyOrderResponseVo = buyOrderService.orderDetail(orderSn);
return R.ok().put("result", buyOrderResponseVo);
}
/**
* 删除订单
*
* @param orderSn 订单号
* @return R
*/
@RequestMapping(path = "/orderDel")
public R orderDel(@RequestParam("orderSn") String orderSn) {
LambdaQueryWrapper<BuyOrder> w = new LambdaQueryWrapper();
w.eq(BuyOrder::getOrderSn,orderSn);
BuyOrder order = buyOrderService.getOne(w);
order.setOrderStatus("4");
buyOrderService.saveOrUpdate(order);
buyOrderService.removeById(order.getOrderId());
return R.ok();
}
/**
* 下单
* TODO 原下单接口,新版本上线后废弃
*
* @param buyOrder 订单
* @return R
*/
@RequestMapping("/buySave")
@Transactional
public R buySave(@RequestBody BuyOrder buyOrder) throws IOException {
return R.error("app版本太低请升级后再购买");
}
//预售书重复购买提示
@RequestMapping(value = "/presaleRemark", method = RequestMethod.POST)
public R presaleRemark(@RequestBody Map<String,Object> params) {
String remark = "";
String[] productIds = params.get("productIds").toString().split(",");
for (String productId:productIds){
ShopProduct shopProduct = shopProductService.getById(productId);
if (shopProduct!=null&&"03".equals(shopProduct.getGoodsType())){
Long c = buyOrderService.count(new MPJLambdaWrapper<BuyOrder>()
.leftJoin(BuyOrderProduct.class,BuyOrderProduct::getOrderId,BuyOrder::getOrderId)
.eq(BuyOrder::getUserId, ShiroUtils.getUId())
.in(BuyOrder::getOrderStatus,1,2,3)
.eq(BuyOrderProduct::getProductId,shopProduct.getProductId()));
if (c>0){
remark += ""+shopProduct.getProductName()+"";
}
}
}
if (!remark.isEmpty()){
remark = "亲爱的用户,系统检测到您已购买过预售书籍"+remark+",为防止重复下单,温馨提示。";
}
return R.ok().put("remark",remark);
}
/**
* 下单
*
* @param buyOrder
* @return
* @throws IOException
*/
@RequestMapping(value = "/placeOrder", method = RequestMethod.POST)
@Transactional
public R placeOrder(@RequestBody BuyOrder buyOrder) {
List<BuyOrderProduct> buyOrderProductList = buyOrder.getProductList();
// 订单实收金额
BigDecimal totalPrice = new BigDecimal(0);
//是否存在手摸或脚模,修改用户的脉穴权限
List<Integer> sjc =Arrays.asList(128,129,130,131,136,137,139,1612,1957);
boolean sj_check = false;
//是否存在时辰取穴的权限触发商品
List<Integer> scqq = Arrays.asList(133,134,135);
boolean scqq_check = false;
//五运六气权限
List<Integer> wylq = Arrays.asList(39,62,123,127);
boolean wylq_check = false;
List<Integer> prescript_b = Arrays.asList(43,62,124);
boolean prescriot_b_check = false;
if (buyOrder.getVipDiscountAmount()!=null&&buyOrder.getVipDiscountAmount().compareTo(new BigDecimal(0))>0
&&buyOrder.getCouponId()!=null&&buyOrder.getCouponId()!=0){
return R.error(500, "优惠不能叠加");
}
int mechFlag = 2;
String mechStr = "";
// 遍历商品总价计算
for (BuyOrderProduct buyOrderProduct : buyOrderProductList) {
if(sjc.contains(buyOrderProduct.getProductId())){
sj_check = true;
}
if(scqq.contains(buyOrderProduct.getProductId())){
scqq_check = true;
}
if(wylq.contains(buyOrderProduct.getProductId())){
wylq_check = true;
}
if(prescript_b.contains(buyOrderProduct.getProductId())){
prescriot_b_check = true;
}
Integer productId = buyOrderProduct.getProductId();
int quantity = buyOrderProduct.getQuantity();
ShopProduct product = shopProductService.getById(productId);
if (product.getPayMerchant()==1){
buyOrder.setOrderType("lsorder");
}
if (mechFlag==2){
mechFlag = product.getPayMerchant();
}
if (product.getPayMerchant()!=mechFlag){
mechStr = mechStr+"<"+product.getProductName()+">";
}
BigDecimal price = getRealPrice(product);
if (buyOrder.getVipDiscountAmount()!=null&&buyOrder.getVipDiscountAmount().compareTo(new BigDecimal(0))>0
&&userVipService.isVip()&&product.getIsVipPrice()==1){
if (shopProductService.getVipPrice(product).compareTo(BigDecimal.ZERO)>0){
price = shopProductService.getVipPrice(product);
}
}
if (!handleStock(buyOrderProduct, product)) {
return R.error(500, "库存不足");
}
if (StringUtils.isNotEmpty(mechStr)){
return R.error(500, mechStr+"不能和其他商品同时付款");
}
totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(quantity)));
}
//商品价格减去优惠券的优惠金额
if (buyOrder.getCouponId()!=null&&buyOrder.getCouponId()!=0){
CouponHistory couponHistory = couponHistoryService.getById(buyOrder.getCouponId());
if (couponHistory!=null){
if (couponHistory.getStatus()==0){
if (couponHistory.getEffectType()!=0){
if (couponHistory.getStartTime().getTime()<new Date().getTime()&&
couponHistory.getEndTime().getTime()>new Date().getTime()){
}else {
return R.error("优惠券使用时间未到");
}
}
CouponEntity coupon = couponService.getById(couponHistory.getCouponId());
if (coupon != null){
totalPrice = totalPrice.subtract(coupon.getCouponAmount());
}
}else {
if (couponHistory.getStatus()==1){
return R.error("优惠券已被使用");
}else if (couponHistory.getStatus() == 2){
return R.error("优惠券已过期");
}
}
}
}
//加上运费金额
totalPrice = totalPrice.add(getShoppingAmount(buyOrder));
//减去积分抵扣
totalPrice = totalPrice.subtract(buyOrder.getJfDeduction()==null?BigDecimal.ZERO:buyOrder.getJfDeduction());
if(buyOrder.getRealMoney().compareTo(totalPrice)!=0){
return R.error("系统错误订单金额异常!");
}
String orderSn = IdWorker.getTimeId().substring(0, 32);
buyOrder.setOrderSn(orderSn);
if(buyOrder.getAddressId()!=0){
QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", buyOrder.getAddressId());
UserAddress userAddress = userAddressService.getOne(queryWrapper);
UserAddressVo vo = new UserAddressVo();
vo = userAddressService.getAddressName(vo, userAddress.getRegionCode());
buyOrder.setProvince(vo.getProvince());
buyOrder.setCity(vo.getCity());
buyOrder.setDistrict(vo.getCounty());
buyOrder.setAddress(userAddress.getDetailAddress());
String str = buyOrder.getShippingUser()+buyOrder.getAddress()+buyOrder.getRemark();
if (str.contains("+")||str.contains("&")) {
return R.error(500, "信息中不能含有“+”、“&”符号!");
}
}
buyOrder.setOrderStatus("0");
buyOrderService.save(buyOrder);
//解决购物车相关问题
for (BuyOrderProduct buyOrderProduct : buyOrderProductList) {
buyOrderProduct.setOrderId(buyOrder.getOrderId());
if (Constants.BUY_TYPE_CART.equals(buyOrder.getBuyType())) {
handleBuyCart(buyOrder, buyOrderProduct);
}
}
buyOrderProductService.saveBatch(buyOrderProductList);
// 1. 虚拟币支付
if (Constants.PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) {
buyOrder.setOrderStatus(Constants.ORDER_STATUS_TO_BE_SHIPPED);
MyUserEntity user = this.myUserService.getById(buyOrder.getUserId());
if (usePeanutCoin(user, totalPrice,sj_check,scqq_check,wylq_check,prescriot_b_check)&&useJfCoin(user,buyOrder.getJfDeduction())) {
// 更新订单状态
if(buyOrderService.checkWlOrder(buyOrder.getOrderSn())){
buyOrderService.updateOrderStatus(user.getId(), buyOrder.getOrderSn(), "0");
}else{
buyOrderService.updateOrderStatus(user.getId(), buyOrder.getOrderSn(), "2");
}
//记录用户虚拟币消费
if(totalPrice.compareTo(BigDecimal.ZERO)>0){
transactionDetailsService.recordTransaction(buyOrder, user, totalPrice);
}
//记录用户积分消费情况
if(buyOrder.getJfDeduction()!=null&&buyOrder.getJfDeduction().compareTo(BigDecimal.ZERO) > 0){
jfTransactionDetailsService.recordJfTransaction(buyOrder, user, buyOrder.getJfDeduction());
}
//消费用户积分并记录用户积分消费记录
addEbookToUser(buyOrderProductList, buyOrder, 0);
//开课
buyOrderService.addCourseToUser("天医币",buyOrder);
//使用优惠券
if (buyOrder.getCouponId()!=null&&buyOrder.getCouponId()!=0){
CouponHistory couponHistory = couponHistoryService.getById(buyOrder.getCouponId());
couponHistory.setOrderId(buyOrder.getOrderId());
couponService.useCouponAmount(couponHistory);
}
//发放优惠卷
couponService.insertCouponHistoryByProductId(buyOrder);
} else {
rabbitTemplate.convertAndSend(
DelayQueueConfig.ORDER_TO_BE_PAY_EXCHANGE,
DelayQueueConfig.ORDER_TO_BE_PAY_ROUTING_KEY,
buyOrder.getOrderId(),
messagePostProcessor()
);
return R.error(500, "天医币余额不足!");
}
}
// 2. 微信支付,需要预支付
if (Constants.PAYMENT_METHOD_WECHAT_PAY.equals(buyOrder.getPaymentMethod())) {
WechatPaymentInfo paymentInfo = new WechatPaymentInfo();
paymentInfo.setOrderSn(orderSn);
paymentInfo.setOrderType(buyOrder.getOrderType());
paymentInfo.setBuyOrderId(buyOrder.getOrderId());
paymentInfo.setTotalAmount(totalPrice);
if(buyOrder.getCome()==null||buyOrder.getCome()==0){
paymentInfo.setAppName(buyOrder.getAppName());
} else if (buyOrder.getCome()==2){
paymentInfo.setAppName("wumen");
} else if (buyOrder.getCome()==1) {
paymentInfo.setAppName("zmzm");
} else if (buyOrder.getCome()==3) {
paymentInfo.setAppName("xlkj");
} else if (buyOrder.getCome()==4) {
paymentInfo.setAppName("thyy");
}
wxpayService.prepay(paymentInfo);
}
rabbitTemplate.convertAndSend(
DelayQueueConfig.ORDER_TO_BE_PAY_EXCHANGE,
DelayQueueConfig.ORDER_TO_BE_PAY_ROUTING_KEY,
buyOrder.getOrderId(),
messagePostProcessor()
);
Map<String, Object> result = new HashMap<>();
result.put("orderSn", buyOrder.getOrderSn());
result.put("money", totalPrice);
return R.ok(result);
}
//订单退款进度
@RequestMapping("/refundDetail")
public R refundOrderDetail(@RequestBody Map params){
Object orderIdObj = params.get("orderId");
if(orderIdObj == null || orderIdObj.toString().trim().equals("")){
return R.error("orderId不能为空");
}
int order_id = Integer.parseInt(orderIdObj.toString().trim());
QueryWrapper<BuyOrderRefund> wapper = new QueryWrapper<>();
wapper.eq("order_id",order_id);
BuyOrderRefund refundInfo = buyOrderRefundService.getOne(wapper);
if(refundInfo==null){
return R.error("退款信息不存在");
}
QueryWrapper<BuyOrderRefundLog> wapper2 = new QueryWrapper<>();
wapper2.eq("refund_id",refundInfo.getId()).orderByDesc("id");
List<BuyOrderRefundLog> list = buyOrderRefundLogService.list(wapper2);
for (BuyOrderRefundLog log : list){
if(log.getType()==4){
log.setTitle("天医币已退还");
log.setContent("天医币已退还到账户,可在我的->天医币中查看明细");
}else if(log.getType()==5){
log.setTitle("积分已退还");
log.setContent("积分已退还到账户,可在我的->积分中查看明细");
}else if(log.getType()==2){
log.setTitle(log.getStatus()==1?"到账成功":(log.getStatus()==2?"支付宝处理中":"提交支付宝处理"));
log.setContent(log.getStatus()==1?"已退到您的支付宝,到账时间以支付宝处理时间为准,可前往「支付宝-账单」查看":(log.getStatus()==2?"已将退款提交给支付宝处理":"支付宝处理中通常情况下退款会原路退回您的支付账户预计会在1-7天内到账"));
}else if(log.getType()==1){
log.setTitle(log.getStatus()==1?"到账成功":(log.getStatus()==2?"微信处理中":"提交微信处理"));
log.setContent(log.getStatus()==1?"已退到您的微信,到账时间以微信处理时间为准,可前往「微信-账单」查看":(log.getStatus()==2?"已将退款提交给微信处理":"微信处理中通常情况下退款会原路退回您的支付账户预计会在1-7天内到账"));
}else if(log.getType()==0){
log.setTitle("发起退款");
log.setContent("系统会在1-2天内提交处理");
}
}
/* BuyOrderRefundLog log = new BuyOrderRefundLog();
log.setId(0);
log.setRefundId(refundInfo.getId());
log.setType(0);
log.setStatus(1);
log.setCreateTime(refundInfo.getCreateTime());
log.setTitle("发起退款");
log.setContent("系统会在1-2天内提交处理");
list.add(log);*/
Map<String,Object> result = new HashMap<>();
BigDecimal shippingMoney = refundInfo.getDeductShipping()==1?refundInfo.getShippingMoney():BigDecimal.ZERO;
result.put("orderMoney",refundInfo.getFee().add(refundInfo.getJfDeduction().add(shippingMoney)));
result.put("refundFee",refundInfo.getFee());
result.put("payType",refundInfo.getPayType());
result.put("refundJf",refundInfo.getJfDeduction());
result.put("shippingMoney",shippingMoney);
result.put("list",list);
return R.ok().put("info",result);
}
@RequestMapping(value = "/refundOrder", method = RequestMethod.POST)
@Transactional
public R refundOrder(@RequestBody Map<String, Object> params) {
Object orderIdObject = params.get("orderId");
if(orderIdObject == null || orderIdObject.toString().trim().equals("")){
return R.error("orderId不能为空");
}
int orderId = Integer.parseInt(orderIdObject.toString());
QueryWrapper<BuyOrder> queryWapper = new QueryWrapper<>();
queryWapper.eq("order_id",orderId);
BuyOrder buyOrder = buyOrderService.getOne(queryWapper);
if(buyOrder==null){
return R.error("订单不存在");
}
MyUserEntity user = myUserService.getById(buyOrder.getUserId());
if (user == null) {
return R.error("订单对应用户不存在");
}
if(Constants.ORDER_STATUS_REFUND.equals(buyOrder.getOrderStatus())
|| Constants.ORDER_STATUS_REFUNDING.equals(buyOrder.getOrderStatus())){
return R.error("请勿重复提交退款");
}else if (Constants.ORDER_STATUS_TO_BE_PAID.equals(buyOrder.getOrderStatus())
|| Constants.ORDER_STATUS_FAIL.equals(buyOrder.getOrderStatus())
|| Constants.ORDER_STATUS_OUT_OF_TIME.equals(buyOrder.getOrderStatus())) {
return R.error("当前订单状态不支持退单");
}
if(Constants.PAYMENT_METHOD_ALI_PAY.equals(buyOrder.getPaymentMethod())){
return R.error("当前订单支付方式暂不支持退单");
}
//设置状态为退款中
buyOrder.setOrderStatus(Constants.ORDER_STATUS_REFUNDING);
buyOrderService.updateById(buyOrder);
BigDecimal refundFee = buyOrder.getRealMoney();
BigDecimal shippingMoney = buyOrder.getShippingMoney()==null?BigDecimal.ZERO:buyOrder.getShippingMoney();
int deductShipping = params.containsKey("deductShipping") && params.get("deductShipping")!=null?Integer.parseInt(params.get("deductShipping").toString()):0;
if(refundFee.compareTo(BigDecimal.ZERO)>0 && shippingMoney.compareTo(BigDecimal.ZERO)>0 && deductShipping==1){
refundFee = refundFee.subtract(shippingMoney);
refundFee = refundFee.compareTo(BigDecimal.ZERO)>0?refundFee:BigDecimal.ZERO;
}
String remark = params.containsKey("remark") && params.get("remark").toString()!=null?params.get("remark").toString():"";
BuyOrderRefund buyOrderRefund = new BuyOrderRefund();
String refundNo = buyOrderRefundService.genRefundNo();
buyOrderRefund.setRefundNo(refundNo);
buyOrderRefund.setOrderId(buyOrder.getOrderId());
buyOrderRefund.setOrderSn(buyOrder.getOrderSn());
buyOrderRefund.setUserId(buyOrder.getUserId());
buyOrderRefund.setType(params.containsKey("deductShipping")?"后台":"线上"); //id
buyOrderRefund.setPayType(buyOrder.getPaymentMethod());
buyOrderRefund.setFee(refundFee);
buyOrderRefund.setJfDeduction(buyOrder.getJfDeduction());
buyOrderRefund.setShippingMoney(deductShipping==1?buyOrder.getShippingMoney():BigDecimal.ZERO);
buyOrderRefund.setDeductShipping(deductShipping);
buyOrderRefund.setRemark(remark);
buyOrderRefundService.save(buyOrderRefund);
buyOrderRefundLogService.insertRefundLog(buyOrderRefund.getId(),0,1);
int refundId = buyOrderRefund.getId();
if (Constants.PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) {
if(refundFee.compareTo(BigDecimal.ZERO)>0){
//退还虚拟币
transactionDetailsService.refundRecord(buyOrder,user,refundFee);
user.setPeanutCoin(user.getPeanutCoin().add(refundFee));
myUserService.updateById(user);
//记录退款进度
buyOrderRefundLogService.insertRefundLog(refundId,4,1);
//积分、其他权益退回
buyOrderService.refundOrder(buyOrder,user,refundId);
//更改订单状态为已退款
buyOrder.setOrderStatus(Constants.ORDER_STATUS_REFUND);
buyOrderService.updateById(buyOrder);
return R.ok("ok");
}
} else if (Constants.PAYMENT_METHOD_WECHAT_PAY.equals(buyOrder.getPaymentMethod())) {
buyOrderRefundLogService.insertRefundLog(refundId,1,0);
if (refundFee.compareTo(BigDecimal.ZERO) > 0) {
WeChatRefundInfo weChatRefundInfo = new WeChatRefundInfo();
weChatRefundInfo.setOrderSn(buyOrder.getOrderSn());
weChatRefundInfo.setOrderId(buyOrder.getOrderId());
weChatRefundInfo.setOrderType(buyOrder.getOrderType());
weChatRefundInfo.setRefundNo(buyOrderRefund.getRefundNo());
weChatRefundInfo.setTotalAmount(buyOrder.getRealMoney());
weChatRefundInfo.setRefundAmount(buyOrderRefund.getFee());
weChatRefundInfo.setRemark("用户申请退款");
weChatRefundInfo.setRefundId(buyOrderRefund.getId());
if(buyOrder.getCome()==null||buyOrder.getCome()==0){
weChatRefundInfo.setAppName(buyOrder.getAppName());
} else if (buyOrder.getCome()==2){
weChatRefundInfo.setAppName("wumen");
} else if (buyOrder.getCome()==1) {
weChatRefundInfo.setAppName("zmzm");
} else if (buyOrder.getCome()==3) {
weChatRefundInfo.setAppName("xlkj");
} else if (buyOrder.getCome()==4) {
weChatRefundInfo.setAppName("thyy");
}
try {
wxpayService.refund(weChatRefundInfo);
} catch (Exception e) {
System.out.println("msg=" + e.getMessage()); // 👈 关键
}
}
}
// else if (Constants.PAYMENT_METHOD_ALI_PAY.equals(buyOrder.getPaymentMethod())) {
// buyOrderRefundLogService.insertRefundLog(refundId,2,0);
// if (refundFee.compareTo(BigDecimal.ZERO) > 0) {
// Map<String, Object> refundParams = new HashMap<>();
// refundParams.put("orderSn", buyOrder.getOrderSn());
// refundParams.put("refundFee", refundFee);
// String refundResult = aliPayService.refund(refundParams);
// JSONObject resultJson = JSONObject.parseObject(refundResult);
// JSONObject responseJson = resultJson.getJSONObject("alipay_trade_refund_response");
// if (responseJson == null
// || !"10000".equals(responseJson.getString("code"))
// || !"Y".equals(responseJson.getString("fund_change"))) {
// return R.error("支付宝退款申请失败");
// }else{
// buyOrderRefundLogService.insertRefundLog(refundId,3,2);
// }
// }
// }
return R.ok("ok");
}
@RequestMapping("/llll")
public R ls(){
LambdaQueryWrapper<BuyOrder> wrapper = new LambdaQueryWrapper<>();
ArrayList<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add(3);
wrapper.gt(BuyOrder::getOrderId,4522);
wrapper.in(BuyOrder::getOrderStatus,integers);
wrapper.eq(BuyOrder::getOrderType,"order");
List<BuyOrder> list = buyOrderService.list(wrapper);
for (BuyOrder b : list){
List<Integer> orderBookId = shopProductBookService.getOrderBookId(b.getOrderSn());
// System.out.println(orderBookId);
userEbookBuyService.addBookForUser(b.getUserId(),orderBookId);
}
return R.ok();
}
@RequestMapping("/llll1")
public R ls1(){
Integer[] is = {39,62,123,127};
List<Integer> collect = buyOrderProductService.getBaseMapper().selectList(new LambdaQueryWrapper<BuyOrderProduct>().in(BuyOrderProduct::getProductId, is)).stream().map(BuyOrderProduct::getOrderId).collect(Collectors.toList());
LambdaQueryWrapper<BuyOrder> wrapper = new LambdaQueryWrapper<>();
List<Integer> integers = Arrays.asList(1,2,3);
wrapper.in(BuyOrder::getOrderStatus,integers);
wrapper.in(BuyOrder::getOrderId,collect);
wrapper.eq(BuyOrder::getOrderType,"order");
List<BuyOrder> list = buyOrderService.list(wrapper);
for (BuyOrder b : list){
MyUserEntity byId = myUserService.getById(b.getUserId());
byId.setWylqPower(1);
myUserService.updateById(byId);
}
return R.ok();
}
/**
* 计算运费
*
* @param vo
* @return
*/
@RequestMapping(path = "/calculateTransportPrice", method = RequestMethod.POST)
public R getTransportPrice(@RequestBody ProductTransportVo vo) {
//商品列表和收货区域编码
String regionCode = vo.getRegionCode();
List<ProductRequestVo> products = vo.getProducts();
//查询默认快递公司代码 defaultExpress.getParamValue()
QueryWrapper<SysConfigEntity> configQueryWrapper = new QueryWrapper<>();
configQueryWrapper.eq("param_key", "DEFAULT_EXPRESS");
SysConfigEntity defaultExpress = sysConfigService.getOne(configQueryWrapper);
if (defaultExpress == null) {
return R.error("未设置默认快递");
}
//总运费
BigDecimal totalExpressFee = new BigDecimal(0);
BigDecimal totalWeight01 = new BigDecimal(0);
BigDecimal totalWeight02 = new BigDecimal(0);
BigDecimal totalWeight04 = new BigDecimal(0);
for (ProductRequestVo product : products) {
ShopProduct p = shopProductService.getById(product.getProductId());
if (p != null) {
//现售:《针灸六经法要》 港澳台西藏不包邮 其他地区包邮
if (p.getProductId().equals(135)&&!regionCode.equals("710000")&&!regionCode.equals("810000")
&&!regionCode.equals("820000")&&!regionCode.startsWith("54")) {
continue;
}
//包邮
if(p.getIsFreeMail()==0){
continue;
}else {
BigDecimal weight = BigDecimal.valueOf(Double.valueOf(p.getWeight()) / 1000.0);
BigDecimal totalWeight = weight.multiply(new BigDecimal(product.getQuantity()));
if ("01".equals(p.getGoodsType())){
totalWeight01 = totalWeight01.add(totalWeight);
}
if ("02".equals(p.getGoodsType())){
totalWeight02 = totalWeight02.add(totalWeight);
}
//预售书单独计算
if ("03".equals(p.getGoodsType())){
totalExpressFee = totalExpressFee.add(
expressFeeService.calculateExpressFee(defaultExpress.getParamValue(), totalWeight.setScale(0, RoundingMode.UP), regionCode));
}
if ("04".equals(p.getGoodsType())){
totalWeight04 = totalWeight04.add(totalWeight);
}
}
}else {
return R.error("未查询到商品");
}
}
if(totalWeight01.compareTo(BigDecimal.ZERO)!=0){
totalExpressFee = totalExpressFee.add(
expressFeeService.calculateExpressFee(defaultExpress.getParamValue(), totalWeight01.setScale(0, RoundingMode.UP), regionCode));
}
if(totalWeight02.compareTo(BigDecimal.ZERO)!=0){
totalExpressFee = totalExpressFee.add(
expressFeeService.calculateExpressFee(defaultExpress.getParamValue(), totalWeight02.setScale(0, RoundingMode.UP), regionCode));
}
if(totalWeight04.compareTo(BigDecimal.ZERO)!=0){
totalExpressFee = totalExpressFee.add(
expressFeeService.calculateExpressFee(defaultExpress.getParamValue(), totalWeight04.setScale(0, RoundingMode.UP), regionCode));
}
return R.ok().put("result", totalExpressFee);
}
/**
* 列表
*/
@RequestMapping("/getMyOrderList")
public R getMyOrderList(@RequestParam Map<String, Object> params) {
PageUtils page = buyOrderService.getMyOrderList(params);
return R.ok().put("page", page);
}
/**
* @param orderSn 订单号
* @return R
*/
@RequestMapping(value = "/cancelOrder", method = RequestMethod.GET)
@Transactional
public R appDelete(@RequestParam("orderSn") String orderSn) {
// QueryWrapper<BuyOrder> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("order_sn", orderSn);
// BuyOrder buyOrder = buyOrderService.getOne(queryWrapper);
// if (buyOrder == null) {
// return R.error("订单不存在");
// }
// //回滚优惠卷
// if (buyOrder.getCouponId()!=null&&buyOrder.getCouponId()!=0){
// buyOrder.setCouponId(null);
// buyOrderService.updateById(buyOrder);
// }
// // 库存回滚
// QueryWrapper<BuyOrderProduct> buyOrderProductQueryWrapper = new QueryWrapper<>();
// buyOrderProductQueryWrapper.eq("order_id", buyOrder.getOrderId());
// List<BuyOrderProduct> buyOrderProductList = buyOrderProductService.list(buyOrderProductQueryWrapper);
// for (BuyOrderProduct buyOrderProduct : buyOrderProductList) {
// Integer productId = buyOrderProduct.getProductId();
// ShopProduct product = shopProductService.getById(productId);
// product.setProductStock(product.getProductStock() + buyOrderProduct.getQuantity());
// shopProductService.updateById(product);
// }
// buyOrderService.removeById(buyOrder.getOrderId());
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody BuyOrder buyOrder) {
buyOrderService.updateById(buyOrder);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody List<String> orderSnList) {
// QueryWrapper<BuyOrder> queryWrapper = new QueryWrapper<>();
// queryWrapper.in("order_sn", orderSnList);
// buyOrderService.remove(queryWrapper);
return R.ok();
}
/**
* app 端 取消订单
*/
@RequestMapping("/appDelete")
@Transactional
public R appDelete(@RequestParam("orderId") Integer orderId) {
//1. 判断订单状态
// BuyOrder buyOrder = buyOrderService.getById(orderId);
// if (buyOrder != null) {
// //回滚优惠卷
// if (buyOrder.getCouponId()!=null&&buyOrder.getCouponId()!=0){
// buyOrder.setCouponId(null);
// buyOrderService.updateById(buyOrder);
// }
// // 库存回滚
// List<BuyOrderDetail> buyOrderDetailEntities = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetail>()
// .eq("order_id", buyOrder.getOrderId()));
// for (BuyOrderDetail buyOrderDetailEntity : buyOrderDetailEntities) {
// Integer productId = buyOrderDetailEntity.getProductId();
// ShopProduct product = shopProductService.getById(productId);
// product.setProductStock(product.getProductStock() + buyOrderDetailEntity.getQuantity());
// shopProductService.updateById(product);
// }
// buyOrderService.removeById(orderId);
// }
return R.ok();
}
/**
* 充值专用订单生成接口
*/
@RequestMapping("/rechargeSave")
@Transactional
public R rechargeSave(@RequestBody BuyOrder buyOrder) throws IOException {
buyOrder.setOrderStatus("0");
buyOrder.setOrderType("point");
String timeId = IdWorker.getTimeId().substring(0, 32);
buyOrder.setOrderSn(timeId);
buyOrderService.save(buyOrder);
//下单微信支付预付款订单
if(Constants.PAYMENT_METHOD_WECHAT_PAY.equals(buyOrder.getPaymentMethod())){
BuyOrder buyOrderEntity = buyOrderService.getBaseMapper().selectOne(new LambdaQueryWrapper<BuyOrder>().eq(BuyOrder::getOrderSn, timeId));
WechatPaymentInfo paymentInfo = new WechatPaymentInfo();
paymentInfo.setOrderSn(buyOrderEntity.getOrderSn());
paymentInfo.setBuyOrderId(Integer.valueOf(buyOrderEntity.getProductId()));
paymentInfo.setTotalAmount(buyOrderEntity.getRealMoney());
// paymentInfo.setAppName(buyOrder.getAppName());
if (buyOrder.getCome()==2){
paymentInfo.setAppName("wumen");
} else if (buyOrder.getCome()==1) {
paymentInfo.setAppName("zmzm");
} else if (buyOrder.getCome()==3) {
paymentInfo.setAppName("xlkj");
} else if (buyOrder.getCome()==4) {
paymentInfo.setAppName("thyy");
}else {
paymentInfo.setAppName(buyOrder.getAppName());
}
wxpayService.prepay(paymentInfo);
}
rabbitTemplate.convertAndSend(
DelayQueueConfig.ORDER_TO_BE_PAY_EXCHANGE,
DelayQueueConfig.ORDER_TO_BE_PAY_ROUTING_KEY,
buyOrder.getOrderId(),
messagePostProcessor()
);
return R.ok().put("orderSn", timeId);
}
/**
* 获取订单详情
* TODO 新版本上线后删除
*
* @param orderId
* @return
*/
@RequestMapping("/getOrderDetail")
public R getOrderDetail(@RequestParam Integer orderId) {
LambdaQueryWrapper<BuyOrder> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(BuyOrder::getOrderId, orderId);
BuyOrder one = buyOrderService.getOne(wrapper);
if (one.equals(null)) {
return R.error("order error:order is null");
}
//添加用户信息
one.setUser(myUserService.getById(one.getUserId()));
//添加商品信息
LambdaQueryWrapper<BuyOrderDetail> wrapper1 = new LambdaQueryWrapper<>();
wrapper1.eq(BuyOrderDetail::getOrderId, orderId);
List<BuyOrderDetail> buyOrderDetailEntities = buyOrderDetailService.getBaseMapper().selectList(wrapper1);
one.setProducts(buyOrderDetailEntities);
return R.ok().put("detail", one);
}
/**
* 获取订单详情
*
* @param orderId 订单 ID
* @return R
* TODO 新版本上线后 该方法删除
*/
@RequestMapping(value = "/getOrderInfo", method = RequestMethod.GET)
public R appGetOrderInfo(@RequestParam("orderId") Integer orderId) {
BuyOrder buyOrder = buyOrderService.getById(orderId);
QueryWrapper<BuyOrderDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("order_id", orderId);
List<BuyOrderDetail> buyOrderDetailList = buyOrderDetailService.list(queryWrapper);
for (BuyOrderDetail buyOrderDetail : buyOrderDetailList) {
ShopProduct prod = shopProductService.getById(buyOrderDetail.getProductId());
if (prod != null) {
buyOrderDetail.setImage(prod.getProductImages());
}
}
return R.ok().put("result", buyOrder);
}
/**
* 修改订单地址
*
* @param addressRequestVo 地址请求 value object
* @return R
*/
@RequestMapping(value = "/modifyConsigneeAddress", method = RequestMethod.POST)
public R modifyOrderAddress(@RequestBody ModifyOrderAddressRequestVo addressRequestVo) {
QueryWrapper<BuyOrder> buyOrderQueryWrapper = new QueryWrapper<>();
buyOrderQueryWrapper.eq("order_sn", addressRequestVo.getOrderSn());
BuyOrder buyOrder = buyOrderService.getOne(buyOrderQueryWrapper);
String provinceCode = addressRequestVo.getProvinceCode();
QueryWrapper<Province> provinceQueryWrapper = new QueryWrapper<>();
provinceQueryWrapper.eq("region_code", provinceCode);
Province province = provinceService.getOne(provinceQueryWrapper);
buyOrder.setProvince(province.getProvName());
String cityCode = addressRequestVo.getCityCode();
QueryWrapper<City> cityQueryWrapper = new QueryWrapper<>();
cityQueryWrapper.eq("region_code", cityCode);
City city = cityService.getOne(cityQueryWrapper);
buyOrder.setCity(city.getCityName());
String countyCode = addressRequestVo.getCountyCode();
QueryWrapper<County> countyQueryWrapper = new QueryWrapper<>();
countyQueryWrapper.eq("region_code", countyCode);
County county = countyService.getOne(countyQueryWrapper);
buyOrder.setDistrict(county.getCountyName());
buyOrder.setShippingUser(addressRequestVo.getConsigneeName());
buyOrder.setUserPhone(addressRequestVo.getConsigneeMobile());
buyOrder.setAddress(addressRequestVo.getAddress());
String str = buyOrder.getShippingUser()+buyOrder.getAddress()+buyOrder.getRemark();
if (str.contains("+")||str.contains("&")) {
return R.error(500, "信息中不能含有“+”、“&”符号!");
}
buyOrderService.updateById(buyOrder);
return R.ok();
}
/**
* 获取订单地址
*
* @param orderSn 订单号
* @return R
*/
@RequestMapping(value = "/getConsigneeAddress", method = RequestMethod.GET)
public R getOrderAddress(@RequestParam("orderSn") String orderSn) {
QueryWrapper<BuyOrder> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("order_sn", orderSn);
BuyOrder buyOrder = buyOrderService.getOne(queryWrapper);
OrderAddressResponseVo responseVo = new OrderAddressResponseVo();
responseVo.setConsigneeMobile(buyOrder.getUserPhone());
responseVo.setConsigneeName(buyOrder.getShippingUser());
responseVo.setDetailAddress(buyOrder.getAddress());
String provinceName = buyOrder.getProvince();
String cityName = buyOrder.getCity();
String countyName = buyOrder.getDistrict();
QueryWrapper<Province> provinceQueryWrapper = new QueryWrapper<>();
provinceQueryWrapper.eq("prov_name", provinceName);
Province province = provinceService.getOne(provinceQueryWrapper);
responseVo.setProvinceCode(province.getRegionCode());
QueryWrapper<City> cityQueryWrapper = new QueryWrapper<>();
cityQueryWrapper.eq("city_name", cityName);
City city = cityService.getOne(cityQueryWrapper);
responseVo.setCityCode(city.getRegionCode());
QueryWrapper<County> countyQueryWrapper = new QueryWrapper<>();
countyQueryWrapper.eq("county_name", countyName);
County county = countyService.getOne(countyQueryWrapper);
responseVo.setCountyCode(county.getRegionCode());
return R.ok().put("result", responseVo);
}
/**
* 查询订单快递
*
* @param expressOrderSn 运单号
* @return R
*/
// @RequestMapping(value = "/queryExpress", method = RequestMethod.GET)
// public R queryExpress(@RequestParam("expressOrderSn") String expressOrderSn,
// @RequestParam("expressCompanyCode") String expressCompanyCode,
// @RequestParam("customerName") String customerName) {
//
// ExpressQueryResponseVo vo = new ExpressQueryResponseVo();
// ExpressQueryResponse expressQueryResponse = expressOrderService.queryExpressOrder(expressCompanyCode, expressOrderSn, customerName);
// vo.setLogisticCode(expressQueryResponse.getLogisticCode());
// vo.setTraces(expressQueryResponse.getTraces());
// return R.ok().put("result", vo);
// }
/**
* 查询快递订单轨迹
* @param expressOrderSn
* @return
*/
@RequestMapping("/searchExpress")
public R searchExpress(@RequestParam String expressOrderSn){
LambdaQueryWrapper<ExpressOrder> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ExpressOrder::getExpressOrderSn,expressOrderSn);
ExpressOrder expressOrder = expressOrderService.getBaseMapper().selectOne(wrapper);
if(expressOrder==null){
return R.error("查询失败");
}
String tel = expressOrder.getConsigneeMobile().substring(expressOrder.getConsigneeMobile().length()-4);
ExpressQueryResponse expressQueryResponse = expressOrderService.queryExpressOrder(expressOrder.getExpressCompanyCode(), expressOrderSn, tel);
return R.ok().put("express",expressQueryResponse);
}
/**
* 检查可合并的订单信息
*
* @return
*/
@RequestMapping("/checkOrder")
public R checkOrder(@RequestParam Map<String, Object> params) {
Page page = buyOrderService.checkOrder(params);
return R.ok().put("page", page);
}
/**
* 检查传来的orderId 是否有可合并的其他订单信息
*
* @param orderIds
* @return
*/
@RequestMapping("/checkMerge")
public R checkMerge(@RequestBody Integer[] orderIds) {
List list = buyOrderService.checkOrder(orderIds);
return R.ok().put("list", list);
}
/**
* 分包发货
*
* @param expressCompanyCode 快递公司编码
* @param buyOrderProductId 订单商品
* @return R
*/
@RequestMapping(value = "/delivery", method = RequestMethod.POST)
public R delivery(@RequestParam("expressCompanyCode") String expressCompanyCode,
@RequestBody List<Integer> buyOrderProductId) throws Exception {
return buyOrderService.delivery(expressCompanyCode, buyOrderProductId);
}
@RequestMapping("/mytest")
public R mytest() throws IOException {
String mytest = buyOrderService.mytest();
return R.ok().put("url",mytest);
}
/**
* 获取商品实际价格
*
* @param product 商品信息
* @return 商品实际价格
*/
private BigDecimal getRealPrice(ShopProduct product) {
BigDecimal activityPrice = product.getActivityPrice();
return (activityPrice == null || activityPrice.equals(BigDecimal.ZERO)) ? product.getPrice() : activityPrice;
}
/**
* 处理商品库存
* TODO 新版本上线后删除此方法
*
* @param buyOrderDetail
* @param product
* @return
*/
private boolean handleStock(BuyOrderDetail buyOrderDetail, ShopProduct 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 buyOrderProduct 订单商品信息
* @param product 商品
* @return boolean
*/
private boolean handleStock(BuyOrderProduct buyOrderProduct, ShopProduct product) {
int quantity = buyOrderProduct.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 getShoppingAmount(BuyOrder buyOrder) {
return buyOrder.getOrderMoney() == null ? BigDecimal.ZERO : buyOrder.getShippingMoney();
}
/**
* 使用虚拟币支付
*
* @param user
* @param totalPrice
* @return
*/
private boolean usePeanutCoin(MyUserEntity user, BigDecimal totalPrice, boolean sj_check, boolean scqq_check, boolean wylq_check, boolean prescript_b_check) {
if (user.getPeanutCoin().compareTo(totalPrice) >= 0) {
if(totalPrice.compareTo(BigDecimal.ZERO)==0){//纯积分支付,虚拟币不用支付
return true;
}
user.setPeanutCoin(user.getPeanutCoin().subtract(totalPrice));
if (sj_check){
user.setPointPower(1);
}
if(scqq_check){
user.setTgdzPower(1);
}
if(wylq_check){
user.setWylqPower(1);
}
if(prescript_b_check){
user.setPrescriptBPower(1);
}
this.myUserService.updateById(user);
return true;
}
return false;
}
private boolean useJfCoin(MyUserEntity user,BigDecimal jf){
if(jf==null){
return true;
}
if(user.getJf().compareTo(jf)>=0){
user.setJf(user.getJf().subtract(jf));
this.myUserService.updateById(user);
return true;
}else{
return false;
}
}
/**
* 给用户添加电子书
* TODO 新版本上线删除此接口
* @param products
*
* @param buyOrder
*/
private void addEbookToUser(List<BuyOrderDetail> products, BuyOrder buyOrder) {
List<Integer> productIds = products.stream().map(BuyOrderDetail::getProductId).collect(Collectors.toList());
for (Integer productId : productIds) {
List<Integer> collect = shopProductBookService.getBaseMapper().selectList(new LambdaQueryWrapper<ShopProductBookEntity>()
.eq(ShopProductBookEntity::getProductId, productId)
.eq(ShopProductBookEntity::getDelFlag, 0)).stream().map(ShopProductBookEntity::getBookId).collect(Collectors.toList());
userEbookBuyService.addBookForUser(buyOrder.getUserId(), collect);
}
}
/**
* 给用户添加电子书
* TODO 这里的参数 0 没用 新版本上线后删除
*
* @param products
* @param buyOrder
*/
private void addEbookToUser(List<BuyOrderProduct> products, BuyOrder buyOrder, Integer x) {
List<Integer> productIds = products.stream().map(BuyOrderProduct::getProductId).collect(Collectors.toList());
for (Integer productId : productIds) {
List<Integer> collect = shopProductBookService.getBaseMapper().selectList(new LambdaQueryWrapper<ShopProductBookEntity>()
.eq(ShopProductBookEntity::getProductId, productId)
.eq(ShopProductBookEntity::getDelFlag, 0)).stream().map(ShopProductBookEntity::getBookId).collect(Collectors.toList());
userEbookBuyService.addBookForUser(buyOrder, buyOrder.getUserId(), collect);
}
}
/**
* 购物车
* TODO 新版本上线后删除此方法
*
* @param buyOrder
* @param buyOrderDetail
*/
private void handleBuyCart(BuyOrder buyOrder, BuyOrderDetail 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);
}
}
/**
* 购物车
*
* @param buyOrder 订单
* @param buyOrderProduct
*/
private void handleBuyCart(BuyOrder buyOrder, BuyOrderProduct buyOrderProduct) {
List<OrderCartEntity> orderCartList = orderCartService.getBaseMapper().selectList(new QueryWrapper<OrderCartEntity>()
.eq("user_id", buyOrder.getUserId()).eq("product_id", buyOrderProduct.getProductId()));
if (orderCartList.size() > 0) {
List<Integer> collect = orderCartList.stream().map(OrderCartEntity::getCartId).collect(Collectors.toList());
orderCartService.removeByIds(collect);
}
}
private MessagePostProcessor messagePostProcessor() {
return message -> {
//设置有效期30分钟
message.getMessageProperties().setExpiration(String.valueOf(30 * 60 * 1000));
return message;
};
}
}