Просмотр исходного кода

[下订单][修改]:下订单流程整理

release_toaliyun_real
Stormeye Wu 7 лет назад
Родитель
Сommit
a9c098df4e
9 измененных файлов: 378 добавлений и 649 удалений
  1. +5
    -6
      mallinkCApi/src/main/java/com/iformall/controller/WxCardPayController.java
  2. +3
    -141
      mallinkCApi/src/main/java/com/iformall/controller/WxOrderController.java
  3. +11
    -78
      mallinkCApi/src/main/java/com/iformall/controller/WxPayOrderController.java
  4. +13
    -0
      mallinkService/src/main/java/com/iformall/domain/po/WxCoupon.java
  5. +0
    -16
      mallinkService/src/main/java/com/iformall/service/WxOrderService.java
  6. +52
    -43
      mallinkService/src/main/java/com/iformall/service/impl/WxOrderGroupServiceImpl.java
  7. +270
    -320
      mallinkService/src/main/java/com/iformall/service/impl/WxOrderServiceImpl.java
  8. +23
    -44
      mallinkService/src/main/java/com/iformall/service/impl/WxPayOrderServiceImpl.java
  9. +1
    -1
      mallinkService/src/main/resources/mapper/WxOrderGroupMapper.xml

+ 5
- 6
mallinkCApi/src/main/java/com/iformall/controller/WxCardPayController.java Просмотреть файл

@@ -70,6 +70,10 @@ public class WxCardPayController extends BaseController {
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "totalFee不能为空");
}

BigDecimal totalFee = new BigDecimal(totalFeeStr);
totalFee.setScale(2, BigDecimal.ROUND_HALF_UP); // 第一个变量是小数位数,第二个变量是取舍方法(四舍五入)
Integer payment = totalFee.multiply(new BigDecimal(100)).intValue();

Long cardId = null;
Long merchantId = null;
try {
@@ -85,18 +89,13 @@ public class WxCardPayController extends BaseController {
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "merchantId转换失败");
}

BigDecimal totalFee = new BigDecimal(totalFeeStr);
totalFee.setScale(2, BigDecimal.ROUND_HALF_UP); // 第一个变量是小数位数,第二个变量是取舍方法(四舍五入)

Integer payment = totalFee.multiply(new BigDecimal(100)).intValue();

WxCardInfo cardInfo = wxCardInfoService.getById(cardId);
if(cardInfo == null) {
logger.error("卡不存在: " + cardIdStr);
return new ResultData(ErrorCode.CARD_IS_NOT_FOUND);
}

if(payment>cardInfo.getRemainingAmount()) {
if(payment > cardInfo.getRemainingAmount()) {
logger.error("卡余额不足: " + cardIdStr);
return new ResultData(ErrorCode.CARD_REMAIN_AMOUNT_IS_NOT_ENOUGH);
}


+ 3
- 141
mallinkCApi/src/main/java/com/iformall/controller/WxOrderController.java Просмотреть файл

@@ -44,148 +44,8 @@ public class WxOrderController extends BaseController {
@Autowired
private WxCouponService wxCouponService;


@ApiOperation(value = "免费领取", notes = "{\"couponChannelId\":\"String\",\"couponId\":\"String\",\"formId\":\"String\"}")
@PostMapping("freeCoupon")
public ResultData freeCoupon(@RequestBody Map<String, String> paramMap) {
//Assert.notNull(wxOrders.getName(), "角色名不能为空");
//Assert.isTrue(!checkUnique(sysRole.getName(), null), "重复的角色名");
String couponChannelIdStr = paramMap.get("couponChannelId");
String couponIdStr = paramMap.get("couponId");
String formId = paramMap.get("formId");
if (StringUtils.isBlank(couponChannelIdStr)) {
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId不能为空");
}
Long couponChannelId = 0L, couponId = 0L;
try {
couponChannelId = Long.valueOf(couponChannelIdStr);
} catch (NumberFormatException e) {
logger.error("couponChannelId convert error, " + couponChannelIdStr + ", e:" + e.getMessage());
return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR.getCode(), "couponChannelId: " + couponChannelIdStr + ", e:" + e.getMessage());
}
WxCouponChannel wxCouponChannel = wxCouponChannelService.getById(couponChannelId);
if (wxCouponChannel == null) {
logger.error("couponChannelId convert error, " + couponChannelIdStr);
return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR.getCode(), "找不到发布的频道");
}
if (wxCouponChannel.getStatus() == EnumCouponChannelStatus.STATUS_TAKE_OFFF.getCode()) {
logger.error("此券已下架:" + couponChannelIdStr);
return new ResultData(ErrorCode.COUPON_CHANNEL_IS_TAKE_OFF.getCode(), "此券已下架");
}
if (StringUtils.isBlank(couponIdStr)) {
couponId = wxCouponChannel.getCouponId();
}

WxOrder order = null;

try {
order = wxOrderService.saveFreeCouponOrder(getUserId(), couponChannelId, couponId, formId);
return new ResultData(order);
} catch (MallinkException e) {
logger.error(e.getMessage());
return new ResultData(e.getErrorCode(), e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
return new ResultData(ErrorCode.ORDER_IS_FAIL, e.getMessage());
}
}

@ApiOperation(value = "下订单", notes = "{\"couponChannelId\":\"String\",\"couponId\":\"String\",\"press\":\"String\",\"orderGroupId\":\"String\",\"formId\":\"String\"}")
@PostMapping("save")
public ResultData saveOrder(@RequestBody Map<String, String> paramMap) {
logger.info("OrderSave: " + paramMap.toString());
//Assert.notNull(wxOrders.getName(), "角色名不能为空");
//Assert.isTrue(!checkUnique(sysRole.getName(), null), "重复的角色名");
String couponChannelIdStr = paramMap.get("couponChannelId");
String couponIdStr = paramMap.get("couponId");
String pressStr = paramMap.get("press");
String orderGroupIdStr = paramMap.get("orderGroupId");
String formId = paramMap.get("formId");

if (StringUtils.isBlank(couponChannelIdStr)) {
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId不能为空");
}
Long couponChannelId = 0L, couponId = 0L, orderGroupId = null;
boolean isPress = false;

if (StringUtils.isNotBlank(couponChannelIdStr)) {
try {
couponChannelId = Long.valueOf(couponChannelIdStr);
} catch (NumberFormatException e) {
logger.error("couponChannelId convert error, " + couponChannelIdStr + ", e:" + e.getMessage());
return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR.getCode(), "couponChannelId: " + couponChannelIdStr + ", e:" + e.getMessage());
}
WxCouponChannel wxCouponChannel = wxCouponChannelService.getById(couponChannelId);
if (wxCouponChannel == null) {
logger.error("couponChannelId convert error, " + couponChannelIdStr);
return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR);
}

if (wxCouponChannel.getTargetAd().equals(EnumCouponChannelType.COUPON_CHANNEL_ID_TIMED.getCode())) {
Date now = new Date();
if (wxCouponChannel.getBeginTime().getTime() > now.getTime()) {
logger.error("此券活动未开始:" + couponChannelIdStr);
return new ResultData(ErrorCode.COUPON_CHANNEL_IS_NOT_STARTED);
}
if (wxCouponChannel.getEndTime().getTime() < now.getTime()) {
logger.error("此券活动已结束:" + couponChannelIdStr);
return new ResultData(ErrorCode.COUPON_CHANNEL_IS_END);
}
}

if (wxCouponChannel.getStatus() == EnumCouponChannelStatus.STATUS_TAKE_OFFF.getCode()) {
logger.error("此券已下架:" + couponChannelIdStr);
return new ResultData(ErrorCode.COUPON_CHANNEL_IS_TAKE_OFF);
}
if (StringUtils.isBlank(couponIdStr)) {
couponId = wxCouponChannel.getCouponId();
}
}
if (couponId <= 0 && !StringUtils.isBlank(couponIdStr)) {
try {
couponId = Long.valueOf(couponIdStr);
} catch (NumberFormatException e) {
logger.error("couponId convert error, " + couponIdStr + ", e:" + e.getMessage());
return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR.getCode(), "couponId: " + couponIdStr + ", e:" + e.getMessage());
}
}

if (couponId <= 0) {
logger.error("couponChannelId或者couponId不能为空");
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId或者couponId不能为空");
}

if(pressStr != null) {
try{
isPress = Boolean.valueOf(pressStr);
} catch (Exception e) {
logger.error("press转换失败");
}
}

if (orderGroupIdStr != null) {
try {
orderGroupId = Long.valueOf(orderGroupIdStr);
} catch (Exception e) {
logger.error("orderGroupId转换失败");
}
}

WxCUser user = getUser();
try {
WxOrder order = wxOrderService.saveCouponOrder(user, couponChannelId, couponId, isPress, orderGroupId, formId);
return new ResultData(order);
} catch (MallinkException e) {
logger.error(e.getMessage());
return new ResultData(e.getErrorCode(), e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
return new ResultData(ErrorCode.ORDER_IS_FAIL, e.getMessage());
}
}

@ApiOperation(value = "下订单", notes = "{\"couponChannelId\":\"String\",\"couponId\":\"String\",\"press\":\"String\",\"orderGroupId\":\"String\",\"formId\":\"String\"}")
@PostMapping("save_new")
public ResultData saveOrderNew(@RequestBody OrderSaveDto orderSaveDto) {
logger.info("OrderSave: " + orderSaveDto);
if (orderSaveDto.getCouponChannelId() == null) {
@@ -200,19 +60,21 @@ public class WxOrderController extends BaseController {
logger.error("couponChannelId或者couponId不能为空");
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId或者couponId不能为空");
}
// 是否砍价
boolean isPress = orderSaveDto.getPress() != null ? orderSaveDto.getPress() : false;

WxCUser user = getUser();
try {
//WxOrder order = wxOrderService.saveCouponOrder(user, couponChannelId, couponId, isPress, orderGroupId, formId);
WxOrder order = null;
WxCoupon coupon = wxCouponService.getById(couponId);
if (coupon == null) {
return new ResultData(ErrorCode.COUPON_IS_EMPTY);
}
if (wxOrderService.checkCouponIsFree(coupon)) {
// 免费券
order = wxOrderService.saveFreeOrderForCoupon(user, coupon, orderSaveDto.getCouponChannelId(), orderSaveDto.getFormId());
} else {
// 有价券
order = wxOrderService.saveNoFreeOrderForCoupon(user, coupon, orderSaveDto.getCouponChannelId(), isPress, orderSaveDto.getOrderGroupId(), orderSaveDto.getFormId());
}
return new ResultData(order);


+ 11
- 78
mallinkCApi/src/main/java/com/iformall/controller/WxPayOrderController.java Просмотреть файл

@@ -78,7 +78,7 @@ public class WxPayOrderController extends BaseController {

@ApiOperation(value = "更新支付订单状态", notes = "{\"payOrderId\":\"string\",\"orderId\":\"string\",\"status\":integer,\"reason\":\"string\"}")
@PostMapping("/updatePayOrder")
public ResultData updatePayOrder(@RequestBody Map<String, Object> paramMap) {
public ResultData updatePayOrderNew(@RequestBody Map<String, Object> paramMap) {
logger.info("/api/pay/updatePayOrder" + paramMap.toString());
String payOrderIdStr = (String) paramMap.get("payOrderId");
String orderIdStr = (String) paramMap.get("orderId");
@@ -104,6 +104,11 @@ public class WxPayOrderController extends BaseController {
}
}

if(payOrderIdStr.equalsIgnoreCase("0")) {
// 免费券直接返回成功
return new ResultData(Result.SUCCESS, "免费券支付状态更新成功");
}

WxPayOrder payOrder = new WxPayOrder();
payOrder.setId(payOrderId);
payOrder.setOrderId(orderId);
@@ -113,91 +118,19 @@ public class WxPayOrderController extends BaseController {
WxOrder order = null;

try {
if(status.equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode()) && !payOrderIdStr.equals("0")) {
//有价券支付成功
if (status.equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
// 前端提示支付成功, 不作为支付成功标志,只检查支付订单状态
// 有价券不走update, callback更新
payOrder = wxPayOrderService.getById(payOrderId);
if(payOrder.getPayOrderStatus().equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
if (payOrder.getPayOrderStatus().equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
order = wxOrderService.getById(orderId);
return new ResultData(Result.SUCCESS, "支付状态更新成功", order);
} else {
return new ResultData(ErrorCode.PAY_ORDER_ERROR, "支付未状态,请等待!!");
}
} else {
// 1. 免费券,status = 1,成功
// 2. 有价券,status = 2,取消支付
if(status.equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
wxPayOrderService.handlePayOrderStatusUpdate(payOrder, 1);
} else if (status.equals(EnumPayStatus.PAY_STATUS_FAIL.getCode())) {
wxPayOrderService.handlePayOrderStatusUpdate(payOrder, 2);
}
}
return new ResultData(Result.SUCCESS, "支付状态更新成功");
} catch (MallinkException e) {
logger.error("支付状态更新失败2: " + payOrder.toString() + ", e:" + e.getMessage());
return new ResultData(e.getErrorCode(), e.getMessage());
} catch (Exception e) {
logger.error("支付状态更新失败3: " + payOrder.toString() + ", e:" + e.getMessage());
return new ResultData(ErrorCode.PAY_ORDER_ERROR, "支付状态更新失败3: " + payOrder.toString() + ", e:" + e.getMessage());
}
}

@ApiOperation(value = "更新支付订单状态", notes = "{\"payOrderId\":\"string\",\"orderId\":\"string\",\"status\":integer,\"reason\":\"string\"}")
@PostMapping("/updatePayOrder_new")
public ResultData updatePayOrderNew(@RequestBody Map<String, Object> paramMap) {
logger.info("/api/pay/updatePayOrder" + paramMap.toString());
String payOrderIdStr = (String) paramMap.get("payOrderId");
String orderIdStr = (String) paramMap.get("orderId");
String reasonStr = (String) paramMap.get("reason");
Integer status = (Integer) paramMap.get("status");
if (StringUtils.isBlank(orderIdStr)) {
logger.info("orderId不能为空: " + paramMap.toString());
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId不能为空");
}
Long payOrderId = 0L, orderId = 0L;
try {
orderId = Long.valueOf(orderIdStr);
} catch (NumberFormatException e) {
logger.error("orderId参数不正确: " + paramMap.toString() + ", e:" + e.getMessage());
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId参数不正确");
}
if (!StringUtils.isBlank(payOrderIdStr)) {
try {
payOrderId = Long.valueOf(payOrderIdStr);
} catch (NumberFormatException e) {
logger.error("payOrderId参数不正确: " + paramMap.toString() + ", e:" + e.getMessage());
return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "payOrderId参数不正确");
}
}

WxPayOrder payOrder = new WxPayOrder();
payOrder.setId(payOrderId);
payOrder.setOrderId(orderId);
payOrder.setPayOrderStatus(status);
payOrder.setFailReason(reasonStr);

WxOrder order = null;

try {
//支付成功
if (status.equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
//有价券
if(!payOrderIdStr.equals("0")){
// 前端提示支付成功, 不作为支付成功标志,只检查支付订单状态
// 有价券不走update, callback更新
payOrder = wxPayOrderService.getById(payOrderId);
if(payOrder.getPayOrderStatus().equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
order = wxOrderService.getById(orderId);
return new ResultData(Result.SUCCESS, "支付状态更新成功", order);
} else {
return new ResultData(ErrorCode.PAY_ORDER_ERROR, "支付未状态,请等待!!");
}
} else {
//免费券
wxPayOrderService.handlePayOrderStatusUpdateFree(payOrder);
}
} else if (status.equals(EnumPayStatus.PAY_STATUS_FAIL.getCode())){
//支付失败
} else if (status.equals(EnumPayStatus.PAY_STATUS_FAIL.getCode())) {
// 有价券支付失败
wxPayOrderService.handlePayOrderStatusUpdate(payOrder, EnumPayStatus.PAY_STATUS_FAIL.getCode());
}
return new ResultData(Result.SUCCESS, "支付状态更新成功");


+ 13
- 0
mallinkService/src/main/java/com/iformall/domain/po/WxCoupon.java Просмотреть файл

@@ -2,6 +2,7 @@ package com.iformall.domain.po;

import com.iformall.common.SortColumn;
import com.iformall.domain.vo.WxCouponStatisVo;
import com.iformall.enums.EnumCouponType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@@ -542,6 +543,18 @@ public class WxCoupon extends BaseEntity {
this.orgInventory = orgInventory;
}

public boolean checkIsCreditCoupon() {
if(type == null) {
return false;
}

if(type == EnumCouponType.COUPON_CREDIT.getCode() ||
type == EnumCouponType.COUPON_CREDIT_PARK.getCode()) {
return true;
}
return false;
}

public static enum Field
{
Id_ASC("`id` ASC"),Id_DESC("`id` DESC")


+ 0
- 16
mallinkService/src/main/java/com/iformall/service/WxOrderService.java Просмотреть файл

@@ -32,15 +32,6 @@ public interface WxOrderService {

ResultData microPayListOnDateAsPage(Long bUserId, Integer type, String date, Integer pageIndex, Integer pageSize);


/**
* 下免费券订单接口
* @param userId
* @param couponId
* @return WxOrder
*/
WxOrder saveFreeCouponOrder(Long userId, Long couponChannelId, Long couponId, String formId);

/**
* 提交订单
* @param user
@@ -83,13 +74,6 @@ public interface WxOrderService {
*/
int couponOrderSuccess(WxOrder updateOrder);

/**
* orderSuccess 订单已支付(免费券)
* @param updateOrder
* @return
*/
int couponOrderSuccessFree(WxOrder updateOrder);

/**
* microPayOrderSuccess 刷卡支付成功
* @param updateOrder


+ 52
- 43
mallinkService/src/main/java/com/iformall/service/impl/WxOrderGroupServiceImpl.java Просмотреть файл

@@ -36,6 +36,9 @@ import java.util.stream.Collectors;
public class WxOrderGroupServiceImpl implements WxOrderGroupService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());

private final Long notOrderGroupId = 0L;
private final int endPeople = 0;

@Autowired
WxOrderGroupMapper wxOrderGroupMapper;

@@ -67,30 +70,26 @@ public class WxOrderGroupServiceImpl implements WxOrderGroupService {
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void createOrderGroup(WxOrder order, WxCoupon wxCoupon) {
Long orderGroupId = order.getOrderGroupId();
Long notOrderGroupId = 0L;
//查看是否首次拼团,orderGroupId不等于0代表不是首次拼团,因为第二个加入的拼团者肯定有团单号
if (!orderGroupId.equals(notOrderGroupId)) {
WxOrderGroup wxOrderGroup = new WxOrderGroup();
wxOrderGroup.setId(orderGroupId);
wxOrderGroup.setUpdateDate(new Date());
logger.info("非首次拼团,更新拼团信息");
int row = wxOrderGroupMapper.updateOrderGroup(wxOrderGroup);
if (row == 0) {
// 非首次拼团
// 参与拼团
WxOrderGroup wxOrderGroup = wxOrderGroupMapper.selectByPrimaryKey(orderGroupId);
if(wxOrderGroup.getRemainPeople() < endPeople + 1) {
logger.info(">>>>>>>>>>>>参团失败 修改订单状态后定时退款 团单号" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
wxOrderGroup = wxOrderGroupMapper.selectByPrimaryKey(orderGroupId);
Integer remainPeople = wxOrderGroup.getRemainPeople();
int endPeople = 0;
Integer remainPeople = wxOrderGroup.getRemainPeople()-1;
wxOrderGroup.setStatus(remainPeople == endPeople ? EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode() : wxOrderGroup.getStatus());
wxOrderGroup.setUpdateDate(new Date());
try {
wxOrderGroupMapper.updateByPrimaryKeySelective(wxOrderGroup);
} catch (Exception e) {
logger.error("更新拼团信息失败", e);
logger.info("非首次拼团,更新拼团信息, 剩余人数-1");
int row = wxOrderGroupMapper.updateOrderGroup(wxOrderGroup);
if (row != 1) {
logger.info(">>>>>>>>>>>>参团失败 修改订单状态后定时退款 团单号" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
//更新order

// 更新订单信息
order.setOrderStatus(wxOrderGroup.getStatus());
order.setPressEndDate(wxOrderGroup.getExpiredDate());
order.setOrderGroupId(wxOrderGroup.getId());
@@ -101,34 +100,7 @@ public class WxOrderGroupServiceImpl implements WxOrderGroupService {
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
if (remainPeople == endPeople) {
//得到所有拼团的order
WxOrder wxOrder = new WxOrder();
wxOrder.setTenantId(order.getTenantId());
wxOrder.setOrderGroupId(orderGroupId);
List<WxOrder> list = wxOrderMapper.findList(wxOrder).parallelStream()
.filter(o -> {
return o.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING.getCode()) ||
o.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode());
}).collect(Collectors.toList());
for (WxOrder temp : list) {
try {
wxOrderService.couponOrderSuccess(temp);
} catch (Exception e) {
logger.error("创建COUPON_ORDER失败", e);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
}
//拼团成功后把待支付的取消
wxOrder.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_UNPAID.getCode());
list = wxOrderMapper.select(wxOrder);
for (WxOrder temp : list) {
//去库存
wxOrderService.updateOrderStatus(temp);
//拼团取消
temp.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_BREAK.getCode());
wxOrderMapper.updateByPrimaryKeySelective(temp);
}

actionAfterOrderGroupSuccess(order, orderGroupId);
}
} else {
logger.info("首次拼团,创建拼团信息");
@@ -170,6 +142,43 @@ public class WxOrderGroupServiceImpl implements WxOrderGroupService {

}

/**
* 拼团成功后,完成拼团相关工作
* @param order
* @param orderGroupId
*/
private void actionAfterOrderGroupSuccess(WxOrder order, Long orderGroupId) {
// 拼团完成
// 得到所有拼团的order
WxOrder wxOrder = new WxOrder();
wxOrder.setTenantId(order.getTenantId());
wxOrder.setOrderGroupId(orderGroupId);
List<WxOrder> list = wxOrderMapper.findList(wxOrder).parallelStream()
.filter(o -> {
return o.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING.getCode()) ||
o.getOrderStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode());
}).collect(Collectors.toList());
// 已成功订单,用户领取couponOrder
for (WxOrder temp : list) {
try {
wxOrderService.couponOrderSuccess(temp);
} catch (Exception e) {
logger.error("创建COUPON_ORDER失败", e);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
}
// 拼团成功后,取消待支付订单
wxOrder.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_UNPAID.getCode());
list = wxOrderMapper.select(wxOrder);
for (WxOrder temp : list) {
//去库存
wxOrderService.updateOrderStatus(temp);
//拼团取消
temp.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_BREAK.getCode());
wxOrderMapper.updateByPrimaryKeySelective(temp);
}
}

@Override
public ResultData queryRemainOne(WxOrderGroup wxOrderGroup, Long userId) {
//取过期时间最大的数据


+ 270
- 320
mallinkService/src/main/java/com/iformall/service/impl/WxOrderServiceImpl.java Просмотреть файл

@@ -176,8 +176,13 @@ public class WxOrderServiceImpl implements WxOrderService {
}


/**
* 用户购买的订单数量
* @param user
* @param counpon
* @return
*/
private int getUserOrderCount(WxCUser user, WxCoupon counpon) {
// 用户购买的券包数量
// + Order 待支付
try {
WxOrder orderQ = new WxOrder();
@@ -199,8 +204,13 @@ public class WxOrderServiceImpl implements WxOrderService {

}

/**
* 用户购买的券包数量- 待使用的券
* @param user
* @param counpon
* @return
*/
private int getUserCouponOrderCount(WxCUser user, WxCoupon counpon) {
// 用户购买的券包数量
// + couponOrder ---待使用
try {
WxCouponOrder couponOrderQ = new WxCouponOrder();
@@ -219,6 +229,12 @@ public class WxOrderServiceImpl implements WxOrderService {
}


/**
* 减库存
* @param user
* @param coupon
* @param couponIdStr
*/
private void stockReduce(WxCUser user, WxCoupon coupon, String couponIdStr) {
long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
String timeStr = String.valueOf(time);
@@ -237,6 +253,7 @@ public class WxOrderServiceImpl implements WxOrderService {
}

int count = 0;
// 有价券
if (coupon.getSalePrice() > 0) {
// 检查是否未支付订单
try {
@@ -253,7 +270,7 @@ public class WxOrderServiceImpl implements WxOrderService {
throw new MallinkException(ErrorCode.ORDER_UNPAID);
}
}
//检查已购买数量
// 检查用户已购买数量
try {
count = getUserCouponOrderCount(user, coupon);
} catch (Exception e) {
@@ -269,12 +286,8 @@ public class WxOrderServiceImpl implements WxOrderService {
}

try {
WxCoupon updateRecord = new WxCoupon();
updateRecord.setId(coupon.getId());
updateRecord.setRemainInventory(coupon.getRemainInventory() - 1);
updateRecord.setUpdateDate(new Date());
// 减库存
wxCouponMapper.updateByPrimaryKeySelective(updateRecord);
wxCouponMapper.reduceInventory(coupon.getId(), 1);
} catch (RuntimeException e) {
logger.error("此券减库存失败, couponId: " + couponIdStr);
throw new MallinkException(ErrorCode.ORDER_IS_FAIL);
@@ -328,11 +341,16 @@ public class WxOrderServiceImpl implements WxOrderService {
}
}

/**
* 检查券商户是否可用
* @param couponId
* @return
*/
private boolean isCouponMerchantValid(Long couponId) {
Map paramMap = new HashMap<>();
paramMap.put("productId",couponId);
paramMap.put("productId", couponId);
List<WxMerchantVo> merchantVoList = wxCouponMerchantMapper.findMerchantNameList(paramMap);
if (merchantVoList.stream().anyMatch((cm->cm.getMerchantStatus().equals(EnumMerchantStatus.VALID.getCode())))){
if (merchantVoList.stream().anyMatch((cm -> cm.getMerchantStatus().equals(EnumMerchantStatus.VALID.getCode())))) {
return true;
}
return false;
@@ -364,21 +382,8 @@ public class WxOrderServiceImpl implements WxOrderService {
throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
}
// 拼团
if (orderGroupId != null && !orderGroupId.equals(0L)) {
WxOrderGroup group = wxOrderGroupMapper.selectByPrimaryKey(orderGroupId);
if (group.getStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode())) {
logger.error("下订单拼团人数已满>>>" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FINISHED);
}
WxOrder order = new WxOrder();
order.setOrderGroupId(group.getId());
order.setCUserId(user.getId());
order.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_UNPAID.getCode());
long count = wxOrderMapper.selectCount(order);
if (count > 0) {
logger.error("重复的拼团>>>" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_UNPAID);
}
if (isOrderGroup(orderGroupId)) {
checkOrderGroup(user, orderGroupId);
}

// 减库存操作
@@ -470,7 +475,7 @@ public class WxOrderServiceImpl implements WxOrderService {
record.setPressCurrentNum(0);
// 砍价券过期时间取券的过期时间和砍价限制时间中时间小的那个
Date pressEndDate = DateUtils.getHourTimeAfter(coupon.getPressLimitHours(), new Date());
if(pressEndDate.after(coupon.getValidEndDate()))
if (pressEndDate.after(coupon.getValidEndDate()))
pressEndDate = coupon.getValidEndDate();
record.setPressEndDate(pressEndDate);
record.setPressCurrentValue(coupon.getPrice() - coupon.getSalePrice());
@@ -551,6 +556,7 @@ public class WxOrderServiceImpl implements WxOrderService {
throw new MallinkException(ErrorCode.USER_IS_EMPTY);
}

// 检查商户
WxMerchant wxMerchant = wxMerchantMapper.selectByPrimaryKey(user.getMerchantId());
if (wxMerchant == null) {
logger.error("商户不存在, merchantId: " + user.getMerchantId());
@@ -561,6 +567,8 @@ public class WxOrderServiceImpl implements WxOrderService {
throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_VALID);
}

WxOrder record = new WxOrder();

Date curr = new Date();

BigDecimal totalFee = new BigDecimal(totalFeeStr);
@@ -575,8 +583,6 @@ public class WxOrderServiceImpl implements WxOrderService {
// tenant_id + merchant_id + title + subtitle
String bodyStr = "刷卡支付, 金额:" + totalFeeStr;


WxOrder record = new WxOrder();
record.setId(orderNumber);
record.setTenantId(user.getTenantId());
record.setOrderNumber(orderNumber);
@@ -642,25 +648,24 @@ public class WxOrderServiceImpl implements WxOrderService {
* @param order
* @param coupon
*/
private WxCouponOrder createCouponOrder(WxCUser user, WxOrder order, WxCoupon coupon) {
private WxCouponOrder createCouponOrder(WxOrder order, WxCUser user, WxCoupon coupon) {
Date curr = new Date();
Date valid_date = null;
if (coupon.getValidType().equals(EnumValidStatus.VALID_RANGE.getCode()) ||
coupon.getType().equals(EnumCouponType.COUPON_TINGCHE.getCode())){
coupon.getType().equals(EnumCouponType.COUPON_TINGCHE.getCode())) {
valid_date = coupon.getValidEndDate();
}
else {
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(curr);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.DAY_OF_MONTH, 1+coupon.getValidDays());
calendar.add(Calendar.DAY_OF_MONTH, 1 + coupon.getValidDays());
valid_date = calendar.getTime();
}
boolean isCard = false;
// 检查是否是储值卡
if(coupon.getType().equals(EnumCouponType.CARD_MULTIMCH.getCode())) {
if (coupon.getType().equals(EnumCouponType.CARD_MULTIMCH.getCode())) {
isCard = true;
}
final IdWorker idWorker = IdWorker.get();
@@ -675,7 +680,7 @@ public class WxOrderServiceImpl implements WxOrderService {
couponOrder.setAutoRefund(coupon.getAutoRefund());
couponOrder.setOrderId(order.getOrderNumber());
couponOrder.setExpiredTime(valid_date);
if(!isCard) {
if (!isCard) {
couponOrder.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USE_WAIT.getCode());
} else {
couponOrder.setCouponOrderStatus(EnumCouponOrderStatus.CARD_USING.getCode());
@@ -687,7 +692,7 @@ public class WxOrderServiceImpl implements WxOrderService {
wxCouponOrderMapper.insertSelective(couponOrder);

/// 储值卡信息添加
if(isCard) {
if (isCard) {
WxPayOrder payOrder = null;
try {
WxPayOrder payOrderQ = new WxPayOrder();
@@ -722,95 +727,6 @@ public class WxOrderServiceImpl implements WxOrderService {
return couponOrder;
}

@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
public WxOrder saveFreeCouponOrder(Long userId, Long couponChannelId, Long couponId, String formId) {
// check 用户状态
WxCUser user = null;
try {
user = wxCUserMapper.selectByPrimaryKey(userId);
} catch (Exception e) {
logger.error("userId : " + userId + ", e: " + e.getMessage());
}
if (user == null) {
logger.error("用户不存在, userId: " + userId);
throw new MallinkException(ErrorCode.USER_IS_EMPTY);
}

// 检查券状态
String couponIdStr = String.valueOf(couponId);
WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(couponId);
if (coupon == null) {
logger.error("券不存在, couponId: " + couponIdStr);
throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
}
if (coupon.getStatus() == EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode()) {
logger.error("券已下架, couponId: " + couponIdStr);
throw new MallinkException(ErrorCode.COUPON_IS_TAKE_OFF);
}
if (coupon.getSalePrice() != 0) {
logger.error("券不免费, couponId: " + couponIdStr);
throw new MallinkException(ErrorCode.COUPON_IS_NOT_FREE);
}

// 减库存操作
try {
stockReduce(user, coupon, couponIdStr);
} catch (Exception e) {
logger.error(e.getMessage());
}


int payment = coupon.getSalePrice();

Date curr = new Date();

final IdWorker idWorker = IdWorker.get();
Long orderNumber = idWorker.nextId();

// body
// tenant_id + merchant_id + title + subtitle
String bodyStr = coupon.getTitle() + "/" + coupon.getSubTitle();

WxOrder record = new WxOrder();
record.setId(orderNumber);
record.setTenantId(user.getTenantId());
record.setOrderNumber(orderNumber);
record.setCouponChannelId(couponChannelId);
record.setProductId(couponId);
record.setType(EnumOrderType.COUPON.getCode());
record.setcUserId(user.getId());
record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
record.setPayment(payment);
record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
record.setDetail(bodyStr);
record.setCreateDate(curr);
record.setUpdateDate(curr);
record.setFormId(formId);

// 保存订单
try {
wxOrderMapper.insertSelective(record);
} catch (Exception e) {
logger.error("保存订单:" + e.getMessage());
// 库存恢复
stockBack(record);
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}

// 创建couponOrder
try {
WxCouponOrder couponOrder = createCouponOrder(user, record, coupon);
} catch (Exception e) {
logger.error("保存订单:" + e.getMessage());
// 库存恢复
stockBack(record);
throw new MallinkException(ErrorCode.COUPON_ORDER_SAVE_ERR);
}

return record;
}

@Override
@Transactional(propagation = Propagation.NESTED, readOnly = false, rollbackFor = {Exception.class})
public WxCouponOrder sendFreeCouponToUser(Long userId, Long couponId) {
@@ -883,7 +799,7 @@ public class WxOrderServiceImpl implements WxOrderService {
// 创建couponOrder
WxCouponOrder couponOrder = null;
try {
couponOrder = createCouponOrder(user, record, coupon);
couponOrder = createCouponOrder(record, user, coupon);
} catch (Exception e) {
logger.error("保存订单:" + e.getMessage());
// 库存恢复
@@ -898,6 +814,7 @@ public class WxOrderServiceImpl implements WxOrderService {
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
public int couponOrderSuccess(WxOrder updateOrder) {
Date currentDate = new Date();
// 检查券相关
WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(updateOrder.getProductId());
if (coupon == null) {
logger.error("券不存在, couponId: " + updateOrder.getProductId());
@@ -907,6 +824,7 @@ public class WxOrderServiceImpl implements WxOrderService {
logger.error("券已下架, couponId: " + updateOrder.getProductId());
throw new MallinkException(ErrorCode.COUPON_IS_TAKE_OFF);
}
// 检查用户
WxCUser user = wxCUserMapper.selectByPrimaryKey(updateOrder.getcUserId());
if (user == null) {
logger.error("用户不存在, userId: " + updateOrder.getcUserId());
@@ -920,6 +838,7 @@ public class WxOrderServiceImpl implements WxOrderService {
if (updateOrder.getOrderGroupId().equals(0L)) {
updateT.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
} else {
// 拼团设为已完成状态
updateT.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode());
}
updateT.setUpdateDate(currentDate);
@@ -933,53 +852,38 @@ public class WxOrderServiceImpl implements WxOrderService {

// 创建couponOrder
try {
createCouponOrder(user, updateOrder, coupon);
createCouponOrder(updateOrder, user, coupon);
} catch (Exception e) {
logger.error("保存订单:" + e.getMessage());
logger.error("创建券包:" + e.getMessage());
throw new MallinkException(ErrorCode.COUPON_ORDER_SAVE_ERR);
}

// 增加成长值和积分和发券
addScoreAndCreditAndSendCoupon(updateOrder, coupon, user);
// 订单+券包 流程 完成
actionAfterCouponOrderSuccess(updateOrder, coupon, user);
return ret;
}

@Override
public int couponOrderSuccessFree(WxOrder updateOrder) {
WxCoupon coupon = wxCouponMapper.selectByPrimaryKey(updateOrder.getProductId());
if (coupon == null) {
logger.error("券不存在, couponId: " + updateOrder.getProductId());
throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
}
if (coupon.getStatus() == EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode()) {
logger.error("券已下架, couponId: " + updateOrder.getProductId());
throw new MallinkException(ErrorCode.COUPON_IS_TAKE_OFF);
}
WxCUser user = wxCUserMapper.selectByPrimaryKey(updateOrder.getcUserId());
if (user == null) {
logger.error("用户不存在, userId: " + updateOrder.getcUserId());
throw new MallinkException(ErrorCode.USER_IS_EMPTY);
}
// 增加成长值和积分和发券
addScoreAndCreditAndSendCoupon(updateOrder, coupon, user);
return 0;
}

private void addScoreAndCreditAndSendCoupon(WxOrder updateOrder, WxCoupon coupon, WxCUser user) {
// 发券couponOrder
/**
* 下订单后操作
* @param updateOrder
* @param coupon
* @param user
*/
private void actionAfterCouponOrderSuccess(WxOrder updateOrder, WxCoupon coupon, WxCUser user) {
// 交易发券
try {
wxCouponSendService.sendCouponToUser(EnumCouponSendSendType.C_ORDER,updateOrder);
wxCouponSendService.sendCouponToUser(EnumCouponSendSendType.C_ORDER, updateOrder);
} catch (Exception e) {
logger.error("订单发券:" + e.getMessage());
}
// 成长值 计算
// 成长值
try {
wxScoreRulesService.addScore2(EnumScoreType.CONSUMPTION, updateOrder, coupon.getBusiness());
} catch (Exception e) {
logger.error("成长值:" + e.getMessage());
}

// 积分 计算
// 积分
try {
//-------此处为【现金支付】记录增加积分操作-------
WxCreditHistory creditHistory = new WxCreditHistory();
@@ -1000,6 +904,9 @@ public class WxOrderServiceImpl implements WxOrderService {
}
}

/**
* 积分设置来源商户
*/
private void setMerchantId(WxCoupon coupon, WxCreditHistory creditHistory) {
WxCouponMerchant wxCouponMerchant = new WxCouponMerchant();
wxCouponMerchant.setProductId(coupon.getId());
@@ -1027,13 +934,13 @@ public class WxOrderServiceImpl implements WxOrderService {
}
// B端用户
WxMerchantBUser bUser = wxMerchantBUserMapper.selectByPrimaryKey(updateOrder.getProductId());
if(bUser == null) {
if (bUser == null) {
logger.error("B端用户不存在, bUserId: " + updateOrder.getProductId());
throw new MallinkException(ErrorCode.USER_IS_EMPTY);
}
// 基于B端User查找merchant
WxMerchant wxMerchant = wxMerchantMapper.selectByPrimaryKey(bUser.getMerchantId());
if(wxMerchant == null) {
if (wxMerchant == null) {
logger.error("商户不存在, merchantId: " + bUser.getMerchantId());
throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
}
@@ -1188,7 +1095,7 @@ public class WxOrderServiceImpl implements WxOrderService {
List<WxPayOrder> payOrders = wxPayOrderMapper.select(payOrderQ);

// 3. wx pay order close
for(WxPayOrder payOrder: payOrders) {
for (WxPayOrder payOrder : payOrders) {
try {
wxPayOrderService.payOrderClose(appInfo, payOrder);
} catch (Exception e) {
@@ -1282,7 +1189,7 @@ public class WxOrderServiceImpl implements WxOrderService {
public Map<String, Object> queryOrderSummary(String tenantId) {
Map<String, Object> result = new HashMap<>();
queryMerchantCount(tenantId, result);
queryOrderSummary(tenantId,result);
queryOrderSummary(tenantId, result);
return result;
}

@@ -1294,30 +1201,30 @@ public class WxOrderServiceImpl implements WxOrderService {
String thirtyTime = DateUtils.getTimeBefore(29, new Date());
params.put("startdate", thirtyTime + " 00:00:00");
params.put("enddate", systemTime + " 23:59:59");
Long allMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
result.put("allMerchantCount",allMerchantCount);
Long allMerchantCount = wxOrderMapper.queryOrderForMerchantCount(params);
result.put("allMerchantCount", allMerchantCount);
//今日
params.put("startdate", systemTime + " 00:00:00");
params.put("enddate", systemTime + " 23:59:59");
Long todayMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
result.put("todayMerchantCount",todayMerchantCount);
Long todayMerchantCount = wxOrderMapper.queryOrderForMerchantCount(params);
result.put("todayMerchantCount", todayMerchantCount);
//昨日
String yesterday = DateUtils.getTimeBefore(1, new Date());
params.put("startdate", yesterday + " 00:00:00");
params.put("enddate", yesterday + " 23:59:59");
Long yesterdayMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
result.put("yesterdayMerchantCount",yesterdayMerchantCount);
Long yesterdayMerchantCount = wxOrderMapper.queryOrderForMerchantCount(params);
result.put("yesterdayMerchantCount", yesterdayMerchantCount);
//上周
String lastweek = DateUtils.getTimeBefore(7, new Date());
params.put("startdate", lastweek + " 00:00:00");
params.put("enddate", lastweek + " 23:59:59");
Long lastweekMerchantCount=wxOrderMapper.queryOrderForMerchantCount(params);
result.put("lastweekMerchantCount",lastweekMerchantCount);
Long lastweekMerchantCount = wxOrderMapper.queryOrderForMerchantCount(params);
result.put("lastweekMerchantCount", lastweekMerchantCount);
//商户数日环比
if (yesterdayMerchantCount > 0) {
double hbd = (double) (todayMerchantCount - yesterdayMerchantCount) / yesterdayMerchantCount * 100;
double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
result.put("increasedPercentMerchant", hb+"%");
result.put("increasedPercentMerchant", hb + "%");
} else {
result.put("increasedPercentMerchant", "--");
}
@@ -1325,7 +1232,7 @@ public class WxOrderServiceImpl implements WxOrderService {
if (lastweekMerchantCount > 0) {
double hbd = (double) (todayMerchantCount - lastweekMerchantCount) / lastweekMerchantCount * 100;
double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
result.put("increasedPercentWeekMerchant", hb+"%");
result.put("increasedPercentWeekMerchant", hb + "%");
} else {
result.put("increasedPercentWeekMerchant", "--");
}
@@ -1340,46 +1247,46 @@ public class WxOrderServiceImpl implements WxOrderService {
params.put("startdate", thirtyTime + " 00:00:00");
params.put("enddate", systemTime + " 23:59:59");
params.put("order_status", "1");
Long allPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long allPayOrderSummary = wxOrderMapper.queryOrderForSum(params);
params.put("order_status", "4");
Long allRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long allRefundOrderSummary = wxOrderMapper.queryOrderForSum(params);
result.put("allRefundOrderSummary", allRefundOrderSummary);
Long allOrderSummary = allPayOrderSummary - allRefundOrderSummary;
result.put("allOrderSummary",allPayOrderSummary);
result.put("allOrderSummary", allPayOrderSummary);
//今日
params.put("startdate", systemTime + " 00:00:00");
params.put("enddate", systemTime + " 23:59:59");
params.put("order_status", "1");
Long todayPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long todayPayOrderSummary = wxOrderMapper.queryOrderForSum(params);
params.put("order_status", "4");
Long todayRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long todayRefundOrderSummary = wxOrderMapper.queryOrderForSum(params);
result.put("todayRefundOrderSummary", todayRefundOrderSummary);
result.put("todayOrderSummary",todayPayOrderSummary);
result.put("todayOrderSummary", todayPayOrderSummary);
//昨日
String yesterday = DateUtils.getTimeBefore(1, new Date());
params.put("startdate", yesterday + " 00:00:00");
params.put("enddate", yesterday + " 23:59:59");
params.put("order_status", "1");
Long yesterdayPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long yesterdayPayOrderSummary = wxOrderMapper.queryOrderForSum(params);
params.put("order_status", "4");
Long yesterdayRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long yesterdayRefundOrderSummary = wxOrderMapper.queryOrderForSum(params);
result.put("yesterdayRefundOrderSummary", yesterdayRefundOrderSummary);
result.put("yesterdayOrderSummary",yesterdayPayOrderSummary);
result.put("yesterdayOrderSummary", yesterdayPayOrderSummary);
//上周
String lastweek = DateUtils.getTimeBefore(7, new Date());
params.put("startdate", lastweek + " 00:00:00");
params.put("enddate", lastweek + " 23:59:59");
params.put("order_status", "1");
Long lastweekPayOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long lastweekPayOrderSummary = wxOrderMapper.queryOrderForSum(params);
params.put("order_status", "4");
Long lastweekRefundOrderSummary=wxOrderMapper.queryOrderForSum(params);
Long lastweekRefundOrderSummary = wxOrderMapper.queryOrderForSum(params);
result.put("lastweekRefundOrderSummary", lastweekRefundOrderSummary);
result.put("lastweekOrderSummary",lastweekPayOrderSummary);
result.put("lastweekOrderSummary", lastweekPayOrderSummary);
//商户数日环比
if (yesterdayPayOrderSummary > 0) {
double hbd = (double) (todayPayOrderSummary - yesterdayPayOrderSummary) / yesterdayPayOrderSummary * 100;
double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
result.put("increasedPercentSummary", hb+"%");
result.put("increasedPercentSummary", hb + "%");
} else {
result.put("increasedPercentSummary", "--");
}
@@ -1387,13 +1294,15 @@ public class WxOrderServiceImpl implements WxOrderService {
if (lastweekPayOrderSummary > 0) {
double hbd = (double) (todayPayOrderSummary - lastweekPayOrderSummary) / lastweekPayOrderSummary * 100;
double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
result.put("increasedPercentWeekSummary", hb+"%");
result.put("increasedPercentWeekSummary", hb + "%");
} else {
result.put("increasedPercentWeekSummary", "--");
}
}

/** 砍价 */
/**
* 砍价
*/
@Override
public PageInfo<WxOrderCouponPressVo> listPressVoAsPage(WxOrder record, Integer pageIndex, Integer pageSize) {
return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderMapper.findListOfPress(record));
@@ -1423,63 +1332,49 @@ public class WxOrderServiceImpl implements WxOrderService {
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
public WxOrder saveFreeOrderForCoupon(WxCUser user, WxCoupon coupon, Long couponChannelId, String formId) {
// 1. check user info and coupon info
// 2. 减库存
// 3. save order
// 4. 积分券 -- 扣减积分
// 10. coupon order
// 11. 生成完成后一系列操作
userCouponMerchantCheck(user, coupon);
if (coupon.getType() == EnumCouponType.COUPON_CREDIT.getCode() || coupon.getType() == EnumCouponType.COUPON_CREDIT_PARK.getCode()) {
if (coupon.checkIsCreditCoupon()) {
//若用户剩余积分比积分售价低则不能支付
if (user.getCredit() == null || user.getCredit() < coupon.getCreditPrice()) {
throw new MallinkException(ErrorCode.CREDIT_NOT_ENOUGH);
}
}
// 2. 减库存操作
String couponIdStr = String.valueOf(coupon.getId());
// 减库存操作
stockReduce(user, coupon, couponIdStr);
Date curr = new Date();
// body
String bodyStr = "";
try {
bodyStr = Utility.substring(coupon.getTitle(), Math.min(62, coupon.getTitle().getBytes().length), "utf-8");
} catch (Exception e) {
logger.error("body:" + e.getMessage());
bodyStr = /*wxMerchant.getName() + */ "-" + EnumCouponType.getEnum(coupon.getType());
// 3. 当积分券或者积分停车券时 则进行积分支付
Integer orderType;
if (coupon.checkIsCreditCoupon()) {
creditPay(user, coupon);
orderType = EnumOrderType.CREDIT.getCode();
} else {
orderType = EnumOrderType.COUPON.getCode();
}
final IdWorker idWorker = IdWorker.get();
Long orderNumber = idWorker.nextId();
// 4. 保存Order
WxOrder record = new WxOrder();
record.setId(orderNumber);
record.setTenantId(user.getTenantId());
record.setOrderNumber(orderNumber);
record.setCouponChannelId(couponChannelId);
record.setProductId(coupon.getId());
//当积分券或者积分停车券时 则进行积分支付
creditPay(user, coupon, record);
record.setType(orderType);
record.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode());
record.setcUserId(user.getId());
record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
record.setPayment(0);
record.setDetail(bodyStr);
record.setCreateDate(curr);
record.setUpdateDate(curr);
record.setOrderGroupId(0L);
record.setFormId(formId);
record.setOrderGroupId(0L);
try {
// 保存订单
wxOrderMapper.insertSelective(record);
} catch (RuntimeException e) {
saveFreeOrder(record, user, coupon);
} catch (Exception e) {
logger.error("下订单:" + e.getMessage());
// 库存恢复
stockBack(record);
logger.error("保存订单:" + e.getMessage());
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}
// 创建couponOrder

// 5. 创建couponOrder
try {
createCouponOrder(user, record, coupon);
createCouponOrder(record, user, coupon);
} catch (Exception e) {
logger.error("保存订单:" + e.getMessage());
logger.error("couponOrder失败:" + e.getMessage());
// 库存恢复
stockBack(record);
throw new MallinkException(ErrorCode.COUPON_ORDER_SAVE_ERR);
@@ -1487,7 +1382,39 @@ public class WxOrderServiceImpl implements WxOrderService {
return record;
}

private void userCouponMerchantCheck(WxCUser user, WxCoupon coupon) {
/**
* 保存订单-免费
* @param record
* @param user
* @param coupon
*/
private void saveFreeOrder(WxOrder record, WxCUser user, WxCoupon coupon) {
Date curr = new Date();
// body
String bodyStr = "";
try {
bodyStr = Utility.substring(coupon.getTitle(), Math.min(62, coupon.getTitle().getBytes().length), "utf-8");
} catch (Exception e) {
logger.error("body:" + e.getMessage());
bodyStr = "券" + '-' + EnumCouponType.getEnum(coupon.getType());
}

final IdWorker idWorker = IdWorker.get();
Long orderNumber = idWorker.nextId();
record.setId(orderNumber);
record.setTenantId(user.getTenantId());
record.setOrderNumber(orderNumber);
record.setProductId(coupon.getId());
record.setcUserId(user.getId());
record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
record.setDetail(bodyStr);
record.setCreateDate(curr);
record.setUpdateDate(curr);
// 保存订单
wxOrderMapper.insertSelective(record);
}

private void userCouponMerchantCheck(WxCUser user, WxCoupon coupon) throws MallinkException {
// 检查用户
if (user == null) {
logger.error("用户不存在");
@@ -1498,70 +1425,60 @@ public class WxOrderServiceImpl implements WxOrderService {
logger.error("券不存在");
throw new MallinkException(ErrorCode.COUPON_IS_EMPTY);
}
// 检查券状态
if (coupon.getStatus().equals(EnumCouponStatus.COUPON_STATUS_TAKE_OFFF.getCode())) {
logger.error("券已下架, couponId: " + coupon.getId());
throw new MallinkException(ErrorCode.COUPON_ORDER_IS_INVALID);
}
// 检查券商户信息
if (!isCouponMerchantValid(coupon.getId())) {
logger.error("商户不存在, couponId: " + coupon.getId());
throw new MallinkException(ErrorCode.MERCHANT_INFO_NOT_FOUND);
}
// 检查 优惠券 库存
if (coupon.getRemainInventory() <= 0) {
logger.error("此券库存为0, couponId: " + coupon.getId());
throw new MallinkException(ErrorCode.REMAIN_IS_EMPTY);
}
}

private void creditPay(WxCUser user, WxCoupon coupon, WxOrder record) {
if (coupon.getType() == EnumCouponType.COUPON_CREDIT.getCode() || coupon.getType() == EnumCouponType.COUPON_CREDIT_PARK.getCode()) {
//-------此处为【积分支付】记录增加积分操作-------
WxCreditHistory creditHistory = new WxCreditHistory();
//记录操作人类型 操作人id
if (user.getOperatorType() == EnumUserType.MALLUSER.getCode()) {
creditHistory.setOperatorType(EnumUserType.MALLUSER.getCode());
creditHistory.setOperatorId(user.getOperatorId());
} else {
creditHistory.setOperatorType(EnumUserType.CUSER.getCode());
creditHistory.setOperatorId(user.getId());
}
creditHistory.setCreditNum(coupon.getCreditPrice());
creditHistory.setCUserId(user.getId());
creditHistory.setTenantId(user.getTenantId());
creditHistory.setCreditType(EnumScoreType.CHANGE_CREDIT.getCode());
creditHistory.setCouponId(coupon.getId());
//如果券与商户一对一 则直接将消费商户更新为此商户 若一对多 则消费商户显示多商户
setMerchantId(coupon, creditHistory);
wxCreditHistoryService.saveOrUpdate(creditHistory);
record.setType(EnumOrderType.CREDIT.getCode());
private void creditPay(WxCUser user, WxCoupon coupon) {
//-------此处为【积分支付】记录增加积分操作-------
WxCreditHistory creditHistory = new WxCreditHistory();
//记录操作人类型 操作人id
if (user.getOperatorType() == EnumUserType.MALLUSER.getCode()) {
creditHistory.setOperatorType(EnumUserType.MALLUSER.getCode());
creditHistory.setOperatorId(user.getOperatorId());
} else {
record.setType(EnumOrderType.COUPON.getCode());
creditHistory.setOperatorType(EnumUserType.CUSER.getCode());
creditHistory.setOperatorId(user.getId());
}
creditHistory.setCreditNum(coupon.getCreditPrice());
creditHistory.setCUserId(user.getId());
creditHistory.setTenantId(user.getTenantId());
creditHistory.setCreditType(EnumScoreType.CHANGE_CREDIT.getCode());
creditHistory.setCouponId(coupon.getId());
//如果券与商户一对一 则直接将消费商户更新为此商户 若一对多 则消费商户显示多商户
setMerchantId(coupon, creditHistory);
wxCreditHistoryService.saveOrUpdate(creditHistory);
}

@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
public WxOrder saveNoFreeOrderForCoupon(WxCUser user, WxCoupon coupon, Long couponChannelId, boolean isPress, Long orderGroupId, String formId) {
// 1. check user info and coupon info
// 2. save order
// 拼团
// 拼团
userCouponMerchantCheck(user, coupon);
if (orderGroupId != null && !orderGroupId.equals(0L)) {
WxOrderGroup group = wxOrderGroupMapper.selectByPrimaryKey(orderGroupId);
if (group.getStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode())) {
logger.error("下订单拼团人数已满>>>" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FINISHED);
}
WxOrder order = new WxOrder();
order.setOrderGroupId(group.getId());
order.setCUserId(user.getId());
order.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_UNPAID.getCode());
long count = wxOrderMapper.selectCount(order);
if (count > 0) {
logger.error("重复的拼团>>>" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_UNPAID);
}
// 2. 拼团检查
if (isOrderGroup(orderGroupId)) {
checkOrderGroup(user, orderGroupId);
}
String couponIdStr = String.valueOf(coupon.getId());
// 减库存操作
// 3. 减库存操作
stockReduce(user, coupon, couponIdStr);
Date curr = new Date();

// 4. 保存订单
Long orderNumber;
// 4.1 券价格
int payment = coupon.getSalePrice();
Integer orderStatus = EnumOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode();
if (isPress || coupon.getType().equals(EnumCouponType.COUPON_PRESS.getCode())) {
@@ -1576,6 +1493,71 @@ public class WxOrderServiceImpl implements WxOrderService {
orderStatus = EnumOrderStatus.ORDER_STATUS_COOPERATING_UNPAID.getCode();
}
}

// 4.2 保存订单
WxOrder record = new WxOrder();
record.setCouponChannelId(couponChannelId);
record.setOrderGroupId(orderGroupId);
record.setFormId(formId);
record.setPayment(payment);
record.setOrderStatus(orderStatus);
try {
orderNumber = saveNoFreeOrder(record, user, coupon, isPress);
} catch (Exception e) {
// 库存恢复
stockBack(record);
logger.error("保存订单:" + e.getMessage());
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}

if (isPress) {
// 5. 第一次砍价
try {
firstPress(record, user, coupon, orderNumber);
}catch (Exception e) {
// 库存恢复
stockBack(record);
logger.error("第一次砍价失败:" + e.getMessage());
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}
}
return record;
}

/**
* 初始砍价
* @param record
* @param user
* @param coupon
* @param orderNumber
*/
private void firstPress(WxOrder record, WxCUser user, WxCoupon coupon, Long orderNumber) {
// 保存砍价信息
int total = coupon.getPrice() - coupon.getSalePrice();
int left_total = total;
WxOrderPress orderPress = new WxOrderPress();
orderPress.setId(IdWorker.get().nextId());
orderPress.setOrderId(orderNumber);
orderPress.setUserId(user.getId());
orderPress.setCreateDate(new Date());
orderPress.setFirst(EnumOrderPressType.FIRST.getCode());
int lPressValue = PressUtils.stateLessPressValue(total, left_total, coupon.getPressLimitNum(), 0);
orderPress.setPressValue(lPressValue);
wxOrderPressMapper.insertSelective(orderPress);
// 更新订单砍价信息
WxOrder orderUpdatePress = new WxOrder();
orderUpdatePress.setId(record.getId());
orderUpdatePress.setPressCurrentNum(1);
orderUpdatePress.setPressCurrentValue(left_total - orderPress.getPressValue());
orderUpdatePress.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PRESSING.getCode());
orderUpdatePress.setUpdateDate(new Date());
wxOrderMapper.updateByPrimaryKeySelective(orderUpdatePress);
}

private Long saveNoFreeOrder(WxOrder record, WxCUser user, WxCoupon coupon, boolean isPress) {
Long orderNumber;
Date curr = new Date();

// body
// tenant_id + merchant_id + title + subtitle
String bodyStr = "";
@@ -1583,85 +1565,53 @@ public class WxOrderServiceImpl implements WxOrderService {
bodyStr = Utility.substring(coupon.getTitle(), Math.min(62, coupon.getTitle().getBytes().length), "utf-8");
} catch (Exception e) {
logger.error("body:" + e.getMessage());
bodyStr = /*wxMerchant.getName() + */ "-" + EnumCouponType.getEnum(coupon.getType());
bodyStr = "-" + EnumCouponType.getEnum(coupon.getType()).getMessage();
}
final IdWorker idWorker = IdWorker.get();
Long orderNumber = idWorker.nextId();
WxOrder record = new WxOrder();
orderNumber = idWorker.nextId();
record.setId(orderNumber);
record.setTenantId(user.getTenantId());
record.setOrderNumber(orderNumber);
record.setCouponChannelId(couponChannelId);
record.setProductId(coupon.getId());
record.setType(EnumOrderType.COUPON.getCode());
record.setOrderStatus(orderStatus);
record.setcUserId(user.getId());
record.setPaymentType(EnumPayType.PAY_PAYMENT.getCode());
record.setPayment(payment);
record.setDetail(bodyStr);
record.setCreateDate(curr);
record.setUpdateDate(curr);
record.setOrderGroupId(orderGroupId);
record.setFormId(formId);
if (isPress) {
// 初始砍价信息
record.setPressCurrentNum(0);
// 砍价券过期时间取券的过期时间和砍价限制时间中时间小的那个
Date pressEndDate = DateUtils.getHourTimeAfter(coupon.getPressLimitHours(), new Date());
if(pressEndDate.after(coupon.getValidEndDate()))
if (pressEndDate.after(coupon.getValidEndDate()))
pressEndDate = coupon.getValidEndDate();
record.setPressEndDate(pressEndDate);
record.setPressCurrentValue(coupon.getPrice() - coupon.getSalePrice());
}
try {
// 保存订单
wxOrderMapper.insertSelective(record);
} catch (RuntimeException e) {
// 库存恢复
stockBack(record);
logger.error("保存订单:" + e.getMessage());
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}
if (isPress) {
// 初始砍价
// 添加 wx_order_press
int total = coupon.getPrice() - coupon.getSalePrice();
int left_total = total;
WxOrderPress orderPress = new WxOrderPress();
orderPress.setId(idWorker.nextId());
orderPress.setOrderId(orderNumber);
orderPress.setUserId(user.getId());
orderPress.setCreateDate(new Date());
orderPress.setFirst(EnumOrderPressType.FIRST.getCode());
int lPressValue = PressUtils.stateLessPressValue(total, left_total, coupon.getPressLimitNum(), 0);
orderPress.setPressValue(lPressValue);
try {
// 保存订单
wxOrderPressMapper.insertSelective(orderPress);
} catch (RuntimeException e) {
// 库存恢复
stockBack(record);
logger.error("保存砍价记录Err:" + e.getMessage());
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}
// 更新砍价信息
WxOrder orderUpdatePress = new WxOrder();
orderUpdatePress.setId(record.getId());
orderUpdatePress.setPressCurrentNum(1);
orderUpdatePress.setPressCurrentValue(left_total - orderPress.getPressValue());
orderUpdatePress.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PRESSING.getCode());
orderUpdatePress.setUpdateDate(new Date());
try {
// 保存订单
wxOrderMapper.updateByPrimaryKeySelective(orderUpdatePress);
} catch (RuntimeException e) {
// 库存恢复
stockBack(record);
logger.error("更新订单记录Err:" + e.getMessage());
throw new MallinkException(ErrorCode.ORDER_SAVE_ERR);
}
wxOrderMapper.insertSelective(record);
return orderNumber;
}

private void checkOrderGroup(WxCUser user, Long orderGroupId) {
WxOrderGroup group = wxOrderGroupMapper.selectByPrimaryKey(orderGroupId);
if (group.getStatus().equals(EnumOrderStatus.ORDER_STATUS_COOPERATING_COMPLETE.getCode())) {
logger.error("下订单拼团人数已满>>>" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FINISHED);
}
WxOrder order = new WxOrder();
order.setOrderGroupId(group.getId());
order.setCUserId(user.getId());
order.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_UNPAID.getCode());
long count = wxOrderMapper.selectCount(order);
if (count > 0) {
logger.error("重复的拼团>>>" + orderGroupId);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_UNPAID);
}
return record;
}

private boolean isOrderGroup(Long orderGroupId) {
return orderGroupId != null && !orderGroupId.equals(0L);
}




+ 23
- 44
mallinkService/src/main/java/com/iformall/service/impl/WxPayOrderServiceImpl.java Просмотреть файл

@@ -1187,45 +1187,34 @@ public class WxPayOrderServiceImpl implements WxPayOrderService {
throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "支付订单数据库更新失败: " + e.getMessage());
}


//如果是Coupon是团购类型创建拼团信息不创建COUPON_ORDER
//查询券的类型
Long productId = order.getProductId();
WxCoupon wxCoupon = wxCouponMapper.selectByPrimaryKey(productId);
Integer type = wxCoupon.getType();
if (type.equals(EnumCouponType.COUPON_GROUP.getCode()) && wxCoupon.getSalePrice().equals(record.getPayAmount())) {
try {
wxOrderGroupService.createOrderGroup(order, wxCoupon);
} catch (Exception e) {
logger.error("参团失败" + e.getMessage());
order.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_FAILD.getCode());
order.setUpdateDate(new Date());
wxOrderMapper.updateByPrimaryKeySelective(order);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
} else {
// 修改订单状态
try {
wxOrderService.couponOrderSuccess(order);
} catch (Exception e) {
logger.error(e.getMessage());
throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "订单更新");
if(wxCoupon != null) {
if (isOrderGroupCoupon(record, wxCoupon)) {
// 如果是Coupon是拼团, 创建拼团信息, 不创建COUPON_ORDER
try {
wxOrderGroupService.createOrderGroup(order, wxCoupon);
} catch (Exception e) {
logger.error("参团失败" + e.getMessage());
order.setOrderStatus(EnumOrderStatus.ORDER_STATUS_COOPERATING_FAILD.getCode());
order.setUpdateDate(new Date());
wxOrderMapper.updateByPrimaryKeySelective(order);
throw new MallinkException(ErrorCode.ORDER_GROUP_COOPERATING_FAILD);
}
} else {
// 普通券, 修改订单状态
try {
wxOrderService.couponOrderSuccess(order);
} catch (Exception e) {
logger.error(e.getMessage());
throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "订单更新");
}
}
}
}

/*
Map<String, String> msgMap = new HashMap<>();
try {
msgMap.put("name", String.valueOf(order.getCouponId()));
msgMap.put("orderNo", String.valueOf(order.getId()));
msgMap.put("createTime", Utility.getDataFormatString3(order.getCreateDate()));
msgMap.put("standingTime", order.getCreateDate() + "-" + currentDate );
// 短信 通知 商户
//smsSenderHandler.sendSms("SMS_18195394", order.getMobile(), msgMap);
} catch (Exception e) {
logger.error("pay success handle, sms send exception, payOrderi: " + updatePayOrder+ ", msgMap: " + msgMap.toString() + ", e: " + e.getMessage());
}
*/
private boolean isOrderGroupCoupon(WxPayOrder record, WxCoupon wxCoupon) {
return wxCoupon.getType().equals(EnumCouponType.COUPON_GROUP.getCode()) && wxCoupon.getSalePrice().equals(record.getPayAmount());
}

@Override
@@ -1484,16 +1473,6 @@ public class WxPayOrderServiceImpl implements WxPayOrderService {
throw new MallinkException(ErrorCode.USER_IS_EMPTY);
}
}
// 修改订单状态
try {
int _count = wxOrderService.couponOrderSuccessFree(order);
if (_count > 1) {
throw new MallinkException(ErrorCode.ORDER_IS_FAIL);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "订单更新");
}
}

private WxAppinfo getWxAppinfo(Integer orderType, String tenentId) {


+ 1
- 1
mallinkService/src/main/resources/mapper/WxOrderGroupMapper.xml Просмотреть файл

@@ -92,7 +92,7 @@
</select>
<update id="updateOrderGroup" parameterType="com.iformall.domain.po.WxOrderGroup">
update wx_order_group set remain_people=remain_people-1,update_date=#{updateDate} where id=#{id} and remain_people>0
update wx_order_group set remain_people=remain_people-1,status=#{status},update_date=#{updateDate} where id=#{id} and remain_people>0
</update>


Загрузка…
Отмена
Сохранить